### IsoSurface ( numOfGridPts, size ) `numOfGridPts` - number of grid pooints *{ Number/Int = 16 }* `size` - grid bounding box size *{ Number = 1 }*
557693
function IsoSurface(numOfGridPts, size) {
  size = size || 1;
  this.numOfGridPts = numOfGridPts || 16;

  this.tresholdValue = 1;

  this.makeGrid(size);

  Geometry.call(this, { vertices: true, normals: true, texCoords: true, faces: true });
}
1044384
def points(self):
        
        # Get grid dimensions
        nx, ny, nz = self.dimensions
        nx -= 1
        ny -= 1
        nz -= 1
        # get the points and convert to spacings
        dx, dy, dz = self.spacing
        # Now make the cell arrays
        ox, oy, oz = self.origin
        x = np.insert(np.cumsum(np.full(nx, dx)), 0, 0.0) + ox
        y = np.insert(np.cumsum(np.full(ny, dy)), 0, 0.0) + oy
        z = np.insert(np.cumsum(np.full(nz, dz)), 0, 0.0) + oz
        xx, yy, zz = np.meshgrid(x,y,z, indexing='ij')
        return np.c_[xx.ravel(), yy.ravel(), zz.ravel()]
285453
def H_iso(x,params):
    
    #r = (np.sqrt(np.sum(x[:3]**2))-params[2])**2
    r = np.sum(x[:3]**2)
    return 0.5*np.sum(x[3:]**2)-Grav*params[0]/(params[1]+np.sqrt(params[1]**2+r))
439534
function() {
    var numStars = 2000;
    var geometry = new THREE.BufferGeometry();
    var positions = new Float32Array( numStars * 3 );
    var radius = this.STAGE_SIZE - 1;
    var v = new THREE.Vector3();
    for (var i = 0; i < positions.length; i += 3) {
      v.set(this.random(i + 23) - 0.5, this.random(i + 24), this.random(i + 25) - 0.5);
      v.normalize();
      v.multiplyScalar(radius);
      positions[i  ] = v.x;
      positions[i+1] = v.y;
      positions[i+2] = v.z;
    }
    geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
    geometry.setDrawRange(0, 0); // don't draw any yet
    var material = new THREE.PointsMaterial({size: 0.01, color: 0xCCCCCC, fog: false});
    this.stars.setObject3D('mesh', new THREE.Points(geometry, material));
  }
1140709
def createCellsDensity (self):
        ''' '''
        from .. import sim

        cells = []
        shape = sim.net.params.shape
        sizeX = sim.net.params.sizeX
        sizeY = sim.net.params.sizeY
        sizeZ = sim.net.params.sizeZ
        
        # calculate volume
        if shape == 'cuboid':
            volume = sizeY/1e3 * sizeX/1e3 * sizeZ/1e3  
        elif shape == 'cylinder':
            volume = sizeY/1e3 * sizeX/1e3/2 * sizeZ/1e3/2 * pi
        elif shape == 'ellipsoid':
            volume = sizeY/1e3/2.0 * sizeX/1e3/2.0 * sizeZ/1e3/2.0 * pi * 4.0 / 3.0

        for coord in ['x', 'y', 'z']:
            if coord+'Range' in self.tags:  # if user provided absolute range, convert to normalized
                self.tags[coord+'normRange'] = [point / getattr(sim.net.params, 'size'+coord.upper()) for point in self.tags[coord+'Range']]
            if coord+'normRange' in self.tags:  # if normalized range, rescale volume
                minv = self.tags[coord+'normRange'][0] 
                maxv = self.tags[coord+'normRange'][1] 
                volume = volume * (maxv-minv)

        funcLocs = None  # start with no locations as a function of density function
        if isinstance(self.tags['density'], basestring): # check if density is given as a function 
            if shape == 'cuboid':  # only available for cuboids
                strFunc = self.tags['density']  # string containing function
                strVars = [var for var in ['xnorm', 'ynorm', 'znorm'] if var in strFunc]  # get list of variables used 
                if not len(strVars) == 1:
                    print('Error: density function (%s) for population %s does not include "xnorm", "ynorm" or "znorm"'%(strFunc,self.tags['pop']))
                    return
                coordFunc = strVars[0] 
                lambdaStr = 'lambda ' + coordFunc +': ' + strFunc # convert to lambda function 
                densityFunc = eval(lambdaStr)
                minRange = self.tags[coordFunc+'Range'][0]
                maxRange = self.tags[coordFunc+'Range'][1]

                interval = 0.001  # interval of location values to evaluate func in order to find the max cell density
                maxDensity = max(list(map(densityFunc, (np.arange(minRange, maxRange, interval)))))  # max cell density 
                maxCells = volume * maxDensity  # max number of cells based on max value of density func 
                
                self.rand.Random123(int(maxDensity), sim.net.lastGid, sim.cfg.seeds['loc'])
                locsAll = minRange + ((maxRange-minRange)) * np.array([self.rand.uniform(0, 1) for i in range(int(maxCells))])  # random location values 
                locsProb = np.array(list(map(densityFunc, locsAll))) / maxDensity  # calculate normalized density for each location value (used to prune)
                allrands = np.array([self.rand.uniform(0, 1) for i in range(len(locsProb))])  # create an array of random numbers for checking each location pos 
                
                makethiscell = locsProb>allrands  # perform test to see whether or not this cell should be included (pruning based on density func)
                funcLocs = [locsAll[i] for i in range(len(locsAll)) if i in np.array(makethiscell.nonzero()[0],dtype='int')] # keep only subset of yfuncLocs based on density func
                self.tags['numCells'] = len(funcLocs)  # final number of cells after pruning of location values based on density func
                if sim.cfg.verbose: print('Volume=%.2f, maxDensity=%.2f, maxCells=%.0f, numCells=%.0f'%(volume, maxDensity, maxCells, self.tags['numCells']))
            else:
                print('Error: Density functions are only implemented for cuboid shaped networks')
                exit(0)
        else:  # NO ynorm-dep
            self.tags['numCells'] = int(self.tags['density'] * volume)  # = density (cells/mm^3) * volume (mm^3)

        # calculate locations of cells 
        self.rand.Random123(self.tags['numCells'], sim.net.lastGid, sim.cfg.seeds['loc'])
        self.rand.uniform(0, 1)
        vec = h.Vector(self.tags['numCells']*3)
        vec.setrand(self.rand)
        randLocs = np.array(vec).reshape(self.tags['numCells'], 3)  # create random x,y,z locations

        if sim.net.params.shape == 'cylinder':
            # Use the x,z random vales 
            rho = randLocs[:,0] # use x rand value as the radius rho in the interval [0, 1)
            phi = 2 * pi * randLocs[:,2] # use z rand value as the angle phi in the interval [0, 2*pi) 
            x = (1 + sqrt(rho) * cos(phi))/2.0
            z = (1 + sqrt(rho) * sin(phi))/2.0
            randLocs[:,0] = x
            randLocs[:,2] = z
    
        elif sim.net.params.shape == 'ellipsoid':
            # Use the x,y,z random vales 
            rho = np.power(randLocs[:,0], 1.0/3.0) # use x rand value as the radius rho in the interval [0, 1); cuberoot
            phi = 2 * pi * randLocs[:,1] # use y rand value as the angle phi in the interval [0, 2*pi) 
            costheta = (2 * randLocs[:,2]) - 1 # use z rand value as cos(theta) in the interval [-1, 1); ensures uniform dist 
            theta = arccos(costheta)  # obtain theta from cos(theta)
            x = (1 + rho * cos(phi) * sin(theta))/2.0
            y = (1 + rho * sin(phi) * sin(theta))/2.0
            z = (1 + rho * cos(theta))/2.0 
            randLocs[:,0] = x
            randLocs[:,1] = y
            randLocs[:,2] = z

        for icoord, coord in enumerate(['x', 'y', 'z']):
            if coord+'normRange' in self.tags:  # if normalized range, rescale random locations
                minv = self.tags[coord+'normRange'][0] 
                maxv = self.tags[coord+'normRange'][1] 
                randLocs[:,icoord] = randLocs[:,icoord] * (maxv-minv) + minv
            if funcLocs and coordFunc == coord+'norm':  # if locations for this coordinate calculated using density function
                randLocs[:,icoord] = funcLocs

        if sim.cfg.verbose and not funcLocs: print('Volume=%.4f, density=%.2f, numCells=%.0f'%(volume, self.tags['density'], self.tags['numCells']))

        for i in self._distributeCells(self.tags['numCells'])[sim.rank]:
            gid = sim.net.lastGid+i
            self.cellGids.append(gid)  # add gid list of cells belonging to this population - not needed?
            cellTags = {k: v for (k, v) in self.tags.items() if k in sim.net.params.popTagsCopiedToCells}  # copy all pop tags to cell tags, except those that are pop-specific
            cellTags['pop'] = self.tags['pop']
            cellTags['xnorm'] = randLocs[i,0]  # calculate x location (um)
            cellTags['ynorm'] = randLocs[i,1]  # calculate y location (um)
            cellTags['znorm'] = randLocs[i,2]  # calculate z location (um)
            cellTags['x'] = sizeX * randLocs[i,0]  # calculate x location (um)
            cellTags['y'] = sizeY * randLocs[i,1]  # calculate y location (um)
            cellTags['z'] = sizeZ * randLocs[i,2]  # calculate z location (um)
            cells.append(self.cellModelClass(gid, cellTags)) # instantiate Cell object
            if sim.cfg.verbose: 
                print(('Cell %d/%d (gid=%d) of pop %s, pos=(%2.f, %2.f, %2.f), on node %d, '%(i, self.tags['numCells']-1, gid, self.tags['pop'],cellTags['x'], cellTags['y'], cellTags['z'], sim.rank)))
        sim.net.lastGid = sim.net.lastGid + self.tags['numCells'] 
        return cells
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 );
			}
		}
	}
1372891
def correct(repeat_border_atoms = false)
      
      # Hash for storing bounding planes and the out-of-plane vector
      # by which each atom will be displaced to move it into the primitive volume
      # key = bounding plane
      # value = out-of-plane lattice vector used to displace atoms
      planes_vecs = {}

      # Define the primitive volume as six planes by 
      # finding the normal to each pair of lattice vectors
      # and making a plane with this normal that includes
      #   1. The point at the head of the third lattice vector 
      #      and pointing in the positive direction
      #
      #   2. The point at the tail of the third lattice vector
      #      and pointing in the negative direction  
      #
      (0..2).each do |i|
        out_vector = lattice_vectors[i] # The out of plane vector
        plane_vectors = lattice_vectors.reject{|v| v == out_vector} # The in plane vectors
        norm = cross(plane_vectors[0], plane_vectors[1])
        # if the norm has a component in the direction of the out of plane vector
        # then use the head of the out-of-plane vector as the intersection point
        # otherwise use the tail (the origin)
        if 0 < dot(norm, out_vector)
          # First plane is in direction of norm and intersects head
          # Displace vector is +1 if plane intersects tail and -1 if plane intersects head.
          planes_vecs[Plane.new(norm[0], norm[1], norm[2], out_vector[0], out_vector[1], out_vector[2])] = out_vector*(-1)
          # Second plane is opposite direction of norm and intersects tail
          planes_vecs[Plane.new(-norm[0], -norm[1], -norm[2], 0, 0, 0)] = out_vector*1
        else
          # First plane is in opposite direction of norm and intersects head
          planes_vecs[Plane.new(-norm[0], -norm[1], -norm[2], out_vector[0], out_vector[1], out_vector[2])] = out_vector*(-1)
          # Second plane is in direction of norm and intersects tail
          planes_vecs[Plane.new(norm[0], norm[1], norm[2], 0, 0, 0)] = out_vector*1
        end
      end

      # Make a coyp of the unit cell
      new_unit_cell = self.copy

      # atoms on the border will be repeated with
      # periodicity of lattice vectors for better rendering
      border_atoms = {}
      
      # Move each atom behind all the planes
      new_unit_cell.atoms(false).each_with_index do |atom, i|
        planes_vecs.each_pair do |p, v|
          if p.distance_to_point(0,0,0) == 0
            # If the plane intersects the origin then 
            # move atoms not on the plane (inequality)
            while p.distance_to_point(atom.x, atom.y, atom.z) > 1e-4
              atom.displace!(v[0], v[1], v[2])
            end
          else
            # Move atoms that lie on the plane if the plane doesn't intersect the origin
            while p.distance_to_point(atom.x, atom.y, atom.z) >= -1e-4
              atom.displace!(v[0], v[1], v[2])
            end
          end
          
          # This part repeats atoms on the unit cell boundaries
          # useful for drawing pictures, but these atoms are really repeats
          # Add each border that intersects the atom to a list
          if p.distance_to_point(atom.x, atom.y, atom.z) == 0
            if border_atoms[atom]
              border_atoms[atom] << v
            else
              border_atoms[atom] = [v]
            end
          end
        end
      end

      

      # Add more border atoms for each combination of lattice planes
      if repeat_border_atoms
        border_atoms.each_pair{|atom, planes|
          planes.size.times{|i|
            combos = Volume.choose(planes, i+1)
            combos.each{|combo|
              x = combo.inject(0){|sum, v| sum = sum + v[0]}
              y = combo.inject(0){|sum, v| sum = sum + v[1]}
              z = combo.inject(0){|sum, v| sum = sum + v[2]}
              puts [x,y,z]
              new_unit_cell.atoms(:allAtoms) << atom.displace(x, y, z)
            }
          }
        }
      end
      new_unit_cell.atoms.uniq!
      # new_unit_cell.make_bonds
      return new_unit_cell

    end
855910
function(hexDimensions, radius) {
  var positionArray = [];
  var pixelCoordinates;

  //For every hex, place an instance of the original mesh. The symbol fills in 3 of the 6 lines, the other 3 being shared with an adjacent hex

  //Make a hexagonal grid of hexagons since it is approximately circular.
  var u = 0;
  var v = 0;
  //For each radius
  positionArray.push({ y: 0, x: 0 });
  for (var i = 1; i < radius + 1; i++) {
    //Hold u constant as the radius, add an instance for each v
    for (v = -i; v <= 0; v++) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(i, v);

      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }

    //Hold u constant as negative the radius, add an instance for each v
    for (v = 0; v <= i; v++) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(-i, v);
      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }

    //Hold v constant as the radius, add an instance for each u
    for (u = -i + 1; u <= 0; u++) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(u, i);
      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }

    //Hold v constant as negative the radius, add an instance for each u
    for (u = 0; u < i; u++) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(u, -i);
      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }

    //Hold w constant as the radius, add an instance for each u + v = -i
    for (u = -i + 1, v = -1; v > -i; u++, v--) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(u, v);
      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }

    //Hold w constant as the negative radius, add an instance for each u + v = i
    for (u = i - 1, v = 1; v < i; u--, v++) {
      pixelCoordinates = hexDimensions.getPixelCoordinates(u, v);
      positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x });
    }
  }

  return positionArray;
}
1076474
function() {
        //wait for the map to be initialized before proceeding
        var mapBounds = this.map.getExtent();
        if (!mapBounds) {
            return;
        }
        
        //clear out the old grid
        this.gratLayer.destroyFeatures();
        
        //get the projection objects required
        var llProj = new OpenLayers.Projection("EPSG:4326");
        var mapProj = this.map.getProjectionObject();
        var mapRes = this.map.getResolution();
        
        //if the map is in lon/lat, then the lines are straight and only one
        //point is required
        if (mapProj.proj && mapProj.proj.projName == "longlat") {
            this.numPoints = 1;
        }
        
        //get the map center in EPSG:4326
        var mapCenter = this.map.getCenter(); //lon and lat here are really map x and y
        var mapCenterLL = new OpenLayers.Pixel(mapCenter.lon, mapCenter.lat);
        OpenLayers.Projection.transform(mapCenterLL, mapProj, llProj);
        
        /* This block of code determines the lon/lat interval to use for the
         * grid by calculating the diagonal size of one grid cell at the map
         * center.  Iterates through the intervals array until the diagonal
         * length is less than the targetSize option.
         */
        //find lat/lon interval that results in a grid of less than the target size
        var testSq = this.targetSize*mapRes;
        testSq *= testSq;   //compare squares rather than doing a square root to save time
        var llInterval;
        for (var i=0; i<this.intervals.length; ++i) {
            llInterval = this.intervals[i];   //could do this for both x and y??
            var delta = llInterval/2;  
            var p1 = mapCenterLL.offset({x: -delta, y: -delta});  //test coords in EPSG:4326 space
            var p2 = mapCenterLL.offset({x: delta, y: delta});
            OpenLayers.Projection.transform(p1, llProj, mapProj); // convert them back to map projection
            OpenLayers.Projection.transform(p2, llProj, mapProj);
            var distSq = (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y);
            if (distSq <= testSq) {
                break;
            }
        }
        //alert(llInterval);
        
        //round the LL center to an even number based on the interval
        mapCenterLL.x = Math.floor(mapCenterLL.x/llInterval)*llInterval;
        mapCenterLL.y = Math.floor(mapCenterLL.y/llInterval)*llInterval;
        //TODO adjust for minutses/seconds?
        
        /* The following 2 blocks calculate the nodes of the grid along a 
         * line of constant longitude (then latitiude) running through the
         * center of the map until it reaches the map edge.  The calculation
         * goes from the center in both directions to the edge.
         */
        //get the central longitude line, increment the latitude
        var iter = 0;
        var centerLonPoints = [mapCenterLL.clone()];
        var newPoint = mapCenterLL.clone();
        var mapXY;
        do {
            newPoint = newPoint.offset({x: 0, y: llInterval});
            mapXY = OpenLayers.Projection.transform(newPoint.clone(), llProj, mapProj);
            centerLonPoints.unshift(newPoint);
        } while (mapBounds.containsPixel(mapXY) && ++iter<1000);
        newPoint = mapCenterLL.clone();
        do {          
            newPoint = newPoint.offset({x: 0, y: -llInterval});
            mapXY = OpenLayers.Projection.transform(newPoint.clone(), llProj, mapProj);
            centerLonPoints.push(newPoint);
        } while (mapBounds.containsPixel(mapXY) && ++iter<1000);
        
        //get the central latitude line, increment the longitude
        iter = 0;
        var centerLatPoints = [mapCenterLL.clone()];
        newPoint = mapCenterLL.clone();
        do {
            newPoint = newPoint.offset({x: -llInterval, y: 0});
            mapXY = OpenLayers.Projection.transform(newPoint.clone(), llProj, mapProj);
            centerLatPoints.unshift(newPoint);
        } while (mapBounds.containsPixel(mapXY) && ++iter<1000);
        newPoint = mapCenterLL.clone();
        do {          
            newPoint = newPoint.offset({x: llInterval, y: 0});
            mapXY = OpenLayers.Projection.transform(newPoint.clone(), llProj, mapProj);
            centerLatPoints.push(newPoint);
        } while (mapBounds.containsPixel(mapXY) && ++iter<1000);
        
        //now generate a line for each node in the central lat and lon lines
        //first loop over constant longitude
        var lines = [];
        for(var i=0; i < centerLatPoints.length; ++i) {
            var lon = centerLatPoints[i].x;
            var pointList = [];
            var labelPoint = null;
            var latEnd = Math.min(centerLonPoints[0].y, 90);
            var latStart = Math.max(centerLonPoints[centerLonPoints.length - 1].y, -90);
            var latDelta = (latEnd - latStart)/this.numPoints;
            var lat = latStart;
            for(var j=0; j<= this.numPoints; ++j) {
                var gridPoint = new OpenLayers.Geometry.Point(lon,lat);
                gridPoint.transform(llProj, mapProj);
                pointList.push(gridPoint);
                lat += latDelta;
                if (gridPoint.y >= mapBounds.bottom && !labelPoint) {
                    labelPoint = gridPoint;
                }
            }
            if (this.labelled) {
                //keep track of when this grid line crosses the map bounds to set
                //the label position
                //labels along the bottom, add 10 pixel offset up into the map
                //TODO add option for labels on top
                var labelPos = new OpenLayers.Geometry.Point(labelPoint.x,mapBounds.bottom);
                var labelAttrs = {
                    value: lon,
                    label: this.labelled?OpenLayers.Util.getFormattedLonLat(lon, "lon", this.labelFormat):"",
                    labelAlign: "cb",
                    xOffset: 0,
                    yOffset: 2
                }; 
                this.gratLayer.addFeatures(new OpenLayers.Feature.Vector(labelPos,labelAttrs));
            }
            var geom = new OpenLayers.Geometry.LineString(pointList);
            lines.push(new OpenLayers.Feature.Vector(geom));
        }
        
        //now draw the lines of constant latitude
        for (var j=0; j < centerLonPoints.length; ++j) {
            lat = centerLonPoints[j].y;
            if (lat<-90 || lat>90) {  //latitudes only valid between -90 and 90
                continue;
            }
            var pointList = [];
            var lonStart = centerLatPoints[0].x;
            var lonEnd = centerLatPoints[centerLatPoints.length - 1].x;
            var lonDelta = (lonEnd - lonStart)/this.numPoints;
            var lon = lonStart;
            var labelPoint = null;
            for(var i=0; i <= this.numPoints ; ++i) {
                var gridPoint = new OpenLayers.Geometry.Point(lon,lat);
                gridPoint.transform(llProj, mapProj);
                pointList.push(gridPoint);
                lon += lonDelta;
                if (gridPoint.x < mapBounds.right) {
                    labelPoint = gridPoint;
                }
            }
            if (this.labelled) {
                //keep track of when this grid line crosses the map bounds to set
                //the label position
                //labels along the right, 30 pixel offset left into the map
                //TODO add option for labels on left
                var labelPos = new OpenLayers.Geometry.Point(mapBounds.right, labelPoint.y); 
                var labelAttrs = {
                    value: lat,
                    label: this.labelled?OpenLayers.Util.getFormattedLonLat(lat, "lat", this.labelFormat):"",
                    labelAlign: "rb",
                    xOffset: -2,
                    yOffset: 2
                }; 
                this.gratLayer.addFeatures(new OpenLayers.Feature.Vector(labelPos,labelAttrs));
            }
            var geom = new OpenLayers.Geometry.LineString(pointList);
            lines.push(new OpenLayers.Feature.Vector(geom));
          }
          this.gratLayer.addFeatures(lines);
    }
999664
function mesh1D(array, level) {
  var zc = zeroCrossings(array, level)
  var n = zc.length
  var npos = new Array(n)
  var ncel = new Array(n)
  for(var i=0; i<n; ++i) {
    npos[i] = [ zc[i] ]
    ncel[i] = [ i ]
  }
  return {
    positions: npos,
    cells: ncel
  }
}
563546
function Sphere(r, nsides, nsegments) {
  r = r || 0.5;
  nsides = nsides || 36;
  nsegments = nsegments || 18;

  Geometry.call(this, { vertices: true, normals: true, texCoords: true, faces: true });

  var vertices = this.vertices;
  var texCoords = this.texCoords;
  var normals = this.normals;
  var faces = this.faces;

  var degToRad = 1/180.0 * Math.PI;

  var dphi   = 360.0/nsides;
  var dtheta = 180.0/nsegments;

  function evalPos(theta, phi) {
    var pos = new Vec3();
    pos.x = r * Math.sin(theta * degToRad) * Math.sin(phi * degToRad);
    pos.y = r * Math.cos(theta * degToRad);
    pos.z = r * Math.sin(theta * degToRad) * Math.cos(phi * degToRad);
    return pos;
  }

  for (var segment=0; segment<=nsegments; ++segment) {
    var theta = segment * dtheta;
    for (var side=0; side<=nsides; ++side) {
      var phi = side * dphi;
      var pos = evalPos(theta, phi);
      var normal = pos.dup().normalize();
      var texCoord = new Vec2(phi/360.0, theta/180.0);

      vertices.push(pos);
      normals.push(normal);
      texCoords.push(texCoord);

      if (segment == nsegments) continue;
      if (side == nsides) continue;

      if (segment == 0) {
        faces.push([
          (segment  )*(nsides+1) + side,
          (segment+1)*(nsides+1) + side,
          (segment+1)*(nsides+1) + side + 1
        ]);
      }
      else if (segment == nsegments - 1) {
        faces.push([
          (segment  )*(nsides+1) + side,
          (segment+1)*(nsides+1) + side + 1,
          (segment  )*(nsides+1) + side + 1
        ]);
      }
      else {
        faces.push([
          (segment  )*(nsides+1) + side,
          (segment+1)*(nsides+1) + side,
          (segment+1)*(nsides+1) + side + 1,
          (segment  )*(nsides+1) + side + 1
        ]);
      }
    }
  }

  this.computeEdges();
}
127565
function (ctx, size, texMeters) {

    if (this.data.grid == 'none') return;

    // one grid feature each 2 meters

    var num = Math.floor(texMeters / 2);
    var step = size / (texMeters / 2); // 2 meters == <step> pixels
    var i, j, ii;

    ctx.fillStyle = this.data.gridColor;

    switch (this.data.grid) {
      case '1x1':
      case '2x2': {
        if (this.data.grid == '1x1') {
          num = num * 2;
          step = size / texMeters;
        }
        for (i = 0; i < num; i++) {
          ii = Math.floor(i * step);
          ctx.fillRect(0, ii, size, 1);
          ctx.fillRect(ii, 0, 1, size);
        }
        break;
      }
      case 'crosses': {
        var l = Math.floor(step / 20);
        for (i = 0; i < num + 1; i++) {
          ii = Math.floor(i * step);
          for (j = 0; j < num + 1; j++) {
            var jj = Math.floor(-l + j * step);
            ctx.fillRect(jj, ii, l * 2, 1);
            ctx.fillRect(ii, jj, 1, l * 2);
          }
        }
        break;
      }
      case 'dots': {
        for (i = 0; i < num + 1; i++) {
          for (j = 0; j < num + 1; j++) {
            ctx.beginPath(); ctx.arc(Math.floor(j * step), Math.floor(i * step), 4, 0, Math.PI * 2); ctx.fill();
          }
        }
        break;
      }
      case 'xlines': {
        for (i = 0; i < num; i++) {
          ctx.fillRect(Math.floor(i * step), 0, 1, size);
        }
        break;
      }
      case 'ylines': {
        for (i = 0; i < num; i++) {
          ctx.fillRect(0, Math.floor(i * step), size, 1);
        }
        break;
      }
    }
  }
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;
	}
641204
def multigrid(bounds, points_count):
    
    if len(bounds)==1:
        return np.linspace(bounds[0][0], bounds[0][1], points_count).reshape(points_count, 1)
    x_grid_rows = np.meshgrid(*[np.linspace(b[0], b[1], points_count) for b in bounds])
    x_grid_columns = np.vstack([x.flatten(order='F') for x in x_grid_rows]).T
    return x_grid_columns
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
  }
}
158061
def grid_complexity(self):
        
        return sum([level.A.shape[0] for level in self.levels]) /\
            float(self.levels[0].A.shape[0])
236944
private boolean checkEdgeCount( SquareGrid grid ) {

		int left = 0, right = grid.columns-1;
		int top = 0, bottom = grid.rows-1;

		for (int row = 0; row < grid.rows; row++) {
			boolean skip = grid.get(row,0) == null;

			for (int col = 0; col < grid.columns; col++) {
				SquareNode n = grid.get(row,col);
				if( skip ) {
					if ( n != null )
						return false;
				} else {
					boolean horizontalEdge =  col == left || col == right;
					boolean verticalEdge =  row == top || row == bottom;

					boolean outer = horizontalEdge || verticalEdge;
					int connections = n.getNumberOfConnections();

					if( outer ) {
						if( horizontalEdge && verticalEdge ) {
							if( connections != 1 )
								return false;
						} else if( connections != 2 )
							return false;
					} else {
						if( connections != 4 )
							return false;
					}
				}
				skip = !skip;
			}
		}
		return true;
	}