Takes atoms object (with a defined cell) and a radial cutoff.
    Returns a supercell centered around the original cell
    generously extended to contain all spheres with the given radial
    cutoff centered around the original atoms.
769838
def _get_supercell(obj, rCut=5.0):
    rCutHard = rCut + 5  # Giving extra space for hard cutOff
    

    cell_vectors = obj.get_cell()
    a1, a2, a3 = cell_vectors[0], cell_vectors[1], cell_vectors[2]

    # vectors perpendicular to two cell vectors
    b1 = np.cross(a2, a3, axis=0)
    b2 = np.cross(a3, a1, axis=0)
    b3 = np.cross(a1, a2, axis=0)
    # projections onto perpendicular vectors
    p1 = np.dot(a1, b1) / np.dot(b1, b1) * b1
    p2 = np.dot(a2, b2) / np.dot(b2, b2) * b2
    p3 = np.dot(a3, b3) / np.dot(b3, b3) * b3
    xyz_arr = np.linalg.norm(np.array([p1, p2, p3]), axis=1)
    cell_images = np.ceil(rCutHard/xyz_arr)
    nx = int(cell_images[0])
    ny = int(cell_images[1])
    nz = int(cell_images[2])
    suce = obj * (1+2*nx, 1+2*ny, 1+2*nz)
    shift = obj.get_cell()

    shifted_suce = suce.copy()
    shifted_suce.translate(-shift[0]*nx - shift[1]*ny - shift[2]*nz)

    return shifted_suce
1008568
public static final Atom getCentroid(Atom[] atomSet){

		// if we don't catch this case, the centroid returned is (NaN,NaN,NaN), which can cause lots of problems down the line
		if (atomSet.length==0)
			throw new IllegalArgumentException("Atom array has length 0, can't calculate centroid!");


		double[] coords = new double[3];

		coords[0] = 0;
		coords[1] = 0;
		coords[2] = 0 ;

		for (Atom a : atomSet) {
			coords[0] += a.getX();
			coords[1] += a.getY();
			coords[2] += a.getZ();
		}

		int n = atomSet.length;
		coords[0] = coords[0] / n;
		coords[1] = coords[1] / n;
		coords[2] = coords[2] / n;

		Atom vec = new AtomImpl();
		vec.setCoords(coords);
		return vec;

	}
294812
def get_enclosing_orthorhombic_box(cell):
    
    
    # Cell vectors
    cx, cy, cz = cell
    
    # The cell has eight corners, one is at the origin, three at cx, cy, cz
    # and the last ones are...
    c1 = cx+cy
    c2 = cx+cz
    c3 = cy+cz
    c4 = cx+cy+cz
    
    corners = np.array([[0,0,0],cx,cy,cz,c1,c2,c3,c4])
    lower = np.min(corners, axis=0)
    upper = np.max(corners, axis=0)
    
    return lower, upper
808187
function ParticleSystem() {
  var prefabGeometry = new THREE.TetrahedronGeometry(0.5);
  var prefabCount = 2000;
  var geometry = new BAS.PrefabBufferGeometry(prefabGeometry, prefabCount);

  var i, j, offset;

  // animation
  var aAnimation = geometry.createAttribute('aAnimation', 3);

  var minDuration = 1.0;
  var maxDuration = 1.0;
  var maxDelay = 0;

  this.totalDuration = maxDuration + maxDelay;

  for (i = 0, offset = 0; i < prefabCount; i++) {
    var delay = 0;
    var duration = THREE.Math.randFloat(minDuration, maxDuration);

    for (j = 0; j < prefabGeometry.vertices.length; j++) {
      aAnimation.array[offset] = delay;
      aAnimation.array[offset + 1] = duration;

      offset += 3;
    }
  }

  // position
  var aPosition = geometry.createAttribute('aPosition', 3);
  var position = new THREE.Vector3();

  for (i = 0, offset = 0; i < prefabCount; i++) {
    position.x = THREE.Math.randFloatSpread(40);
    position.y = THREE.Math.randFloatSpread(40);
    position.z = THREE.Math.randFloatSpread(40);

    for (j = 0; j < prefabGeometry.vertices.length; j++) {
      aPosition.array[offset] = position.x;
      aPosition.array[offset + 1] = position.y;
      aPosition.array[offset + 2] = position.z;

      offset += 3;
    }
  }

  // axis angle
  var aAxisAngle = geometry.createAttribute('aAxisAngle', 4);
  var axis = new THREE.Vector3();
  var angle;

  for (i = 0, offset = 0; i < prefabCount; i++) {
    axis.x = THREE.Math.randFloatSpread(2);
    axis.y = THREE.Math.randFloatSpread(2);
    axis.z = THREE.Math.randFloatSpread(2);
    axis.normalize();
    angle = Math.PI * 2;

    for (j = 0; j < prefabGeometry.vertices.length; j++) {
      aAxisAngle.array[offset] = axis.x;
      aAxisAngle.array[offset + 1] = axis.y;
      aAxisAngle.array[offset + 2] = axis.z;
      aAxisAngle.array[offset + 3] = angle;

      offset += 4;
    }
  }

  var material = new BAS.PhongAnimationMaterial(
    {
      flatShading: true,
      transparent: true,
      uniforms: {
        uTime: {value: 0}
      },
      uniformValues: {
      },
      vertexFunctions: [
        BAS.ShaderChunk['quaternion_rotation']
      ],
      vertexParameters: [
        'uniform float uTime;',
        'attribute vec2 aAnimation;',
        'attribute vec3 aPosition;',
        'attribute vec4 aAxisAngle;'
      ],
      vertexInit: [
        'float tProgress = clamp(uTime - aAnimation.x, 0.0, aAnimation.y) / aAnimation.y;'
      ],
      vertexPosition: [
        'vec4 tQuat = quatFromAxisAngle(aAxisAngle.xyz, aAxisAngle.w * tProgress);',
        'transformed = rotateVector(tQuat, transformed);',

        'transformed += aPosition;'
      ],
    }
  );

  THREE.Mesh.call(this, geometry, material);

  this.frustumCulled = false;
  this.castShadow = true;
  this.receiveShadow = true;

  // depth material is used for directional & spot light shadows
  this.customDepthMaterial = BAS.Utils.createDepthAnimationMaterial(material);
  // distance material is used for point light shadows
  this.customDistanceMaterial = BAS.Utils.createDistanceAnimationMaterial(material);
}
967671
private Polygon getCellPolygon() {
        final Coordinate[] summits = new Coordinate[5];
        double x1 = minX + cellI * deltaX;
        double y1 = minY + cellJ * deltaY;
        double x2 = minX + (cellI + 1) * deltaX;
        double y2 = minY + (cellJ + 1) * deltaY;
        summits[0] = new Coordinate(x1, y1);
        summits[1] = new Coordinate(x2, y1);
        summits[2] = new Coordinate(x2, y2);
        summits[3] = new Coordinate(x1, y2);
        summits[4] = new Coordinate(x1, y1);
        final LinearRing g = GF.createLinearRing(summits);
        final Polygon gg = GF.createPolygon(g, null);
        cellI++;
        return gg;
    }
305132
def copy(self):
        
        return GrainBoundary(self.lattice, self.species_and_occu, self.frac_coords,
                             self.rotation_axis, self.rotation_angle, self.gb_plane,
                             self.join_plane, self.init_cell, self.vacuum_thickness,
                             self.ab_shift, self.site_properties, self.oriented_unit_cell)
222823
function(center, radius) {
      var vertArrays = this.vertArrays();
      for (var i = 0; i < vertArrays.length; ++i) {
        radius = vertArrays[i].updateSquaredSphereRadius(center, radius);
      }
      return radius;
  }
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();
}
814551
function sphereVoxels(cx, cy, cz, r, col){
    return function(cons, nil){
      sphere(cx, cy, cz, r)(function(x, y, z, res){
        return cons(x, y, z, col, res);
      }, nil);
    };
  }
1026970
private static Shape createAtomHighlight(IAtom atom, double radius) {
        double x = atom.getPoint2d().x;
        double y = atom.getPoint2d().y;

        return new RoundRectangle2D.Double(x - radius, y - radius, 2 * radius, 2 * radius, 2 * radius, 2 * radius);
    }
391361
def extract(self, point_x, point_y, radius=0):
        '''
        
        '''
        row, col = map_pixel(point_x, point_y, self.x_cell_size, self.y_cell_size,
                             self.xmin, self.ymax)
        col2 = np.abs(radius/self.x_cell_size).astype(int)
        row2 = np.abs(radius/self.y_cell_size).astype(int)
        return GeoRaster(self.raster[max(row-row2, 0):min(row+row2+1, self.shape[0]), \
                        max(col-col2, 0):min(col+col2+1, self.shape[1])], self.geot,
                        nodata_value=self.nodata_value,\
                        projection=self.projection, datatype=self.datatype)
705537
def _parse_geometry(self, geom):
        
        atoms = []
        for i, line in enumerate(geom.splitlines()):
           sym, atno, x, y, z = line.split()
           atoms.append(Atom(sym, [float(x), float(y), float(z)], id=i))
        
        return Molecule(atoms)
716530
def ball_and_sticks(self, ball_radius=0.05, stick_radius=0.02, colorlist=None, opacity=1.0):
        

        # Add the spheres

        if colorlist is None:
            colorlist = [get_atom_color(t) for t in self.topology['atom_types']]
        sizes = [ball_radius] * len(self.topology['atom_types'])

        spheres = self.add_representation('spheres', {'coordinates': self.coordinates.astype('float32'),
                                                      'colors': colorlist,
                                                      'radii': sizes,
                                                      'opacity': opacity})

        def update(self=self, spheres=spheres):
            self.update_representation(spheres, {'coordinates': self.coordinates.astype('float32')})

        self.update_callbacks.append(update)

        # Add the cylinders

        if 'bonds' in self.topology and self.topology['bonds'] is not None:
            start_idx, end_idx = zip(*self.topology['bonds'])
            # Added this so bonds don't go through atoms when opacity<1.0
            new_start_coords = []
            new_end_coords = []
            for bond_ind, bond in enumerate(self.topology['bonds']):
                trim_amt = (ball_radius**2 - stick_radius**2)**0.5 if ball_radius>stick_radius else 0
                start_coord = self.coordinates[bond[0]]
                end_coord = self.coordinates[bond[1]]
                vec = (end_coord-start_coord)/np.linalg.norm(end_coord-start_coord)
                new_start_coords.append(start_coord+vec*trim_amt)
                new_end_coords.append(end_coord-vec*trim_amt)

            cylinders = self.add_representation('cylinders', {'startCoords': np.array(new_start_coords,dtype='float32'),
                                                  'endCoords': np.array(new_end_coords,dtype='float32'),
                                                  'colors': [0xcccccc] * len(new_start_coords),
                                                  'radii': [stick_radius] * len(new_start_coords),
                                                  'opacity': opacity})
            # Update closure
            def update(self=self, rep=cylinders, start_idx=start_idx, end_idx=end_idx):
                self.update_representation(rep, {'startCoords': self.coordinates[list(start_idx)],
                                                 'endCoords': self.coordinates[list(end_idx)]})

            self.update_callbacks.append(update)
        self.autozoom(self.coordinates)
1162293
function Sphere3D( x , y , z , r ) {
	this.center = new Vector3D( x , y , z ) ;
	this.r = + r ;
}
320704
def _setup_grid(self, cutoff, unit_cell, grid):
        """"""
        if grid is None:
            # automatically choose a decent grid
            if unit_cell is None:
                grid = cutoff/2.9
            else:
                # The following would be faster, but it is not reliable
                # enough yet.
                #grid = unit_cell.get_optimal_subcell(cutoff/2.0)
                divisions = np.ceil(unit_cell.spacings/cutoff)
                divisions[divisions<1] = 1
                grid = unit_cell/divisions

        if isinstance(grid, float):
            grid_cell = UnitCell(np.array([
                [grid, 0, 0],
                [0, grid, 0],
                [0, 0, grid]
            ]))
        elif isinstance(grid, UnitCell):
            grid_cell = grid
        else:
            raise TypeError("Grid must be None, a float or a UnitCell instance.")

        if unit_cell is not None:
            # The columns of integer_matrix are the unit cell vectors in
            # fractional coordinates of the grid cell.
            integer_matrix = grid_cell.to_fractional(unit_cell.matrix.transpose()).transpose()
            if abs((integer_matrix - np.round(integer_matrix))*self.unit_cell.active).max() > 1e-6:
                raise ValueError("The unit cell vectors are not an integer linear combination of grid cell vectors.")
            integer_matrix = integer_matrix.round()
            integer_cell = UnitCell(integer_matrix, unit_cell.active)
        else:
            integer_cell = None

        return grid_cell, integer_cell
578709
public static  Atom centerOfMass(Atom[] points) {
		Atom center = new AtomImpl();

		float totalMass = 0.0f;
		for (Atom a : points) {
			float mass = a.getElement().getAtomicMass();
			totalMass += mass;
			center = scaleAdd(mass, a, center);
		}

		center = scaleEquals(center, 1.0f/totalMass);
		return center;
	}
185083
function (splane, coplanarfrontnodes, coplanarbacknodes, frontnodes, backnodes) {
    let polygon = this.polygon
    if (polygon) {
      let bound = poly3.measureBoundingSphere(polygon)
      let sphereradius = bound[1] + EPS // FIXME Why add imprecision?
      let spherecenter = bound[0]
      let d = vec3.dot(splane, spherecenter) - splane[3]
      if (d > sphereradius) {
        frontnodes.push(this)
      } else if (d < -sphereradius) {
        backnodes.push(this)
      } else {
        let splitresult = splitPolygonByPlane(splane, polygon)
        switch (splitresult.type) {
          case 0:
            // coplanar front:
            coplanarfrontnodes.push(this)
            break

          case 1:
            // coplanar back:
            coplanarbacknodes.push(this)
            break

          case 2:
            // front:
            frontnodes.push(this)
            break

          case 3:
            // back:
            backnodes.push(this)
            break

          case 4:
            // spanning:
            if (splitresult.front) {
              let frontnode = this.addChild(splitresult.front)
              frontnodes.push(frontnode)
            }
            if (splitresult.back) {
              let backnode = this.addChild(splitresult.back)
              backnodes.push(backnode)
            }
            break
        }
      }
    }
  }