Convert cartesian to spherical coordinates passed as (N,3) shaped arrays.
433995
def cartesian_to_spherical(cartesian):
    """"""
    xyz = cartesian
    xy = xyz[:,0]**2 + xyz[:,1]**2
    r = np.sqrt(xy + xyz[:,2]**2)
    phi = np.arctan2(np.sqrt(xy), xyz[:,2]) # for elevation angle defined from Z-axis down
    #ptsnew[:,4] = np.arctan2(xyz[:,2], np.sqrt(xy)) # for elevation angle defined from XY-plane up
    theta = np.arctan2(xyz[:,1], xyz[:,0])
    return np.array([r, theta, phi]).T
135006
def convert_coordinates(coords, origin, wgs84, wrapped):
    
    if isinstance(coords, list) or isinstance(coords, tuple):
        try:
            if isinstance(coords[0], list) or isinstance(coords[0], tuple):
                return [convert_coordinates(list(c), origin, wgs84, wrapped) for c in coords]
            elif isinstance(coords[0], float):
                c = list(transform(origin, wgs84, *coords))
                if wrapped and c[0] < -170:
                    c[0] = c[0] + 360
                return c

        except IndexError:
            pass

    return None
205439
def zmat_to_cart(zmat):
    """"""

    numbers = zmat["number"]
    N = len(numbers)
    coordinates = np.zeros((N, 3), float)

    # special cases for the first coordinates
    coordinates[1, 2] = zmat["distance"][1]
    if zmat["rel1"][2] == 1:
        sign = -1
    else:
        sign = 1
    coordinates[2, 2] = zmat["distance"][2]*sign*np.cos(zmat["angle"][2])
    coordinates[2, 1] = zmat["distance"][2]*sign*np.sin(zmat["angle"][2])
    coordinates[2] += coordinates[2-zmat["rel1"][2]]

    ref0 = 3
    for (number, distance, rel1, angle, rel2, dihed, rel3) in zmat[3:]:
        ref1 = ref0 - rel1
        ref2 = ref0 - rel2
        ref3 = ref0 - rel3
        if ref1 < 0: ref1 = 0
        if ref2 < 0: ref2 = 0
        if ref3 < 0: ref3 = 0
        # define frame axes
        origin = coordinates[ref1]
        new_z = coordinates[ref2] - origin
        norm_z = np.linalg.norm(new_z)
        if norm_z < 1e-15:
            new_z = np.array([0, 0, 1], float)
        else:
            new_z /= np.linalg.norm(new_z)
        new_x = coordinates[ref3] - origin
        new_x -= np.dot(new_x, new_z)*new_z
        norm_x = np.linalg.norm(new_x)
        if norm_x < 1e-15:
            new_x = random_orthonormal(new_z)
        else:
            new_x /= np.linalg.norm(new_x)
        # we must make our axes frame left handed due to the poor IUPAC
        # definition of the sign of a dihedral angle.
        new_y = -np.cross(new_z, new_x)

        # coordinates of new atom:
        x = distance*np.cos(dihed)*np.sin(angle)
        y = distance*np.sin(dihed)*np.sin(angle)
        z = distance*np.cos(angle)
        coordinates[ref0] = origin + x*new_x + y*new_y + z*new_z
        # loop
        ref0 += 1

    return numbers, coordinates
717998
def spherical_to_cartesian(r,theta,phi):
    
    x = r * np.sin(phi) * np.cos(theta)
    y = r * np.sin(phi) * np.sin(theta)
    z = r * np.cos(phi)
    return (x,y,z)
161453
def get_transformation(self, coordinates):
        """"""
        atom1, atom2, atom3, atom4 = self.hinge_atoms
        a = coordinates[atom1] - coordinates[atom2]
        a /= np.linalg.norm(a)
        b = coordinates[atom3] - coordinates[atom4]
        b /= np.linalg.norm(b)
        direction = 0.5*(a+b)
        direction *= np.random.uniform(-self.max_amplitude, self.max_amplitude)
        result = Translation(direction)
        return result
1338138
function convertShapesToCoords(shapes) {
  var tile_width = 40;

  var new_shapes = map2d(shapes, function(loc) {
    // It would be loc.r + 1 and loc.c + 1 but that has been removed
    // to account for the one-tile width of padding added in doParse.
    var row = loc.r * tile_width;
    var col = loc.c * tile_width;
    return {x: row, y: col}
  });
  return new_shapes;
}
1291862
def vec2pix(nside, x, y, z, nest=False):
    """"""
    theta, phi = vec2ang(np.transpose([x, y, z]))
    # hp.vec2ang() returns raveled arrays, which are 1D.
    if np.isscalar(x):
        theta = theta.item()
        phi = phi.item()
    else:
        shape = np.shape(x)
        theta = theta.reshape(shape)
        phi = phi.reshape(shape)
    lon, lat = _healpy_to_lonlat(theta, phi)
    return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring')
179152
def _spherical_to_cartesian(cls, coord, center):
        
        r, theta, phi, r_dot, theta_dot, phi_dot = coord
        x = r * cos(phi) * cos(theta)
        y = r * cos(phi) * sin(theta)
        z = r * sin(phi)

        vx = r_dot * x / r - y * theta_dot - z * phi_dot * cos(theta)
        vy = r_dot * y / r + x * theta_dot - z * phi_dot * sin(theta)
        vz = r_dot * z / r + r * phi_dot * cos(phi)

        return np.array([x, y, z, vx, vy, vz], dtype=float)
770272
def shape(self):
        ""
        keys = self.keys()
        if self.ndims == 1:
            return (len(keys), 1)
        return len(set(k[0] for k in keys)), len(set(k[1] for k in keys))
1364189
def from_arrays(cls, name, verts, normals, n_verts=3):

        """"""

        # Put header in string
        wavefront_str = "o {name}\n".format(name=name)

        # Write Vertex data from vert_dict
        for vert in verts:
            wavefront_str += "v {0} {1} {2}\n".format(*vert)

        # Write (false) UV Texture data
        wavefront_str += "vt 1.0 1.0\n"

        for norm in normals:
            wavefront_str += "vn {0} {1} {2}\n".format(*norm)


        # Write Face Indices (1-indexed)
        for wall_idx, vert_indices in enumerate(grouper(n_verts, range(1, len(verts) + 1))):
            face_str = 'f '
            for idx in vert_indices:
                face_str += "{v}/1/{n} ".format(v=idx, n=wall_idx + 1)
            wavefront_str += face_str + '\n'

        return WavefrontWriter(string=wavefront_str)
608292
def _get_cartesian_edge_set(self):
        
        # Get projection space for cartesian projection
        edge_sets = numpy.vstack(self.edge_set)
        west, east, north, south = utils.get_spherical_bounding_box(
            edge_sets[:, 0],
            edge_sets[:, 1])
        self.proj = utils.OrthographicProjection(west, east, north, south)

        for edges in self.edge_set:
            # Project edges into cartesian space
            px, py = self.proj(edges[:, 0], edges[:, 1])
            # Store the two end-points of the trace
            self.cartesian_endpoints.append(
                numpy.array([[px[0], py[0], edges[0, 2]],
                             [px[-1], py[-1], edges[-1, 2]]]))
            self.cartesian_edges.append(numpy.column_stack([px, py,
                                                            edges[:, 2]]))
            # Get surface length vector for the trace - easier in cartesian
            lengths = numpy.sqrt((px[:-1] - px[1:]) ** 2. +
                                 (py[:-1] - py[1:]) ** 2.)
            self.length_set.append(lengths)
            # Get cumulative surface length vector
            self.cum_length_set.append(
                numpy.hstack([0., numpy.cumsum(lengths)]))
        return edge_sets
278933
def grid_from_coordinate_transform(numPix, Mpix2coord, ra_at_xy_0, dec_at_xy_0):
    
    a = np.arange(numPix)
    matrix = np.dstack(np.meshgrid(a, a)).reshape(-1, 2)
    x_grid = matrix[:, 0]
    y_grid = matrix[:, 1]
    ra_grid = x_grid * Mpix2coord[0, 0] + y_grid * Mpix2coord[0, 1] + ra_at_xy_0
    dec_grid = x_grid * Mpix2coord[1, 0] + y_grid * Mpix2coord[1, 1] + dec_at_xy_0
    return ra_grid, dec_grid
683541
def _create_and_rotate_coordinate_arrays(self, x, y, p):
        

        if p.aspect_ratio == 0 or p.size == 0:
            x = x * 0.0
            y = y * 0.0
        else:
            x = (x*10.0) / (p.size*p.aspect_ratio)
            y = (y*10.0) / p.size

        offset = np.exp(p.size)
        pattern_x = np.add.outer(np.sin(p.orientation)*y, np.cos(p.orientation)*x) + offset
        pattern_y = np.subtract.outer(np.cos(p.orientation)*y, np.sin(p.orientation)*x) + offset

        np.clip(pattern_x, 0, np.Infinity, out=pattern_x)
        np.clip(pattern_y, 0, np.Infinity, out=pattern_y)

        return pattern_x, pattern_y
1319239
def cartisian_from_fractional(coordinate, lattice_array):
    """"""
    orthogonalisation_M = np.matrix(lattice_array)
    orthogonal = orthogonalisation_M * coordinate.reshape(-1, 1)
    return np.array(orthogonal.reshape(1, -1))
92750
def rotate_2D(angle):
    
    return N.array([[N.cos(angle),-N.sin(angle)],
                    [N.sin(angle),N.cos(angle)]])
553881
def projection_to_raster_coords(self, lat, lon):
        
        r_px_py = np.array([1, lon, lat])
        tg = inv(np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]]))
        return np.inner(tg, r_px_py)[1:]
213592
def _dump_multipolygon(obj, decimals):
    
    coords = obj['coordinates']
    mp = 'MULTIPOLYGON (%s)'

    polys = (
        # join the polygons in the multipolygon
        ', '.join(
            # join the rings in a polygon,
            # and wrap in parens
            '(%s)' % ', '.join(
                # join the points in a ring,
                # and wrap in parens
                '(%s)' % ', '.join(
                    # join coordinate values of a vertex
                    ' '.join(_round_and_pad(c, decimals) for c in pt)
                    for pt in ring)
                for ring in poly)
            for poly in coords)
    )
    mp %= polys
    return mp