Skip to content

Commit

Permalink
Update docs (#122)
Browse files Browse the repository at this point in the history
  • Loading branch information
martinateruzzi authored Nov 16, 2021
1 parent 6d82183 commit 4dc5d7d
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 67 deletions.
62 changes: 42 additions & 20 deletions grape/fault_diagnosis.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,18 @@ def fitness_iteration_parallel(self, out_queue, ichunk, chunk_length,
index of the individual, the individual itself, and its fitness.
:param multiprocessing.queues.Queue out_queue: multiprocessing queue
:param int ichunk: index of the chunk under consideration
:param int ichunk: index of the chunk under consideration.
:param int chunk_length: lengths of the chunks (the last chunk may
be shorter due to non-even division of the number of generations by
the number of processors)
the number of processors).
:param list individuals: list of individuals on which to perform
fitness evaluation.
:param list perturbed_nodes: nodes(s) involved in the perturbing event.
:param dict initial_condition: initial status (boolean) for the graph
switches.
:param origin: origin of the perturbation. Nodes can be resitant to
different kinds of perturbations, default to None.
:type origin: string, optional
"""

for iter_ind in range(len(individuals)):
Expand All @@ -106,13 +108,16 @@ def fitness_evaluation_parallel(self, pop, perturbed_nodes,
Wrapper for fitness evaluation. This methods spawns the processes for
fitness evaluation and collects the results.
:param list pop: list of individuals
:param list pop: list of individuals.
:param list perturbed_nodes: nodes(s) involved in the perturbing event.
:param dict initial_condition: initial status (boolean) for the graph
switches.
:param origin: origin of the perturbation. Nodes can be resitant to
different kinds of perturbations, default to None.
:type origin: string, optional
:return: list of tuples constituted by the index of the individual,
the individual itself, and its fitness
the individual itself, and its fitness.
:rtype: list
"""

Expand Down Expand Up @@ -157,6 +162,9 @@ def fitness_evaluation(self, individual, perturbed_nodes,
perturbing event.
:param dict initial_condition: initial status (boolean) for the graph
switches.
:param origin: origin of the perturbation. Nodes can be resitant to
different kinds of perturbations, default to None.
:type origin: string, optional
"""

acts = np.sum(np.not_equal(list(initial_condition.values()),
Expand Down Expand Up @@ -226,7 +234,10 @@ def optimizer(self, perturbed_nodes, initial_condition, params, weights,
(default to -1.0)
- 'w5': weight for service balance over users (default to 2.0)
:param bool parallel: flag for parallel fitness evaluation of
initial population
initial populations.
:param origin: origin of the perturbation. Nodes can be resitant to
different kinds of perturbations, default to None.
:type origin: string, optional
"""

logging.getLogger().setLevel(logging.INFO)
Expand Down Expand Up @@ -263,28 +274,24 @@ def optimizer(self, perturbed_nodes, initial_condition, params, weights,
for ind, f in zip(pop, fitnesses):
ind.fitness.values = (np.dot(w, np.asarray(f)),)

# Variable keeping track of the number of generations
# Generations
g = 0

result = []
# Begin the evolution

# Population is made by individuals and fitnesses
pop = [list(couple) for couple in zip(pop, fitnesses)]
pop.sort(key=lambda x: np.dot(w, np.asarray(x[1])))

while g < params['ngen']:

# A new generation
g = g + 1

# Select the next generation individuals
# Select next generation
offspring = [x[0] for x in pop[:params['nsel']]]
pop = pop[:params['nsel']]

invalid_ind = []

# Apply crossover and mutation on the offspring
# Crossover and mutation on the offspring
for parent1, parent2 in zip(offspring[::2], offspring[1::2]):
if random.random() < params['tresh']:
child1 = toolbox.clone(parent1)
Expand Down Expand Up @@ -401,11 +408,14 @@ def rm_nodes(self, node, graph, origin, visited=None, broken_nodes=None):
:param str node: the id of the node to remove.
:param nx.DiGraph graph: graph on which to apply the node deletion
:param origin: origin of the perturbation. Nodes can be resitant to
different kinds of perturbations, default to None.
:type origin: string, optional
:param visited: nodes already visited, default to None.
:type visited: set, optional
:param broken_nodes: nodes that got broken along the perturbation,
default to None.
:type visited: list, optional
:type broken_nodes: list, optional
"""

if visited is None:
Expand Down Expand Up @@ -508,6 +518,9 @@ def delete_a_node(self, node, origin):
Delete a node in the graph.
:param str node: the id of the node to remove.
:param origin: origin of the perturbation. Nodes can be resitant to
different kinds of perturbations, default to None.
:type origin: string, optional
.. warning:: the node id must be contained in the graph.
No check is done within this function.
Expand Down Expand Up @@ -555,10 +568,13 @@ def apply_perturbation(self, perturbed_nodes, params, weights, parallel,
(default to -1.0)
- 'w5': weight for service balance over users (default to 2.0)
:param bool parallel: flag for parallel fitness evaluation of
initial population
:param bool verbose: flag for verbose printing
initial population.
:param bool verbose: flag for verbose printing.
:param origin: origin of the perturbation. Nodes can be resitant to
different kinds of perturbations, default to None.
:type origin: string, optional
:param str kind: type of simulation, used to label output files,
default to 'element'
default to 'element'.
.. note:: A perturbation, depending on the considered system,
may spread in all directions starting from the damaged
Expand Down Expand Up @@ -671,10 +687,13 @@ def simulate_element_perturbation(self, perturbed_nodes,
- 'w5': weight for service balance over users (default to 2.0)
:type weights: dict, optional
:param parallel: flag for parallel fitness evaluation of
initial population, default to False
initial population, default to False.
:type parallel: bool, optional
:param verbose: flag for verbose output, default to True
:param verbose: flag for verbose output, default to True.
:type verbose: bool, optional
:param origin: origin of the perturbation. Nodes can be resitant to
different kinds of perturbations, default to None.
:type origin: string, optional
.. note:: A perturbation, depending on the considered system,
may spread in all directions starting from the damaged
Expand Down Expand Up @@ -723,8 +742,11 @@ def simulate_area_perturbation(self, perturbed_areas, params={'npop': 300,
- 'w5': weight for service balance over users (default to 2.0)
:type weights: dict, optional
:param parallel: flag for parallel fitness evaluation of
initial population, default to False
initial population, default to False.
:type parallel: bool, optional
:param origin: origin of the perturbation. Nodes can be resitant to
different kinds of perturbations, default to None.
:type origin: string, optional
.. note:: A perturbation, depending on the considered system,
may spread in all directions starting from the damaged
Expand Down
102 changes: 55 additions & 47 deletions grape/general_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,8 @@ def floyd_warshall_kernel(self, distance, predecessor, init, stop,
:param distance: matrix of distances.
:type distance: numpy.ndarray or multiprocessing.sharedctypes.RawArray
:param predecessor: matrix of predecessors.
:type predecessor: numpy.ndarray or multiprocessing.sharedctypes.RawArray
:type predecessor: numpy.ndarray or
multiprocessing.sharedctypes.RawArray
:param int init: starting column of numpy matrix slice.
:param int stop: ending column of numpy matrix slice.
:param multiprocessing.synchronize.Barrier barrier:
Expand Down Expand Up @@ -1199,8 +1200,7 @@ def compute_outdegree_centrality(self):
def compute_service(self):
"""
Compute service for every node,
together with edge splitting.
Compute service for every node, together with edge splitting.
:return: computed service computed for every node;
splitting computed for every edge.
Expand Down Expand Up @@ -1268,56 +1268,64 @@ def print_graph(self, radius=None, initial_pos=None, fixed_nodes=None,
:type radius: float, optional, default to 1/sqrt(n) where n is the
number of nodes in the graph
:param initial_pos: initial positions for nodes as a dictionary with
node as keys and values as a coordinate list or tuple. If None,
then use random initial positions.
:type initial_pos: dict, optional, default to None
:param fixed_nodes: nodes to keep fixed at initial position. ValueError
raised if `fixed_nodes` specified and `initial_pos` not.
:type fixed_nodes: list, optional, default to None
node as keys and values as a coordinate list or tuple, default to
None. If None, then use random initial positions.
:type initial_pos: dict, optional
:param fixed_nodes: nodes to keep fixed at initial position, default to
None. ValueError raised if `fixed_nodes` specified and
`initial_pos` not.
:type fixed_nodes: list, optional
:param n_iter: maximum number of iterations taken in spring layout
simulation.
:type n_iter: int, optional, default to 500
simulation, default to 500.
:type n_iter: int, optional
:param thresh: threshold for relative error in node position changes.
The iteration stops if the error is below this threshold.
:type thresh: float, optional, default to 0.0001
:param size: size of nodes.
:type size: int, optional, default to 800
:param border: color of node borders.
:type border: color, optional, default to 'black'
:param edge_width: width of edges.
:type edge_width: float, optional, default to 1.0
:param arrow_size: size of the arrow head’s length and width.
:type arrow_size: int, optional, default to 10
:param fsize: font size for text labels.
:type fsize: int, optional, default to 12
:param fcolor: font color string for labels.
:type fcolor: string, optional, default to 'k' (black)
:param ffamily: font family for labels.
:type ffamily: string, optional, default to 'sans-serif'
:param title: title for figure window.
:type title: string, optional, defaut to 'Graph'
The iteration stops if the error is below this threshold,
default to 0.0001.
:type thresh: float, optional
:param size: size of nodes, default to 800.
:type size: int, optional
:param border: color of node borders, default to 'black'.
:type border: color, optional
:param edge_width: width of edges, default to 1.0.
:type edge_width: float, optional
:param arrow_size: size of the arrow head’s length and width,
default to 10.
:type arrow_size: int, optional
:param fsize: font size for text labels, default to 12.
:type fsize: int, optional
:param fcolor: font color string for labels, default to 'k' (black).
:type fcolor: string, optional
:param ffamily: font family for labels, default to 'sans-serif'.
:type ffamily: string, optional
:param title: title for figure window, default to 'Graph'.
:type title: string, optional
:param input_cmap: colormap for coloring the different areas with
different colors. If None, all nodes are colored as white.
:type input_cmap: Matplotlib colormap, optional, default to None
:param legend: show the legend on/off.
:type legend: bool, optional, default to True
:param legend_loc: the location of the legend.
:type legend_loc: str, optional, default to 'upper right'
:param legend_ncol: the number of columns that the legend has.
:type legend_ncol: int, optional, default to 1
different colors, default to None.
If None, all nodes are colored as white.
:type input_cmap: Matplotlib colormap
:param legend: show the legend on/off, default to True.
:type legend: bool, optional
:param legend_loc: the location of the legend, default to 'upper right'.
:type legend_loc: str, optional
:param legend_ncol: the number of columns that the legend has,
default to 1.
:type legend_ncol: int, optional
:param legend_anchor: box that is used to position the legend in
conjunction with loc.
:type legend_anchor: 2-tuple, or 4-tuple of floats, optional,
defaults to axes.bbox (if called as a method to Axes.legend)
or figure.bbox (if Figure.legend).
This argument allows arbitrary placement of the legend
conjunction with loc, defaults to axes.bbox (if called as a method
to Axes.legend) or figure.bbox (if Figure.legend). This argument
allows arbitrary placement of the legend.
:type legend_anchor: 2-tuple, or 4-tuple of floats, optional
:param legend_fsize: the font size of the legend. The value must be
numeric, implying the size the absolute font size in points.
:type legend_fsize: int, optional, default to 12
:param save_to_file: name of the file where to save the graph drawing.
The extension is guesses from the filename.
numeric, implying the size the absolute font size in points,
default to 12.
:type legend_fsize: int, optional
:param save_to_file: name of the file where to save the graph drawing,
default to None. The extension is guesses from the filename.
Interactive window is rendered in any case.
:type save_to_file: string, optional, default to None
:type save_to_file: string, optional
:param status: include initial condition of switches in printed graph.
To activate it, set it to 'initial', default to None.
:type status: string, optional
:return: a dictionary of positions keyed by node.
:rtype: dict
Expand Down

0 comments on commit 4dc5d7d

Please sign in to comment.