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

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

        self._graph = lv_connect.lv_connect_generators(self.grid_district, self._graph, debug)
1242868
def generate_layout(bpmn_graph):
    
    classification = generate_elements_clasification(bpmn_graph)
    (sorted_nodes_with_classification, backward_flows) = topological_sort(bpmn_graph, classification[0])
    grid = grid_layout(bpmn_graph, sorted_nodes_with_classification)
    set_coordinates_for_nodes(bpmn_graph, grid)
    set_flows_waypoints(bpmn_graph)
628056
def node_link_data(graph: BELGraph) -> Mapping[str, Any]:
    
    nodes = sorted(graph, key=methodcaller('as_bel'))

    mapping = dict(zip(nodes, count()))

    return {
        'directed': True,
        'multigraph': True,
        'graph': graph.graph.copy(),
        'nodes': [
            _augment_node(node)
            for node in nodes
        ],
        'links': [
            dict(chain(
                data.copy().items(),
                [('source', mapping[u]), ('target', mapping[v]), ('key', key)]
            ))
            for u, v, key, data in graph.edges(keys=True, data=True)
        ]
    }
807304
def connect(self):
        """"""
        try:
            for group in ('inlets', 'receivers', 'outlets', 'senders'):
                self._connect_subgroup(group)
        except BaseException:
            objecttools.augment_excmessage(
                'While trying to build the node connection of the `%s` '
                'sequences of the model handled by element `%s`'
                % (group[:-1], objecttools.devicename(self)))
542025
def connect(self):
        
        logger.info("Connecting to %s:%s", self._host, self._port)
        reader, writer = yield from asyncio.open_connection(
                self._host, self._port, loop=self._loop)
        self._ioloop_future = ensure_future(
                self._ioloop(reader, writer), loop=self._loop)
        logger.info("Connected")
851409
def dbg_draw(self, filename):
        
        import matplotlib.pyplot as pyplot  # pylint: disable=import-error
        from networkx.drawing.nx_agraph import graphviz_layout  # pylint: disable=import-error

        tmp_graph = networkx.DiGraph()
        for from_block, to_block in self.transition_graph.edges():
            node_a = "%#08x" % from_block.addr
            node_b = "%#08x" % to_block.addr
            if node_b in self._ret_sites:
                node_b += "[Ret]"
            if node_a in self._call_sites:
                node_a += "[Call]"
            tmp_graph.add_edge(node_a, node_b)
        pos = graphviz_layout(tmp_graph, prog='fdp')   # pylint: disable=no-member
        networkx.draw(tmp_graph, pos, node_size=1200)
        pyplot.savefig(filename)
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)
623799
def showGrid( self ):
        
        delegate = self.itemDelegate()
        if ( isinstance(delegate, XTreeWidgetDelegate) ):
            return delegate.showGrid()
        return False
520152
def print_loopy(self, as_url=True):
        
        init_str = ''
        node_id = 1
        node_list = {}
        for node, data in self.graph.nodes(data=True):
            node_name = data['name']
            nodex = int(500*numpy.random.rand())
            nodey = int(500*numpy.random.rand())
            hue = int(5*numpy.random.rand())
            node_attr = [node_id, nodex, nodey, 1, node_name, hue]
            node_list[node] = node_attr
            node_id += 1
        nodes = list(node_list.values())

        edges = []
        for s, t, data in self.graph.edges(data=True):
            s_id = node_list[s][0]
            t_id = node_list[t][0]
            if data['polarity'] == 'positive':
                pol = 1
            else:
                pol = -1
            edge = [s_id, t_id, 89, pol, 0]
            edges.append(edge)

        labels = []
        components = [nodes, edges, labels]
        model = json.dumps(components, separators=(',', ':'))
        if as_url:
            model = 'http://ncase.me/loopy/v1/?data=' + model
        return model
48411
def graph_add_node(self, node_object):
        
        if ((node_object not in self._graph.nodes()) and
            (isinstance(node_object, (StationDing0,
                                      CableDistributorDing0,
                                      LVLoadAreaCentreDing0,
                                      CircuitBreakerDing0,
                                      GeneratorDing0)))):
            self._graph.add_node(node_object)
1315545
def log_setup(debug_bool):
    

    level = logging.DEBUG if debug_bool else logging.INFO

    logging.config.dictConfig(
        {
            "version": 1,
            "disable_existing_loggers": False,
            "formatters": {
                "verbose": {
                    "format": "%(asctime)s %(levelname)-8s %(name)s %(module)s "
                    "%(process)d %(thread)d %(message)s",
                    "datefmt": "%Y-%m-%d %H:%M:%S",
                }
            },
            "handlers": {
                "console": {
                    "class": "logging.StreamHandler",
                    "formatter": "verbose",
                    "level": level,
                    "stream": "ext://sys.stdout",
                }
            },
            "loggers": {
                "": {
                    "handlers": ["console"],
                    "level": level,
                    "class": "logging.StreamHandler",
                }
            },
        }
    )
451660
function() {
      var t = this,
          branches = t.model.get('branches'),
          leaves = t.model.get('leaves');

      // Determine if we should connect a monitor to this node
      //
      // Connect a monitor if:
      // * There isn't one already connected, and
      // * There's a monitor definition available, and
      // * We're open, or
      // *   preFetch is selected, and
      // *     we have no parent or our parent is open
      //
      // ** Is there any way to make this logic simpler?
      var shouldConnect = !t.model.hasMonitor()
        && t.options.monitorParams
        && (t.model.get('isOpen')
          || (t.options.preFetch
            && (!t.options.parentView
              || t.options.parentView.model.get('isOpen'))));

      // Connect to the monitor if we've determined we should
      if (shouldConnect) {

        // If there isn't any model data to display, show Loading...
        if (!branches || !leaves) {
          t.loading = $('<li>Loading...</li>').appendTo(t.$el);
        }

        // Build and connect the Monitor
        var initParams = _.extend(
          {},
          t.options.monitorParams.initParams || {},
          {path:t.options.path}
        );
        var monitorParams = _.extend(
          {},
          t.options.monitorParams,
          {initParams: initParams}
        );
        t.monitor = new Monitor(monitorParams);
        t.model.attachMonitor(t.monitor);

        // Call our handlers once connected
        t.monitor.on('connect', function(){
          setTimeout(function(){
            for (var i in t.connectHandlers) {
              var handler = t.connectHandlers[i];
              handler(t.monitor);
            }
          },10);
        });

        // Connect the monitor and process errors.  Successes will change
        // the underlying data model (or not), causing a re-render.
        t.monitor.connect(function(error) {

          // Remove the Loading... message
          if (t.loading) {
            t.loading.remove();
            t.loading = null;
          }

          // Handle errors
          if (error) {
            $('<li>(connection problem)</li>').appendTo(t.$el);
            console.error('TreeView monitor connection problem:', error, t.monitor);

            // Detach the problem monitor so it'll have another chance
            // if the user opens/closes the branch.
            t.model.detachMonitor();
          }

        });
      }
    }
1262814
def generate_nodes(self, topology):
        
        nodes = []

        devices = topology['devices']
        hypervisors = topology['conf']

        for device in sorted(devices):
            hv_id = devices[device]['hv_id']
            try:
                tmp_node = Node(hypervisors[hv_id], self.port_id)
            except IndexError:
                tmp_node = Node({}, self.port_id)
            # Start building the structure
            tmp_node.node['properties']['name'] = device
            tmp_node.node['id'] = devices[device]['node_id']
            tmp_node.node['x'] = devices[device]['x']
            tmp_node.node['y'] = devices[device]['y']
            tmp_node.device_info['from'] = devices[device]['from']
            tmp_node.device_info['type'] = devices[device]['type']
            tmp_node.device_info['desc'] = devices[device]['desc']

            if 'ext_conf' in devices[device]:
                tmp_node.device_info['ext_conf'] = devices[device]['ext_conf']

            # Node Label
            tmp_node.node['label']['text'] = device
            if 'hx' in devices[device] and 'hy' in devices[device]:
                tmp_node.node['label']['x'] = devices[device]['hx']
                tmp_node.node['label']['y'] = devices[device]['hy']

            if 'model' in devices[device]:
                tmp_node.device_info['model'] = devices[device]['model']
            else:
                tmp_node.device_info['model'] = ''

            tmp_node.set_description()
            tmp_node.set_type()

            # Now lets process the rest
            for item in sorted(devices[device]):
                tmp_node.add_device_items(item, devices[device])

            if tmp_node.device_info['type'] == 'Router':
                tmp_node.add_info_from_hv()
                tmp_node.node['router_id'] = devices[device]['node_id']
                tmp_node.calc_mb_ports()

                for item in sorted(tmp_node.node['properties']):
                    if item.startswith('slot'):
                        tmp_node.add_slot_ports(item)
                    elif item.startswith('wic'):
                        tmp_node.add_wic_ports(item)

                # Add default ports to 7200 and 3660
                if tmp_node.device_info['model'] == 'c7200':
                    # tmp_node.add_slot_ports('slot0')
                    # C7200 doesnt have any ports by default
                    pass
                elif tmp_node.device_info['model'] == 'c3600' \
                        and tmp_node.device_info['chassis'] == '3660':
                    tmp_node.node['properties']['slot0'] = 'Leopard-2FE'

                # Calculate the router links
                tmp_node.calc_device_links()

            elif tmp_node.device_info['type'] == 'Cloud':
                try:
                    tmp_node.calc_cloud_connection()
                except RuntimeError as err:
                    print(err)

            elif tmp_node.device_info['type'] == 'FrameRelaySwitch':
                tmp_node.process_mappings()

            elif tmp_node.device_info['type'] == 'VirtualBoxVM':
                tmp_node.add_to_virtualbox()
                tmp_node.add_vm_ethernet_ports()
                tmp_node.calc_device_links()

            elif tmp_node.device_info['type'] == 'QemuVM':
                tmp_node.add_to_qemu()
                tmp_node.set_qemu_symbol()
                tmp_node.add_vm_ethernet_ports()
                tmp_node.calc_device_links()

            # Get the data we need back from the node instance
            self.links.extend(tmp_node.links)
            self.configs.extend(tmp_node.config)
            self.port_id += tmp_node.get_nb_added_ports(self.port_id)

            nodes.append(tmp_node.node)

        return nodes
565149
def get_graphs(self, run_key, debug=False):
    
    graph_dict = (self._run_key_to_debug_graphs if debug else
                  self._run_key_to_original_graphs)
    graph_wrappers = graph_dict.get(run_key, {})
    graph_defs = dict()
    for device_name, wrapper in graph_wrappers.items():
      graph_defs[device_name] = wrapper.graph_def
    return graph_defs
430872
def _build_graph(self):
        
        self._graph.add_nodes_from(self.tasks)
        for node1 in self._graph.nodes:
            for node2 in self._graph.nodes:
                for input_file in node1.inputs:
                    for output_file in node2.outputs:
                        if output_file == input_file:
                            self._graph.add_edge(node2, node1)
        for order, task in enumerate(topological_sort(self._graph)):
            task.predecessors = self._graph.predecessors(task)
            task.order = order
1357732
def connect_nodes(nodes):
    """"""
    for n, next_node in zip(nodes, nodes[1:]):
        if isinstance(n, ControlFlowNode):
            _connect_control_flow_node(n, next_node)
        elif isinstance(next_node, ControlFlowNode):
            n.connect(next_node.test)
        elif isinstance(next_node, RestoreNode):
            continue
        elif CALL_IDENTIFIER in next_node.label:
            continue
        else:
            n.connect(next_node)
15326
def plot_or_print(example_farm, example_cluster):
    

    """

    # plot or print power output
    if plt:
        example_cluster.power_output.plot(legend=True, label='example cluster')
        example_farm.power_output.plot(legend=True, label='example farm')
        plt.show()
    else:
        print(example_cluster.power_output)
        print(example_farm.power_output)