Equivalent of Octave's `meshgrid` in Chapel - simulation

Octave provides a utility function called meshgrid that generates point fields. This is very useful in large scale simulations for evaluating functions at certain points. With Chapels Domain feature, the mesh could be distributed. Is there a library that provides this functionality?

This isn't fully general (or tested in detail), but how about this for a prototype
proc meshgrid(arrs : ?T ... ?nsize) where
isArray(T) && (nsize > 0)
{
const lo = arrs.indices.first;
// All elements have the same type T, so we only need to check that.
assert(arrs[lo].rank==1);
type retType = nsize*arrs[lo].eltType;
// Define the output domain
var tmp : nsize*range;
for ii in arrs.indices do (tmp(ii),) = arrs[ii].domain.dims();
var Dom = {(...tmp)};
var retval : [Dom] retType;
forall ijk in Dom {
for ii in lo.. #nsize do retval[ijk](ii) = arrs(ii)[ijk(ii)];
}
return retval;
}
Here's an example
var x = [1,2,5];
var y = [2,1];
writeln(meshgrid(x,y));
which yields
(1, 2) (1, 1)
(2, 2) (2, 1)
(5, 2) (5, 1)
I chose to save the indices as tuple elements, since that seemed most natural in terms of the ways I might use this (given Chapel promotion).

Related

Logic behind Two Number Sum Algorithm

Could someone explain to me the logic behind this hashMap algorithm? I'm getting confused about how the algorithm receives the total sum. I'm starting to learn about algorithms, so it's a little confusing for me. I made comments in my code to pinpoint each line code, but I'm not sure I'm grasping logic correctly. I'm just looking for an easier way to understand how the algorithm works to avoid confusing myself.
//**calculate Two Number Sum
func twoNumberSum(_ array: [Int], _ targetSum: Int) -> [Int] {
//1) initilize our Array to hold Integer Value: Boolean value to store value into hashTable
var numbersHashMap = [Int:Bool]()
//2) create placeHolder called number that iterates through our Array.
for number in array {
//3) variable = y - x
let match = targetSum - number
//4) ??
if let exists = numbersHashMap[match], exists {
//5) match = y / number = x
return [match, number] //
} else {
//6) Store number in HashTable and repeats
numbersHashMap[number] = true
}
}
return []
}
twoNumberSum([3,5,-4, 8, 11, 1, -1, -6], 10)
// x = Number
// y = Unknown *Solve for Y*
Sure, I can walk you through it. So we have a list of numbers, are we are trying to find two numbers that add together to make the specified target. To do this, for each number x, we check if (target - x) is in the list. If it is not, then we add x to the list. If it is, then we return x and (target - x).
Step 4 in your code is the part where we check if (target - x) is in the list. To see why this makes sense, let's walk through an example.
Say we have [2, 3, -1] and our target is 1. In this case, we first consider x = 2 and check our hashmap for (target - x) = (1 - 2) = -1. Since -1 is not in the hashmap, we add 2 to the hashmap. We then consider x = 3 and check for (1 - 3) = -2. Again, -2 is not in the hashmap, so we add it. Now we check x - -1. In this case, when we check (target - x) = (1 - (-1)) = 2, 2 is in the hashmap. Intuitively, we have already "seen" 2, and know that 2 and -1 can be added to get our value.
This is what provides the speed optimization over checking every two numbers in the list.

Set/sequence summation operator?

I have a set, S = { 1, 2, 3, 4, 5 }.
If I wanted to sum this in standard logic it's just ∑S (no MathJax on SO so I can't format this nicely).
What's the VDM equivalent? I don't see anything in the numerics/sets section of the language reference.
There isn't a standard library function to do this (though perhaps there should be). You would sum a set with a simple recursive function:
sum: set of nat +> nat
sum(s) ==
if s = {}
then 0
else let e in set s in
e + sum(s \ {e})
measure card s;
The "let" selects an arbitrary element from the set, and then add that to the sum of the remainder. The measure says that the recursion always deals with smaller sets.
This should work:
sum(S)
But you could find this very easily.

Shortening If/Else from if(x == y || x == z) to if(x == y || z) in swift

I'm making an app where I have to put a lot of if/else statements. I know you can do as in the title in some other coding language, but I'm not sure if you can do it in Swift.
How do you shorten this:
if x == y || x == z {
//do something
}
To something like this:
if x == y || z {
//do something
}
Perhaps you could consider using an array and checking to see if x is in the array, like in the following example:
let (x, y, z) = (3, 8, 3)
if [y, z].contains(x) {
//True
}
If you're comparing objects (like UIImage), use containsObject instead of contains:
if [x, y, z].containsObject(y) {
//True
}
I conject that there is no sensible language (swift included), that distributes comparison == across logical or ||.
The way you've written it - x == y || x == z - is the most compact form.
Jack Greenhill's answer does indeed go into the right direction. However with more and more values, his method will get very inefficient, since it has to check every element of the array against equality, therefore complexity O(n).
A very underrated data structure, which can do this kind of operation in O(1) should be used instead: The Set. It uses hash values to check quickly whether a value is present or not. You can use it like this:
let x = 3
let values : Set = [1, 3, 6, 1, 7] // {6, 7, 3, 1}
if values.contains(x) {
// ...
}
This takes the same amount of time, whether values contains just one or 1000 elements. An array would be 1000 times slower.
Oftentimes the decision to use an array is made before even considering a set. If your elements don't have any order and can only occur once (which is actually more often the case than you'd think), you probably want a set. A set gives you useful methods, such as union, isSubset, interception and more, for free by just putting your elements in it. The only additional requirement for the element type is to conform to Hashable.
Perhaps this:
switch x {
case y, z : // do then
default : // do else
}

Why do th array range primitives consume their sources?

The range primitives that are dedicated to the built-in arrays consume their sources but one could easily design a range system that would rather be based on the .ptr of the source (at first look that's more flexible).
struct ArrayRange(T)
{
private T* _front;
private T* _back;
this(ref T[] stuff) {
_front = stuff.ptr;
_back = _front + stuff.length;
}
#property bool empty(){return _front == _back;}
#property T front(){ return *_front;}
#property T back(){return *_back;}
void popFront(){ ++_front;}
void popBack(){--_back;}
T[] array(){return _front[0 .. _back - _front];}
typeof(this) save() {
auto r = this.array.dup;
return typeof(this)(r);
}
}
void main(string[] args)
{
auto s = "bla".dup;
// here the source is 'fire-proofed'
auto rng = ArrayRange!char(s);
rng.popFront;
assert (s == "bla");
assert (rng.array == "la");
// default primitives: now the source is consumed
import std.array;
s.popFront;
assert (s == "la");
}
Why is the default system not based on pointer arithmetic since poping the front imply reallocations/less efficiency?
Any rationale for this design?
I agree with you, there is no reason to reallocate at each popFront. Good thing that's not what happens then!
The popFront mechanism is quite alike what you presented, and the source isn't consumed, only the array on which you call popFront (because, it is a pop after all). What you implemented is what happens when you slice an array: you get a reference range to the original array:
auto a = [1, 2, 3];
auto s = a[];
s.popFront;
assert(s == [2, 3]);
assert(a == [1, 2, 3]);
.dup is there to provide a copy of an array so that you can safely modify the copy without changing the original, so it copies the original array then provides an input range to this copy. Of course you can modify the copy (that's the point), and popFront will change it but still uses pointer arithmetic and without changing the source.
auto a = [1, 2, 3];
auto s = a.dup;
s.popFront;
assert(s = [2, 3]);
assert(a = [1, 2, 3]);
.dup may not seem very useful as such because we are using it with arrays, but it is really important when dealing with "pure" ranges as a range is often lazy not to consume it. As the copy of the range is consumed and not the initial one, we can safely pass this copy to a function and still have our initial lazy range intact.

Easy way to create and initialise a 3D table of structs in Matlab

I would like to be able to initialise a big table in matlab easily.
Say I have the bounds x, y, z = 5, 4, 3. I want to be able to make a 5x4x3 table where each element is a struct that stores count and sum. Count and sum in this struct should be 0 when initialised.
I thought it would be enough to do this:
table = []
table(5,4,3) = struct('sum', 0, 'count', 0)
And this would work for a double but not with a structure evidently.
Any ideas?
EDIT:
As another question, (bonus if you will) is there a way to force matlab to store the struct, but when you access the element (i.e., table(1, 2, 3)) get it to return the average (i.e., table(1,2,3).sum/table(1,2,3).count).
Its not vital to the question but it would certainly be cool.
You'll need just to replace the line table = [] to avoid the error, that is
clear table;
table(5,4,3) = struct('sum', 0, 'count', 0)
works fine. Note, however, that this command only initializes one field of your array, i.e., the memory allocation is incomplete. To initialize all fields of your array, you can use
table2(1:5,1:4,1:3) = struct('sum', 0, 'count', 0)
to visualize the difference, use whos, which returns
>> whos
Name Size Bytes Class Attributes
table 5x4x3 736 struct
table2 5x4x3 8288 struct
Your second question can be solved, for instance, by using anonymous functions
myMean = #(a) a.sum./a.count; %define the function
myMean(table2(2,2,2)) % access the mean in the field (2,2,2)