Follows a set of ops assuming their value is False and find blocked Switch paths.

    This is used to prune away parts of the model graph that are only used during the training
    phase (like dropout, batch norm, etc.).
436611
def tensors_blocked_by_false(ops):
    
    blocked = []
    def recurse(op):
        if op.type == "Switch":
            blocked.append(op.outputs[1]) # the true path is blocked since we assume the ops we trace are False
        else:
            for out in op.outputs:
                for c in out.consumers():
                    recurse(c)
    for op in ops:
        recurse(op)

    return blocked
1178956
static public void filterBlockedElements(List<Context> executionContexts) {
    for (Context context : executionContexts) {
      Model model = new Model(context.getModel());
      List<Edge> edges = model.getEdges();
      List<Vertex> vertices = model.getVertices();

      ListIterator<Edge> e_it = edges.listIterator();
      while (e_it.hasNext()) {
        Edge edge = e_it.next();
        if (edge.hasProperty("blocked") &&
            (boolean) edge.getProperty("blocked")) {
          e_it.remove();
        }
      }
      ListIterator<Vertex> v_it = vertices.listIterator();
      while (v_it.hasNext()) {
        Vertex vertex = v_it.next();
        if (vertex.hasProperty("blocked") &&
            (boolean) vertex.getProperty("blocked")) {
          e_it = edges.listIterator();
          while (e_it.hasNext()) {
            Edge e = e_it.next();
            if (e.getSourceVertex() == vertex) {
              e_it.remove();
            } else if (e.getTargetVertex() == vertex) {
              e_it.remove();
            }
          }
          v_it.remove();
        }
      }
      context.setModel(model.build());
    }
  }
212580
private BitSet findPreviouslyDeadBlocks() throws DataflowAnalysisException, CFGBuilderException {
        BitSet deadBlocks = new BitSet();
        ValueNumberDataflow vnaDataflow = classContext.getValueNumberDataflow(method);
        for (Iterator<BasicBlock> i = vnaDataflow.getCFG().blockIterator(); i.hasNext();) {
            BasicBlock block = i.next();
            ValueNumberFrame vnaFrame = vnaDataflow.getStartFact(block);
            if (vnaFrame.isTop()) {
                deadBlocks.set(block.getLabel());
            }
        }

        return deadBlocks;
    }
80381
def _edges_from_permutation(self, feature_pathway_dict):
        
        network_edges = {}
        for feature, pathway_list in feature_pathway_dict.items():
            for i in range(len(pathway_list)):
                for j in range(i + 1, len(pathway_list)):
                    vertex_i = pathway_list[i]
                    vertex_j = pathway_list[j]
                    new_edge = self.edge_tuple(vertex_i, vertex_j)
                    if new_edge not in network_edges:
                        network_edges[new_edge] = []
                    network_edges[new_edge].append(feature)
        self._augment_network(network_edges)
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)
403217
public void breakCycles()
	{
		for (GraphObject go : new ArrayList<GraphObject>(result))
		{
			if (go instanceof Node)
			{
				Node node = (Node) go;

				for (Edge edge : node.getDownstream())
				{
					if (result.contains(edge) && !isSafe(node, edge))
					{
						result.remove(edge);
					}
				}
			}
		}
	}
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
774292
private int skipForward() {
        int numSkips = 0;
        _next = null;
        while (_iterator.hasNext() && getBlock(_next = _iterator.next()) != 0) {
            numSkips++;
            _next = null;
        }
        return numSkips;
    }
1240739
private static void recDrawEdges(SVGPath path, double minx, double miny, List<double[]> r_edges, long[] b) {
    // Draw all "missing" edges
    for(int i = 0; i < r_edges.size(); i++) {
      if(BitsUtil.get(b, i)) {
        continue;
      }
      final double[] edge = r_edges.get(i);
      final double x_i = minx + edge[0], y_i = miny + edge[1];
      if(!isFinite(x_i) || !isFinite(y_i)) {
        continue;
      }
      path.moveTo(minx, miny).drawTo(x_i, y_i);
      // Recursion
      BitsUtil.setI(b, i);
      recDrawEdges(path, x_i, y_i, r_edges, b);
      BitsUtil.clearI(b, i);
    }
  }
827255
def on_batch_end(self, train, **kwargs:Any)->None:
        ""
        if train:
            if self.idx_s >= len(self.lr_scheds): return {'stop_training': True, 'stop_epoch': True}
            self.opt.lr = self.lr_scheds[self.idx_s].step()
            self.opt.mom = self.mom_scheds[self.idx_s].step()
            # when the current schedule is complete we move onto the next
            # schedule. (in 1-cycle there are two schedules)
            if self.lr_scheds[self.idx_s].is_done:
                self.idx_s += 1
375053
private void backpropagate() {
        for (int l = net.length; --l > 0;) {
            backpropagate(net[l], net[l - 1]);
        }
    }
581925
def bfs(self, graph, start):
        
        newstatediag = {}

        # maintain a queue of paths
        queue = []
        visited = []
        # push the first path into the queue
        queue.append(start)
        while queue:
            # get the first path from the queue
            state = queue.pop(0)
            # get the last node from the path
            # visited
            visited.append(state.id)
            # enumerate all adjacent nodes, construct a new path and push it
            # into the queue
            for key in state.trans:
                if state.trans[key] != []:
                    if key not in visited:
                        for nextstate in graph:
                            if graph[nextstate].id == key:
                                queue.append(graph[nextstate])
                                break
        i = 0
        for state in graph:
            if graph[state].id in visited:
                newstatediag[i] = graph[state]
                i = i + 1

        return newstatediag
451374
def find_paths_breadth_first(from_target, to_target, log):
  """"""
  log.debug('Looking for all paths from {} to {}'.format(from_target.address.reference(),
                                                         to_target.address.reference()))

  if from_target == to_target:
    yield [from_target]
    return

  visited_edges = set()
  to_walk_paths = deque([[from_target]])
  while len(to_walk_paths) > 0:
    cur_path = to_walk_paths.popleft()
    target = cur_path[-1]

    if len(cur_path) > 1:
      prev_target = cur_path[-2]
    else:
      prev_target = None
    current_edge = (prev_target, target)

    if current_edge not in visited_edges:
      for dep in target.dependencies:
        dep_path = cur_path + [dep]
        if dep == to_target:
          yield dep_path
        else:
          to_walk_paths.append(dep_path)
      visited_edges.add(current_edge)
655469
private boolean removeUnnecesaryEdgesIfAny(final DirectedGraph<Object, JobGraphLink> graph,
            final SourceColumnFinder sourceColumnFinder) {
        final Collection<JobGraphLink> allLinks = graph.getEdges();
        final List<JobGraphLink> linksToRemove = new ArrayList<>();
        for (final JobGraphLink link : allLinks) {
            boolean removeable = true;

            if (link.getRequirement() != null) {
                // only links without requirements are candidates for removal
                removeable = false;
            }

            if (removeable) {
                final Object toVertex = link.getTo();
                final Collection<JobGraphLink> edgesGoingIn = graph.getInEdges(toVertex);
                if (edgesGoingIn.size() <= 1) {
                    // if this is the only edge going in, there is no
                    // special interest
                    removeable = false;
                }

                if (removeable) {
                    // check if these links represents a "shortcut" path that
                    // can be left out
                    for (final JobGraphLink edgeGoingIn : edgesGoingIn) {
                        if (edgeGoingIn != link) {
                            if (!isEdgeShortcutFor(graph, link, edgeGoingIn)) {
                                removeable = false;
                                break;
                            }
                        }
                    }

                    if (removeable) {
                        logger.debug("Removing unnecesary JobGraphLink: {}", link);
                        linksToRemove.add(link);
                    }
                }
            }
        }

        for (final JobGraphLink link : linksToRemove) {
            graph.removeEdge(link);
        }

        return !linksToRemove.isEmpty();
    }
628717
def _blockedPairs(self, blocks):
        

        block, blocks = core.peek(blocks)
        self._checkBlock(block)

        product = itertools.product

        pairs = (product(base, target) for base, target in blocks)

        return pairs
257512
def shake_shake_skip_connection(x, output_filters, stride, is_training):
  """"""
  curr_filters = common_layers.shape_list(x)[-1]
  if curr_filters == output_filters:
    return x
  stride_spec = [1, stride, stride, 1]
  # Skip path 1.
  path1 = tf.nn.avg_pool(x, [1, 1, 1, 1], stride_spec, "VALID")
  path1 = tf.layers.conv2d(
      path1, int(output_filters / 2), (1, 1), padding="SAME", name="path1_conv")

  # Skip path 2.
  pad_arr = [[0, 0], [0, 1], [0, 1], [0, 0]]  # First pad with 0's then crop.
  path2 = tf.pad(x, pad_arr)[:, 1:, 1:, :]
  path2 = tf.nn.avg_pool(path2, [1, 1, 1, 1], stride_spec, "VALID")
  path2 = tf.layers.conv2d(
      path2, int(output_filters / 2), (1, 1), padding="SAME", name="path2_conv")

  # Concat and apply BN.
  final_path = tf.concat(values=[path1, path2], axis=-1)
  final_path = tf.layers.batch_normalization(
      final_path, training=is_training, name="final_path_bn")
  return final_path
908676
def _parse_loops_from_graph(self, graph):
        
        outtop = []
        outall = []
        for subg in networkx.strongly_connected_component_subgraphs(graph):
            if len(subg.nodes()) == 1:
                if len(list(subg.successors(list(subg.nodes())[0]))) == 0:
                    continue
            thisloop, allloops = self._parse_loop_graph(subg, graph)
            if thisloop is not None:
                outall += allloops
                outtop.append(thisloop)
        return outtop, outall