Split a mesh by connectivity and order the pieces by increasing area.

    :param int maxdepth: only consider this number of mesh parts.

    .. hint:: |splitmesh| |splitmesh.py|_
359402
def splitByConnectivity(actor, maxdepth=100):
    
    actor.addIDs()
    pd = actor.polydata()
    cf = vtk.vtkConnectivityFilter()
    cf.SetInputData(pd)
    cf.SetExtractionModeToAllRegions()
    cf.ColorRegionsOn()
    cf.Update()
    cpd = cf.GetOutput()
    a = Actor(cpd)
    alist = []

    for t in range(max(a.scalars("RegionId")) - 1):
        if t == maxdepth:
            break
        suba = a.clone().threshold("RegionId", t - 0.1, t + 0.1)
        area = suba.area()
        alist.append([suba, area])

    alist.sort(key=lambda x: x[1])
    alist.reverse()
    blist = []
    for i, l in enumerate(alist):
        l[0].color(i + 1)
        l[0].mapper.ScalarVisibilityOff()
        blist.append(l[0])
    return blist
546266
void splitEdge_(int edge1, int edge2, int intersectionCluster,
			SegmentIntersector intersector) {

		disconnectEdge_(edge1);// disconnects the edge from the clusters. The
								// edge still remembers the clusters.
		if (edge2 != -1)
			disconnectEdge_(edge2);// disconnects the edge from the clusters.
									// The edge still remembers the clusters.

		// Collect all edges that are affected when the clusters change position
		// due to snapping
		// The edges are collected in 
		// Collect the modified clusters in m_modified_clusters.
		processSplitHelper1_(0, edge1, intersector);
		if (edge2 != -1)
			processSplitHelper1_(1, edge2, intersector);

		if (intersectionCluster != -1) {
			intersector.getResultPoint().getXY(pt_1);
			getClusterXY(intersectionCluster, pt_2);
			if (!pt_2.isEqual(pt_1))
				m_modified_clusters.add(intersectionCluster);
		}

		// remove modified clusters from the event queue. We'll reincert them
		// later
		for (int i = 0, n = m_modified_clusters.size(); i < n; i++) {
			int cluster = m_modified_clusters.get(i);
			int eventQnode = getClusterEventQNode(cluster);
			if (eventQnode != -1) {
				m_event_q.deleteNode(eventQnode, -1);
				setClusterEventQNode_(cluster, -1);
			}
		}

		int edgeOrigins1 = getEdgeOriginVertices(edge1);
		int edgeOrigins2 = (edge2 != -1) ? getEdgeOriginVertices(edge2) : -1;

		// Adjust the vertex coordinates and split the segments in the the edit
		// shape.
		applyIntersectorToEditShape_(edgeOrigins1, intersector, 0);
		if (edge2 != -1)
			applyIntersectorToEditShape_(edgeOrigins2, intersector, 1);

		// Produce clusters, and new edges. The new edges are added to
		// 
		createEdgesAndClustersFromSplitEdge_(edge1, intersector, 0);
		if (edge2 != -1)
			createEdgesAndClustersFromSplitEdge_(edge2, intersector, 1);

		m_edge_vertices.deleteList(edgeOrigins1);
		deleteEdge_(edge1);

		if (edge2 != -1) {
			m_edge_vertices.deleteList(edgeOrigins2);
			deleteEdge_(edge2);
		}

		// insert clusters into the event queue and the edges into the sweep
		// structure.
		for (int i = 0, n = m_modified_clusters.size(); i < n; i++) {
			int cluster = m_modified_clusters.get(i);
			if (cluster == m_sweep_point_cluster)
				m_b_sweep_point_cluster_was_modified = true;

			int eventQnode = getClusterEventQNode(cluster);
			if (eventQnode == -1) {
				int vertex = getClusterFirstVertex(cluster);
				assert (getClusterFromVertex(vertex) == cluster);

				eventQnode = m_event_q.addUniqueElement(vertex, -1);// O(logN)
																	// operation
				if (eventQnode == -1) {// the cluster is coinciding with another
										// one. merge.
					int existingNode = m_event_q.getDuplicateElement(-1);
					int v = m_event_q.getElement(existingNode);
					assert (m_shape.isEqualXY(vertex, v));
					int existingCluster = getClusterFromVertex(v);
					mergeClusters_(existingCluster, cluster);
				} else {
					setClusterEventQNode_(cluster, eventQnode);
				}
			} else {
				// if already inserted (probably impossible) case
			}
		}

		m_modified_clusters.clear(false);
	}
1028789
def split(self, t):
        """"""
        bpoints1, bpoints2 = split_bezier(self.bpoints(), t)
        return CubicBezier(*bpoints1), CubicBezier(*bpoints2)
31766
def cutWithMesh(self, mesh, invert=False):
        
        if isinstance(mesh, vtk.vtkPolyData):
            polymesh = mesh
        if isinstance(mesh, Actor):
            polymesh = mesh.polydata()
        else:
            polymesh = mesh.GetMapper().GetInput()
        poly = self.polydata()

        # Create an array to hold distance information
        signedDistances = vtk.vtkFloatArray()
        signedDistances.SetNumberOfComponents(1)
        signedDistances.SetName("SignedDistances")

        # implicit function that will be used to slice the mesh
        ippd = vtk.vtkImplicitPolyDataDistance()
        ippd.SetInput(polymesh)

        # Evaluate the signed distance function at all of the grid points
        for pointId in range(poly.GetNumberOfPoints()):
            p = poly.GetPoint(pointId)
            signedDistance = ippd.EvaluateFunction(p)
            signedDistances.InsertNextValue(signedDistance)

        # add the SignedDistances to the grid
        poly.GetPointData().SetScalars(signedDistances)

        # use vtkClipDataSet to slice the grid with the polydata
        clipper = vtk.vtkClipPolyData()
        clipper.SetInputData(poly)
        if invert:
            clipper.InsideOutOff()
        else:
            clipper.InsideOutOn()
        clipper.SetValue(0.0)
        clipper.Update()
        return self.updateMesh(clipper.GetOutput())
471561
def partsphere(self, x):
        """"""
        self.counter += 1
        # return np.random.rand(1)[0]**0 * sum(x**2) + 1 * np.random.rand(1)[0]
        dim = len(x)
        x = array([x[i % dim] for i in xrange(2 * dim)])
        N = 8
        i = self.counter % dim
        # f = sum(x[i:i + N]**2)
        f = sum(x[np.random.randint(dim, size=N)]**2)
        return f
206946
def number_of_partitions(max_range, max_sum):
    '''
    
    '''
    M = max_sum + 1
    N = len(max_range) 
    arr = np.zeros(shape=(M,N), dtype = int)    
    arr[:,-1] = np.where(np.arange(M) <= min(max_range[-1], max_sum), 1, 0)
    for i in range(N-2,-1,-1):
        for j in range(max_range[i]+1):
            arr[j:,i] += arr[:M-j,i+1] 
    return arr.sum(axis = 0)
168359
def splitIntoLines(self, maxWidth, maxHeight, splitted=False):
        
        self.lines = []
        self.height = 0
        self.maxWidth = self.width = maxWidth
        self.maxHeight = maxHeight
        boxStack = []

        style = self.style
        x = 0

        # Start with indent in first line of text
        if not splitted:
            x = style["textIndent"]

        lenText = len(self)
        pos = 0
        while pos < lenText:

            # Reset values for new line
            posBegin = pos
            line = Line(style)

            # Update boxes for next line
            for box in copy.copy(boxStack):
                box["x"] = 0
                line.append(BoxBegin(box))

            while pos < lenText:

                # Get fragment, its width and set X
                frag = self[pos]
                fragWidth = frag["width"]
                frag["x"] = x
                pos += 1

                # Keep in mind boxes for next lines
                if isinstance(frag, BoxBegin):
                    boxStack.append(frag)
                elif isinstance(frag, BoxEnd):
                    boxStack.pop()

                # If space or linebreak handle special way
                if frag.isSoft:
                    if frag.isLF:
                        line.append(frag)
                        break
                        # First element of line should not be a space
                    if x == 0:
                        continue
                        # Keep in mind last possible line break

                # The elements exceed the current line
                elif fragWidth + x > maxWidth:
                    break

                # Add fragment to line and update x
                x += fragWidth
                line.append(frag)

            # Remove trailing white spaces
            while line and line[-1].name in ("space", "br"):
                line.pop()

            # Add line to list
            line.dumpFragments()
            # if line:
            self.height += line.doLayout(self.width)
            self.lines.append(line)

            # If not enough space for current line force to split
            if self.height > maxHeight:
                return posBegin

            # Reset variables
            x = 0

        # Apply alignment
        self.lines[- 1].isLast = True
        for line in self.lines:
            line.doAlignment(maxWidth, style["textAlign"])

        return None
1169296
def split(self, maxweight):
        
        # NB: can be called only after .set_weights() has been called
        idx = {ri: i for i, ri in enumerate(self.rup_indices)}
        for rup_indices in general.block_splitter(
                self.rup_indices, maxweight, lambda ri: self.weights[idx[ri]]):
            if rup_indices:
                # some indices may have weight 0 and are discarded
                rgetter = self.__class__(
                    self.filename, list(rup_indices), self.grp_id,
                    self.trt, self.samples, self.rlzs_by_gsim,
                    self.first_event)
                rgetter.weight = sum([self.weights[idx[ri]]
                                      for ri in rup_indices])
                yield rgetter
1321147
def get_halfs(self, vertex1, vertex2):
        
        def grow(origin, other):
            frontier = set(self.neighbors[origin])
            frontier.discard(other)
            result = set([origin])
            while len(frontier) > 0:
                pivot = frontier.pop()
                if pivot == other:
                    raise GraphError("The graph can not be separated in two halfs "
                                     "by disconnecting vertex1 and vertex2.")
                pivot_neighbors = set(self.neighbors[pivot])
                pivot_neighbors -= result
                frontier |= pivot_neighbors
                result.add(pivot)
            return result

        vertex1_part = grow(vertex1, vertex2)
        vertex2_part = grow(vertex2, vertex1)
        return vertex1_part, vertex2_part
402780
private int chooseMaximalExtendedSplitAxis(List<? extends SpatialComparable> objects) {
    // maximum and minimum value for the extension
    int dimension = objects.get(0).getDimensionality();
    double[] maxExtension = new double[dimension];
    double[] minExtension = new double[dimension];
    Arrays.fill(minExtension, Double.MAX_VALUE);

    // compute min and max value in each dimension
    for (SpatialComparable object : objects) {
      for (int d = 0; d < dimension; d++) {
        double min, max;
        min = object.getMin(d);
        max = object.getMax(d);

        if (maxExtension[d] < max) {
          maxExtension[d] = max;
        }

        if (minExtension[d] > min) {
          minExtension[d] = min;
        }
      }
    }

    // set split axis to dim with maximal extension
    int splitAxis = -1;
    double max = 0;
    for (int d = 0; d < dimension; d++) {
      double currentExtension = maxExtension[d] - minExtension[d];
      if (max < currentExtension) {
        max = currentExtension;
        splitAxis = d;
      }
    }
    return splitAxis;
  }
436872
def set_split_extents_by_split_size(self):
        

        if self.split_size is None:
            if (
                _np.all([s is not None for s in self.split_num_slices_per_axis])
                and
                _np.all([s > 0 for s in self.split_num_slices_per_axis])
            ):
                self.split_size = _np.product(self.split_num_slices_per_axis)
            else:
                raise ValueError(
                    (
                        "Got invalid self.split_num_slices_per_axis=%s, all elements "
                        +
                        "need to be integers greater than zero when self.split_size is None."
                    )
                    %
                    self.split_num_slices_per_axis
                )
        self.logger.debug(
            "Pre  cannonicalise: self.split_num_slices_per_axis=%s",
            self.split_num_slices_per_axis)
        self.split_num_slices_per_axis = \
            calculate_num_slices_per_axis(
                self.split_num_slices_per_axis,
                self.split_size,
                self.array_shape
            )
        self.logger.debug(
            "Post cannonicalise: self.split_num_slices_per_axis=%s",
            self.split_num_slices_per_axis)
        # Define the start and stop indices (extents) for each axis slice
        self.split_shape = self.split_num_slices_per_axis.copy()
        self.split_begs = [[], ] * len(self.array_shape)
        self.split_ends = [[], ] * len(self.array_shape)
        for i in range(len(self.array_shape)):
            self.split_begs[i], self.split_ends[i] = \
                self.calculate_axis_split_extents(
                    self.split_shape[i],
                    self.array_shape[i]
            )
789011
protected double splitThresholdSq( Point2D_I32 a , Point2D_I32 b ) {
		return Math.max(2,a.distance2(b)* toleranceFractionSq);
	}
62342
public int maxComponent() {
        int absX = Math.abs(x);
        int absY = Math.abs(y);
        int absZ = Math.abs(z);
        int absW = Math.abs(w);
        if (absX >= absY && absX >= absZ && absX >= absW) {
            return 0;
        } else if (absY >= absZ && absY >= absW) {
            return 1;
        } else if (absZ >= absW) {
            return 2;
        }
        return 3;
    }
478071
def _scale_mesh(self, scale):
        
        pos_ks = ['vertices', 'centers']

        # TODO: scale velocities???

        # handle scale
        self.update_columns_dict({k: self[k]*scale for k in pos_ks})

        self.update_columns(areas=self.areas*(scale**2))
        self._volume *= scale**3
        if self._area is not None:
            # self._area is None for wd meshes
            self._area += scale**2
903445
public void split() {
    if(hasChildren()) {
      return;
    }

    final boolean issplit = (maxSplitDimension >= (getDimensionality() - 1));
    final int childLevel = issplit ? level + 1 : level;
    final int splitDim = issplit ? 0 : maxSplitDimension + 1;
    final double splitPoint = getMin(splitDim) + (getMax(splitDim) - getMin(splitDim)) * .5;

    // left and right child
    for(int i = 0; i < 2; i++) {
      double[] min = SpatialUtil.getMin(this); // clone
      double[] max = SpatialUtil.getMax(this); // clone

      // right child
      if(i == 0) {
        min[splitDim] = splitPoint;
      }
      // left child
      else {
        max[splitDim] = splitPoint;
      }

      ModifiableDBIDs childIDs = split.determineIDs(getIDs(), new HyperBoundingBox(min, max), d_min, d_max);
      if(childIDs != null) {
        // right child
        if(i == 0) {
          rightChild = new CASHInterval(min, max, split, childIDs, splitDim, childLevel, d_min, d_max);
        }
        // left child
        else {
          leftChild = new CASHInterval(min, max, split, childIDs, splitDim, childLevel, d_min, d_max);
        }
      }
    }

    if(LOG.isDebuggingFine()) {
      StringBuilder msg = new StringBuilder();
      msg.append("Child level ").append(childLevel).append(",  split Dim   ").append(splitDim);
      if(leftChild != null) {
        msg.append("\nleft   ").append(leftChild);
      }
      if(rightChild != null) {
        msg.append("\nright   ").append(rightChild);
      }
      LOG.fine(msg.toString());
    }
  }
81627
public int maxDepth()
    {
        Map<DFAState<T>,Integer> indexOf = new NumMap<>();
        Map<DFAState<T>,Long> depth = new NumMap<>();
        Deque<DFAState<T>> stack = new ArrayDeque<>();
        maxDepth(root, indexOf, stack, depth);
        long d = depth.get(root);
        assert d >= 0;
        if (d >= Integer.MAX_VALUE)
        {
            return Integer.MAX_VALUE;
        }
        else
        {
            return (int) d;
        }
    }
816775
private int calculateMaxPendingSplits(int splitAffinity, int totalDepth)
    {
        if (totalDepth == 0) {
            return maxPendingSplitsPerTask;
        }
        // Use half the queue for any split
        // Reserve the other half for splits that have some amount of network affinity
        double queueFraction = 0.5 * (1.0 + splitAffinity / (double) totalDepth);
        return (int) Math.ceil(maxPendingSplitsPerTask * queueFraction);
    }