Prune influence map to include only edges where the object of the
        upstream rule matches the subject of the downstream rule.
5245
def prune_influence_map_subj_obj(self):
        """"""
        def get_rule_info(r):
            result = {}
            for ann in self.model.annotations:
                if ann.subject == r:
                    if ann.predicate == 'rule_has_subject':
                        result['subject'] = ann.object
                    elif ann.predicate == 'rule_has_object':
                        result['object'] = ann.object
            return result
        im = self.get_im()
        rules = im.nodes()
        edges_to_prune = []
        for r1, r2 in itertools.permutations(rules, 2):
            if (r1, r2) not in im.edges():
                continue
            r1_info = get_rule_info(r1)
            r2_info = get_rule_info(r2)
            if 'object' not in r1_info or 'subject' not in r2_info:
                continue
            if r1_info['object'] != r2_info['subject']:
                logger.info("Removing edge %s --> %s" % (r1, r2))
                edges_to_prune.append((r1, r2))
        im.remove_edges_from(edges_to_prune)
584000
def _(s: Influence) -> bool:
    
    return is_grounded(s.subj) and is_grounded(s.obj)
1195888
def build_upstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate:
    """"""
    nodes = set(nodes)

    def upstream_filter(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool:
        """Pass for relations for which one of the given nodes is the object."""
        return v in nodes and graph[u][v][k][RELATION] in CAUSAL_RELATIONS

    return upstream_filter
158237
def remove_filtered_nodes(graph, node_predicates=None):
    
    nodes = list(filter_nodes(graph, node_predicates=node_predicates))
    graph.remove_nodes_from(nodes)
1296468
def transitively_reduce(self):
        
        removals = set()

        for from_node, neighbors in self._edges.items():
            childpairs = \
                [(c1, c2) for c1 in neighbors for c2 in neighbors if c1 != c2]

            for child1, child2 in childpairs:
                if self.has_path(child1, child2) \
                   and not self.has_path(child1, from_node):
                    removals.add((from_node, child2))

        for edge in removals:
            self.remove_edge(edge[0], edge[1])
680838
def _match_value_filter(self, p, value):
        
        return self._VALUE_FILTER_MAP[p[0]](value[p[1]], p[2])
579381
private Graph<K, VV, EV> removeVertices(DataSet<Vertex<K, VV>> verticesToBeRemoved) {

		DataSet<Vertex<K, VV>> newVertices = getVertices().coGroup(verticesToBeRemoved).where(0).equalTo(0)
				.with(new VerticesRemovalCoGroup<>()).name("Remove vertices");

		DataSet <Edge< K, EV>> newEdges = newVertices.join(getEdges()).where(0).equalTo(0)
				// if the edge source was removed, the edge will also be removed
				.with(new ProjectEdgeToBeRemoved<>()).name("Edges to be removed")
				// if the edge target was removed, the edge will also be removed
				.join(newVertices).where(1).equalTo(0)
				.with(new ProjectEdge<>()).name("Remove edges");

		return new Graph<>(newVertices, newEdges, context);
	}
1028653
def filterEffect(self, teff):
        
        ret = False
        for effect in teff.effects:
            ret = self._matchAnyEffects(effect) or ret
        return ret
1297558
def relations_of(self, target, include_object=False):
        '''  '''
        relations = (target if isinstance(target, RamGraphDBNode) else self._get_item_node(target)).outgoing
        if include_object:
            for k in relations:
                for v in relations[k]:
                    if hasattr(v, 'obj'): # filter dead links
                        yield k, v.obj
        else:
            yield from relations
1154052
def get_upstream_causal_subgraph(graph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]):
    
    return get_subgraph_by_edge_filter(graph, build_upstream_edge_predicate(nbunch))
497770
def _prune_components(self):
        
        seen_components = set(map(lambda x: x.component, self._remote_candidates))
        missing_components = self._components - seen_components
        if missing_components:
            self.__log_info('Components %s have no candidate pairs' % missing_components)
            self._components = seen_components
557863
def prune_feed_map(meta_graph, feed_map):
  """"""
  node_names = [x.name + ":0" for x in meta_graph.graph_def.node]
  keys_to_delete = []
  for k, _ in feed_map.items():
    if k not in node_names:
      keys_to_delete.append(k)
  for k in keys_to_delete:
    del feed_map[k]
464651
void removeEdgeRole(EdgeRole er, boolean preserveData) {
        if (er.getVertexLabel() != this) {
            throw new IllegalStateException("Trying to remove a EdgeRole from a non owner VertexLabel");
        }
        Collection<VertexLabel> ers;
        switch (er.getDirection()) {
            // we don't support both
            case BOTH:
                throw new IllegalStateException("BOTH is not a supported direction");
            case IN:
                ers = er.getEdgeLabel().getInVertexLabels();
                break;
            case OUT:
                ers = er.getEdgeLabel().getOutVertexLabels();
                break;
            default:
                throw new IllegalStateException("Unknown direction!");
        }
        if (!ers.contains(this)) {
            throw new IllegalStateException("Trying to remove a EdgeRole from a non owner VertexLabel");
        }
        // the edge had only this vertex on that direction, remove the edge
        if (ers.size() == 1) {
            er.getEdgeLabel().remove(preserveData);
        } else {
            getSchema().getTopology().lock();
            switch (er.getDirection()) {
                // we don't support both
                case BOTH:
                    throw new IllegalStateException("BOTH is not a supported direction");
                case IN:
                    uncommittedRemovedInEdgeLabels.put(er.getEdgeLabel().getFullName(), EdgeRemoveType.ROLE);
                    er.getEdgeLabel().removeInVertexLabel(this, preserveData);
                    break;
                case OUT:
                    uncommittedRemovedOutEdgeLabels.put(er.getEdgeLabel().getFullName(), EdgeRemoveType.ROLE);
                    er.getEdgeLabel().removeOutVertexLabel(this, preserveData);
                    break;
            }

            this.getSchema().getTopology().fire(er, "", TopologyChangeAction.DELETE);
        }
    }
1013775
def nameTuple(s: Influence) -> Tuple[str, str]:
    
    return top_grounding(s.subj), top_grounding(s.obj)
219773
def sparsify(sess, eval_model, pruning_strategy, pruning_params):
  """"""
  weights = tf.trainable_variables()

  def should_prune(name):
    """Whether to prune a weight or not."""
    in_whitelist = not pruning_params.white_list or any(
        e in name for e in pruning_params.white_list)
    in_blacklist = any(e in name for e in pruning_params.black_list)

    if pruning_params.white_list and not in_whitelist:
      return False
    elif in_blacklist:
      return False

    return True

  weights = [w for w in weights if should_prune(w.name)]
  tf.logging.info("Pruning weights: %s" % weights)
  unpruned_weights = sess.run(weights)

  reset_op = tf.no_op()
  for w, ow in zip(weights, unpruned_weights):
    op = tf.assign(w, ow)
    reset_op = tf.group(reset_op, op)

  for sparsity in pruning_params.sparsities:
    set_weights_op = tf.no_op()
    for w in weights:
      op = tf.assign(w, pruning_strategy(w, sparsity))
      set_weights_op = tf.group(set_weights_op, op)
    sess.run(set_weights_op)

    acc = eval_model()
    tf.logging.info("\tPruning to sparsity = %f: acc = %f" % (sparsity, acc))
    sess.run(reset_op)
1309932
def _prune_edges(G, X, traj_lengths, pruning_thresh=0.1, verbose=False):
  ''''''
  W = G.matrix('dense', copy=True)
  degree = G.degree(kind='out', weighted=False)
  i = 0
  num_bad = 0
  for n in traj_lengths:
    s, t = np.nonzero(W[i:i+n-1])
    graph_edges = X[t] - X[s+i]
    traj_edges = np.diff(X[i:i+n], axis=0)
    traj_edges = np.repeat(traj_edges, degree[i:i+n-1], axis=0)
    theta = paired_distances(graph_edges, traj_edges, 'cosine')
    bad_edges = theta > pruning_thresh
    s, t = s[bad_edges], t[bad_edges]
    if verbose:  # pragma: no cover
      num_bad += np.count_nonzero(W[s,t])
    W[s,t] = 0
    i += n
  if verbose:  # pragma: no cover
    print('removed %d bad edges' % num_bad)
  return Graph.from_adj_matrix(W)
985647
def prune_if_smaller_than(self, small_size, a_or_u):
        ""
        if self._prune_all_if_small(small_size, a_or_u):
            return

        for node in self._nodes:
            node.prune_if_smaller_than(small_size, a_or_u)

        self._prune_some_if_small(small_size, a_or_u)