from sonata.io import File, Edge
        data = File(data_files=[self.subs('$NETWORK_DIR/excvirt_cortex_edges.h5')],
                data_type_files=[self.subs('$NETWORK_DIR/excvirt_cortex_edge_types.csv')])
978133
def createConns(self):
        # SONATA method - works but same results as NeuroMLlite
        '''
        
        '''

        # NeuroMLlite Method
        self.edges_info = {}
        self.conn_info = {}

        synMechSubs = {'level_of_detail': 'mod', 
                        'erev': 'e'}
        
        if 'edges' in self.network_config['networks']:
            for e in self.network_config['networks']['edges']:
                edges_file = self.subs(e['edges_file'])
                edge_types_file = self.subs(e['edge_types_file'])

                print("\nLoading edges from %s and %s"%(edges_file,edge_types_file))

                h5file=tables.open_file(edges_file,mode='r')

                print("Opened HDF5 file: %s"%(h5file.filename))
                self.parse_group(h5file.root.edges)
                h5file.close()
                self.edges_info[self.current_edge] = load_csv_props(edge_types_file)
                self.current_edge = None

        for conn in self.conn_info:
            
            pre_node = self.conn_info[conn]['pre_node']
            post_node = self.conn_info[conn]['post_node']
            
            print('   Adding projection %s: %s -> %s '%(conn, pre_node, post_node))

            # add all synMechs in this projection to netParams.synMechParams
            for type in self.edges_info[conn]:
                syn_label = self.edges_info[conn][type]['dynamics_params'].split('.')[0]
                if syn_label not in sim.net.params.synMechParams:
                    dynamics_params_file = self.subs(self.network_config['components']['synaptic_models_dir']) +'/'+self.edges_info[conn][type]['dynamics_params']        
                    syn_dyn_params = load_json(dynamics_params_file)
                    synMechParams = dict(syn_dyn_params)
                    for k in synMechParams:  # replace keys
                        if k in synMechSubs:
                            synMechParams[synMechSubs[k]] = synMechParams.pop(k) 
                    synMechParams['mod'] = self.edges_info[conn][type]['model_template']
                    sim.net.params.synMechParams[syn_label] = synMechParams
                    print('   Added synMech %s '%(syn_label))

            # add individual connections in this projection
            for i in range(len(self.conn_info[conn]['pre_id'])):
                pre_id = self.conn_info[conn]['pre_id'][i]
                post_id = self.conn_info[conn]['post_id'][i]
                pre_gid = self.cell_info[pre_node]['gid_from_id'][pre_id] 
                post_gid = self.cell_info[post_node]['gid_from_id'][post_id]


                if post_gid in sim.net.gid2lid:

                    type = self.conn_info[conn]['edge_type_id'][i]

                    print('   Conn: type %s pop %s (id %s) -> pop %s (id %s) MAPPED TO: cell gid %s -> cell gid %s'%(type,pre_node,pre_id,post_node,post_id, pre_gid,post_gid))
                    #print(self.edges_info[conn][type])
                    
                    connParams = {}
                    postCell = sim.net.cells[sim.net.gid2lid[post_gid]]

                    # preGid
                    connParams['preGid'] = pre_gid

                    # synMech
                    connParams['synMech'] = self.edges_info[conn][type]['dynamics_params'].split('.')[0]                
                    
                    # weight
                    sign = syn_dyn_params['sign'] if 'sign' in syn_dyn_params else 1
                    try:
                        weight = self.conn_info[conn]['syn_weight'][i] 
                    except:
                        weight = self.edges_info[conn][type]['syn_weight'] if 'syn_weight' in self.edges_info[conn][type] else 1.0
                    connParams['weight'] = sign*weight
                    
                    # delay
                    connParams['delay'] = self.edges_info[conn][type]['delay'] if 'delay' in self.edges_info[conn][type] else 0
                    
                    # sec 
                    sec_id = self.conn_info[conn]['sec_id'][i] 
                    connParams['sec'] = postCell.secLists['SONATA_sec_id'][sec_id]

                    # loc
                    connParams['loc'] = self.conn_info[conn]['sec_x'][i] 

                    # add connection
                    postCell.addConn(connParams)
981819
function(modes) {
      var graph = this.viz.graph,
          accessors = {
            'node-property': {
              'getter': 'getData',
              'setter': 'setData'
            },
            'edge-property': {
              'getter': 'getData',
              'setter': 'setData'
            },
            'node-style': {
              'getter': 'getCanvasStyle',
              'setter': 'setCanvasStyle'
            },
            'edge-style': {
              'getter': 'getCanvasStyle',
              'setter': 'setCanvasStyle'
            }
          };

      //parse modes
      var m = {};
      if($.type(modes) == 'array') {
        for(var i=0, len=modes.length; i < len; i++) {
          var elems = modes[i].split(':');
          m[elems.shift()] = elems;
        }
      } else {
        for(var p in modes) {
          if(p == 'position') {
            m[modes.position] = [];
          } else {
            m[p] = $.splat(modes[p]);
          }
        }
      }
      
      graph.eachNode(function(node) { 
        node.startPos.set(node.pos);
        $.each(['node-property', 'node-style'], function(p) {
          if(p in m) {
            var prop = m[p];
            for(var i=0, l=prop.length; i < l; i++) {
              node[accessors[p].setter](prop[i], node[accessors[p].getter](prop[i]), 'start');
            }
          }
        });
        $.each(['edge-property', 'edge-style'], function(p) {
          if(p in m) {
            var prop = m[p];
            node.eachAdjacency(function(adj) {
              for(var i=0, l=prop.length; i < l; i++) {
                adj[accessors[p].setter](prop[i], adj[accessors[p].getter](prop[i]), 'start');
              }
            });
          }
        });
      });
      return m;
    }
138078
def _canonicalize_edge_modifications(edge_data: EdgeData) -> Optional[Tuple]:
    """"""
    if edge_data is None:
        return

    modifier = edge_data.get(MODIFIER)
    location = edge_data.get(LOCATION)
    effect = edge_data.get(EFFECT)

    if modifier is None and location is None:
        return

    result = []

    if modifier == ACTIVITY:
        if effect:
            effect_name = effect.get(NAME)
            effect_identifier = effect.get(IDENTIFIER)

            t = (
                ACTIVITY,
                effect[NAMESPACE],
                effect_name or effect_identifier,
            )

        else:
            t = (ACTIVITY,)

        result.append(t)

    elif modifier == DEGRADATION:
        t = (DEGRADATION,)
        result.append(t)

    elif modifier == TRANSLOCATION:
        if effect:
            from_loc_name = effect[FROM_LOC].get(NAME)
            from_loc_identifier = effect[FROM_LOC].get(IDENTIFIER)
            to_loc_name = effect[TO_LOC].get(NAME)
            to_loc_identifier = effect[TO_LOC].get(IDENTIFIER)

            t = (
                TRANSLOCATION,
                edge_data[EFFECT][FROM_LOC][NAMESPACE],
                from_loc_name or from_loc_identifier,
                edge_data[EFFECT][TO_LOC][NAMESPACE],
                to_loc_name or to_loc_identifier,
            )
        else:
            t = (TRANSLOCATION,)
        result.append(t)

    if location:
        location_name = location.get(NAME)
        location_identifier = location.get(IDENTIFIER)

        t = (
            LOCATION,
            location[NAMESPACE],
            location_name or location_identifier,
        )
        result.append(t)

    if not result:
        raise ValueError('Invalid data: {}'.format(edge_data))

    return tuple(result)
513387
def _init_edges_relationships(rel2src2dsts, rel2dst2srcs):
        """"""
        edge_rel2fromto = {}
        relationships = set(rel2src2dsts).union(rel2dst2srcs)
        for reltype in relationships:
            edge_from_to = []
            if reltype in rel2src2dsts:
                for parent, children in rel2src2dsts[reltype].items():
                    for child in children:
                        edge_from_to.append((child, parent))
            if reltype in rel2dst2srcs:
                for parent, children in rel2dst2srcs[reltype].items():
                    for child in children:
                        edge_from_to.append((child, parent))
            edge_rel2fromto[reltype] = edge_from_to
        return edge_rel2fromto
484871
def network_interfaces
      netifcs = []
      procfs_file("net", "dev") do |file|
        file.read.scan(NET_DATA) do |columns|
          type = case columns[0]
            when /^eth/ then NetworkInterface::ETHERNET_TYPE
            when /^lo/  then NetworkInterface::LOOPBACK_TYPE
          end

          netifcs << NetworkInterface.new(columns[0].to_sym, columns[1].to_i,
                                          columns[3].to_i,   columns[4].to_i,
                                          columns[9].to_i,   columns[11].to_i,
                                          type)
        end
      end
      netifcs
    end
16721
def edges
      edge_ary = Array.new(4)
      edge_ary[0] = FiniteLine.new( base_point, base_point+u_vector)
      edge_ary[1] = FiniteLine.new( base_point+u_vector, base_point+u_vector+v_vector)
      edge_ary[2] = FiniteLine.new( base_point+u_vector+v_vector, base_point+v_vector)
      edge_ary[3] = FiniteLine.new( base_point+v_vector, base_point)
      return edge_ary
    end
1237896
def itemData(self, f=None, savePath=None):
        

        params = {
        }
        if f is not None and \
           f.lower() in ['zip', 'json']:
            params['f'] = f
        url = "%s/data" % self.root
        if self.type in ["Shapefile", "CityEngine Web Scene", "Web Scene", "KML",
                         "Code Sample",
                         "Code Attachment", "Operations Dashboard Add In",
                         "CSV", "CSV Collection", "CAD Drawing", "Service Definition",
                         "Microsoft Word", "Microsoft Powerpoint",
                         "Microsoft Excel", "PDF", "Image",
                         "Visio Document", "iWork Keynote", "iWork Pages",
                         "iWork Numbers", "Map Document", "Map Package",
                         "Basemap Package", "Tile Package", "Project Package",
                         "Task File", "ArcPad Package", "Explorer Map",
                         "Globe Document", "Scene Document", "Published Map",
                         "Map Template", "Windows Mobile Package", "Pro Map",
                         "Layout", "Layer", "Layer Package", "File Geodatabase",
                         "Explorer Layer", "Geoprocessing Package", "Geoprocessing Sample",
                         "Locator Package", "Rule Package", "Workflow Manager Package",
                         "Desktop Application", "Desktop Application Template",
                         "Code Sample", "Desktop Add In", "Explorer Add In",
                         "ArcGIS Desktop Add-In", "ArcGIS Explorer Add-In",
                         "ArcGIS Explorer application configuration", "ArcGIS Explorer document",
                         ]:
            if savePath is None:
                raise AttributeError('savePath must be provided for a item of type: %s' % self.type)
            if os.path.isdir(savePath) == False:
                os.makedirs(savePath)
            result = self._get(url=url,
                               param_dict=params,
                               securityHandler=self._securityHandler,
                               proxy_url=self._proxy_url,
                               proxy_port=self._proxy_port,
                               out_folder=savePath,
                               file_name=self.name)
            return result
        else:
            results =  self._get(url, params,
                                 proxy_port=self._proxy_port,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url)
            return results
592576
def to_import(self):
        # type: () -> ImportEndpoint
        
        # Properties
        properties = self.get_properties()

        # Framework UUID
        fw_uid = self.get_framework_uuid()

        # Endpoint name
        try:
            # From Pelix UID
            name = properties[pelix.remote.PROP_ENDPOINT_NAME]
        except KeyError:
            # Generated
            name = "{0}.{1}".format(fw_uid, self.get_service_id())

        # Configuration / kind
        configurations = self.get_configuration_types()

        # Interfaces
        specifications = self.get_interfaces()

        return ImportEndpoint(
            self.get_id(),
            fw_uid,
            configurations,
            name,
            specifications,
            properties,
        )
1213389
def edges_to_dict_of_dataframes(grid, edges):
    
    omega = 2 * pi * 50
    srid = int(cfg_ding0.get('geo', 'srid'))

    lines = {'line_id': [], 'bus0': [], 'bus1': [], 'x': [], 'r': [],
             's_nom': [], 'length': [], 'cables': [], 'geom': [],
             'grid_id': []}

    # iterate over edges and add them one by one
    for edge in edges:

        line_name = '_'.join(['MV',
                              str(grid.id_db),
                              'lin',
                              str(edge['branch'].id_db)])

        # TODO: find the real cause for being L, C, I_th_max type of Series
        if (isinstance(edge['branch'].type['L'], Series) or
                isinstance(edge['branch'].type['C'], Series)):
            x = omega * edge['branch'].type['L'].values[0] * 1e-3
        else:

            x = omega * edge['branch'].type['L'] * 1e-3

        if isinstance(edge['branch'].type['R'], Series):
            r = edge['branch'].type['R'].values[0]
        else:
            r = edge['branch'].type['R']

        if (isinstance(edge['branch'].type['I_max_th'], Series) or
                isinstance(edge['branch'].type['U_n'], Series)):
            s_nom = sqrt(3) * edge['branch'].type['I_max_th'].values[0] * \
                    edge['branch'].type['U_n'].values[0]
        else:
            s_nom = sqrt(3) * edge['branch'].type['I_max_th'] * \
                    edge['branch'].type['U_n']

        # get lengths of line
        l = edge['branch'].length / 1e3

        lines['line_id'].append(line_name)
        lines['bus0'].append(edge['adj_nodes'][0].pypsa_id)
        lines['bus1'].append(edge['adj_nodes'][1].pypsa_id)
        lines['x'].append(x * l)
        lines['r'].append(r * l)
        lines['s_nom'].append(s_nom)
        lines['length'].append(l)
        lines['cables'].append(3)
        lines['geom'].append(from_shape(
            LineString([edge['adj_nodes'][0].geo_data,
                        edge['adj_nodes'][1].geo_data]),
            srid=srid))
        lines['grid_id'].append(grid.id_db)

    return {'Line': DataFrame(lines).set_index('line_id')}
71899
def assign_line_results(grid, line_data):
    

    package_path = ding0.__path__[0]

    edges = [edge for edge in grid.graph_edges()
             if (edge['adj_nodes'][0] in grid._graph.nodes() and not isinstance(
            edge['adj_nodes'][0], LVLoadAreaCentreDing0))
             and (
             edge['adj_nodes'][1] in grid._graph.nodes() and not isinstance(
                 edge['adj_nodes'][1], LVLoadAreaCentreDing0))]

    decimal_places = 6
    for edge in edges:
        s_res = [
            round(sqrt(
                max(abs(line_data.loc["MV_{0}_lin_{1}".format(grid.id_db, edge[
                    'branch'].id_db), 'p0'][0]),
                    abs(line_data.loc["MV_{0}_lin_{1}".format(grid.id_db, edge[
                        'branch'].id_db), 'p1'][0])) ** 2 +
                max(abs(line_data.loc["MV_{0}_lin_{1}".format(grid.id_db, edge[
                    'branch'].id_db), 'q0'][0]),
                    abs(line_data.loc["MV_{0}_lin_{1}".format(grid.id_db, edge[
                        'branch'].id_db), 'q1'][0])) ** 2),decimal_places),
            round(sqrt(
                max(abs(line_data.loc["MV_{0}_lin_{1}".format(grid.id_db, edge[
                    'branch'].id_db), 'p0'][1]),
                    abs(line_data.loc["MV_{0}_lin_{1}".format(grid.id_db, edge[
                        'branch'].id_db), 'p1'][1])) ** 2 +
                max(abs(line_data.loc["MV_{0}_lin_{1}".format(grid.id_db, edge[
                    'branch'].id_db), 'q0'][1]),
                    abs(line_data.loc["MV_{0}_lin_{1}".format(grid.id_db, edge[
                        'branch'].id_db), 'q1'][1])) ** 2),decimal_places)]

        edge['branch'].s_res = s_res
630803
def kallisto_table(kallisto_dir, index):
    
    quant_dir = os.path.join(kallisto_dir, "quant")
    out_file = os.path.join(quant_dir, "matrix.csv")
    if file_exists(out_file):
        return out_file
    tsvfile = os.path.join(quant_dir, "matrix.tsv")
    ecfile = os.path.join(quant_dir, "matrix.ec")
    cellsfile = os.path.join(quant_dir, "matrix.cells")
    fastafile = os.path.splitext(index)[0] + ".fa"
    fasta_names = fasta.sequence_names(fastafile)
    ec_names = get_ec_names(ecfile, fasta_names)
    df = pd.read_table(tsvfile, header=None, names=["ec", "cell", "count"])
    df["ec"] = [ec_names[x] for x in df["ec"]]
    df = df.pivot(index='ec', columns='cell', values='count')
    cellnames = get_cell_names(cellsfile)
    colnames = [cellnames[x] for x in df.columns]
    df.columns = colnames
    df.to_csv(out_file)
    return out_file
943088
def from_perseus(network_table, networks):
    
    graphs = []
    for guid, graph_attr in zip(network_table['GUID'], network_table.values):
        network = networks[guid]
        edge_table = network['edge_table']
        if edge_table[['Source', 'Target']].duplicated().any():
            warnings.warn('Duplicate edges were found and ignored in network {}'.format(network['name']))
        G = nx.from_pandas_edgelist(edge_table, 'Source', 'Target', True, create_using=nx.DiGraph())
        for attr, value in zip(network_table.columns, graph_attr):
            G.graph[attr] = value
        node_table = network['node_table']
        if node_table['Node'].duplicated().any():
            warnings.warn('Duplicate nodes were found and ignored in network {}'.format(network['name']))
        node_column = node_table['Node']
        for name, attributes in zip(node_column, node_table.values):
            if name not in G:
                G.add_node(name)
            for attr, value in zip(node_table.columns, attributes):
                G.node[name][attr] = value
        graphs.append(G)
    return graphs
936211
def graph_from_cov_df(df, threshold=.5, gain=2., n=None, class_dict=CLASSES):
    """"""
    n = n or len(df)
    nodes = [{'group': class_dict.get(name, 0), "name": name} for name in df.index.values][:n]
    edges = []
    for i, (row_name, row) in enumerate(df.iterrows()):
        for j, value in enumerate(row.values):
            if i > j and value * gain > threshold and i < n and j < n:
                edges += [{'source': i, 'target': j, 'value': gain * value}]
    return nodes, edges
679214
def edges(self):
        ""
        if util.config.future_deprecations:
            self.param.warning('Histogram.edges is deprecated in favor of '
                               'common dimension_values method.')
        return self.interface.coords(self, self.kdims[0], edges=True)
179663
def from_file(filename="feff.inp"):
        
        with zopen(filename, "rt") as f:
            lines = list(clean_lines(f.readlines()))
        params = {}
        eels_params = []
        ieels = -1
        ieels_max = -1
        for i, line in enumerate(lines):
            m = re.match(r"([A-Z]+\d*\d*)\s*(.*)", line)
            if m:
                key = m.group(1).strip()
                val = m.group(2).strip()
                val = Tags.proc_val(key, val)
                if key not in ("ATOMS", "POTENTIALS", "END", "TITLE"):
                    if key in ["ELNES", "EXELFS"]:
                        ieels = i
                        ieels_max = ieels + 5
                    else:
                        params[key] = val
            if ieels >= 0:
                if i >= ieels and i <= ieels_max:
                    if i == ieels + 1:
                        if int(line.split()[1]) == 1:
                            ieels_max -= 1
                    eels_params.append(line)

        if eels_params:
            if len(eels_params) == 6:
                eels_keys = ['BEAM_ENERGY', 'BEAM_DIRECTION', 'ANGLES', 'MESH', 'POSITION']
            else:
                eels_keys = ['BEAM_ENERGY', 'ANGLES', 'MESH', 'POSITION']
            eels_dict = {"ENERGY": Tags._stringify_val(eels_params[0].split()[1:])}
            for k, v in zip(eels_keys, eels_params[1:]):
                eels_dict[k] = str(v)
            params[str(eels_params[0].split()[0])] = eels_dict

        return Tags(params)
1011419
def edgepaths(self):
        
        if self._edgepaths:
            return self._edgepaths
        if pd is None:
            paths = connect_edges(self)
        else:
            paths = connect_edges_pd(self)
        return self.edge_type(paths, kdims=self.nodes.kdims[:2])
1178372
def inv_edges(json):
    """"""
    for edge in json['edges']:
        sub, obj = edge['sub'], edge['obj']
        edge['sub'] = obj
        edge['obj'] = sub

        edge['pred'] += 'INVERTED'