The matrix of connections that are severed by this cut.
16087
def cut_matrix(self, n):
        """"""
        cm = np.zeros((n, n))

        for part in self.partition:
            from_, to = self.direction.order(part.mechanism, part.purview)
            # All indices external to this part
            external = tuple(set(self.indices) - set(to))
            cm[np.ix_(from_, external)] = 1

        return cm
1066712
def cycle_cut(self, cycle_len_thresh=12, directed=False, copy=True):
    '''
    '''
    symmetric = not directed
    adj = self.kernelize('binary').matrix('csr', 'dense', copy=True)
    if symmetric:
      adj = adj + adj.T

    removed_edges = []
    while True:
      c = _atomic_cycle(adj, cycle_len_thresh, directed=directed)
      if c is None:
        break
      # remove edges in the cycle
      ii, jj = c.T
      adj[ii,jj] = 0
      if symmetric:
        adj[jj,ii] = 0
      removed_edges.extend(c)

    #XXX: if _atomic_cycle changes, may need to do this on each loop
    if ss.issparse(adj):
      adj.eliminate_zeros()

    # select only the necessary cuts
    ii, jj = _find_cycle_inducers(adj, removed_edges, cycle_len_thresh,
                                  directed=directed)
    # remove the bad edges
    return self.remove_edges(ii, jj, symmetric=symmetric, copy=copy)
1291735
private static List<Segmentation> getSegmentations(String str, int begin, int end, int nbMaxComponents, int minComponentSize, List<CuttingPoint> cuttingPoints) {
		List<Segmentation> s = new ArrayList<Segmentation>(nbMaxComponents);
		for(CuttingPoint cp:getPossibleCuttingPoints(str, begin, end, nbMaxComponents, minComponentSize)) {
			s.add(new Segmentation(str, addToDuplicate(cuttingPoints, cp, nbMaxComponents - 1)));
			if(nbMaxComponents > 2) {
				if(cp.isHypen())
					// recursivity on the left part only if the cp was an hypen
					if((cp.getIndex() - begin) >= 2*minComponentSize)
						s.addAll(getSegmentations(str, begin, cp.getIndex(), nbMaxComponents -1, minComponentSize, addToDuplicate(cuttingPoints, cp, nbMaxComponents - 1)));
				
				if((end - (cp.getIndex() + cp.getOffset())) >= 2*minComponentSize)
					s.addAll(getSegmentations(str, cp.getIndex() + cp.getOffset(), end, nbMaxComponents -1, minComponentSize, addToDuplicate(cuttingPoints, cp, nbMaxComponents - 1)));
			}
		}
		return s;
	}
17136
def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False):
    

    node_orig = 1

    if directed:
        graph = Dot(graph_type='digraph')
    else:
        graph = Dot(graph_type='graph')

    for row in matrix:
        if not directed:
            skip = matrix.index(row)
            r = row[skip:]
        else:
            skip = 0
            r = row
        node_dest = skip + 1

        for e in r:
            if e:
                graph.add_edge(
                    Edge(
                        node_prefix + node_orig,
                        node_prefix + node_dest))
            node_dest += 1
        node_orig += 1

    return graph
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);
	}
1054527
function(connection, collection, from, to, options, cb) {
      return connections[connection].deleteEdges(from, to, options, cb);
    }
1201810
def neighbors( open_list=[], closed_list=[] )
      i,j = free_cell      
      up = moved_matrix_with_parent(i, j, i-1, j, open_list, closed_list)
      down = moved_matrix_with_parent(i, j, i+1, j, open_list, closed_list)
      left = moved_matrix_with_parent(i, j, i, j-1, open_list, closed_list)
      right = moved_matrix_with_parent(i, j, i, j+1, open_list, closed_list)

      moved = []
      moved << up if !up.nil? 
      moved << down if !down.nil? 
      moved << left if !left.nil? 
      moved << right if !right.nil? 

      return moved
    end
966043
def matrix_from_edges(edges):
    ''''''
    max_col = 0
    cols = []
    rows = []
    vals = []
    if type(edges) is defaultdict:
        edge_list = []
        for i, neighbors in edges.items():
            for j in neighbors:
                if i <= j:
                    edge_list.append((i,j))
        edges = edge_list
    for i, edge in enumerate(edges):
        s, t = edge[0], edge[1]
        weight = 1 if len(edge) == 2 else edge[2]
        cols.append(min(s,t))
        cols.append(max(s,t))
        rows.append(i)
        rows.append(i)
        vals.append(weight)
        vals.append(-weight)
        if cols[-1] > max_col:
            max_col = cols[-1]
    return coo_matrix((vals, (rows, cols)), shape=(rows[-1]+1, max_col+1))
1248522
def connectivity_matrix(cm):
    """"""
    # Special case for empty matrices.
    if cm.size == 0:
        return True
    if cm.ndim != 2:
        raise ValueError("Connectivity matrix must be 2-dimensional.")
    if cm.shape[0] != cm.shape[1]:
        raise ValueError("Connectivity matrix must be square.")
    if not np.all(np.logical_or(cm == 1, cm == 0)):
        raise ValueError("Connectivity matrix must contain only binary "
                         "values.")
    return True
737479
def convert_to_adjacency_matrix(matrix):
    
    for i in range(matrix.shape[0]):
        
        if isspmatrix(matrix):
            col = find(matrix[:,i])[2]
        else:
            col = matrix[:,i].T.tolist()[0]

        coeff = max( Fraction(c).limit_denominator().denominator for c in col )
        matrix[:,i] *= coeff

    return matrix
135883
def _sliced_shape(self, shapes, i, major_axis):
        
        sliced_shapes = []
        for desc, axis in zip(shapes, major_axis):
            shape = list(desc.shape)
            if axis >= 0:
                shape[axis] = self.slices[i].stop - self.slices[i].start
            sliced_shapes.append(DataDesc(desc.name, tuple(shape), desc.dtype, desc.layout))
        return sliced_shapes
1162233
def get_adjacent_matrix(self):
        
        edges = self.edges
        num_edges = len(edges) + 1
        adj = np.zeros([num_edges, num_edges])

        for k in range(num_edges - 1):
            adj[edges[k].L, edges[k].R] = 1
            adj[edges[k].R, edges[k].L] = 1

        return adj
1002378
function matrixToOperations (matrix, i, j) {
  if (i === 0 && j === 0) {
    return [];
  } else if (i === 0) {
    return matrixToOperations(matrix, i, j - 1).concat("add");
  } else if (j === 0) {
    return matrixToOperations(matrix, i - 1, j).concat("remove");
  } else {
    var left = matrix[i][j - 1];
    var up = matrix[i - 1][j];
    var upleft = matrix[i - 1][j - 1];

    if (upleft <= up && upleft <= left) {
      if (upleft === matrix[i][j]) {
        return matrixToOperations(matrix, i - 1, j - 1).concat("eq");
      } else {
        return matrixToOperations(matrix, i - 1, j - 1).concat("replace");
      }
    } else if (left <= upleft && left <= up) {
      return matrixToOperations(matrix, i, j - 1).concat("add");
    } else {
      return matrixToOperations(matrix, i - 1, j).concat("remove");
    }
  }
}
316124
private void boundaryLineExteriorLine_(int half_edge, int id_a, int id_b,
			int cluster_index_a, int predicate) {
		if (m_matrix[predicate] == 0)
			return;

		if (m_topo_graph.getHalfEdgeUserIndex(m_topo_graph
				.getHalfEdgePrev(m_topo_graph.getHalfEdgeTwin(half_edge)),
				m_visited_index) != 1) {
			int cluster = m_topo_graph.getHalfEdgeTo(half_edge);
			int clusterParentage = m_topo_graph.getClusterParentage(cluster);

			if ((clusterParentage & id_b) == 0) {
				int index = m_topo_graph.getClusterUserIndex(cluster,
						cluster_index_a);
				assert (index != -1);

				if (index % 2 != 0) {
					assert ((m_topo_graph.getClusterParentage(cluster) & id_a) != 0);
					m_matrix[predicate] = 0;
				}
			}
		}
	}
1241521
def _eliminate_leafs(self, graph):
        
        result = []
        idset = set([id(x) for x in graph])
        for n in graph:
            refset = set([id(x) for x in get_referents(n)])
            if refset.intersection(idset):
                result.append(n)
        return result
998680
private void cutNode(Entry<T> entry) {
        /* Begin by clearing the node's mark, since we just cut it. */
        entry.mIsMarked = false;

        /* Base case: If the node has no parent, we're done. */
        if (entry.mParent == null) return;

        /* Rewire the node's siblings around it, if it has any siblings. */
        if (entry.mNext != entry) { // Has siblings
            entry.mNext.mPrev = entry.mPrev;
            entry.mPrev.mNext = entry.mNext;
        }

        /* If the node is the one identified by its parent as its child,
         * we need to rewrite that pointer to point to some arbitrary other
         * child.
         */
        if (entry.mParent.mChild == entry) {
            /* If there are any other children, pick one of them arbitrarily. */
            if (entry.mNext != entry) {
                entry.mParent.mChild = entry.mNext;
            }
            /* Otherwise, there aren't any children left and we should clear the
             * pointer and drop the node's degree.
             */
            else {
                entry.mParent.mChild = null;
            }
        }

        /* Decrease the degree of the parent, since it just lost a child. */
        --entry.mParent.mDegree;

        /* Splice this tree into the root list by converting it to a singleton
         * and invoking the merge subroutine.
         */
        entry.mPrev = entry.mNext = entry;
        mMin = mergeLists(mMin, entry);

        /* Mark the parent and recursively cut it if it's already been
         * marked.
         */
        if (entry.mParent.mIsMarked)
            cutNode(entry.mParent);
        else
            entry.mParent.mIsMarked = true;

        /* Clear the relocated node's parent; it's now a root. */
        entry.mParent = null;
    }
484070
def apply_cut(self, cut):
        
        return Subsystem(self.network, self.state, self.node_indices,
                         cut=cut, mice_cache=self._mice_cache)