The indices of nodes in the mechanism system.
966370
def mechanism_indices(self, direction):
        """"""
        return {
            Direction.CAUSE: self.effect_indices,
            Direction.EFFECT: self.cause_indices
        }[direction]
383908
def compute_rpo(self):
        
        nb = len(self.nodes) + 1
        for node in self.post_order():
            node.num = nb - node.po
        self.rpo = sorted(self.nodes, key=lambda n: n.num)
48485
def expressions(self):
        
        if self._expressions is None:
            expressions = [n.expression for n in self.nodes]
            expressions = [e for e in expressions if e]
            self._expressions = expressions
        return self._expressions
1174769
function(node, l, b, r, t)
{
    return (max(node.bb_r, r) - min(node.bb_l, l))*(max(node.bb_t, t) - min(node.bb_b, b));
}
668497
def fig_network_input_structure(fig, params, bottom=0.1, top=0.9, transient=200, T=[800, 1000], Df= 0., mlab= True, NFFT=256, srate=1000,
             window=plt.mlab.window_hanning, noverlap=256*3/4, letters='abcde', flim=(4, 400),
             show_titles=True, show_xlabels=True, show_CSD=False):
    '''
    
    
    '''
    #load spike as database
    networkSim = CachedNetwork(**params.networkSimParams)
    if analysis_params.bw:
        networkSim.colors = phlp.get_colors(len(networkSim.X))


    # ana_params.set_PLOS_2column_fig_style(ratio=ratio)
    # fig = plt.figure()
    # fig.subplots_adjust(left=0.06, right=0.94, bottom=0.09, top=0.92, wspace=0.5, hspace=0.2)
    
    #use gridspec to get nicely aligned subplots througout panel
    gs1 = gridspec.GridSpec(5, 5, bottom=bottom, top=top)
    
    
    ############################################################################ 
    # A part, full dot display
    ############################################################################
    
    ax0 = fig.add_subplot(gs1[:, 0])
    phlp.remove_axis_junk(ax0)
    phlp.annotate_subplot(ax0, ncols=5, nrows=1, letter=letters[0],
                     linear_offset=0.065)
   
    x, y = networkSim.get_xy(T, fraction=1)
    networkSim.plot_raster(ax0, T, x, y,
                           markersize=0.2, marker='_',
                           alpha=1.,
                           legend=False, pop_names=True,
                           rasterized=False)
    ax0.set_ylabel('population', labelpad=0.)
    ax0.set_xticks([800,900,1000])
   
    if show_titles:
        ax0.set_title('spiking activity',va='center')
    if show_xlabels:
        ax0.set_xlabel(r'$t$ (ms)', labelpad=0.)
    else:
        ax0.set_xlabel('')
      
    ############################################################################
    # B part, firing rate spectra
    ############################################################################

  
    # Get the firing rate from Potjan Diesmann et al network activity
    #collect the spikes x is the times, y is the id of the cell.
    T_all=[transient, networkSim.simtime]
    bins = np.arange(transient, networkSim.simtime+1)
        
    x, y = networkSim.get_xy(T_all, fraction=1)

    # create invisible axes to position labels correctly
    ax_ = fig.add_subplot(gs1[:, 1])
    phlp.annotate_subplot(ax_, ncols=5, nrows=1, letter=letters[1],
                                 linear_offset=0.065)
    if show_titles:
        ax_.set_title('firing rate PSD', va='center')
    
    ax_.axis('off')

    colors = phlp.get_colors(len(params.Y))+['k']
    
    COUNTER = 0
    label_set = False
    
    tits = ['L23E/I', 'L4E/I', 'L5E/I', 'L6E/I', 'TC']

    if x['TC'].size > 0:
        TC = True
    else:
        TC = False

    BAxes = []
    for i, X in enumerate(networkSim.X):

        if i % 2 == 0:
            ax1 = fig.add_subplot(gs1[COUNTER, 1])
            phlp.remove_axis_junk(ax1)

            if x[X].size > 0:
                ax1.text(0.05, 0.85, tits[COUNTER],
                    horizontalalignment='left',
                    verticalalignment='bottom',
                    transform=ax1.transAxes)
            BAxes.append(ax1)


        #firing rate histogram
        hist = np.histogram(x[X], bins=bins)[0].astype(float)
        hist -= hist.mean()
        
        if mlab:
            Pxx, freqs=plt.mlab.psd(hist, NFFT=NFFT,
                                    Fs=srate, noverlap=noverlap, window=window)
        else:
            [freqs, Pxx] = hlp.powerspec([hist], tbin= 1.,
                                        Df=Df, pointProcess=False)
            mask = np.where(freqs >= 0.)
            freqs = freqs[mask]
            Pxx = Pxx.flatten()
            Pxx = Pxx[mask]
            Pxx = Pxx/(T_all[1]-T_all[0])**2
        
        if x[X].size > 0:
            ax1.loglog(freqs[1:], Pxx[1:],
                       label=X, color=colors[i],
                       clip_on=True)
            ax1.axis(ax1.axis('tight'))
            ax1.set_ylim([5E-4,5E2])
            ax1.set_yticks([1E-3,1E-1,1E1])
            if label_set == False:
                ax1.set_ylabel(r'(s$^{-2}$/Hz)', labelpad=0.)
                label_set = True
            if i > 1:
                ax1.set_yticklabels([])
            if i >= 6 and not TC and show_xlabels or X == 'TC' and TC and show_xlabels:
                ax1.set_xlabel('$f$ (Hz)', labelpad=0.)
            if TC and i < 8 or not TC and i < 6:
                ax1.set_xticklabels([])    

        else:
            ax1.axis('off')
                       
        ax1.set_xlim(flim)
           
        
        if i % 2 == 0:
            COUNTER += 1
        
        ax1.yaxis.set_minor_locator(plt.NullLocator())
        



    ############################################################################
    # c part, LFP traces and CSD color plots
    ############################################################################
   
    ax2 = fig.add_subplot(gs1[:, 2])
    
    phlp.annotate_subplot(ax2, ncols=5, nrows=1, letter=letters[2],
                     linear_offset=0.065)


    phlp.remove_axis_junk(ax2)
    plot_signal_sum(ax2, params,
                    fname=os.path.join(params.savefolder, 'LFPsum.h5'),
                    unit='mV', T=T, ylim=[-1600, 40],
                    rasterized=False)
    
    # CSD background colorplot
    if show_CSD:
        im = plot_signal_sum_colorplot(ax2, params, os.path.join(params.savefolder, 'CSDsum.h5'),
                                  unit=r'($\mu$Amm$^{-3}$)', T=[800, 1000],
                                  colorbar=False,
                                  ylim=[-1600, 40], fancy=False, cmap=plt.cm.get_cmap('bwr_r', 21),
                                  rasterized=False)
        cb = phlp.colorbar(fig, ax2, im,
                           width=0.05, height=0.4,
                           hoffset=-0.05, voffset=0.3)
        cb.set_label('($\mu$Amm$^{-3}$)', labelpad=0.1)

    ax2.set_xticks([800,900,1000])
    ax2.axis(ax2.axis('tight'))
     
    if show_titles:
        if show_CSD:
            ax2.set_title('LFP & CSD', va='center')
        else:
            ax2.set_title('LFP', va='center')
    if show_xlabels:
        ax2.set_xlabel(r'$t$ (ms)', labelpad=0.)
    else:
        ax2.set_xlabel('')
  
 
    ############################################################################
    # d part, LFP power trace for each layer
    ############################################################################

    freqs, PSD = calc_signal_power(params, fname=os.path.join(params.savefolder,
                                                           'LFPsum.h5'),
                                        transient=transient, Df=Df, mlab=mlab,
                                        NFFT=NFFT, noverlap=noverlap,
                                        window=window)

    channels = [0, 3, 7, 11, 13]
  
    # create invisible axes to position labels correctly
    ax_ = fig.add_subplot(gs1[:, 3])
    phlp.annotate_subplot(ax_, ncols=5, nrows=1, letter=letters[3],
                                 linear_offset=0.065)

    if show_titles:
        ax_.set_title('LFP PSD',va='center')
    
    ax_.axis('off')

    for i, ch in enumerate(channels):

        ax = fig.add_subplot(gs1[i, 3])
        phlp.remove_axis_junk(ax)

        if i == 0:
            ax.set_ylabel('(mV$^2$/Hz)', labelpad=0)

        ax.loglog(freqs[1:],PSD[ch][1:], color='k')
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        if i < 4:
            ax.set_xticklabels([])
        ax.text(0.75, 0.85,'ch. %i' %(channels[i]+1),
                horizontalalignment='left',
                verticalalignment='bottom',
                fontsize=6,
                transform=ax.transAxes)
        ax.tick_params(axis='y', which='minor', bottom='off')
        ax.axis(ax.axis('tight'))
        ax.yaxis.set_minor_locator(plt.NullLocator())

        ax.set_xlim(flim)
        ax.set_ylim(1E-7,2E-4)
        if i != 0 :
            ax.set_yticklabels([])


    if show_xlabels:
        ax.set_xlabel('$f$ (Hz)', labelpad=0.)
    
    ############################################################################
    # e part signal power
    ############################################################################
    
    ax4 = fig.add_subplot(gs1[:, 4])

    phlp.annotate_subplot(ax4, ncols=5, nrows=1, letter=letters[4],
                     linear_offset=0.065)
  
    fname=os.path.join(params.savefolder, 'LFPsum.h5')
    im = plot_signal_power_colorplot(ax4, params, fname=fname, transient=transient, Df=Df,
                                mlab=mlab, NFFT=NFFT, window=window,
                                cmap=plt.cm.get_cmap('gray_r', 12),
                                vmin=1E-7, vmax=1E-4)
    phlp.remove_axis_junk(ax4)

    ax4.set_xlim(flim)

    cb = phlp.colorbar(fig, ax4, im,
                       width=0.05, height=0.5,
                       hoffset=-0.05, voffset=0.5)
    cb.set_label('(mV$^2$/Hz)', labelpad=0.1)


    if show_titles:
        ax4.set_title('LFP PSD', va='center')
    if show_xlabels:
        ax4.set_xlabel(r'$f$ (Hz)', labelpad=0.)
    else:
        ax4.set_xlabel('')
       
    return fig
677099
def mechanism(self):
        """"""
        return tuple(sorted(
            chain.from_iterable(part.mechanism for part in self)))
1312897
def repertoire(self, direction, mechanism, purview):
        
        system = self.system[direction]
        node_labels = system.node_labels

        if not set(purview).issubset(self.purview_indices(direction)):
            raise ValueError('{} is not a {} purview in {}'.format(
                fmt.fmt_mechanism(purview, node_labels), direction, self))

        if not set(mechanism).issubset(self.mechanism_indices(direction)):
            raise ValueError('{} is no a {} mechanism in {}'.format(
                fmt.fmt_mechanism(mechanism, node_labels), direction, self))

        return system.repertoire(direction, mechanism, purview)
684930
def neighbors(self, key):
        """"""
        return {n: attr["bond"] for n, attr in self.graph[key].items()}
523490
def define_nodal_balances(network,snapshots):
    

    #dictionary for constraints
    network._p_balance = {(bus,sn) : LExpression()
                          for bus in network.buses.index
                          for sn in snapshots}

    efficiency = get_switchable_as_dense(network, 'Link', 'efficiency', snapshots)

    for cb in network.links.index:
        bus0 = network.links.at[cb,"bus0"]
        bus1 = network.links.at[cb,"bus1"]

        for sn in snapshots:
            network._p_balance[bus0,sn].variables.append((-1,network.model.link_p[cb,sn]))
            network._p_balance[bus1,sn].variables.append((efficiency.at[sn,cb],network.model.link_p[cb,sn]))

    #Add any other buses to which the links are attached
    for i in [int(col[3:]) for col in network.links.columns if col[:3] == "bus" and col not in ["bus0","bus1"]]:
        efficiency = get_switchable_as_dense(network, 'Link', 'efficiency{}'.format(i), snapshots)
        for cb in network.links.index[network.links["bus{}".format(i)] != ""]:
            bus = network.links.at[cb, "bus{}".format(i)]
            for sn in snapshots:
                network._p_balance[bus,sn].variables.append((efficiency.at[sn,cb],network.model.link_p[cb,sn]))


    for gen in network.generators.index:
        bus = network.generators.at[gen,"bus"]
        sign = network.generators.at[gen,"sign"]
        for sn in snapshots:
            network._p_balance[bus,sn].variables.append((sign,network.model.generator_p[gen,sn]))

    load_p_set = get_switchable_as_dense(network, 'Load', 'p_set', snapshots)
    for load in network.loads.index:
        bus = network.loads.at[load,"bus"]
        sign = network.loads.at[load,"sign"]
        for sn in snapshots:
            network._p_balance[bus,sn].constant += sign*load_p_set.at[sn,load]

    for su in network.storage_units.index:
        bus = network.storage_units.at[su,"bus"]
        sign = network.storage_units.at[su,"sign"]
        for sn in snapshots:
            network._p_balance[bus,sn].variables.append((sign,network.model.storage_p_dispatch[su,sn]))
            network._p_balance[bus,sn].variables.append((-sign,network.model.storage_p_store[su,sn]))

    for store in network.stores.index:
        bus = network.stores.at[store,"bus"]
        sign = network.stores.at[store,"sign"]
        for sn in snapshots:
            network._p_balance[bus,sn].variables.append((sign,network.model.store_p[store,sn]))
617529
private void cascadingRankChange(Node<K, V> y) {
        while (y.mark == true) {
            y.mark = false;
            if (y.rank > 0) {
                --y.rank;
            }
            y = y.parent;
        }
        y.mark = true;
        if (y.rank > 0) {
            --y.rank;
        }
    }
398862
def _throat_props(self):
        
        '''
        network = self.network
        net_Ts = network.throats(self.name)
        conns = network['throat.conns'][net_Ts]
        p1 = conns[:, 0]
        p2 = conns[:, 1]
        coords = network['pore.coords']
        normals = tr.unit_vector(coords[p2]-coords[p1])
        self['throat.normal'] = normals
        self['throat.centroid'] = (coords[p1] + coords[p2])/2
        self['throat.incenter'] = self['throat.centroid']
191439
def dominance_frontier(start_node = self.enter, dom_tree)
      vertices.inject(Hash.new { |h, k| h[k] = Set.new }) do |result, b|
        preds = b.real_predecessors
        if preds.size >= 2
          preds.each do |p|
            b_dominator = dom_tree[b].successors.first
            break unless b_dominator
            runner = dom_tree[p]
            while runner && runner != b_dominator
              result[runner] << b
              runner = runner.successors.first
            end
          end
        end
        result
      end
    end
1015058
function nodeValue(node1, node2) {
    return (node1.dist + heuristic(node1.point)) - (node2.dist + heuristic(node2.point));
  }
718280
def potential_purviews(self, direction, mechanism, purviews=False):
        """"""
        all_purviews = utils.powerset(self.node_indices)
        return irreducible_purviews(
            self.cm, direction, mechanism, all_purviews)
515320
function computeNodeBreadths() {
    var remainingNodes = nodes,
        nextNodes,
        x = 0;

    while (remainingNodes.length) {
      nextNodes = [];
      remainingNodes.forEach(function(node) {
        node.x = x;
        node.dx = nodeWidth;
        node.sourceLinks.forEach(function(link) {
          if (!link.causesCycle) {
            nextNodes.push(link.target);
          }
        });
      });
      remainingNodes = nextNodes;
      ++x;
    }

    //
    moveSinksRight(x);
    scaleNodeBreadths((size[0] - nodeWidth) / (x - 1));
  }
2728
private DNode calculateSourceNode() {
        DNode result = DNode.NOT_FOUND;
        
        for (DNode node : nodes) {
            List<DLink> links = getLinksTo(node);
            if (links.size() == 0) {
                result = node;
                break;
            }
        }
        return result;
    }
157619
public void getMaxBranching(CompleteGraph graph, int root,
                                int[] invertedMaxBranching) {
        // Number of nodes.
        int numNodes = graph.getNumberOfNodes();

        // Branching.
        SparseGraph maxBranching = new SparseGraph();

        /*
         * Weighted edges used to allow weight modification and avoid any impact
         * in the original graph.
         */
        SimpleWeightedEdge[][] edges = new SimpleWeightedEdge[numNodes][numNodes];

        // Disjoint sets for the strongly connected components (SCC).
        DisjointSets sPartition = new DisjointSets(numNodes);
        // Disjoint sets for the weakly connected components (WCC).
        DisjointSets wPartition = new DisjointSets(numNodes);

        /*
         * Priority queues for each strongly connected component. In the
         * beginning, each SCC is composed by exactly one node.
         */
        ArrayList<PriorityQueue<SimpleWeightedEdge>> incomingEdges = new ArrayList<PriorityQueue<SimpleWeightedEdge>>(
                                                                                                                      numNodes);

        // Unique incoming edges for each SCC. Initially, no SCC has such edge.
        SimpleWeightedEdge[] enter = new SimpleWeightedEdge[numNodes];

        /*
         * List of root components, i.e., SCCs that have no incoming edges
         * (enter[scc] == null). In the beginning, every SCC is a root
         * component.
         */
        LinkedList<Integer> rootComponents = new LinkedList<Integer>();

        // Root node of each root component.
        int[] min = new int[numNodes];

        for (int node = 0; node < numNodes; ++node) {

            // Every SCC is a root component.
            rootComponents.add(node);

            /*
             * The head of its root component is its only node. This array is
             * called min in Tarjan's paper.
             */
            min[node] = node;

            // Create a priority queue for each SCC.
            PriorityQueue<SimpleWeightedEdge> sccPriorityQueue = new PriorityQueue<SimpleWeightedEdge>();
            incomingEdges.add(sccPriorityQueue);

            // No incoming edge is considered (nor created) for the root node.
            if (node != root) {
                /*
                 * Create and add all incoming edges of <code>node</code> to its
                 * SCC priority queue.
                 */
                for (int from = 0; from < numNodes; ++from) {
                    if (from == node)
                        // Skip autocycle edges.
                        continue;
                    // Create an weighted edge and add it to the priority queue.
                    edges[from][node] = new SimpleWeightedEdge(from, node,
                                                               graph.getEdgeWeight(from, node));
                    sccPriorityQueue.add(edges[from][node]);
                }
            }
        }

        // Root component with no available incoming edges.
        LinkedList<Integer> doneRootComponents = new LinkedList<Integer>();

        while (!rootComponents.isEmpty()) {
            // Get some arbitrary root component.
            int sccTo = rootComponents.pop();
            // Maximum edge entering the root component 'sccTo'.
            SimpleWeightedEdge maxInEdge = incomingEdges.get(sccTo).poll();

            if (maxInEdge == null) {
                // No edge left to consider in this component.
                doneRootComponents.add(sccTo);
                continue;
            }

            // SCC component of edge 'e' from node: e = (from, to).
            int sccFrom = sPartition.find(maxInEdge.from);

            if (sccFrom == sccTo) {
                // Skip, for now, this component.
                rootComponents.add(sccTo);
                continue;
            }

            // Include the selected edge in the current branching.
            maxBranching.addEdge(maxInEdge.from, maxInEdge.to);

            // SCC component of edge 'e' from node, where e = (from, to).
            int wssFrom = wPartition.find(maxInEdge.from);
            // SCC component of edge 'e' to node, where e = (from, to).
            int wssTo = wPartition.find(maxInEdge.to);

            // Edge connects two weakly connected components.
            if (wssFrom != wssTo) {
                wPartition.union(wssFrom, wssTo);
                enter[sccTo] = maxInEdge;
                continue;
            }

            /*
             * Edge is within the same WCC, thus it inclusion will create a new
             * SCC by uniting some old SCCs (the ones on the path from e.to to
             * e.from).
             */
            double minEdgeWeight = Double.POSITIVE_INFINITY;
            int minScc = -1;
            SimpleWeightedEdge tmpEdge = maxInEdge;
            while (tmpEdge != null) {
                if (tmpEdge.weight < minEdgeWeight) {
                    minEdgeWeight = tmpEdge.weight;
                    minScc = sPartition.find(tmpEdge.to);
                }

                tmpEdge = enter[sPartition.find(tmpEdge.from)];
            }

            // Increment incoming edges weight.
            double inc = minEdgeWeight - maxInEdge.weight;
            for (SimpleWeightedEdge e : incomingEdges.get(sccTo))
                e.weight += inc;

            // Set the head of the current SCC.
            min[sccTo] = min[minScc];

            // Include all used SCCs in the current SCC.
            tmpEdge = enter[sccFrom];
            while (tmpEdge != null) {
                /*
                 * Increment incoming edges weight and include them in the
                 * current SCC priority queue.
                 */
                int tmpSccTo = sPartition.find(tmpEdge.to);
                inc = minEdgeWeight - tmpEdge.weight;
                for (SimpleWeightedEdge e : incomingEdges.get(tmpSccTo)) {
                    e.weight += inc;
                    incomingEdges.get(sccTo).add(e);
                }
                // Remove the priority queue of this SCC.
                incomingEdges.set(tmpSccTo, null);
                sPartition.union(sccTo, tmpSccTo);

                // Next edge.
                tmpEdge = enter[sPartition.find(tmpEdge.from)];
            }

            // Include the new SCC to be considered in the future.
            rootComponents.add(sccTo);
        }

        // Invert the maximum branching.
        boolean[] visited = new boolean[numNodes];
        for (int scc : doneRootComponents)
            invertMaximumBranching(min[scc], maxBranching, visited,
                                   invertedMaxBranching);
    }

    /**
     * Walk through the given branching from <code>node</code> and store the
     * inverted branching in <code>invertedMaxBranching</code>.
     * 
     * In fact, the given branching can include cycles. But it is only necessary
     * to disconsider the last edges of each cycle to get the real branching.
     * Thus, we use the array <code>visited</code>.
     * 
     * @param node
     * @param branching
     * @param visited
     * @param invertedMaxBranching
     */
    private void invertMaximumBranching(int node, SparseGraph branching,
                                        boolean[] visited, int[] invertedMaxBranching) {
        visited[node] = true;
        Set<Integer> toNodes = branching.getOutEdges(node);
        if (toNodes == null)
            return;
        for (int to : toNodes) {
            if (visited[to])
                continue;
            invertedMaxBranching[to] = node;
            invertMaximumBranching(to, branching, visited, invertedMaxBranching);
        }
    }