Creates a grid mesh
173075
function gridMesh(nx, ny, origin, dx, dy) {
  //Unpack default arguments
  origin = origin || [0,0]
  if(!dx || dx.length < origin.length) {
    dx = dup(origin.length)
    if(origin.length > 0) {
      dx[0] = 1
    }
  }
  if(!dy || dy.length < origin.length) {
    dy = dup(origin.length)
    if(origin.length > 1) {
      dy[1] = 1
    }
  }
  //Initialize cells
  var cells = []
    , positions = dup([(nx+1) * (ny+1), origin.length])
    , i, j, k, q, d = origin.length
  for(j=0; j<ny; ++j) {
    for(i=0; i<nx; ++i) {
      cells.push([ p(i,j,nx), p(i+1, j,nx), p(i, j+1,nx) ])
      cells.push([ p(i+1,j,nx), p(i+1,j+1,nx), p(i,j+1,nx) ])
    }
  }
  //Initialize positions
  for(j=0; j<=ny; ++j) {
    for(i=0; i<=nx; ++i) {
      q = positions[ p(i, j, nx) ]
      for(k=0; k<d; ++k) {
        q[k] = origin[k] + dx[k] * i + dy[k] * j
      }
    }
  }
  return {
    positions: positions,
    cells: cells
  }
}
1237505
private function generateGrid()
    {
        $this->addRectangle(
            $this->grid_padding,
            ($this->height-$this->grid_padding),
            ($this->width-$this->grid_padding),
            $this->grid_padding
        );
    }
452566
public Grid setupGrid(float[] vertices) {
        int vc = vertices.length / 3;
        //CTM_POSITION_ELEMENT_COUNT == 3
        // Calculate the mesh boundinggrid. box
        float[] min = new float[3];
        float[] max = new float[3];
        int[] division = new int[3];

        for (int i = 0; i < 3; ++i) {
            min[i] = max[i] = vertices[i];

        }
        for (int i = 1; i < vc; ++i) {
            for (int j = 0; j < 3; j++) {
                min[j] = min(min[j], vertices[i * 3 + j]);
                max[j] = max(max[j], vertices[i * 3 + j]);
            }
        }

        // Determine optimal grid resolution, based on the number of vertices and
        // the bounding box.
        // NOTE: This algorithm is quite crude, and could very well be optimized for
        // better compression levels in the future without affecting the file format
        // or backward compatibility at all.

        float[] factor = new float[3];
        for (int i = 0; i < 3; ++i) {
            factor[i] = max[i] - min[i];
        }

        float sum = factor[0] + factor[1] + factor[2];

        if (sum > 1e-30f) {
            sum = 1.0f / sum;
            for (int i = 0; i < 3; ++i) {
                factor[i] *= sum;
            }
            double wantedGrids = pow(100.0f * vc, 1.0f / 3.0f);
            for (int i = 0; i < 3; ++i) {
                division[i] = (int) ceil(wantedGrids * factor[i]);
                if (division[i] < 1) {
                    division[i] = 1;
                }
            }
        } else {
            division[0] = 4;
            division[1] = 4;
            division[2] = 4;
        }

        return new Grid(Vec3f.from(min), Vec3f.from(max), Vec3i.from(division));
    }
1315715
def generate_base_grid(self, vtk_filename=None):
        
        nd, ed, ed_dir = self.gen_grid_fcn(self.data.shape, self.voxelsize)
        self.add_nodes(nd)
        self.add_edges(ed, ed_dir, edge_low_or_high=0)

        if vtk_filename is not None:
            self.write_vtk(vtk_filename)
1036223
public static <R> SparseGrid<R> create(Grid<? extends R> grid) {
        if (grid == null) {
            throw new IllegalArgumentException("Grid must not be null");
        }
        SparseGrid<R> created = SparseGrid.create(grid.rowCount(), grid.columnCount());
        created.putAll(grid);
        return created;
    }
729994
function Gridpanel( canvas, width, height, left, top ) {
		var gridpanel,
			data = [],
			xValue = function( d ) { return d[ 0 ]; },
			yValue = function( d ) { return d[ 1 ]; },
			yMax = 0, _yMax,
			numRows, numCols,
			graphs, area,
			headers = [
				'Condition 1: really long description which goes on and on',
				'Condition 2',
				'Condition 3'
			],
			labels = headers,
			annotations, title;

		// [1] Instantiate a new gridpanel generator and configure:
		gridpanel = xfig.multipanel( canvas )
			.width( width )
			.height( height )
			.gutter( 120 )
			.position({
				'left': left,
				'top': top
			});

		// Get data:
		d3.json( 'data/gridpanel.data.json', function ( error, json ) {

			numRows = json.length;
			numCols = json.length;

			// [2] For each panel dataset, instantiate a new data generator and configure:
			for ( var i = 0; i < numRows; i++ ) {
				for ( var j = 0; j < numCols; j++ ) {

					data.push(
						xfig.data( [ json[ i ], json[ j ] ] )
							.accessors( 'x', xValue )
							.accessors( 'y', yValue )
					);

					// Compute the yMax:
					_yMax = data[ data.length-1 ].max( yValue );
					yMax = ( yMax < _yMax ) ? _yMax : yMax;
				} // end FOR j
			} // end FOR i

			// Bind the data instance to the gridpanel:
			gridpanel.data( data )
				.rows( numRows )
				.cols( numCols )
				.xMin( 0 )
				.xMax( 1 )
				.yMin( 0 )
				.yMax( yMax )
				.yLabel( 'density [a.u.]' )
				.headers( headers )
				.labels( labels );

			// Create the gridpanel:
			gridpanel.create();

			// [3] Instantiate a new annotations generator and configure:
			annotations = xfig.annotations( gridpanel );

			// Create the annotations element:
			annotations.create();

			// [3.1] Instantiate a new title instance and configure:
			title = annotations.title()
				.top( -80 )
				.left( 450 );

			// Add a (sub)title:
			title.create( 'Subtitle' );

			// [4] For each panel graph, instantiate a new area generator and configure:
			graphs = gridpanel.children().graph;
			for ( var k = 0; k < graphs.length; k++ ) {
				area = xfig.area( graphs[ k ] )
					.labels( [ 'data 0', 'data 1' ] );

				// Create the area:
				area.create();
			} // end FOR k

		});

	}
1195991
private SquareGrid assembleGrid( List<List<SquareNode>> listRows) {
		SquareGrid grid = grids.grow();
		grid.reset();

		List<SquareNode> row0 = listRows.get(0);
		List<SquareNode> row1 = listRows.get(1);

		int offset = row0.get(0).getNumberOfConnections() == 1 ? 0 : 1;

		grid.columns = row0.size() + row1.size();
		grid.rows = listRows.size();

		// initialize grid to null
		for (int i = 0; i < grid.columns * grid.rows; i++) {
			grid.nodes.add(null);
		}

		// fill in the grid
		for (int row = 0; row < listRows.size(); row++) {
			List<SquareNode> list = listRows.get(row);
			int startCol = offset - row%2 == 0 ? 0 : 1;
			// make sure there is the expected number of elements in the row
			int adjustedLength = grid.columns-startCol;
			if( (adjustedLength)-adjustedLength/2 != list.size() ) {
				return null;
			}
			int listIndex = 0;
			for (int col = startCol; col < grid.columns; col += 2) {
				grid.set(row,col,list.get(listIndex++));
			}
		}
		return grid;
	}
155471
def draw_grid(self):
        """"""
        self.screen.fill((0xbb, 0xad, 0xa0), self.origin + (self.game_width, self.game_height))
        for y, row in enumerate(self.grid):
            for x, cell in enumerate(row):
                self.screen.blit(self.tiles[cell], self.get_tile_location(x, y))
604169
def _make_grid_of_axes(self,
                           bounding_rect=cfg.bounding_rect_default,
                           num_rows=cfg.num_rows_per_view_default,
                           num_cols=cfg.num_cols_grid_default,
                           axis_pad=cfg.axis_pad_default,
                           commn_annot=None,
                           **axis_kwargs):
        """"""

        axes_in_grid = list()
        extents = self._compute_cell_extents_grid(bounding_rect=bounding_rect,
                                                  num_cols=num_cols,
                                                  num_rows=num_rows, axis_pad=axis_pad)
        for cell_ext in extents:
            ax_cell = self.fig.add_axes(cell_ext, frameon=False, visible=False,
                                        **axis_kwargs)
            if commn_annot is not None:
                ax_cell.set_title(commn_annot)
            ax_cell.set_axis_off()
            axes_in_grid.append(ax_cell)

        return axes_in_grid
671366
def MeshArrows(*inputobj, **options):
    
    s = options.pop("s", None)
    scale = options.pop("scale", 1)
    c = options.pop("c", "gray")
    alpha = options.pop("alpha", 1)
    res = options.pop("res", 12)

    mesh, u = _inputsort(inputobj)
    startPoints = mesh.coordinates()
    u_values = np.array([u(p) for p in mesh.coordinates()])
    if not utils.isSequence(u_values[0]):
        printc("~times Error: cannot show Arrows for 1D scalar values!", c=1)
        exit()
    endPoints = mesh.coordinates() + u_values
    if u_values.shape[1] == 2:  # u_values is 2D
        u_values = np.insert(u_values, 2, 0, axis=1)  # make it 3d
        startPoints = np.insert(startPoints, 2, 0, axis=1)  # make it 3d
        endPoints = np.insert(endPoints, 2, 0, axis=1)  # make it 3d

    actor = shapes.Arrows(
        startPoints, endPoints, s=s, scale=scale, c=c, alpha=alpha, res=res
    )
    actor.mesh = mesh
    actor.u = u
    actor.u_values = u_values
    return actor
1063385
function createVoxelMesh(gl, voxels, voxelSideTextureIDs, voxelSideTextureSizes, position, pad, that) {
  //Create mesh
  var vert_data = createAOMesh(voxels, voxelSideTextureIDs, voxelSideTextureSizes)
  var vertexArrayObjects = {}

  if (vert_data === null) {
    // no vertices allocated
  } else {
    //Upload triangle mesh to WebGL
    var vert_buf = createBuffer(gl, vert_data)
    var triangleVAO = createVAO(gl, [
      { "buffer": vert_buf,
        "type": gl.UNSIGNED_BYTE,
        "size": 4,
        "offset": 0,
        "stride": 8,
        "normalized": false
      },
      { "buffer": vert_buf,
        "type": gl.UNSIGNED_BYTE,
        "size": 4,
        "offset": 4,
        "stride": 8,
        "normalized": false
      }
    ])
    triangleVAO.length = Math.floor(vert_data.length/8)

    vertexArrayObjects.surface = triangleVAO
  }

  // move the chunk into place
  var modelMatrix = mat4.create()
  var w = voxels.shape[2] - pad  // =[1]=[0]=game.chunkSize
  var translateVector = [
    position[0] * w,
    position[1] * w,
    position[2] * w]

  mat4.translate(modelMatrix, modelMatrix, translateVector)

  //Bundle result and return
  var result = {
    vertexArrayObjects: vertexArrayObjects, // other plugins can add their own VAOs
    center: [w>>1, w>>1, w>>1],
    radius: w,
    modelMatrix: modelMatrix
  }

  if (that) that.emit('meshed', result, gl, vert_data, voxels)

  return result
}
338035
def grid(metadata, layout, params):
  
  x = layout["x"]
  y = layout["y"]
  x_min = np.min(x)
  x_max = np.max(x)
  y_min = np.min(y)
  y_max = np.max(y)

  # this creates the grid
  bins = np.linspace(x_min, x_max, params["n_layer"] - 1)
  xd = np.digitize(x, bins)
  bins = np.linspace(y_min, y_max, params["n_layer"] - 1)
  yd = np.digitize(y, bins)

  # the number of tiles is the number of cells divided by the number of cells in each tile
  num_tiles = int(params["n_layer"]/params["n_tile"])
  print("num tiles", num_tiles)
  # we will save the tiles in an array indexed by the tile coordinates
  tiles = {}
  for ti in range(num_tiles):
    for tj in range(num_tiles):
      tiles[(ti,tj)] = {
        "x": [],
        "y": [],
        "ci": [], # cell-space x coordinate
        "cj": [], # cell-space y coordinate
        "gi": [], # global index
      }

  for i,xi in enumerate(x):
    if(i % 1000 == 0 or i+1 == len(x)):
      print("point", i+1, "/", len(x), end="\r")
    # layout-space coordinates
    yi = y[i]
    # grid-space cell coordinates
    ci = xd[i]
    cj = yd[i]
    # tile coordinate
    ti = math.floor(ci / params["n_tile"])
    tj = math.floor(cj / params["n_tile"])

    # TODO: don't append a point if it doesn't match a filter function provided in params
    filter = params.get("filter", lambda i,metadata: True)
    if(filter(i, metadata=metadata)):
      tiles[(ti,tj)]["x"].append(xi)
      tiles[(ti,tj)]["y"].append(yi)
      tiles[(ti,tj)]["ci"].append(ci)
      tiles[(ti,tj)]["cj"].append(cj)
      tiles[(ti,tj)]["gi"].append(i)
    
  return tiles
626307
static void createRegularGrid( List<List<NodeInfo>> gridByRows , Grid g) {
		g.reset();

		g.columns = gridByRows.get(0).size();
		g.rows = gridByRows.size();

		for (int row = 0; row < g.rows; row++) {
			List<NodeInfo> list = gridByRows.get(row);
			for (int i = 0; i < g.columns; i++) {
				g.ellipses.add(list.get(i).ellipse );
			}
		}
	}
425717
def make_grid_transformed(numPix, Mpix2Angle):
    
    x_grid, y_grid = make_grid(numPix, deltapix=1)
    ra_grid, dec_grid = map_coord2pix(x_grid, y_grid, 0, 0, Mpix2Angle)
    return ra_grid, dec_grid
879739
def iterGrid(self, minZoom, maxZoom):
        ""
        assert minZoom in range(0, len(self.RESOLUTIONS))
        assert maxZoom in range(0, len(self.RESOLUTIONS))
        assert minZoom <= maxZoom

        for zoom in xrange(minZoom, maxZoom + 1):
            [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
            for row in xrange(minRow, maxRow + 1):
                for col in xrange(minCol, maxCol + 1):
                    tileBounds = self.tileBounds(zoom, col, row)
                    yield (tileBounds, zoom, col, row)
269507
def run_mesh(self,
                 mesh=100.0,
                 shift=None,
                 is_time_reversal=True,
                 is_mesh_symmetry=True,
                 with_eigenvectors=False,
                 with_group_velocities=False,
                 is_gamma_center=False):
        

        self.init_mesh(mesh=mesh,
                       shift=shift,
                       is_time_reversal=is_time_reversal,
                       is_mesh_symmetry=is_mesh_symmetry,
                       with_eigenvectors=with_eigenvectors,
                       with_group_velocities=with_group_velocities,
                       is_gamma_center=is_gamma_center)
        self._mesh.run()
353351
public Grid grid(double[][][] data) {
        if (base.dimension != 2) {
            throw new IllegalArgumentException("Grid can be only painted in a 2D canvas. Try surface() for 3D grid.");
        }

        Grid grid = new Grid(data);
        add(grid);
        return grid;
    }