Search code examples
simulationhpcchapel

Equivalent of Octave's `meshgrid` in Chapel


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?


Solution

  • 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).