Connects MV generators (graph nodes) to grid (graph)

        Args
        ----
        debug: bool, defaults to False
            If True, information is printed during process
764085
def connect_generators(self, debug=False):
        

        self._graph = mv_connect.mv_connect_generators(self.grid_district, self._graph, debug)
1021210
def plot_mv_line_loading(self, **kwargs):
        
        if self.network.pypsa is not None and \
                self.network.results.i_res is not None:
            plots.mv_grid_topology(
                self.network.pypsa, self.network.config,
                timestep=kwargs.get('timestep', None),
                line_color='loading',
                node_color=kwargs.get('node_color', None),
                line_load=self.network.results.s_res(),
                filename=kwargs.get('filename', None),
                arrows=kwargs.get('arrows', None),
                grid_district_geom=kwargs.get('grid_district_geom', True),
                background_map=kwargs.get('background_map', True),
                voltage=self.network.results.v_res(),
                limits_cb_lines=kwargs.get('limits_cb_lines', None),
                limits_cb_nodes=kwargs.get('limits_cb_nodes', None),
                xlim=kwargs.get('xlim', None), ylim=kwargs.get('ylim', None),
                lines_cmap=kwargs.get('lines_cmap', 'inferno_r'),
                title=kwargs.get('title', ''),
                scaling_factor_line_width=kwargs.get(
                    'scaling_factor_line_width', None))
        else:
            if self.network.pypsa is None:
                logging.warning("pypsa representation of MV grid needed to "
                                "plot line loading.")
            if self.network.results.i_res is None:
                logging.warning("Currents `i_res` from power flow analysis "
                                "must be available to plot line loading.")
603114
def connect(nodes):
    '''
    
    '''
    for a, b in zip(nodes[:-1], nodes[1:]):
        a.output = b
    b.output = queues.Queue()
329124
def connect_signals(self):
        
        # Connect the signals inside each Work.
        for work in self:
            work.connect_signals()

        # Observe the nodes that must reach S_OK in order to call the callbacks.
        for cbk in self._callbacks:
            #cbk.enable()
            for dep in cbk.deps:
                logger.info("connecting %s \nwith sender %s, signal %s" % (str(cbk), dep.node, dep.node.S_OK))
                dispatcher.connect(self.on_dep_ok, signal=dep.node.S_OK, sender=dep.node, weak=False)
406742
def generate_network(user=None, reset=False):
    

    token = collect_token()

    try:
        gh = login(token=token)
        root_user = gh.user(user)
    except Exception, e:
        # Failed to login using the token, github3.models.GitHubError
        raise e

    graph_nodes = []
    graph_edges = []

    username = user if user is not None else root_user.login

    if not is_cached(username_to_file(username)) or reset:
        graph_nodes.append(username)

        # @TODO: take care of the 'rate limit exceeding' if imposed
        try:
            for person in gh.iter_following(username):
                graph_nodes.append(str(person))
                graph_edges.append((root_user.login, str(person)))

            for i in range(1, root_user.following):
                user = gh.user(graph_nodes[i])
                user_following_edges = [(user.login, str(person)) for person in gh.iter_following(
                    user) if str(person) in graph_nodes]
                graph_edges += user_following_edges
        except Exception, e:
            raise e

        generate_gml(username, graph_nodes, graph_edges, True)
    else:
        reuse_gml(username)

    return username
1003200
def assign_bus_results(grid, bus_data):
    

    # iterate of nodes and assign voltage obtained from power flow analysis
    for node in grid._graph.nodes():
        # check if node is connected to graph
        if (node not in grid.graph_isolated_nodes()
            and not isinstance(node,
                               LVLoadAreaCentreDing0)):
            if isinstance(node, LVStationDing0):
                node.voltage_res = bus_data.loc[node.pypsa_id, 'v_mag_pu']
            elif isinstance(node, (LVStationDing0, LVLoadAreaCentreDing0)):
                if node.lv_load_area.is_aggregated:
                    node.voltage_res = bus_data.loc[node.pypsa_id, 'v_mag_pu']
            elif not isinstance(node, CircuitBreakerDing0):
                node.voltage_res = bus_data.loc[node.pypsa_id, 'v_mag_pu']
            else:
                logger.warning("Object {} has been skipped while importing "
                               "results!")
1277520
def make_dep_graph(depender):
	
	shutit_global.shutit_global_object.yield_to_draw()
	digraph = ''
	for dependee_id in depender.depends_on:
		digraph = (digraph + '"' + depender.module_id + '"->"' + dependee_id + '";\n')
	return digraph
434949
def construct_graph(args):
    """"""

    app = Core(args)

    setup_root(app)

    if args['debug']:
        from circuits import Debugger
        hfoslog("Starting circuits debugger", lvl=warn, emitter='GRAPH')
        dbg = Debugger().register(app)
        # TODO: Make these configurable from modules, navdata is _very_ noisy
        # but should not be listed _here_
        dbg.IgnoreEvents.extend([
            "read", "_read", "write", "_write",
            "stream_success", "stream_complete",
            "serial_packet", "raw_data", "stream",
            "navdatapush", "referenceframe",
            "updateposition", "updatesubscriptions",
            "generatevesseldata", "generatenavdata", "sensordata",
            "reset_flood_offenders", "reset_flood_counters",  # Flood counters
            "task_success", "task_done",  # Thread completion
            "keepalive"  # IRC Gateway
        ])

    hfoslog("Beginning graph assembly.", emitter='GRAPH')

    if args['drawgraph']:
        from circuits.tools import graph

        graph(app)

    if args['opengui']:
        import webbrowser
        # TODO: Fix up that url:
        webbrowser.open("http://%s:%i/" % (args['host'], args['port']))

    hfoslog("Graph assembly done.", emitter='GRAPH')

    return app
342024
void build(int nodeOffset, GraphMeshData graphData, List<int[]> connections) {
		for (int n = 0; n < connections.size(); n++) {
			int[] nodeConnections = connections.get(n);
			MeshData tile = graphData.getTile(n);
			Poly node = graphData.getNode(n);
			for (int connection : nodeConnections) {
				MeshData neighbourTile = graphData.getTile(connection - nodeOffset);
				if (neighbourTile != tile) {
					buildExternalLink(tile, node, neighbourTile);
				} else {
					Poly neighbour = graphData.getNode(connection - nodeOffset);
					buildInternalLink(tile, node, neighbourTile, neighbour);
				}
			}
		}
	}
1170437
def connect_output(self, node):
        

        if len(self.outputs) == self.max_outputs:
            raise TooManyOutputsError("Attempted to connect too many nodes to the output of a node", max_outputs=self.max_outputs, stream=self.stream)

        self.outputs.append(node)
1068999
def get_branches(grid):
    

    station = grid._station

    tree = nx.dfs_tree(grid._graph, station)

    # TODO: idea
    # 1. build tree from lv_grid station as root -> diretions should point to
    # descending leafs
    # 2. for analysis of current issues get list of descendants with
    # nx.descendants(tree, station). Sum peak load / gen capacity
    # 3. Extract nodes belonging to main route of a branch by checking all
    # successors if these are LVCalbleDistributors
    # notes and hints:
    # 1. associated edges can be accessed via grid._graph.in_edges(<node>)
    # respectively grid._graph.out_edges(<node>)
    # 2. when using nx.descendants(tree, station) make sure the order of nodes
    # is maintained as this is important to properly assess voltage and over-
    # loading issues

    # first_cbl_dists = [x for x in grid._graph.neighbors(station)
    #                    if isinstance(x, LVCableDistributorDing0)]


    # if len(first_cbl_dists) > 0:
    #     ancestors =  nx.ancestors(grid._graph, first_cbl_dists[0])
    # else:
    #     ancestors = None
    # return ancestors
    branch_heads = list(nx.neighbors(tree, station))

    descendants = {branch_head: list(nx.descendants(tree, branch_head)) for
                   branch_head in branch_heads}



    return descendants
852953
def log_prov_graph(self):
        
        glogger.debug("Spec generation provenance graph:")
        glogger.debug(self.prov_g.serialize(format='turtle'))
179178
def import_generators(self, generator_scenario=None):
        
        if generator_scenario:
            self.network.generator_scenario = generator_scenario
        data_source = 'oedb'
        import_generators(network=self.network, data_source=data_source)
47669
public static void main(String[] args) throws Exception {
    Builder processingGraphBuilder = Builder.newBuilder();

    /**
     * A supplier streamlet of random GameScore objects is cloned into two
     * separate streamlets.
     */
    List<Streamlet<GameScore>> splitGameScoreStreamlet = processingGraphBuilder
        .newSource(GameScore::new)
        .clone(2);

    /**
     * Elements in the first cloned streamlet go to the database sink.
     */
    splitGameScoreStreamlet.get(0)
        .toSink(new DatabaseSink());

    /**
     * Elements in the second cloned streamlet go to the logging sink.
     */
    splitGameScoreStreamlet.get(1)
        .toSink(new FormattedLogSink());

    Config config = Config.defaultConfig();

    // Fetches the topology name from the first command-line argument
    String topologyName = StreamletUtils.getTopologyName(args);

    // Finally, the processing graph and configuration are passed to the Runner, which converts
    // the graph into a Heron topology that can be run in a Heron cluster.
    new Runner().run(topologyName, config, processingGraphBuilder);
  }
643404
def plot_mv_storage_integration(self, **kwargs):
        
        if self.network.pypsa is not None:
            plots.mv_grid_topology(
                self.network.pypsa, self.network.config,
                node_color='storage_integration',
                filename=kwargs.get('filename', None),
                grid_district_geom=kwargs.get('grid_district_geom', True),
                background_map=kwargs.get('background_map', True),
                xlim=kwargs.get('xlim', None), ylim=kwargs.get('ylim', None),
                title=kwargs.get('title', ''))
        else:
            if self.network.pypsa is None:
                logging.warning("pypsa representation of MV grid needed to "
                                "plot storage integration in MV grid.")
1348439
def build(self):
        ''''''
        # right now we do not worry about status of nodes
        # connecting the output to the input of other nodes
        #
        # NOTE: This is implemented in the least efficient way just for
        # testing. It has to be re-implemented.
        #
        # refer to http://stackoverflow.com/questions/33494376/networkx-add-edges-to-graph-from-node-attributes
        #
        # several cases triggers dependency.
        if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']:
            env.log_to_file('DAG', 'build DAG')
        for wf in range(self._forward_workflow_id + 1):
            indexed = [x for x in self.nodes() if x._wf_index == wf]
            indexed.sort(key=lambda x: x._node_index)

            for idx, node in enumerate(indexed):
                # 1. if a node changes context (using option alias), all later steps
                # has to rely on it.
                if node._context['__changed_vars__']:
                    for later_node in indexed[idx + 1:]:
                        if node._context['__changed_vars__'] & (
                                later_node._context['__signature_vars__']
                                | later_node._context['__environ_vars__']):
                            self.add_edge(node, later_node)

                # 2. if the input of a step is undetermined, it has to be executed
                # after all its previous steps.
                if not node._input_targets.valid() and idx > 0:
                    # if there is some input specified, it does not use default
                    # input, so the relationship can be further looked before
                    if node._input_targets.undetermined():
                        # if the input is dynamic, has to rely on previous step...
                        if 'dynamic' in node._context['__environ_vars__']:
                            self.add_edge(indexed[idx - 1], node)
                        else:
                            # otherwise let us look back.
                            for prev_node in indexed[idx - 1::-1]:
                                if node._context[
                                        '__environ_vars__'] & prev_node._context[
                                            '__changed_vars__']:
                                    self.add_edge(prev_node, node)
                    else:
                        self.add_edge(indexed[idx - 1], node)
        #
        # 3. if the input of a step depends on the output of another step
        for target, in_node in self._all_depends_files.items():
            if target not in self._all_output_files:
                continue
            # it is possible that multiple nodes satisfy the same target
            out_node = self._all_output_files[target]
            for i in in_node:
                for j in out_node:
                    if j != i:
                        self.add_edge(j, i)
        self.mark_dirty()
1227338
def example_stats(filename):
    

    nd = results.load_nd_from_pickle(filename=filename)

    nodes_df, edges_df = nd.to_dataframe()

    # get statistical numbers about grid
    stats = results.calculate_mvgd_stats(nd)

    # plot distribution of load/generation of subjacent LV grids
    stations = nodes_df[nodes_df['type'] == 'LV Station']
    f, axarr = plt.subplots(2, sharex=True)
    f.suptitle("Peak load (top) / peak generation capacity (bottom) at LV "
               "substations in kW")
    stations['peak_load'].hist(bins=20, alpha=0.5, ax=axarr[0])
    axarr[0].set_title("Peak load in kW")
    stations['generation_capacity'].hist(bins=20, alpha=0.5, ax=axarr[1])
    axarr[1].set_title("Peak generation capacity in kW")
    plt.show()

    # Introduction of report
    print("You are analyzing MV grid district {mvgd}\n".format(
        mvgd=int(stats.index.values)))

    # print all the calculated stats
    # this isn't a particularly beautiful format but it is
    # information rich
    with option_context('display.max_rows', None,
                        'display.max_columns', None,
                        'display.max_colwidth', -1):
        print(stats.T)