code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
lv_stats = {}
for la in nd._mv_grid_districts[0].lv_load_areas():
for lvgd in la.lv_grid_districts():
station_neighbors = list(lvgd.lv_grid._graph[
lvgd.lv_grid._station].keys())
# check if nodes of a statio are members of list gen... | def lv_grid_generators_bus_bar(nd) | Calculate statistics about generators at bus bar in LV grids
Parameters
----------
nd : ding0.NetworkDing0
Network container object
Returns
-------
lv_stats : dict
Dict with keys of LV grid repr() on first level. Each of the grids has
a set of statistical information ab... | 8.326947 | 7.419044 | 1.122375 |
abs_path = os.path.abspath(path)
if len(nd._mv_grid_districts) > 1:
name_extension = '_{number}-{number2}'.format(
number=nd._mv_grid_districts[0].id_db,
number2=nd._mv_grid_districts[-1].id_db)
else:
name_extension = '_{number}'.format(number=nd._mv_grid_distr... | def save_nd_to_pickle(nd, path='', filename=None) | Use pickle to save the whole nd-object to disc
The network instance is entirely pickled to a file.
Parameters
----------
nd : NetworkDing0
Ding0 grid container object
path : str
Absolute or relative path where pickle should be saved. Default is ''
which means pickle is save... | 4.342109 | 3.969701 | 1.093813 |
abs_path = os.path.abspath(path)
if filename is None:
raise NotImplementedError
return pickle.load(open(os.path.join(abs_path, filename), "rb")) | def load_nd_from_pickle(filename=None, path='') | Use pickle to save the whole nd-object to disc
Parameters
----------
filename : str
Filename of nd pickle
path : str
Absolute or relative path where pickle should be saved. Default is ''
which means pickle is save to PWD
Returns
-------
nd : NetworkDing0
Din... | 3.332886 | 4.019889 | 0.829099 |
# cable and line kilometer distribution
f, axarr = plt.subplots(2, 2, sharex=True)
stats.hist(column=['Length of MV overhead lines'], bins=5, alpha=0.5, ax=axarr[0, 0])
stats.hist(column=['Length of MV underground cables'], bins=5, alpha=0.5, ax=axarr[0, 1])
stats.hist(column=['Length of LV ov... | def plot_cable_length(stats, plotpath) | Cable length per MV grid district | 2.629634 | 2.498987 | 1.05228 |
# Generation capacity vs. peak load
sns.set_context("paper", font_scale=1.1)
sns.set_style("ticks")
# reformat to MW
gen_cap_indexes = ["Gen. Cap. of MV at v_level 4",
"Gen. Cap. of MV at v_level 5",
"Gen. Cap. of LV at v_level 6",
... | def plot_generation_over_load(stats, plotpath) | Plot of generation over load | 3.914292 | 3.904088 | 1.002614 |
pickle_name = cfg_ding0.get('output', 'nd_pickle')
# self.nd = self.read_pickles_from_files(pickle_name)
# TODO: instead of passing a list of mvgd's, pass list of filenames plus optionally a basth_path
for mvgd in mv_grid_districts[1:]:
filename = os.path.join(
self.base_path... | def concat_nd_pickles(self, mv_grid_districts) | Read multiple pickles, join nd objects and save to file
Parameters
----------
mv_grid_districts : list
Ints describing MV grid districts | 3.325568 | 3.369687 | 0.986907 |
##############################
# close circuit breakers
nw.control_circuit_breakers(mode='close')
##############################
nodes_idx = 0
nodes_dict = {}
branches_idx = 0
branches_dict = {}
for district in nw.mv_grid_districts():
# nodes voltage
for node in ... | def calculate_mvgd_voltage_current_stats(nw) | MV Voltage and Current Statistics for an arbitrary network
Parameters
----------
nw: :any:`list` of NetworkDing0
The MV grid(s) to be studied
Returns
-------
pandas.DataFrame
nodes_df : Dataframe containing voltage statistics for every node in the MVGD
pandas.DataFrame
... | 2.248526 | 2.218987 | 1.013312 |
##############################
# close circuit breakers
nw.control_circuit_breakers(mode='close')
##############################
nodes_idx = 0
nodes_dict = {}
branches_idx = 0
branches_dict = {}
for mv_district in nw.mv_grid_districts():
for LA in mv_district.lv_load_are... | def calculate_lvgd_voltage_current_stats(nw) | LV Voltage and Current Statistics for an arbitrary network
Note
----
Aggregated Load Areas are excluded.
Parameters
----------
nw: :any:`list` of NetworkDing0
The MV grid(s) to be studied
Returns
-------
pandas.DataFrame
nodes_df : Dataframe containing voltage, res... | 2.043356 | 1.979848 | 1.032077 |
'''Runs ding0 over the districtis selected in mv_grid_districts
It also writes the result in filename. If filename = False,
then the network is not saved.
Parameters
----------
mv_grid_districts: :any:`list` of :obj:`int`
Districts IDs: Defaults to [3545]
filename: str
Defa... | def init_mv_grid(mv_grid_districts=[3545], filename='ding0_tests_grids_1.pkl') | Runs ding0 over the districtis selected in mv_grid_districts
It also writes the result in filename. If filename = False,
then the network is not saved.
Parameters
----------
mv_grid_districts: :any:`list` of :obj:`int`
Districts IDs: Defaults to [3545]
filename: str
Defaults to... | 5.740098 | 3.012362 | 1.905514 |
# make some plot
plotpath = os.path.join(base_path, 'plots')
results.plot_cable_length(stats, plotpath)
plt.show()
results.plot_generation_over_load(stats, plotpath)
plt.show() | def ding0_exemplary_plots(stats, base_path=BASEPATH) | Analyze multiple grid district data generated with Ding0.
Parameters
----------
stats : pandas.DataFrame
Statistics of each MV grid districts
base_path : str
Root directory of Ding0 data structure, i.e. '~/.ding0' (which is
default). | 4.590904 | 5.071285 | 0.905274 |
# load Ding0 data
nds = []
for filename in filenames:
try:
nd_load = results.load_nd_from_pickle(filename=
os.path.join(base_path,
'grids',
... | def nd_load_and_stats(filenames, base_path=BASEPATH) | Load multiple files from disk and generate stats
Passes the list of files assuming the ding0 data structure as default in
:code:`~/.ding0`.
Data will be concatenated and key indicators for each grid district are
returned in table and graphic format.
Parameters
----------
filenames : list o... | 7.649806 | 6.638479 | 1.152343 |
#TODO: finish docstring
# load cable data, file_names and parameter
branch_parameters = grid.network.static_data['MV_cables']
branch_parameters = branch_parameters[branch_parameters['U_n'] == grid.v_level].sort_values('I_max_th')
branch_ctr = 0
for branch, rel_overload in crit_branches.it... | def reinforce_branches_current(grid, crit_branches) | Reinforce MV or LV grid by installing a new branch/line type
Parameters
----------
grid : GridDing0
Grid identifier.
crit_branches : dict
Dict of critical branches with max. relative overloading.
Notes
-----
The branch type to be installed is determined per bran... | 7.415174 | 6.938835 | 1.068648 |
#TODO: finish docstring
# load cable data, file_names and parameter
branch_parameters = grid.network.static_data['{gridlevel}_cables'.format(
gridlevel=grid_level)]
branch_parameters = branch_parameters[branch_parameters['U_n'] == grid.v_level].sort_values('I_max_th')
branch_ctr = 0
... | def reinforce_branches_voltage(grid, crit_branches, grid_level='MV') | Reinforce MV or LV grid by installing a new branch/line type
Parameters
----------
grid : GridDing0
Grid identifier.
crit_branches : :any:`list` of :obj:`int`
List of critical branches. #TODO: check if a list or a dictionary
grid_level : str
Specifying either 'MV' for medium... | 6.807174 | 6.8325 | 0.996293 |
load_factor_lv_trans_lc_normal = cfg_ding0.get(
'assumptions',
'load_factor_lv_trans_lc_normal')
load_factor_lv_trans_fc_normal = cfg_ding0.get(
'assumptions',
'load_factor_lv_trans_fc_normal')
trafo_params = grid.network._static_data['{grid_level}_trafos'.format(
... | def extend_substation(grid, critical_stations, grid_level) | Reinforce MV or LV substation by exchanging the existing trafo and
installing a parallel one if necessary.
First, all available transformers in a `critical_stations` are extended to
maximum power. If this does not solve all present issues, additional
transformers are build.
Parameters
--------... | 4.594412 | 4.266362 | 1.076892 |
grid = crit_stations[0]['node'].grid
trafo_params = grid.network._static_data['{grid_level}_trafos'.format(
grid_level=grid_level)]
trafo_s_max_max = max(trafo_params['S_nom'])
trafo_min_size = trafo_params.loc[trafo_params['S_nom'].idxmin(), :]
v_diff_max_fc = cfg_ding0.get('assumptio... | def extend_substation_voltage(crit_stations, grid_level='LV') | Extend substation if voltage issues at the substation occur
Follows a two-step procedure:
i) Existing transformers are extended by replacement with large nominal
apparent power
ii) New additional transformers added to substation (see 'Notes')
Parameters
----------
crit_stati... | 4.986248 | 4.851055 | 1.027869 |
unsolved_branches = []
cable_lf = cfg_ding0.get('assumptions',
'load_factor_lv_cable_lc_normal')
cables = grid.network.static_data['LV_cables']
# resolve overloading issues for each branch segment
for branch in crit_branches:
I_max_branch_load = branch['s... | def reinforce_lv_branches_overloading(grid, crit_branches) | Choose appropriate cable type for branches with line overloading
Parameters
----------
grid : LVGridDing0
Ding0 LV grid object
crit_branches : :any:`list`
List of critical branches incl. its line loading
Notes
-----
If maximum size cable is not capable to resolve issue due ... | 4.4433 | 4.020983 | 1.105028 |
trafo = extendable_trafos[0]
trafo_s_max_a_before = trafo.s_max_a
trafo_nearest_larger = trafo_params.loc[
trafo_params.loc[
trafo_params['S_nom'] > trafo_s_max_a_before
].loc[
:, 'S_nom'
].idxmin(), :
]
trafo.s_max_a = trafo_nearest_larger['S_nom... | def extend_trafo_power(extendable_trafos, trafo_params) | Extend power of first trafo in list of extendable trafos
Parameters
----------
extendable_trafos : :any:`list`
Trafos with rated power below maximum size available trafo
trafo_params : :pandas:`pandas.DataFrame<dataframe>`
Transformer parameters | 3.047221 | 3.138651 | 0.97087 |
if generator not in self._generators and isinstance(generator,
GeneratorDing0):
self._generators.append(generator)
self.graph_add_node(generator) | def add_generator(self, generator) | Adds a generator to _generators and grid graph if not already existing
Parameters
----------
generator : GridDing0
Description #TODO | 9.448491 | 4.887859 | 1.933053 |
if ((node_object not in self._graph.nodes()) and
(isinstance(node_object, (StationDing0,
CableDistributorDing0,
LVLoadAreaCentreDing0,
CircuitBreakerDing0,
... | def graph_add_node(self, node_object) | Adds a station or cable distributor object to grid graph if not already existing
Parameters
----------
node_object : GridDing0
Description #TODO | 9.427979 | 5.330177 | 1.768793 |
return sorted(self._graph.nodes(), key=lambda _: repr(_)) | def graph_nodes_sorted(self) | Returns an (ascending) sorted list of graph's nodes (name is used as key).
Returns
-------
:any:`list`
Description #TODO check | 10.917467 | 13.801847 | 0.791015 |
edges = nx.get_edge_attributes(self._graph, 'branch')
nodes = list(edges.keys())[list(edges.values()).index(branch)]
return nodes | def graph_nodes_from_branch(self, branch) | Returns nodes that are connected by `branch`
Args
----
branch: BranchDing0
Description #TODO
Returns
-------
(:obj:`GridDing0`, :obj:`GridDing0`)
2-tuple of nodes (Ding0 objects) #TODO:Check | 3.777424 | 4.546659 | 0.830813 |
# TODO: This method can be replaced and speed up by using NetworkX' neighbors()
branches = []
branches_dict = self._graph.adj[node]
for branch in branches_dict.items():
branches.append(branch)
return sorted(branches, key=lambda _: repr(_)) | def graph_branches_from_node(self, node) | Returns branches that are connected to `node`
Args
----
node: GridDing0
Ding0 object (member of graph)
Returns
-------
:any:`list`
List of tuples (node in :obj:`GridDing0`, branch in :obj:`BranchDing0`) ::
(no... | 8.532785 | 10.025211 | 0.851133 |
# get edges with attributes
edges = nx.get_edge_attributes(self._graph, 'branch').items()
# sort them according to connected nodes
edges_sorted = sorted(list(edges), key=lambda _: (''.join(sorted([repr(_[0][0]),repr(_[0][1])]))))
for edge in edges_sorted:
... | def graph_edges(self) | Returns a generator for iterating over graph edges
The edge of a graph is described by the two adjacent node and the branch
object itself. Whereas the branch object is used to hold all relevant
power system parameters.
Yields
------
int
Description #TODO che... | 5.563266 | 4.475753 | 1.242979 |
if (node_source in self._graph.nodes()) and (node_target in self._graph.nodes()):
path = nx.shortest_path(self._graph, node_source, node_target)
else:
raise Exception('At least one of the nodes is not a member of graph.')
if type == 'nodes':
return pa... | def find_path(self, node_source, node_target, type='nodes') | Determines shortest path
Determines the shortest path from `node_source` to
`node_target` in _graph using networkx' shortest path
algorithm.
Args
----
node_source: GridDing0
source node, member of _graph
node_target: GridDing0
target node... | 2.420948 | 2.252124 | 1.074962 |
branches = set()
for node_target in nodes_target:
path = self.find_path(node_source, node_target)
node_pairs = list(zip(path[0:len(path) - 1], path[1:len(path)]))
for n1, n2 in node_pairs:
branches.add(self._graph.adj[n1][n2]['branch'])
... | def find_and_union_paths(self, node_source, nodes_target) | Determines shortest paths from `node_source` to all nodes in `node_target` in _graph using find_path().
The branches of all paths are stored in a set - the result is a list of unique branches.
Args
----
node_source: GridDing0
source node, member of _graph
node_targe... | 2.596536 | 2.723397 | 0.953418 |
length = 0
path = self.find_path(node_source, node_target)
node_pairs = list(zip(path[0:len(path)-1], path[1:len(path)]))
for n1, n2 in node_pairs:
length += self._graph.adj[n1][n2]['branch'].length
return length | def graph_path_length(self, node_source, node_target) | Calculates the absolute distance between `node_source` and `node_target` in meters using find_path() and branches' length attribute.
Args
----
node_source: GridDing0
source node, member of _graph
node_target: GridDing0
target node, member of _graph
Retur... | 3.241385 | 3.089654 | 1.049109 |
return sorted(nx.isolates(self._graph), key=lambda x: repr(x)) | def graph_isolated_nodes(self) | Finds isolated nodes = nodes with no neighbors (degree zero)
Returns
-------
:any:`list` of :obj:`GridDing0`
List of nodes (Ding0 objects) | 6.572395 | 10.34041 | 0.635603 |
if transformer not in self.transformers() and isinstance(transformer, TransformerDing0):
self._transformers.append(transformer) | def add_transformer(self, transformer) | Adds a transformer to _transformers if not already existing
Args
----
transformer : StationDing0
Description #TODO | 9.734548 | 4.636382 | 2.0996 |
for branch in self._grid.graph_edges():
if branch['branch'].ring == self:
yield branch | def branches(self) | #TODO: description | 22.909676 | 19.350052 | 1.183959 |
for lv_load_area in self._grid._graph.nodes():
if isinstance(lv_load_area, LVLoadAreaDing0):
if lv_load_area.ring == self:
yield lv_load_area | def lv_load_areas(self) | #TODO: description | 7.902644 | 7.215632 | 1.095212 |
self.branch_nodes = self.grid.graph_nodes_from_branch(self.branch)
self.grid._graph.remove_edge(self.branch_nodes[0], self.branch_nodes[1])
self.status = 'open' | def open(self) | Open a Circuit Breaker #TODO Check | 5.52843 | 5.226285 | 1.057812 |
self.grid._graph.add_edge(self.branch_nodes[0], self.branch_nodes[1], branch=self.branch)
self.status = 'closed' | def close(self) | Close a Circuit Breaker #TODO Check | 7.493082 | 7.466626 | 1.003543 |
for load_area in sorted(self._lv_load_areas, key=lambda _: repr(_)):
yield load_area | def lv_load_areas(self) | Returns a generator for iterating over load_areas
Yields
------
int
generator for iterating over load_areas | 7.938279 | 6.551208 | 1.211727 |
if lv_load_area not in self.lv_load_areas() and isinstance(lv_load_area, LVLoadAreaDing0):
self._lv_load_areas.append(lv_load_area)
self.mv_grid.graph_add_node(lv_load_area.lv_load_area_centre) | def add_lv_load_area(self, lv_load_area) | Adds a Load Area `lv_load_area` to _lv_load_areas if not already existing
Additionally, adds the associated centre object to MV grid's _graph as node.
Args
----
lv_load_area: LVLoadAreaDing0
instance of class LVLoadAreaDing0 | 4.956326 | 2.367167 | 2.093779 |
if lv_load_area_group not in self.lv_load_area_groups():
self._lv_load_area_groups.append(lv_load_area_group) | def add_lv_load_area_group(self, lv_load_area_group) | Adds a LV load_area to _lv_load_areas if not already existing. | 2.045484 | 1.789218 | 1.143228 |
peak_load = peak_load_satellites = 0
for lv_load_area in self.lv_load_areas():
peak_load += lv_load_area.peak_load
if lv_load_area.is_satellite:
peak_load_satellites += lv_load_area.peak_load
self.peak_load = peak_load
self.peak_load_satel... | def add_peak_demand(self) | Summarizes peak loads of underlying load_areas in kVA.
(peak load sum and peak load of satellites) | 2.76101 | 1.976872 | 1.396656 |
peak_load_aggregated = 0
for lv_load_area in self.lv_load_areas():
if lv_load_area.is_aggregated:
peak_load_aggregated += lv_load_area.peak_load
self.peak_load_aggregated = peak_load_aggregated | def add_aggregated_peak_demand(self) | Summarizes peak loads of underlying aggregated load_areas | 3.134847 | 2.522808 | 1.242603 |
for lv_grid_district in sorted(self._lv_grid_districts, key=lambda _: repr(_)):
yield lv_grid_district | def lv_grid_districts(self) | Returns a generator for iterating over LV grid districts
Yields
------
int
generator for iterating over LV grid districts | 5.523403 | 5.387459 | 1.025233 |
# TODO: check docstring
if lv_grid_district not in self._lv_grid_districts and \
isinstance(lv_grid_district, LVGridDistrictDing0):
self._lv_grid_districts.append(lv_grid_district) | def add_lv_grid_district(self, lv_grid_district) | Adds a LV grid district to _lv_grid_districts if not already existing
Args
----
lv_grid_district: :shapely:`Shapely Polygon object<polygons>`
Descr | 5.583476 | 6.732447 | 0.829338 |
cum_peak_generation = 0
for lv_grid_district in self._lv_grid_districts:
cum_peak_generation += lv_grid_district.lv_grid.station().peak_generation
return cum_peak_generation | def peak_generation(self) | Cumulative peak generation of generators connected to LV grids of
underlying LVGDs | 6.858512 | 4.413432 | 1.554009 |
i, j = pair
return (self._nodes[i.name()], self._nodes[j.name()]) | def get_pair(self, pair) | get pair description
Parameters
----------
pair : :any:`list` of nodes
Descr
Returns
-------
type
Descr | 7.77844 | 11.375124 | 0.683811 |
return all(
[node.route_allocation() is not None for node in list(self._nodes.values()) if node != self._problem.depot()]
) | def is_complete(self) | Returns True if this is a complete solution, i.e, all nodes are allocated
Returns
-------
bool
True if all nodes are llocated. | 14.015121 | 13.059047 | 1.073212 |
new_solution = self.__class__(self._problem, len(self._routes))
# Clone routes
for index, r in enumerate(self._routes):
new_route = new_solution._routes[index]
for node in r.nodes():
# Insere new node on new route
new_node = new_... | def clone(self) | Returns a deep copy of self
Function clones:
* route
* allocation
* nodes
Returns
-------
type
Deep copy of self | 5.31052 | 4.918532 | 1.079696 |
length = 0
for r in self._routes:
length = length + r.length()
return length | def length(self) | Returns the solution length (or cost)
Returns
-------
float
Solution length (or cost). | 6.011125 | 8.171841 | 0.73559 |
g = nx.Graph()
ntemp = []
nodes_pos = {}
demands = {}
demands_pos = {}
for no, node in self._nodes.items():
g.add_node(node)
ntemp.append(node)
coord = self._problem._coord[no]
nodes_pos[node] = tuple(coord)
... | def draw_network(self, anim) | Draws solution's graph using networkx
Parameters
----------
AnimationDing0
AnimationDing0 object | 2.605197 | 2.576071 | 1.011306 |
branches = []
polygon_shp = transform(proj, polygon)
for branch in mv_grid.graph_edges():
nodes = branch['adj_nodes']
branch_shp = transform(proj, LineString([nodes[0].geo_data, nodes[1].geo_data]))
# check if branches intersect with polygon if mode = 'intersects'
if m... | def calc_geo_branches_in_polygon(mv_grid, polygon, mode, proj) | Calculate geographical branches in polygon.
For a given `mv_grid` all branches (edges in the graph of the grid) are
tested if they are in the given `polygon`. You can choose different modes
and projections for this operation.
Parameters
----------
mv_grid : MVGridDing0
MV Grid object. ... | 3.077422 | 2.857816 | 1.076844 |
branches = []
while not branches:
node_shp = transform(proj, node.geo_data)
buffer_zone_shp = node_shp.buffer(radius)
for branch in mv_grid.graph_edges():
nodes = branch['adj_nodes']
branch_shp = transform(proj, LineString([nodes[0].geo_data, nodes[1].geo_d... | def calc_geo_branches_in_buffer(node, mv_grid, radius, radius_inc, proj) | Determines branches in nodes' associated graph that are at least partly
within buffer of `radius` from `node`.
If there are no nodes, the buffer is successively extended by `radius_inc`
until nodes are found.
Parameters
----------
node : LVStationDing0, GeneratorDing0, or CableDistributorD... | 3.692906 | 3.363073 | 1.098075 |
branch_detour_factor = cfg_ding0.get('assumptions', 'branch_detour_factor')
# notice: vincenty takes (lat,lon)
branch_length = branch_detour_factor * vincenty((node_source.geo_data.y, node_source.geo_data.x),
(node_target.geo_data.y, node_target.geo... | def calc_geo_dist_vincenty(node_source, node_target) | Calculates the geodesic distance between `node_source` and `node_target`
incorporating the detour factor specified in :file:`ding0/ding0/config/config_calc.cfg`.
Parameters
----------
node_source: LVStationDing0, GeneratorDing0, or CableDistributorDing0
source node, member of GridDing0._graph
... | 10.581438 | 9.380624 | 1.12801 |
branch_detour_factor = cfg_ding0.get('assumptions', 'branch_detour_factor')
matrix = {}
for i in nodes_pos:
pos_origin = tuple(nodes_pos[i])
matrix[i] = {}
for j in nodes_pos:
pos_dest = tuple(nodes_pos[j])
# notice: vincenty takes (lat,lon), thus th... | def calc_geo_dist_matrix_vincenty(nodes_pos) | Calculates the geodesic distance between all nodes in `nodes_pos` incorporating the detour factor in config_calc.cfg.
For every two points/coord it uses geopy's vincenty function (formula devised by Thaddeus Vincenty,
with an accurate ellipsoidal model of the earth). As default ellipsoidal model of th... | 5.362046 | 5.07497 | 1.056567 |
proj_source = partial(
pyproj.transform,
pyproj.Proj(init='epsg:4326'), # source coordinate system
pyproj.Proj(init='epsg:3035')) # destination coordinate system
# ETRS (equidistant) to WGS84 (conformal) projection
proj_target = partial(
pyproj.transf... | def calc_geo_centre_point(node_source, node_target) | Calculates the geodesic distance between `node_source` and `node_target`
incorporating the detour factor specified in config_calc.cfg.
Parameters
----------
node_source: LVStationDing0, GeneratorDing0, or CableDistributorDing0
source node, member of GridDing0._graph
node_target: LVStati... | 2.408222 | 2.567566 | 0.937939 |
# backup kind and type of branch
branch_kind = graph.adj[node][target_obj_result]['branch'].kind
branch_type = graph.adj[node][target_obj_result]['branch'].type
branch_ring = graph.adj[node][target_obj_result]['branch'].ring
graph.remove_edge(node, target_obj_result)
if isinstance(target... | def disconnect_node(node, target_obj_result, graph, debug) | Disconnects `node` from `target_obj`
Args
----
node: LVLoadAreaCentreDing0, i.e.
Origin node - Ding0 graph object (e.g. LVLoadAreaCentreDing0)
target_obj_result: LVLoadAreaCentreDing0, i.e.
Origin node - Ding0 graph object (e.g. LVLoadAreaCentreDing0)
graph: :networkx:`NetworkX Grap... | 3.832967 | 3.284954 | 1.166825 |
for branch in mv_grid.graph_edges():
if branch['branch'].kind is None:
branch['branch'].kind = mv_grid.default_branch_kind
if branch['branch'].type is None:
branch['branch'].type = mv_grid.default_branch_type | def parametrize_lines(mv_grid) | Set unparametrized branches to default branch type
Args
----
mv_grid: MVGridDing0
MV grid instance
Notes
-----
During the connection process of satellites, new branches are created -
these have to be parametrized. | 4.041998 | 3.173612 | 1.273627 |
# get power factor for loads
cos_phi_load = cfg_ding0.get('assumptions', 'cos_phi_load')
specs = {}
nodes_demands = {}
nodes_pos = {}
nodes_agg = {}
# check if there are only load areas of type aggregated and satellite
# -> treat satellites as normal load areas (allow for routing... | def ding0_graph_to_routing_specs(graph) | Build data dictionary from graph nodes for routing (translation)
Args
----
graph: :networkx:`NetworkX Graph Obj< >`
NetworkX graph object with nodes
Returns
-------
:obj:`dict`
Data dictionary for routing.
See Also
--------
ding0.grid.mv_grid.models.models.... | 5.019336 | 4.942732 | 1.015498 |
# TODO: check docstring
# TODO: Implement debug mode (pass to solver) to get more information while routing (print routes, draw network, ..)
# translate DING0 graph to routing specs
specs = ding0_graph_to_routing_specs(graph)
# create routing graph using specs
RoutingGraph = Graph(specs)... | def solve(graph, debug=False, anim=None) | Do MV routing for given nodes in `graph`.
Translate data from node objects to appropriate format before.
Args
----
graph: :networkx:`NetworkX Graph Obj< >`
NetworkX graph object with nodes
debug: bool, defaults to False
If True, information is printed while routing
anim: An... | 5.30019 | 5.185751 | 1.022068 |
I_max_load = nom_power / (3 ** 0.5 * nom_voltage)
# determine suitable cable for this current
suitable_cables = avail_cables[avail_cables['I_max_th'] > I_max_load]
if not suitable_cables.empty:
cable_type = suitable_cables.loc[suitable_cables['I_max_th'].idxmin(), :]
else:
cab... | def cable_type(nom_power, nom_voltage, avail_cables) | Determine suitable type of cable for given nominal power
Based on maximum occurring current which is derived from nominal power
(either peak load or max. generation capacity) a suitable cable type is
chosen. Thus, no line overloading issues should occur.
Parameters
----------
nom_power : float... | 3.030333 | 2.9481 | 1.027894 |
logging.info('Handling duplications for "%s"', file_path)
f = open_strings_file(file_path, "r+")
header_comment_key_value_tuples = extract_header_comment_key_value_tuples_from_file(f)
file_elements = []
section_file_elements = []
keys_to_objects = {}
duplicates_found = []
for header... | def handle_duplications(file_path) | Omits the duplications in the strings files.
Keys that appear more than once, will be joined to one appearance and the omit will be documented.
Args:
file_path (str): The path to the strings file. | 2.837529 | 2.757862 | 1.028887 |
for resource in self._client._resources:
# set the name param, the keys now have / in them
potion_resource = self._client._resources[resource]
try:
oc_cls = _model_lookup[resource]
oc_cls._api = self
oc_cls._resource ... | def _copy_resources(self) | Copy all of the resources over to the toplevel client
-return: populates self with a pointer to each ._client.Resource | 9.206866 | 7.792552 | 1.181496 |
username = click.prompt("Please enter your One Codex (email)")
if api_key is not None:
return username, api_key
password = click.prompt("Please enter your password (typing will be hidden)", hide_input=True)
# now get the API key
api_key = fetch_api_key_from_uname(username, password, s... | def login_uname_pwd(server, api_key=None) | Prompts user for username and password, gets API key from server
if not provided. | 4.92258 | 4.800658 | 1.025397 |
# fetch_api_key and check_version expect server to end in /
if server[-1] != "/":
server = server + "/"
# creds file path setup
if creds_file is None:
creds_file = os.path.expanduser("~/.onecodex")
# check if the creds file exists and is readable
if not os.path.exists(cred... | def _login(server, creds_file=None, api_key=None, silent=False) | Login main function | 2.739458 | 2.728225 | 1.004117 |
if creds_file is None:
creds_file = os.path.expanduser("~/.onecodex")
try:
os.remove(creds_file)
except Exception as e:
if e.errno == errno.ENOENT:
return False
elif e.errno == errno.EACCES:
click.echo(
"Please check the permissio... | def _remove_creds(creds_file=None) | Remove ~/.onecodex file, returning True if successul or False if the file didn't exist | 2.828179 | 2.309907 | 1.224369 |
if _remove_creds(creds_file=creds_file):
click.echo("Successfully removed One Codex credentials.", err=True)
sys.exit(0)
else:
click.echo("No One Codex API keys found.", err=True)
sys.exit(1) | def _logout(creds_file=None) | Logout main function, just rm ~/.onecodex more or less | 4.038608 | 2.951015 | 1.368549 |
@wraps(fn)
def login_wrapper(ctx, *args, **kwargs):
base_url = os.environ.get("ONE_CODEX_API_BASE", "https://app.onecodex.com")
api_kwargs = {"telemetry": ctx.obj["TELEMETRY"]}
api_key_prior_login = ctx.obj.get("API_KEY")
bearer_token_env = os.environ.get("ONE_CODEX_BEARE... | def login_required(fn) | Requires login before proceeding, but does not prompt the user to login. Decorator should
be used only on Click CLI commands.
Notes
-----
Different means of authentication will be attempted in this order:
1. An API key present in the Click context object from a previous successful authenticatio... | 2.493664 | 2.095085 | 1.190245 |
if json is True:
return self._results()
else:
return self._table() | def results(self, json=True) | Returns the complete results table for the classification.
Parameters
----------
json : bool, optional
Return result as JSON? Default True.
Returns
-------
table : dict | DataFrame
Return a JSON object with the classification results or a Pandas ... | 6.001199 | 8.472309 | 0.708331 |
# TODO: Consider removing this method... since it's kind of trivial
# May want to replace with something that actually gets genome-size adjusted
# abundances from the results table
if ids is None:
# get the data frame
return self.table()
... | def abundances(self, ids=None) | Query the results table to get abundance data for all or some tax ids | 12.489598 | 10.806844 | 1.155712 |
super(Samples, self).save()
if self.metadata is not None:
self.metadata.save() | def save(self) | Persist changes on this Samples object back to the One Codex server along with any changes
on its metadata (if it has any). | 6.085618 | 3.003932 | 2.025884 |
res = cls._resource
if not isinstance(files, string_types) and not isinstance(files, tuple):
raise OneCodexException(
"Please pass a string or tuple or forward and reverse filepaths."
)
if not isinstance(project, Projects) and project is not None... | def upload(
cls, files, metadata=None, tags=None, project=None, coerce_ascii=False, progressbar=None
) | Uploads a series of files to the One Codex server.
Parameters
----------
files : `string` or `tuple`
A single path to a file on the system, or a tuple containing a pairs of paths. Tuple
values will be interleaved as paired-end reads and both files should contain the sam... | 3.27581 | 3.154845 | 1.038343 |
for comment in comments:
if comment not in self.comments and len(comment) > 0:
self.comments.append(comment)
if len(self.comments[0]) == 0:
self.comments.pop(0) | def add_comments(self, comments) | Add comments to the localization entry
Args:
comments (list of str): The comments to be added to the localization entry. | 2.524955 | 2.725772 | 0.926327 |
logging.info("Merging translations")
for lang_dir in os.listdir(localization_bundle_path):
if lang_dir == DEFAULT_LANGUAGE_DIRECTORY_NAME:
continue
for translated_path in glob.glob(os.path.join(localization_bundle_path, lang_dir, "*" + TRANSLATED_SUFFIX)):
strings_pa... | def merge_translations(localization_bundle_path) | Merges the new translation with the old one.
The translated files are saved as '.translated' file, and are merged with old translated file.
Args:
localization_bundle_path (str): The path to the localization bundle. | 2.969527 | 3.082527 | 0.963342 |
# TODO: Refactor into an Exception class
error_code = resp.status_code
if error_code == 402:
error_message = (
"Please add a payment method to upload more samples. If you continue to "
"experience problems, contact us at help@onecodex.com for assistance."
)
... | def raise_api_error(resp, state=None) | Raise an exception with a pretty message in various states of upload | 2.701721 | 2.611308 | 1.034623 |
# Special case validation errors
if len(err_json) == 1 and "validationOf" in err_json[0]:
required_fields = ", ".join(err_json[0]["validationOf"]["required"])
return "Validation error. Requires properties: {}.".format(required_fields)
# General error handling
msg = "; ".join(err.ge... | def pretty_print_error(err_json) | Pretty print Flask-Potion error messages for the user. | 4.538056 | 4.617345 | 0.982828 |
if include_references:
return json.dumps(self._resource._properties, cls=PotionJSONEncoder)
else:
return json.dumps(
{
k: v
for k, v in self._resource._properties.items()
if not isinstance(v, Res... | def _to_json(self, include_references=True) | Convert the model to JSON using the PotionJSONEncode and automatically
resolving the resource as needed (`_properties` call handles this). | 3.067401 | 2.144631 | 1.43027 |
return cls.where(sort=sort, limit=limit) | def all(cls, sort=None, limit=None) | Returns all objects of this type. Alias for where() (without filter arguments).
See `where` for documentation on the `sort` and `limit` parameters. | 6.556911 | 5.158731 | 1.271032 |
check_bind(cls)
# do this here to avoid passing this on to potion
filter_func = keyword_filters.pop("filter", None)
public = False
if any(x["rel"] == "instances_public" for x in cls._resource._schema["links"]):
public = keyword_filters.pop("public", False)
... | def where(cls, *filters, **keyword_filters) | Retrieves objects (Samples, Classifications, etc.) from the One Codex server.
Parameters
----------
filters : objects
Advanced filters to use (not implemented)
sort : string | list, optional
Sort the results by this field (or list of fields). By default in descen... | 4.577348 | 4.724544 | 0.968844 |
check_bind(cls)
# we're just retrieving one object from its uuid
try:
resource = cls._resource.fetch(uuid)
if isinstance(resource, list):
# TODO: Investigate why potion .fetch()
# method is occassionally returning a list her... | def get(cls, uuid) | Retrieve one specific object from the server by its UUID (unique 16-character id). UUIDs
can be found in the web browser's address bar while viewing analyses and other objects.
Parameters
----------
uuid : string
UUID of the object to retrieve.
Returns
-----... | 6.378347 | 7.510483 | 0.849259 |
check_bind(self)
if self.id is None:
raise ServerError("{} object does not exist yet".format(self.__class__.name))
elif not self.__class__._has_schema_method("destroy"):
raise MethodNotSupported("{} do not support deletion.".format(self.__class__.__name__))
... | def delete(self) | Delete this object from the One Codex server. | 5.4529 | 5.145936 | 1.059652 |
check_bind(self)
creating = self.id is None
if creating and not self.__class__._has_schema_method("create"):
raise MethodNotSupported("{} do not support creating.".format(self.__class__.__name__))
if not creating and not self.__class__._has_schema_method("update"):
... | def save(self) | Either create or persist changes on this object back to the One Codex server. | 2.876935 | 2.647536 | 1.086646 |
if not isinstance(file_path, tuple):
raise OneCodexException("Cannot get the interleaved filename without a tuple.")
if re.match(".*[._][Rr][12][_.].*", file_path[0]):
return re.sub("[._][Rr][12]", "", file_path[0])
else:
warnings.warn("Paired-end filenames do not match--are you... | def interleaved_filename(file_path) | Return filename used to represent a set of paired-end files. Assumes Illumina-style naming
conventions where each file has _R1_ or _R2_ in its name. | 6.019132 | 5.040504 | 1.194153 |
_, ext = os.path.splitext(file_path)
if uncompressed:
if ext in {".gz", ".gzip"}:
with gzip.GzipFile(file_path, mode="rb") as fp:
try:
fp.seek(0, os.SEEK_END)
return fp.tell()
except ValueError:
... | def _file_size(file_path, uncompressed=False) | Return size of a single file, compressed or uncompressed | 2.34716 | 2.302177 | 1.019539 |
if isinstance(file_path, tuple):
assert len(file_path) == 2
file_size = sum(_file_size(f, uncompressed=True) for f in file_path)
file_path = interleaved_filename(file_path)
paired = True
else:
file_size = _file_size(file_path, uncompressed=False)
paired = Fal... | def _file_stats(file_path, enforce_fastx=True) | Return information about the file path (or paths, if paired), prior to upload.
Parameters
----------
file_path : `string` or `tuple`
System path to the file(s) to be uploaded
Returns
-------
`string`
Filename, minus compressed extension (.gz or .bz2). If paired, use first path ... | 2.730831 | 2.496361 | 1.093925 |
upload_args = {
"filename": file_name,
"size": file_size,
"upload_type": "standard", # this is multipart form data
}
if metadata:
# format metadata keys as snake case
new_metadata = {}
for md_key, md_val in metadata.items():
new_metadata[sn... | def _call_init_upload(file_name, file_size, metadata, tags, project, samples_resource) | Call init_upload at the One Codex API and return data used to upload the file.
Parameters
----------
file_name : `string`
The file_name you wish to associate this fastx file with at One Codex.
file_size : `integer`
Accurate size of file to be uploaded, in bytes.
metadata : `dict`, o... | 2.934888 | 3.289283 | 0.892258 |
upload_args = {"filename": file_name}
if metadata:
# format metadata keys as snake case
new_metadata = {}
for md_key, md_val in metadata.items():
new_metadata[snake_case(md_key)] = md_val
upload_args["metadata"] = new_metadata
if tags:
upload_args... | def _make_retry_fields(file_name, metadata, tags, project) | Generate fields to send to init_multipart_upload in the case that a Sample upload via
fastx-proxy fails.
Parameters
----------
file_name : `string`
The file_name you wish to associate this fastx file with at One Codex.
metadata : `dict`, optional
tags : `list`, optional
project : `s... | 2.693162 | 3.025556 | 0.890138 |
filename, file_size, file_format = _file_stats(files)
# if filename cannot be represented as ascii, raise and suggest renaming
try:
# python2
ascii_fname = unidecode(unicode(filename))
except NameError:
ascii_fname = unidecode(filename)
if filename != ascii_fname:
... | def upload_sequence(
files,
session,
samples_resource,
metadata=None,
tags=None,
project=None,
coerce_ascii=False,
progressbar=None,
) | Uploads a sequence file (or pair of files) to the One Codex server via either our proxy or directly to S3.
Parameters
----------
files : `list`
A list of paths to files on the system, or tuples containing pairs of paths. Tuples will be
interleaved as paired-end reads and both files should c... | 6.465041 | 6.242902 | 1.035583 |
# need an OrderedDict to preserve field order for S3, required for Python 2.7
multipart_fields = OrderedDict()
for k, v in fields["additional_fields"].items():
multipart_fields[str(k)] = str(v)
# this attribute is only in FASTXInterleave and FilePassthru
mime_type = getattr(file_obj,... | def _direct_upload(file_obj, file_name, fields, session, samples_resource) | Uploads a single file-like object via our validating proxy. Maintains compatibility with direct upload
to a user's S3 bucket as well in case we disable our validating proxy.
Parameters
----------
file_obj : `FASTXInterleave`, `FilePassthru`, or a file-like object
A wrapper around a pair of fast... | 4.346481 | 3.859188 | 1.126268 |
# First attempt to upload via our validating proxy
try:
_direct_upload(file_obj, file_name, fields, session, samples_resource)
sample_id = fields["sample_id"]
except RetryableUploadException:
# upload failed--retry direct upload to S3 intermediate
logging.error("{}: Con... | def upload_sequence_fileobj(file_obj, file_name, fields, retry_fields, session, samples_resource) | Uploads a single file-like object to the One Codex server via either fastx-proxy or directly
to S3.
Parameters
----------
file_obj : `FASTXInterleave`, `FilePassthru`, or a file-like object
A wrapper around a pair of fastx files (`FASTXInterleave`) or a single fastx file. In the
case of... | 5.071667 | 4.744657 | 1.068922 |
if not isinstance(file_path, six.string_types):
raise ValueError(
"Expected file_path to be a string, got {}".format(type(file_path).__name__)
)
file_name, file_size, _ = _file_stats(file_path, enforce_fastx=False)
# disable progressbar while keeping context manager
if... | def upload_document(file_path, session, documents_resource, progressbar=None) | Uploads multiple document files to the One Codex server directly to S3 via an intermediate
bucket.
Parameters
----------
file_path : `str`
A path to a file on the system.
session : `requests.Session`
Connection to One Codex API.
documents_resource : `onecodex.models.Documents`
... | 4.528031 | 4.892467 | 0.925511 |
try:
fields = documents_resource.init_multipart_upload()
except requests.exceptions.HTTPError as e:
raise_api_error(e.response, state="init")
except requests.exceptions.ConnectionError:
raise_connectivity_error(file_name)
s3_upload = _s3_intermediate_upload(
file_ob... | def upload_document_fileobj(file_obj, file_name, session, documents_resource, log=None) | Uploads a single file-like object to the One Codex server directly to S3.
Parameters
----------
file_obj : `FilePassthru`, or a file-like object
If a file-like object is given, its mime-type will be sent as 'text/plain'. Otherwise,
`FilePassthru` will send a compressed type if the file is g... | 5.761273 | 5.600255 | 1.028752 |
import boto3
from boto3.s3.transfer import TransferConfig
from boto3.exceptions import S3UploadFailedError
# actually do the upload
client = boto3.client(
"s3",
aws_access_key_id=fields["upload_aws_access_key_id"],
aws_secret_access_key=fields["upload_aws_secret_access_... | def _s3_intermediate_upload(file_obj, file_name, fields, session, callback_url) | Uploads a single file-like object to an intermediate S3 bucket which One Codex can pull from
after receiving a callback.
Parameters
----------
file_obj : `FASTXInterleave`, `FilePassthru`, or a file-like object
A wrapper around a pair of fastx files (`FASTXInterleave`) or a single fastx file. I... | 2.767095 | 2.868206 | 0.964748 |
assert loc == 0
# rewind progress bar
if self.progressbar:
self.progressbar.update(-self._tell)
self._fp_left.seek(loc)
self._fp_right.seek(loc)
self._tell = loc
self._buf = Buffer() | def seek(self, loc) | Called if upload fails and must be retried. | 7.161305 | 7.357125 | 0.973384 |
assert loc == 0
# rewind progress bar
if self.progressbar:
self.progressbar.update(-self._fp.tell())
self._fp.seek(loc) | def seek(self, loc) | Called if upload fails and must be retried. | 7.871243 | 8.153096 | 0.96543 |
old_localizable_dict = generate_localization_key_to_entry_dictionary_from_file(old_strings_file)
output_file_elements = []
f = open_strings_file(new_strings_file, "r+")
for header_comment, comments, key, value in extract_header_comment_key_value_tuples_from_file(f):
if len(header_comment)... | def merge_strings_files(old_strings_file, new_strings_file) | Merges the old strings file with the new one.
Args:
old_strings_file (str): The path to the old strings file (previously produced, and possibly altered)
new_strings_file (str): The path to the new strings file (newly produced). | 3.15447 | 3.347608 | 0.942306 |
parser.add_argument("--log_path", default="", help="The log file path")
parser.add_argument("--verbose", help="Increase logging verbosity", action="store_true") | def configure_parser(self, parser) | Adds the necessary supported arguments to the argument parser.
Args:
parser (argparse.ArgumentParser): The parser to add arguments to. | 3.950506 | 4.479877 | 0.881833 |
parser = argparse.ArgumentParser(description=self.description())
self.configure_parser(parser)
self.run(parser.parse_args()) | def run_with_standalone_parser(self) | Will run the operation as standalone with a new ArgumentParser | 3.720838 | 3.125711 | 1.190397 |
if metric not in ("simpson", "chao1", "shannon"):
raise OneCodexException(
"For alpha diversity, metric must be one of: simpson, chao1, shannon"
)
# needs read counts, not relative abundances
if self._guess_normalized():
raise OneCode... | def alpha_diversity(self, metric="simpson", rank="auto") | Caculate the diversity within a community.
Parameters
----------
metric : {'simpson', 'chao1', 'shannon'}
The diversity metric to calculate.
rank : {'auto', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species'}, optional
Analysis will be restricted... | 4.169699 | 3.945018 | 1.056953 |
if metric not in ("jaccard", "braycurtis", "cityblock"):
raise OneCodexException(
"For beta diversity, metric must be one of: jaccard, braycurtis, cityblock"
)
# needs read counts, not relative abundances
if self._guess_normalized():
... | def beta_diversity(self, metric="braycurtis", rank="auto") | Calculate the diversity between two communities.
Parameters
----------
metric : {'jaccard', 'braycurtis', 'cityblock'}
The distance metric to calculate.
rank : {'auto', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species'}, optional
Analysis will b... | 4.138778 | 4.000818 | 1.034483 |
# needs read counts, not relative abundances
if self._guess_normalized():
raise OneCodexException("UniFrac requires unnormalized read counts.")
df = self.to_df(rank=rank, normalize=False)
counts = []
for c_id in df.index:
counts.append(df.loc[c_... | def unifrac(self, weighted=True, rank="auto") | A beta diversity metric that takes into account the relative relatedness of community
members. Weighted UniFrac looks at abundances, unweighted UniFrac looks at presence.
Parameters
----------
weighted : `bool`
Calculate the weighted (True) or unweighted (False) distance met... | 4.907873 | 4.882109 | 1.005277 |
# TODO: Hit programmatic endpoint to fetch JWT key, not API key
with requests.Session() as session:
# get the login page normally
text = session.get(server_url + "login").text
# retrieve the CSRF token out of it
csrf = re.search('type="hidden" value="([^"]+)"', text).group(... | def fetch_api_key_from_uname(username, password, server_url) | Retrieves an API key from the One Codex webpage given the username and password | 4.420158 | 4.450814 | 0.993112 |
def version_inadequate(client_version, server_version):
client_version = tuple([int(x) for x in client_version.split("-")[0].split(".")])
server_version = tuple([int(x) for x in server_version.split(".")])
return client_version < server_version
# this will probably live o... | def check_version(version, server) | Check if the current CLI version is supported by the One Codex backend.
Parameters
----------
version : `string`
Current version of the One Codex client library
server : `string`
Complete URL to One Codex server, e.g., https://app.onecodex.com
Returns
-------
`tuple` contai... | 3.843582 | 3.464996 | 1.10926 |
if value is not None and len(value) != 32:
raise click.BadParameter(
"API Key must be 32 characters long, not {}".format(str(len(value)))
)
else:
return value | def valid_api_key(ctx, param, value) | Ensures an API has valid length (this is a click callback) | 2.565888 | 2.172046 | 1.181323 |
if not no_pretty:
click.echo(
json.dumps(j, cls=PotionJSONEncoder, sort_keys=True, indent=4, separators=(",", ": "))
)
else:
click.echo(j) | def pprint(j, no_pretty) | Prints as formatted JSON | 2.994063 | 2.964657 | 1.009919 |
v = sys.version_info
if v.major == 3:
return False # Python 2 issue
if v.major == 2 and v.minor == 7 and v.micro >= 9:
return False # >= 2.7.9 includes the new SSL updates
try:
import OpenSSL # noqa
import ndg # noqa
import pyasn1 # noqa
except Imp... | def is_insecure_platform() | Checks if the current system is missing an SSLContext object | 4.894665 | 4.788428 | 1.022186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.