Creates an ellipsoid with radii around a given midpoint
        :math:`x_0`.
339175
def add_ellipsoid(self, x0, radii, lcar=None, with_volume=True, holes=None):
        
        if holes is None:
            holes = []

        if holes:
            assert with_volume

        # Add points.
        p = [
            self.add_point(x0, lcar=lcar),
            self.add_point([x0[0] + radii[0], x0[1], x0[2]], lcar=lcar),
            self.add_point([x0[0], x0[1] + radii[1], x0[2]], lcar=lcar),
            self.add_point([x0[0], x0[1], x0[2] + radii[2]], lcar=lcar),
            self.add_point([x0[0] - radii[0], x0[1], x0[2]], lcar=lcar),
            self.add_point([x0[0], x0[1] - radii[1], x0[2]], lcar=lcar),
            self.add_point([x0[0], x0[1], x0[2] - radii[2]], lcar=lcar),
        ]
        # Add skeleton.
        # Alternative for circles:
        # `self.add_circle_arc(a, b, c)`
        c = [
            self.add_ellipse_arc(p[1], p[0], p[6], p[6]),
            self.add_ellipse_arc(p[6], p[0], p[4], p[4]),
            self.add_ellipse_arc(p[4], p[0], p[3], p[3]),
            self.add_ellipse_arc(p[3], p[0], p[1], p[1]),
            self.add_ellipse_arc(p[1], p[0], p[2], p[2]),
            self.add_ellipse_arc(p[2], p[0], p[4], p[4]),
            self.add_ellipse_arc(p[4], p[0], p[5], p[5]),
            self.add_ellipse_arc(p[5], p[0], p[1], p[1]),
            self.add_ellipse_arc(p[6], p[0], p[2], p[2]),
            self.add_ellipse_arc(p[2], p[0], p[3], p[3]),
            self.add_ellipse_arc(p[3], p[0], p[5], p[5]),
            self.add_ellipse_arc(p[5], p[0], p[6], p[6]),
        ]
        # Add surfaces (1/8th of the ball surface).
        ll = [
            # one half
            self.add_line_loop([c[4], c[9], c[3]]),
            self.add_line_loop([c[8], -c[4], c[0]]),
            self.add_line_loop([-c[9], c[5], c[2]]),
            self.add_line_loop([-c[5], -c[8], c[1]]),
            # the other half
            self.add_line_loop([c[7], -c[3], c[10]]),
            self.add_line_loop([c[11], -c[7], -c[0]]),
            self.add_line_loop([-c[10], -c[2], c[6]]),
            self.add_line_loop([-c[1], -c[6], -c[11]]),
        ]
        # Create a surface for each line loop.
        s = [self.add_surface(l) for l in ll]

        # Combine the surfaces to avoid seams
        if self._gmsh_major() == 3:
            s = [self.add_compound_surface(s[:4]), self.add_compound_surface(s[4:])]
        else:
            assert self._gmsh_major() == 4
            # <https://gitlab.onelab.info/gmsh/gmsh/issues/507>
            self.add_raw_code(
                "Compound Surface{{{}}};".format(",".join([surf.id for surf in s[:4]]))
            )
            self.add_raw_code(
                "Compound Surface{{{}}};".format(",".join([surf.id for surf in s[4:]]))
            )

        # Create the surface loop.
        surface_loop = self.add_surface_loop(s)
        # if holes:
        #     # Create an array of surface loops; the first entry is the outer
        #     # surface loop, the following ones are holes.
        #     surface_loop = self.add_array([surface_loop] + holes)
        # Create volume.
        volume = self.add_volume(surface_loop, holes) if with_volume else None

        class Ellipsoid(object):
            dimension = 3

            def __init__(self, x0, radii, surface_loop, volume, lcar=None):
                self.x0 = x0
                self.lcar = lcar
                self.radii = radii
                self.surface_loop = surface_loop
                self.volume = volume
                return

        return Ellipsoid(x0, radii, surface_loop, volume, lcar=lcar)
619433
def create(self, r, r_, R=200):
        '''
        '''
        x, y = give_dots(R, r, r_, spins=20)
        xy = np.array([x, y]).T
        xy = np.array(np.around(xy), dtype=np.int64)
        xy = xy[(xy[:, 0] >= -250) & (xy[:, 1] >= -250) &
                (xy[:, 0] < 250) & (xy[:, 1] < 250)]
        xy = xy + 250
        img = np.ones([500, 500], dtype=np.uint8)
        img[:] = 255
        img[xy[:, 0], xy[:, 1]] = 0
        img = misc.imresize(img, [self.img_size, self.img_size])
        fimg = img / 255.0
        return fimg
874055
def prepare_venn_axes(ax, centers, radii):
    '''
    
    '''
    ax.set_aspect('equal')
    ax.set_xticks([])
    ax.set_yticks([])
    min_x = min([centers[i][0] - radii[i] for i in range(len(radii))])
    max_x = max([centers[i][0] + radii[i] for i in range(len(radii))])
    min_y = min([centers[i][1] - radii[i] for i in range(len(radii))])
    max_y = max([centers[i][1] + radii[i] for i in range(len(radii))])
    ax.set_xlim([min_x - 0.1, max_x + 0.1])
    ax.set_ylim([min_y - 0.1, max_y + 0.1])
    ax.set_axis_off()
1211201
def set_ellipsoid(self, ellipsoid):
        
        if not isinstance(ellipsoid, (list, tuple)):
            try:
                self.ELLIPSOID = ELLIPSOIDS[ellipsoid]
                self.ellipsoid_key = ellipsoid
            except KeyError:
                raise Exception(
                    "Invalid ellipsoid. See geopy.distance.ELIPSOIDS"
                )
        else:
            self.ELLIPSOID = ellipsoid
            self.ellipsoid_key = None
        return
1041621
def create_point(self, xcen, ycen, size=10, color='red', fill=None):
        """"""

        if fill is None:
            fill = color

        (x, y) = self.p2c((xcen, ycen))
        x1 = x - size
        x2 = x + size
        y1 = y - size
        y2 = y + size
        self.create_rectangle(x1, y1, x2, y2, fill=fill, outline=color)
791806
public static Element drawEuclidean(SVGPlot svgp, Projection2D proj, NumberVector mid, double radius) {
    double[] v_mid = mid.toArray(); // a copy
    long[] dims = proj.getVisibleDimensions2D();

    SVGPath path = new SVGPath();
    for(int dim = BitsUtil.nextSetBit(dims, 0); dim >= 0; dim = BitsUtil.nextSetBit(dims, dim + 1)) {
      v_mid[dim] += radius;
      double[] p1 = proj.fastProjectDataToRenderSpace(v_mid);
      v_mid[dim] -= radius * 2;
      double[] p2 = proj.fastProjectDataToRenderSpace(v_mid);
      v_mid[dim] += radius;
      // delta vector
      double[] dt1 = new double[v_mid.length];
      dt1[dim] = radius;
      double[] d1 = proj.fastProjectRelativeDataToRenderSpace(dt1);
      for(int dim2 = BitsUtil.nextSetBit(dims, 0); dim2 >= 0; dim2 = BitsUtil.nextSetBit(dims, dim2 + 1)) {
        if(dim < dim2) {
          v_mid[dim2] += radius;
          double[] p3 = proj.fastProjectDataToRenderSpace(v_mid);
          v_mid[dim2] -= radius * 2;
          double[] p4 = proj.fastProjectDataToRenderSpace(v_mid);
          v_mid[dim2] += radius;
          // delta vector
          double[] dt2 = new double[v_mid.length];
          dt2[dim2] = radius;
          double[] d2 = proj.fastProjectRelativeDataToRenderSpace(dt2);

          path.moveTo(p1[0], p1[1]) //
              .cubicTo(p1[0] + d2[0] * EUCLIDEAN_KAPPA, p1[1] + d2[1] * EUCLIDEAN_KAPPA, p3[0] + d1[0] * EUCLIDEAN_KAPPA, p3[1] + d1[1] * EUCLIDEAN_KAPPA, p3[0], p3[1]) //
              .cubicTo(p3[0] - d1[0] * EUCLIDEAN_KAPPA, p3[1] - d1[1] * EUCLIDEAN_KAPPA, p2[0] + d2[0] * EUCLIDEAN_KAPPA, p2[1] + d2[1] * EUCLIDEAN_KAPPA, p2[0], p2[1]) //
              .cubicTo(p2[0] - d2[0] * EUCLIDEAN_KAPPA, p2[1] - d2[1] * EUCLIDEAN_KAPPA, p4[0] - d1[0] * EUCLIDEAN_KAPPA, p4[1] - d1[1] * EUCLIDEAN_KAPPA, p4[0], p4[1]) //
              .cubicTo(p4[0] + d1[0] * EUCLIDEAN_KAPPA, p4[1] + d1[1] * EUCLIDEAN_KAPPA, p1[0] - d2[0] * EUCLIDEAN_KAPPA, p1[1] - d2[1] * EUCLIDEAN_KAPPA, p1[0], p1[1]) //
              .close();
        }
      }
    }
    return path.makeElement(svgp);
  }
515122
def _fit_ellipsoid_partial(locations, cy):
    """"""
    a = np.vstack([locations[:, 0]**2,
                   locations[:, 1]**2 - 2 * locations[:, 1] * cy,
                   locations[:, 2]**2,
                   locations[:, 0]*2,
                   locations[:, 2]*2]).T
    x = sp.linalg.lstsq(a, np.ones(locations.shape[0]))[0]
    c = [-x[3] / x[0], cy, -x[4] / x[2]]
    gam = 1 + x[3]**2 / x[0] + x[4]**2 / x[2]
    r = np.sqrt([gam / x[0], gam / x[1], gam / x[2]])
    return c, r
650953
def ellipse(n=1000, adaptive=False):
    
    u = N.linspace(0,2*N.pi,n)
    # Get a bundle of vectors defining
    # a full rotation around the unit circle
    return N.array([N.cos(u),N.sin(u)]).T
1005350
def createCellsFixedNum (self):
        ''' '''
        from .. import sim

        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+'Range' in self.tags:  # if user provided absolute range, convert to normalized
                self.tags[coord+'normRange'] = [float(point) / getattr(sim.net.params, 'size'+coord.upper()) for point in self.tags[coord+'Range']]
            # constrain to range set by user
            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

        for i in self._distributeCells(int(sim.net.params.scale * 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] # set x location (um)
            cellTags['ynorm'] = randLocs[i,1] # set y location (um)
            cellTags['znorm'] = randLocs[i,2] # set z location (um)
            cellTags['x'] = sim.net.params.sizeX * randLocs[i,0] # set x location (um)
            cellTags['y'] = sim.net.params.sizeY * randLocs[i,1] # set y location (um)
            cellTags['z'] = sim.net.params.sizeZ * randLocs[i,2] # set z location (um)            
            if 'spkTimes' in self.tags:  # if VecStim, copy spike times to params
                if isinstance(self.tags['spkTimes'][0], list):
                    try:
                        cellTags['params']['spkTimes'] = self.tags['spkTimes'][i] # 2D list
                    except:
                        pass
                else:
                    cellTags['params']['spkTimes'] = self.tags['spkTimes'] # 1D list (same for all)
            cells.append(self.cellModelClass(gid, cellTags)) # instantiate Cell object

            if sim.cfg.verbose: print(('Cell %d/%d (gid=%d) of pop %s, on node %d, '%(i, sim.net.params.scale * self.tags['numCells']-1, gid, self.tags['pop'], sim.rank)))
        sim.net.lastGid = sim.net.lastGid + self.tags['numCells'] 
        return cells
902135
def roundrectangle(center_x, center_y, width, height, corner_width, corner_height)
      primitive 'roundrectangle ' + format('%g,%g,%g,%g,%g,%g',
                                           center_x, center_y, width, height, corner_width, corner_height)
    end
911378
def geo_shape(self, sides=5, center=None, distance=None):
        
        assert isinstance(sides, int)

        if distance is None:
            distance = self.random_int(100, 1000)
        else:
            # 6371 => earth radius in km
            # assert that shape radius is maximum half of earth's circumference
            assert isinstance(distance, int)
            assert distance <= EARTH_RADIUS * math.pi, \
                'distance must not be greater than half of earth\'s circumference'

        if center is None:
            # required minimal spherical distance from north/southpole
            dp = distance * 180.0 / EARTH_RADIUS / math.pi
            center = self.geo_point(lat_min=-90.0 + dp, lat_max=90.0 - dp)
        else:
            assert -180.0 <= center[0] <= 180.0, 'Longitude out of bounds'
            assert -90.0 <= center[1] <= 90.0, 'Latitude out of bounds'

        angles = list(self.random_sample(range(360), sides))
        angles.sort()
        points = [_dest_point(center, distance, bearing, EARTH_RADIUS) for bearing in angles]
        # close polygon
        points.append(points[0])

        path = ', '.join([' '.join(p) for p in ([str(lon), str(lat)] for lon, lat in points)])
        return f'POLYGON (( {path} ))'
1075964
def _getshapes_2d(center, max_radius, shape):
    """"""
    index_mean = shape * center
    index_radius = max_radius / 2.0 * np.array(shape)

    # Avoid negative indices
    min_idx = np.maximum(np.floor(index_mean - index_radius), 0).astype(int)
    max_idx = np.ceil(index_mean + index_radius).astype(int)
    idx = [slice(minx, maxx) for minx, maxx in zip(min_idx, max_idx)]
    shapes = [(idx[0], slice(None)),
              (slice(None), idx[1])]
    return tuple(idx), tuple(shapes)
509209
def ix_(selection, shape):
    """"""

    # normalisation
    selection = replace_ellipsis(selection, shape)

    # replace slice and int as these are not supported by numpy.ix_
    selection = [slice_to_range(dim_sel, dim_len) if isinstance(dim_sel, slice)
                 else [dim_sel] if is_integer(dim_sel)
                 else dim_sel
                 for dim_sel, dim_len in zip(selection, shape)]

    # now get numpy to convert to a coordinate selection
    selection = np.ix_(*selection)

    return selection
589500
def mid_point(self):
        '''
        
        '''
        midpoint_angle = self.from_angle + self.sign*self.length_degrees() / 2
        return self.angle_as_point(midpoint_angle)
641418
function closePoint(px, py, ax, ay, bx, by, r) {

    var x = ax,
        y = ay,
        dx = bx - x,
        dy = by - y;

    if (dx !== 0 || dy !== 0) {

        var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);

        if (t >= 1) {
            x = bx;
            y = by;
            t = 1;

        } else if (t > 0) {
            x += dx * t;
            y += dy * t;

        } else {
            t = 0;
        }
    }

    dx = px - x;
    dy = py - y;

    return dx * dx + dy * dy < r * r ? t : null;
}
298964
def make_shape(self):
        
        # In DS9, ellipse can also represents an elliptical annulus
        # For elliptical annulus angle is optional.
        if self.region_type == 'ellipse':
            self.coord[2:] = [x * 2 for x in self.coord[2:]]
            if len(self.coord) % 2 == 1:  # This checks if angle is present
                self.coord[-1] /= 2

        if 'point' in self.meta:
            point = self.meta['point'].split(" ")
            if len(point) > 1:
                self.meta['symsize'] = point[1]
            self.meta['point'] = valid_symbols_ds9[point[0]]

        if 'font' in self.meta:
            fonts = self.meta['font'].split(" ")
            keys = ['font', 'fontsize', 'fontstyle', 'fontweight']
            for i, val in enumerate(fonts):
                self.meta[keys[i]] = val

        self.meta.pop('coord', None)

        self.shape = Shape(coordsys=self.coordsys,
                           region_type=reg_mapping['DS9'][self.region_type],
                           coord=self.coord,
                           meta=self.meta,
                           composite=self.composite,
                           include=self.include,
                          )
475089
def mvee(points, tol=0.001):
    

    # This function is a port of the matlab function by
    # Nima Moshtagh found here:
    # https://www.mathworks.com/matlabcentral/fileexchange/9542-minimum-volume-enclosing-ellipsoid
    # with accompanying writup here:
    # https://www.researchgate.net/profile/Nima_Moshtagh/publication/254980367_MINIMUM_VOLUME_ENCLOSING_ELLIPSOIDS/links/54aab5260cf25c4c472f487a.pdf

    N, d = points.shape

    Q = np.zeros([N,d+1])
    Q[:,0:d] = points[0:N,0:d]
    Q[:,d] = np.ones([1,N])

    Q = np.transpose(Q)
    points = np.transpose(points)
    count = 1
    err = 1
    u = (1/N) * np.ones(shape = (N,))

    while err > tol:

        X = np.dot(np.dot(Q, np.diag(u)), np.transpose(Q))
        M = np.diag( np.dot(np.dot(np.transpose(Q), la.inv(X)),Q))
        jdx = np.argmax(M)
        step_size = (M[jdx] - d - 1)/((d+1)*(M[jdx] - 1))
        new_u = (1 - step_size)*u
        new_u[jdx] = new_u[jdx] + step_size
        count = count + 1
        err = la.norm(new_u - u)
        u = new_u

    U = np.diag(u)
    c = np.dot(points,u)
    A = (1/d) * la.inv(np.dot(np.dot(points,U), np.transpose(points)) - np.outer(c,c) )
    return A, np.transpose(c)