Generate data with two sphere objects.
    :param sz: output data shape is [sz, sz+1, sz+2]
    :param offset:
    :param radius:
    :param seedsz:
    :param add_object_without_seeds: Add also one cube-like object in the corner.
    :return:
349395
def generate_round_data(
    sz=32, offset=0, radius=7, seedsz=3, add_object_without_seeds=False
):
    

    import scipy.ndimage

    # seedsz= int(sz/10)
    space = 2
    seeds = np.zeros([sz, sz + 1, sz + 2], dtype=np.int8)
    xmin = radius + seedsz + offset + 2
    ymin = radius + seedsz + offset + 6
    seeds[offset + 12, xmin + 3 : xmin + 7 + seedsz, ymin : ymin + 2] = 1
    seeds[offset + 20, xmin + 7 : xmin + 12 + seedsz, ymin + 5 : ymin + 7] = 1

    # add temp seed
    if add_object_without_seeds:
        seeds[-3, -3, -3] = 1
    img = np.ones([sz, sz + 1, sz + 2])
    img = img - seeds

    seeds[2 : 10 + seedsz, 2 : 9 + seedsz, 2 : 3 + seedsz] = 2

    # remove temo seed
    if add_object_without_seeds:
        seeds[-3, -3, -3] = 0

    img = scipy.ndimage.morphology.distance_transform_edt(img)
    segm = img < radius
    img = (100 * segm + 80 * np.random.random(img.shape)).astype(np.uint8)
    return img, segm, seeds
381348
function(data) {
    if (!data) return null;
    var geoset = [];
    var self = this;

    function applyNoise(geo, noise) {
      var n = new THREE.Vector3();
      for (var i = 0, numVerts = geo.vertices.length; i < numVerts; i++) {
        n.x = (self.random(i) - 0.5) * noise;
        n.y = (self.random(i + numVerts) - 0.5) * noise;
        n.z = (self.random(i + numVerts * 2) - 0.5) * noise;
        geo.vertices[i].add(n);
      }
    }

    var i, geo, verts;

    for (var j = 0; j < data.length; j++) {

      if (data[j].type == 'lathe') {
        var maxy = -99999;
        var points = [];
        verts = data[j].vertices;
        for (i = 0; i < verts.length; i += 2) {
          points.push(new THREE.Vector2(verts[i], verts[i + 1]));
          if (verts[i + 1] > maxy) {
            maxy = verts[i + 1];
          }
        }
        geo = new THREE.LatheGeometry(points, data[j]['segments'] || 8);
        geo.applyMatrix(new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(-Math.PI, 0, 0)));
        geo.applyMatrix(new THREE.Matrix4().makeTranslation(0, maxy, 0));
        if (data[j]['noise']) applyNoise(geo, data[j].noise);
        geoset.push(geo);
      }

      else if (data[j].type == 'extrude') {
        var shape = new THREE.Shape();
        verts = data[j].vertices;
        for (i = 0; i < verts.length; i+= 2) {
          if (i == 0) shape.moveTo(verts[i], verts[i + 1]);
          else shape.lineTo(verts[i], verts[i + 1]);
        }
        geo = new THREE.ExtrudeGeometry(shape, {amount: 1, bevelEnabled: false});
        geo.applyMatrix(new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(-Math.PI / 2, 0, 0)));
        if (data[j]['noise']) applyNoise(geo, data[j].noise);
        geoset.push(geo);
      }

      else if (data[j].type == 'mesh') {
        geo = new THREE.Geometry();
        verts = data[j].vertices;
        var faces = data[j].faces;
        for (var v = 0; v < verts.length; v += 3) {
          geo.vertices.push(new THREE.Vector3(verts[v], verts[v + 1], verts[v + 2]));
        }
        for (var f = 0; f < faces.length; f += 3) {
          geo.faces.push(new THREE.Face3(faces[f], faces[f + 1], faces[f + 2]));
        }
        if (this.data.flatShading || data[j]['flatShading']) {
          geo.computeFaceNormals();
        }
        else {
          geo.computeVertexNormals();
        }

        if (data[j]['mirror']) {
          geo.merge(geo, new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(0, Math.PI, 0)));
        }

        if (data[j]['noise']) applyNoise(geo, data[j].noise);
        geoset.push(geo);
      }
    }
    return geoset;
  }
1340832
def generateXY(self, **kwargs):
        
        self.num_objects = 0
        xycols = self._readCatalog()

        if xycols is not None:
            # convert the catalog into attribute
            self.xypos = xycols[:3]
            # convert optional columns if they are present
            if self.numcols > 3:
                self.xypos.append(np.asarray(xycols[3], dtype=int)) # source ID
            if self.numcols > 4:
                self.sharp = xycols[4]
            if self.numcols > 5:
                self.round1 = xycols[5]
            if self.numcols > 6:
                self.round2 = xycols[6]
            self.num_objects = len(xycols[0])

        if self.numcols < 3: # account for flux column
            self.xypos.append(np.zeros(self.num_objects, dtype=float))
            self.flux_col = False

        if self.numcols < 4: # add source ID column
            self.xypos.append(np.arange(self.num_objects)+self.start_id)

        if self.use_sharp_round:
            for i in range(len(self.xypos), 7):
                self.xypos.append(np.zeros(self.num_objects, dtype=float))
            self.sharp_col = False

        if self.pars['xyunits'] == 'degrees':
            self.radec = [x.copy() for x in self.xypos]
            if self.wcs is not None:
                self.xypos[:2] = list(self.wcs.all_world2pix(np.array(self.xypos[:2]).T, self.origin).T)
218640
def _concatenate_shape(input_shape, axis=-1):  # pylint: disable=invalid-name
  """"""
  ax = axis % len(input_shape[0])
  concat_size = sum(shape[ax] for shape in input_shape)
  out_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:]
  return out_shape
1296994
def generate_shapes(shapes):
        
        new_shapes = {'ellipse': [], 'rectangle': []}

        for shape in shapes:
            tmp_shape = {}
            for shape_item in shapes[shape]:
                if shape_item != 'type':
                    tmp_shape[shape_item] = shapes[shape][shape_item]

            new_shapes[shapes[shape]['type']].append(tmp_shape)

        return new_shapes
561828
def _make_3d(field, twod):
    
    shp = list(field.shape)
    if twod and 'X' in twod:
        shp.insert(1, 1)
    elif twod:
        shp.insert(0, 1)
    return field.reshape(shp)
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);
    };
  }
811007
def generate_face(shape=None, face_r=1.0, smile_r1=0.5, smile_r2=0.7, eye_r=0.2):
    
    # TODO add axis (ax=0)
    if shape is None:
        shape = [32, 32]
    nd = len(shape)
    if nd == 2:
        sh2 = shape
    else:
        sh2 = shape[1:]
    fc2 = _get_face2(
        sh2, face_r=face_r, smile_r1=smile_r1, smile_r2=smile_r2, eye_r=eye_r
    )

    if nd == 2:
        return fc2
    else:
        fc3 = np.zeros(shape)
        for i in range(fc3.shape[0]):
            fc3[i, :, :] = fc2
        return fc3
1252934
def smart_initialize(self):
        ''''''
        if self.seed is not None: # useful for obtaining consistent results
            np.random.seed(self.seed)
        centroids = np.zeros((self.k, self.data.shape[1]))
        # Randomly choose the first centroid.
        # Since we have no prior knowledge, choose uniformly at random
        idx = np.random.randint(self.data.shape[0])
        centroids[0] = self.data[idx,:].toarray()
        # Compute distances from the first centroid chosen to all the other data points
        squared_distances = pairwise_distances(self.data, centroids[0:1], metric='euclidean').flatten()**2
        for i in range(1, self.k):
            # Choose the next centroid randomly, so that the probability for each data point to be chosen
            # is directly proportional to its squared distance from the nearest centroid.
            # Roughtly speaking, a new centroid should be as far as from ohter centroids as possible.
            idx = np.random.choice(self.data.shape[0], 1, p=squared_distances/sum(squared_distances))
            centroids[i] = self.data[idx,:].toarray()
            # Now compute distances from the centroids to all data points
            squared_distances = np.min(pairwise_distances(self.data, centroids[0:i+1], metric='euclidean')**2,axis=1)
        self.centroids=centroids
        return centroids
725711
def seed_zoom(seeds, zoom):
    
    # import scipy
    # loseeds=seeds
    labels = np.unique(seeds)
    # remove first label - 0
    labels = np.delete(labels, 0)
    # @TODO smart interpolation for seeds in one block
    #        loseeds = scipy.ndimage.interpolation.zoom(
    #            seeds, zoom, order=0)
    loshape = np.ceil(np.array(seeds.shape) * 1.0 / zoom).astype(np.int)
    loseeds = np.zeros(loshape, dtype=np.int8)
    loseeds = loseeds.astype(np.int8)
    for label in labels:
        a, b, c = np.where(seeds == label)
        loa = np.round(a // zoom)
        lob = np.round(b // zoom)
        loc = np.round(c // zoom)
        # loseeds = np.zeros(loshape)

        loseeds[loa, lob, loc] += label
        # this is to detect conflict seeds
        loseeds[loseeds > label] = 100

    # remove conflict seeds
    loseeds[loseeds > 99] = 0

    # import py3DSeedEditor
    # ped = py3DSeedEditor.py3DSeedEditor(loseeds)
    # ped.show()

    return loseeds
1177793
def get_SZ_single(self, alpha=None, beta=None):
        
        if alpha == None:
            alpha = self.alpha
        if beta == None:
            beta = self.beta

        tm_outdated = self._tm_signature != (self.radius, self.radius_type, 
            self.wavelength, self.m, self.axis_ratio, self.shape, self.ddelt, 
            self.ndgs)
        if tm_outdated:
            self._init_tmatrix()

        scatter_outdated = self._scatter_signature != (self.thet0, self.thet, 
            self.phi0, self.phi, alpha, beta, self.orient)

        outdated = tm_outdated or scatter_outdated

        if outdated:
            (self._S_single, self._Z_single) = pytmatrix.calcampl(self.nmax, 
                self.wavelength, self.thet0, self.thet, self.phi0, self.phi, 
                alpha, beta)
            self._set_scatter_signature()

        return (self._S_single, self._Z_single)
597463
def arcball_map_to_sphere(point, center, radius):
    """"""
    v0 = (point[0] - center[0]) / radius
    v1 = (center[1] - point[1]) / radius
    n = v0*v0 + v1*v1
    if n > 1.0:
        # position outside of sphere
        n = math.sqrt(n)
        return numpy.array([v0/n, v1/n, 0.0])
    else:
        return numpy.array([v0, v1, math.sqrt(1.0 - n)])
764659
def within_radius_sphere(self, x, y, radius):
        
        return QueryExpression({
            self : {'$within' : {
                    '$centerSphere' : [[x, y], radius],
                }}
            })
490671
private static SphereCluster calculateCenter(ArrayList<Cluster> assigned, int dimensions) {
		double[] result = new double[dimensions];
		for (int i = 0; i < result.length; i++) {
			result[i] = 0.0;
		}

		if (assigned.size() == 0) {
			return new SphereCluster(result, 0.0);
		}

		for (Cluster point : assigned) {
			double[] center = point.getCenter();
			for (int i = 0; i < result.length; i++) {
				result[i] += center[i];
			}
		}

		// Normalize
		for (int i = 0; i < result.length; i++) {
			result[i] /= assigned.size();
		}

		// Calculate radius: biggest wrapping distance from center
		double radius = 0.0;
		for (Cluster point : assigned) {
			double dist = distance(result, point.getCenter());
			if (dist > radius) {
				radius = dist;
			}
		}
		SphereCluster sc = new SphereCluster(result, radius);
		sc.setWeight(assigned.size());
		return sc;
	}
1071838
function HexSphere(r, level) {
  r = r || 0.5;
  level = level || 1;

  var baseGeom = new Icosahedron(r);
  for(var i=0; i<level; i++) {
    baseGeom = baseGeom.subdivideEdges();
  }

  var vertices = [];
  var faces = [];


  var halfEdgeForVertex = [];
  var halfEdges = baseGeom.computeHalfEdges();
  halfEdges.forEach(function(e) {
    halfEdgeForVertex[e.face[e.slot]] = e;
  });

  for(var i=0; i<baseGeom.vertices.length; i++) {
    var vertexIndex = vertices.length;
    var midPoints = [];
    //collect center points of neighbor faces
    vertexEdgeLoop(halfEdgeForVertex[i], function(e) {
      var midPoint = centroid(elements(baseGeom.vertices, e.face));
      midPoints.push(midPoint);
    });
    midPoints.forEach(function(p, i){
      vertices.push(p);
    });
    if (midPoints.length == 5) {
      faces.push([vertexIndex, vertexIndex+1, vertexIndex+2, vertexIndex+3, vertexIndex+4]);
    }
    if (midPoints.length == 6) {
      faces.push([vertexIndex, vertexIndex+1, vertexIndex+2, vertexIndex+3, vertexIndex+4, vertexIndex+5]);
    }
  }

  vertices.forEach(function(v) {
    v.normalize().scale(r);
  });

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

  this.computeEdges();
}
3026
def zinb_ll(data, P, R, Z):
    
    lls = nb_ll(data, P, R)
    clusters = P.shape[1]
    for c in range(clusters):
        pass
    return lls
238649
function reShape(object, radius, orientation, options, slicer) {
  options = options || {};
  var b = object.getBounds();
  // var s = util.size(b);
  var ar = Math.abs(radius);
  var si = util.sliceParams(orientation, radius, b);

  if (si.axis !== "z")
    throw new Error(
      'util.reShape error: CAG._toPlanePolytons only uses the "z" axis.  You must use the "z" axis for now.'
    );

  var cutplane = CSG$1.OrthoNormalBasis.GetCartesian(
    si.orthoNormalCartesian[0],
    si.orthoNormalCartesian[1]
  ).translate(si.cutDelta);

  var slice = object.sectionCut(cutplane);

  var first = util.axisApply(si.axis, function() {
    return si.positive ? 0 : ar;
  });

  var last = util.axisApply(si.axis, function() {
    return si.positive ? ar : 0;
  });

  var plane = si.positive ? cutplane.plane : cutplane.plane.flipped();

  var slices = slicer(first, last, slice);

  var delta = util
    .slices2poly(
      slices,
      Object.assign(options, {
        si: si
      }),
      si.axis
    )
    .color(options.color);

  var remainder = object.cutByPlane(plane);
  return union([
    options.unionOriginal ? object : remainder,
    delta.translate(si.moveDelta)
  ]);
}