code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
valid_axes = ("country", "state", "year", "month") if any(map(lambda axis: axis not in valid_axes, fallback_aggaxes)): raise ValueError( "All elements of the fallback_aggaxes set must be one of the " f"following: {valid_axes}" ) ...
def parameterize( self, country: Optional[str] = "South Sudan", state: Optional[str] = None, year: Optional[int] = None, month: Optional[int] = None, unit: Optional[str] = None, fallback_aggaxes: List[str] = ["year", "month"], aggfunc: Callable = np.mean, ...
Parameterize the analysis graph. Args: country year month fallback_aggaxes: An iterable of strings denoting the axes upon which to perform fallback aggregation if the desired constraints cannot be met. aggfunc: The func...
3.451286
3.423018
1.008258
for n in nodes: if self.has_node(n): self.remove_node(n)
def delete_nodes(self, nodes: Iterable[str])
Iterate over a set of nodes and remove the ones that are present in the graph.
4.165965
2.907353
1.432906
if self.has_node(node): self.remove_node(node)
def delete_node(self, node: str)
Removes a node if it is in the graph.
6.142513
3.202711
1.91791
if self.has_edge(source, target): self.remove_edge(source, target)
def delete_edge(self, source: str, target: str)
Removes an edge if it is in the graph.
3.951741
2.490349
1.586822
for edge in edges: if self.has_edge(*edge): self.remove_edge(*edge)
def delete_edges(self, edges: Iterable[Tuple[str, str]])
Iterate over a set of edges and remove the ones that are present in the graph.
3.52781
2.720188
1.2969
# Remove redundant paths. for node_pair in tqdm(list(permutations(self.nodes(), 2))): paths = [ list(pairwise(path)) for path in nx.all_simple_paths(self, *node_pair, cutoff) ] if len(paths) > 1: for path in pa...
def prune(self, cutoff: int = 2)
Prunes the CAG by removing redundant paths. If there are multiple (directed) paths between two nodes, this function removes all but the longest paths. Subsequently, it restricts the graph to the largest connected component. Args: cutoff: The maximum path length to consider f...
3.367407
2.974857
1.131956
for p in self.predecessors(n1): for st in self[p][n1]["InfluenceStatements"]: if not same_polarity: st.obj_delta["polarity"] = -st.obj_delta["polarity"] st.obj.db_refs["UN"][0] = (n2, st.obj.db_refs["UN"][0][1]) if not self.h...
def merge_nodes(self, n1: str, n2: str, same_polarity: bool = True)
Merge node n1 into node n2, with the option to specify relative polarity. Args: n1 n2 same_polarity
1.905961
1.921351
0.99199
nodeset = {concept} if reverse: func = self.predecessors else: func = self.successors for i in range(depth): nodeset.update( chain.from_iterable([list(func(n)) for n in nodeset]) ) return AnalysisGraph(se...
def get_subgraph_for_concept( self, concept: str, depth: int = 1, reverse: bool = False )
Returns a new subgraph of the analysis graph for a single concept. Args: concept: The concept that the subgraph will be centered around. depth: The depth to which the depth-first search must be performed. reverse: Sets the direction of causal influence flow to examine. ...
4.371614
4.405163
0.992384
paths = nx.all_simple_paths(self, source, target, cutoff=cutoff) return AnalysisGraph(self.subgraph(set(chain.from_iterable(paths))))
def get_subgraph_for_concept_pair( self, source: str, target: str, cutoff: Optional[int] = None )
Get subgraph comprised of simple paths between the source and the target. Args: source target cutoff
5.099069
5.319389
0.958582
path_generator = ( nx.all_simple_paths(self, source, target, cutoff=cutoff) for source, target in permutations(concepts, 2) ) paths = chain.from_iterable(path_generator) return AnalysisGraph(self.subgraph(set(chain.from_iterable(paths))))
def get_subgraph_for_concept_pairs( self, concepts: List[str], cutoff: Optional[int] = None )
Get subgraph comprised of simple paths between the source and the target. Args: concepts cutoff
3.410166
4.05757
0.840445
def _format(node, level=0): if isinstance(node, ast.AST): fields = [(a, _format(b, level)) for a, b in ast.iter_fields(node)] if include_attributes and node._attributes: fields.extend( [ (a, _format(getattr(node, a), l...
def dump(node, annotate_fields=True, include_attributes=False, indent=" ")
Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. The returned string will show the names and the values for fields. This makes the code impossible to evaluate, so if evaluation is wanted *annotate_fields* must be set to False. Attributes such as line numbe...
1.676937
1.656936
1.012071
lambdaStrings = ["import math\n\n"] state = PGMState(lambdaStrings) generator = GrFNGenerator() generator.mode_mapper = mode_mapper_dict pgm = generator.genPgm(asts, state, {}, "")[0] if pgm.get("start"): pgm["start"] = pgm["start"][0] else: pgm["start"] = generator.fun...
def create_pgm_dict( lambdaFile: str, asts: List, file_name: str, mode_mapper_dict: dict, save_file=False, ) -> Dict
Create a Python dict representing the PGM, with additional metadata for JSON output.
5.18783
5.027509
1.031889
filtered_sts = [] counters = {} def update_counter(counter_name): if counter_name in counters: counters[counter_name] += 1 else: counters[counter_name] = 1 for s in tqdm(sts): update_counter("Original number of statements") # Apply belief...
def filter_and_process_statements( sts, grounding_score_cutoff: float = 0.8, belief_score_cutoff: float = 0.85, concepts_of_interest: List[str] = [], )
Filter preassembled statements according to certain rules.
2.623215
2.567667
1.021634
with open(input, "rb") as f: G = pickle.load(f) G.map_concepts_to_indicators(min_temporal_res="month") G.set_indicator("UN/events/weather/precipitation", "Historical Average Total Daily Rainfall (Maize)", "DSSAT") G.set_indicator("UN/events/human/agriculture/food_production", "H...
def create_CAG_with_indicators(input, output, filename="CAG_with_indicators.pdf")
Create a CAG with mapped indicators
7.740408
7.472154
1.035901
# Set input values for i in self.inputs: self.nodes[i]["value"] = inputs[i] for func_set in self.function_sets: for func_name in func_set: lambda_fn = self.nodes[func_name]["lambda_fn"] output_node = list(self.successors(func_name...
def run( self, inputs: Dict[str, Union[float, Iterable]], torch_size: Optional[int] = None, ) -> Union[float, Iterable]
Executes the GrFN over a particular set of inputs and returns the result. Args: inputs: Input set where keys are the names of input nodes in the GrFN and each key points to a set of input values (or just one). Returns: A set of outputs from executing the G...
2.726019
2.899873
0.940048
G = nx.DiGraph() for (name, attrs) in self.nodes(data=True): if attrs["type"] == "variable": for pred_fn in self.predecessors(name): if not any( fn_type in pred_fn for fn_type in ("condition", "deci...
def to_CAG(self)
Export to a Causal Analysis Graph (CAG) PyGraphviz AGraph object. The CAG shows the influence relationships between the variables and elides the function nodes.
3.37364
2.949736
1.143709
tab = " " result = list() for n in node_set: repr = ( n if self.nodes[n]["type"] == "variable" else f"{n}{inspect.signature(self.nodes[n]['lambda_fn'])}" ) result.append(f"{tab * depth}{repr}") ...
def traverse_nodes(self, node_set, depth=0)
BFS traversal of nodes that returns name traversal as large string. Args: node_set: Set of input nodes to begin traversal. depth: Current traversal depth for child node viewing. Returns: type: String containing tabbed traversal view.
3.559726
3.691306
0.964354
with open(file, "r") as f: data = json.load(f) return cls.from_dict(data, lambdas)
def from_json_and_lambdas(cls, file: str, lambdas)
Builds a GrFN from a JSON object. Args: cls: The class variable for object creation. file: Filename of a GrFN JSON file. Returns: type: A GroundedFunctionNetwork object.
2.680429
3.092383
0.866784
functions = {d["name"]: d for d in data["functions"]} G = nx.DiGraph() scope_tree = nx.DiGraph() def add_variable_node( basename: str, parent: str, index: int, is_loop_index: bool = False ): G.add_node( f"{parent}::{basename}_{ind...
def from_dict(cls, data: Dict, lambdas)
Builds a GrFN object from a set of extracted function data objects and an associated file of lambda functions. Args: cls: The class variable for object creation. data: A set of function data object that specify the wiring of a GrFN object. lambdas: ...
2.546379
2.575062
0.988861
with open(python_file, "r") as f: pySrc = f.read() return cls.from_python_src(pySrc, lambdas_path, json_filename, stem)
def from_python_file( cls, python_file, lambdas_path, json_filename: str, stem: str )
Builds GrFN object from Python file.
2.842518
2.543166
1.117708
asts = [ast.parse(pySrc)] pgm_dict = genPGM.create_pgm_dict( lambdas_path, asts, json_filename, {"FileName": f"{stem}.py"}, # HACK ) lambdas = importlib.__import__(stem + "_lambdas") return cls.from_dict(pgm_dict, lambdas)
def from_python_src( cls, pySrc, lambdas_path, json_filename: str, stem: str, save_file: bool = False, )
Builds GrFN object from Python source code.
6.767515
6.373628
1.061799
stem = Path(fortran_file).stem if tmpdir == "." and "/" in fortran_file: tmpdir = Path(fortran_file).parent preprocessed_fortran_file = f"{tmpdir}/{stem}_preprocessed.f" lambdas_path = f"{tmpdir}/{stem}_lambdas.py" json_filename = stem + ".json" with...
def from_fortran_file(cls, fortran_file: str, tmpdir: str = ".")
Builds GrFN object from a Fortran program.
3.794286
3.682528
1.030348
import tempfile fp = tempfile.NamedTemporaryFile('w+t', delete=False, dir=dir) fp.writelines(fortran_src) fp.close() G = cls.from_fortran_file(fp.name, dir) os.remove(fp.name) return G
def from_fortran_src(cls, fortran_src: str, dir: str = ".")
Create a GroundedFunctionNetwork instance from a string with raw Fortran code. Args: fortran_src: A string with Fortran source code. dir: (Optional) - the directory in which the temporary Fortran file will be created (make sure you have write permission!) Default...
2.791124
2.632385
1.060302
for n in self.nodes(): if self.nodes[n]["type"] == "variable": self.nodes[n]["value"] = None elif self.nodes[n]["type"] == "function": self.nodes[n]["func_visited"] = False
def clear(self)
Clear variable nodes for next computation.
3.131371
2.701942
1.158933
if not isinstance(other, GroundedFunctionNetwork): raise TypeError( f"Expected GroundedFunctionNetwork, but got {type(other)}" ) def shortname(var): return var[var.find("::") + 2 : var.rfind("_")] def shortname_vars(graph, shortname...
def to_FIB(self, other)
Creates a ForwardInfluenceBlanket object representing the intersection of this model with the other input model. Args: other: The GroundedFunctionNetwork object to compare this model to. Returns: A ForwardInfluenceBlanket object to use for model comparison.
2.658684
2.167815
1.226435
A = nx.nx_agraph.to_agraph(self) A.graph_attr.update( {"dpi": 227, "fontsize": 20, "fontname": "Menlo", "rankdir": "TB"} ) A.node_attr.update({"fontname": "Menlo"}) def build_tree(cluster_name, root_graph): subgraph_nodes = [ n[0]...
def to_agraph(self)
Export to a PyGraphviz AGraph object.
2.350634
2.327245
1.01005
CAG = self.to_CAG() A = nx.nx_agraph.to_agraph(CAG) A.graph_attr.update({"dpi": 227, "fontsize": 20, "fontname": "Menlo"}) A.node_attr.update( { "shape": "rectangle", "color": "#650021", "style": "rounded", ...
def to_CAG_agraph(self)
Returns a variable-only view of the GrFN in the form of an AGraph. Returns: type: A CAG constructed via variable influence in the GrFN object.
2.39541
2.504429
0.95647
A = nx.nx_agraph.to_agraph(self.call_graph) A.graph_attr.update({"dpi": 227, "fontsize": 20, "fontname": "Menlo"}) A.node_attr.update( {"shape": "rectangle", "color": "#650021", "style": "rounded"} ) A.edge_attr.update({"color": "#650021", "arrowsize": 0.5})...
def to_call_agraph(self)
Build a PyGraphviz AGraph object corresponding to a call graph of functions.
2.686612
2.502179
1.073709
# Abort run if covers does not match our expected cover set if len(covers) != len(self.cover_nodes): raise ValueError("Incorrect number of cover values.") # Set the cover node values for node_name, val in covers.items(): self.nodes[node_name]["value"] = ...
def run( self, inputs: Dict[str, Union[float, Iterable]], covers: Dict[str, Union[float, Iterable]], torch_size: Optional[int] = None, ) -> Union[float, Iterable]
Executes the FIB over a particular set of inputs and returns the result. Args: inputs: Input set where keys are the names of input nodes in the GrFN and each key points to a set of input values (or just one). Returns: A set of outputs from executing the GrFN...
4.85941
5.160572
0.941642
args = self.inputs Si = self.sobol_analysis( num_samples, { "num_vars": len(args), "names": args, "bounds": [bounds[arg] for arg in args], }, covers ) S2 = Si["S2"] (s2_max, v...
def S2_surface(self, sizes, bounds, presets, covers, use_torch=False, num_samples = 10)
Calculates the sensitivity surface of a GrFN for the two variables with the highest S2 index. Args: num_samples: Number of samples for sensitivity analysis. sizes: Tuple of (number of x inputs, number of y inputs). bounds: Set of bounds for GrFN inputs. p...
2.440497
2.373929
1.028041
val = {"tag": root.tag, "args": []} for node in root: val["args"] += self.parseTree(node, state) return [val]
def process_direct_map(self, root, state) -> List[Dict]
Handles tags that are mapped directly from xml to IR with no additional processing other than recursive translation of any child nodes.
5.23695
5.560524
0.941809
if root.tag in self.AST_TAG_HANDLERS: return self.AST_TAG_HANDLERS[root.tag](root, state) elif root.tag in self.libRtns: return self.process_libRtn(root, state) else: prog = [] for node in root: prog += self.parseTree(no...
def parseTree(self, root, state: ParseState) -> List[Dict]
Parses the XML ast tree recursively to generate a JSON AST which can be ingested by other scripts to generate Python scripts. Args: root: The current root of the tree. state: The current state of the tree defined by an object of the ParseState class. ...
3.638767
3.80892
0.955328
for element in root.iter(): if element.tag == "function": self.functionList.append(element.attrib["name"])
def loadFunction(self, root)
Loads a list with all the functions in the Fortran File Args: root: The root of the XML ast tree. Returns: None Does not return anything but populates a list (self.functionList) that contains all the functions in the Fortran File.
3.2985
3.077926
1.071663
outputDict = {} ast = [] # Parse through the ast once to identify and grab all the functions # present in the Fortran file. for tree in trees: self.loadFunction(tree) # Parse through the ast tree a second time to convert the XML ast # format to a for...
def analyze( self, trees: List[ET.ElementTree], comments: OrderedDict ) -> Dict
Find the entry point for the Fortran file. The entry point for a conventional Fortran file is always the PROGRAM section. This 'if' statement checks for the presence of a PROGRAM segment. If not found, the entry point can be any of the functions or subroutines in the file. So, a...
7.186169
6.318536
1.137315
parser = ArgumentParser( description="Dynamic Bayes Net Executable Model", formatter_class=ArgumentDefaultsHelpFormatter, ) def add_flag(short_arg: str, long_arg: str, help: str): parser.add_argument( "-" + short_arg, "--" + long_arg, help=help, action="store_true" ...
def main()
Run the CLI.
2.680284
2.676215
1.001521
df = pd.read_csv("south_sudan_data_fao.csv") gb = df.groupby("Element") d = [ { "events": [ { k: [ {e: [process_variable_name(k, e)]} for e in list(set(gb.get_group(k)["Item"].tolist())) ...
def construct_FAO_ontology()
Construct FAO variable ontology for use with Eidos.
4.412187
4.002232
1.102432
return create_statement_inspection_table( G[source][target]["InfluenceStatements"] )
def inspect_edge(G: AnalysisGraph, source: str, target: str)
'Drill down' into an edge in the analysis graph and inspect its provenance. This function prints the provenance. Args: G source target
43.430504
31.38369
1.383856
return chain.from_iterable( [ [repr(e.text) for e in s.evidence] for s in G.edges[source, target]["InfluenceStatements"] ] )
def _get_edge_sentences( G: AnalysisGraph, source: str, target: str ) -> List[str]
Return the sentences that led to the construction of a specified edge. Args: G source: The source of the edge. target: The target of the edge.
6.438461
7.178972
0.89685
if type_str == "container": return NodeType.CONTAINER elif type_str == "loop_plate": return NodeType.LOOP elif type_str == "assign": return NodeType.ASSIGN elif type_str == "condition": return NodeType.CONDITION elif type_str == "decision": return NodeTyp...
def get_node_type(type_str)
Returns the NodeType given a name of a JSON function object.
2.667073
2.533612
1.052676
out_format_list = [] for type_item in type_list: item_format = default_output_format(type_item) out_format_list.append(item_format) return out_format_list
def list_output_formats(type_list)
This function takes a list of type names and returns a list of format specifiers for list-directed output of values of those types.
2.537666
2.760731
0.919201
data_type = [] for item in type_list: match = re.match(r"(\d+)(.+)", item) if not match: reps = 1 if item[0] in "FfEegG": data_type.append("REAL") elif item[0] in "Ii": data_type.append("INTEGER") else: ...
def list_data_type(type_list)
This function takes a list of format specifiers and returns a list of data types represented by the format specifiers.
2.500265
2.382027
1.049638
format_list = self._format_list self._re_cvt = self.match_input_fmt(format_list) regexp0_str = "".join([subs[0] for subs in self._re_cvt]) self._regexp_str = regexp0_str self._re = re.compile(regexp0_str) self._match_exps = [ subs[1] for subs in self....
def init_read_line(self)
init_read_line() initializes fields relevant to input matching
3.584789
3.390621
1.057266
format_list = self._format_list output_info = self.gen_output_fmt(format_list) self._output_fmt = "".join([sub[0] for sub in output_info]) self._out_gen_fmt = [sub[1] for sub in output_info if sub[1] is not None] self._out_widths = [sub[2] for sub in output_info if sub[2...
def init_write_line(self)
init_write_line() initializes fields relevant to output generation
3.539822
3.374861
1.04888
if not self._read_line_init: self.init_read_line() match = self._re.match(line) assert match is not None, f"Format mismatch (line = {line})" matched_values = [] for i in range(self._re.groups): cvt_re = self._match_exps[i] cvt_div =...
def read_line(self, line)
Match a line of input according to the format specified and return a tuple of the resulting values
2.906351
2.79686
1.039148
if not self._write_line_init: self.init_write_line() if len(self._out_widths) > len(values): raise For2PyError(f"ERROR: too few values for format {self._format_list}\n") out_strs = [] for i in range(len(self._out_widths)): out_fmt = self._o...
def write_line(self, values)
Process a list of values according to the format specified to generate a line of output.
3.936625
3.764475
1.04573
rexp_list = [] for fmt in fmt_list: rexp_list.extend(self.match_input_fmt_1(fmt)) return rexp_list
def match_input_fmt(self, fmt_list)
Given a list of Fortran format specifiers, e.g., ['I5', '2X', 'F4.1'], this function constructs a list of tuples for matching an input string against those format specifiers.
3.713009
3.517031
1.055722
# first, remove any surrounding space fmt = fmt.strip() # get any leading digits indicating repetition match = re.match("(\d+)(.+)", fmt) if match is None: reps = 1 else: reps = int(match.group(1)) fmt = match.group(2) ...
def match_input_fmt_1(self, fmt)
Given a single format specifier, e.g., '2X', 'I5', etc., this function constructs a list of tuples for matching against that specifier. Each element of this list is a tuple (xtract_re, cvt_re, divisor, cvt_fn) where: xtract_re is a regular expression that extracts an...
3.411802
3.164794
1.078049
rexp_list = [] for fmt in fmt_list: rexp_list.extend(self.gen_output_fmt_1(fmt)) return rexp_list
def gen_output_fmt(self, fmt_list)
given a list of Fortran format specifiers, e.g., ['I5', '2X', 'F4.1'], this function constructs a list of tuples for constructing an output string based on those format specifiers.
3.837218
3.757325
1.021263
# first, remove any surrounding space fmt = fmt.strip() # get any leading digits indicating repetition match = re.match("(\d+)(.+)", fmt) if match is None: reps = 1 else: reps = int(match.group(1)) fmt = match.group(2) ...
def gen_output_fmt_1(self, fmt)
given a single format specifier, get_output_fmt_1() constructs and returns a list of tuples for matching against that specifier. Each element of this list is a tuple (gen_fmt, cvt_fmt, sz) where: gen_fmt is the Python format specifier for assembling this value into ...
4.166907
3.896649
1.069357
adjective_response_dict = {} all_θs = [] # Setting σ_X and σ_Y that are in Eq. 1.21 of the model document. # This assumes that the real-valued variables representing the abstract # concepts are on the order of 1.0. # TODO Make this more general. σ_X = σ_Y = 0.1 for stmt in e[2][...
def constructConditionalPDF( gb, rs: np.ndarray, e: Tuple[str, str, Dict] ) -> gaussian_kde
Construct a conditional probability density function for a particular AnalysisGraph edge.
3.086696
3.089087
0.999226
xs = x.replace("\/", "|").split("/") xs = [x.replace("|", "/") for x in xs] if xs[0] == "FAO": return " ".join(xs[2:]), xs[0] else: return xs[-1], xs[0]
def get_variable_and_source(x: str)
Process the variable name to make it more human-readable.
5.223044
4.482983
1.165082
df = pd.read_sql_table("concept_to_indicator_mapping", con=engine) gb = df.groupby("Concept") _dict = { k: [get_variable_and_source(x) for x in take(n, v["Indicator"].values)] for k, v in gb } return _dict
def construct_concept_to_indicator_mapping(n: int = 1) -> Dict[str, List[str]]
Create a dictionary mapping high-level concepts to low-level indicators Args: n: Number of indicators to return Returns: Dictionary that maps concept names to lists of indicator names.
5.540204
6.089864
0.909742
self.config = builder.configuration.mortality self.population_view = builder.population.get_view(['alive'], query="alive == 'alive'") self.randomness = builder.randomness.get_stream('mortality') self.mortality_rate = builder.value.register_rate_producer('mortality_rate', source...
def setup(self, builder: Builder)
Performs this component's simulation setup. The ``setup`` method is automatically called by the simulation framework. The framework passes in a ``builder`` object which provides access to a variety of framework subsystems and metadata. Parameters ---------- builder : ...
8.704159
8.746886
0.995115
return pd.Series(self.config.mortality_rate, index=index)
def base_mortality_rate(self, index: pd.Index) -> pd.Series
Computes the base mortality rate for every individual. Parameters ---------- index : A representation of the simulants to compute the base mortality rate for. Returns ------- The base mortality rate for all simulants in the index.
7.005514
9.466977
0.739995
effective_rate = self.mortality_rate(event.index) effective_probability = 1 - np.exp(-effective_rate) draw = self.randomness.get_draw(event.index) affected_simulants = draw < effective_probability self.population_view.update(pd.Series('dead', index=event.index[affected_s...
def determine_deaths(self, event: Event)
Determines who dies each time step. Parameters ---------- event : An event object emitted by the simulation containing an index representing the simulants affected by the event and timing information.
6.541428
5.900089
1.1087
components = [] for c in component_list: path, args_plus = c.split('(') cleaned_args = _clean_args(args_plus[:-1].split(','), path) components.append((path, cleaned_args)) return components
def _prep_components(component_list: Sequence[str]) -> List[Tuple[str, Tuple[str]]]
Transform component description strings into tuples of component paths and required arguments. Parameters ---------- component_list : The component descriptions to transform. Returns ------- List of component/argument tuples.
3.925388
4.245823
0.924529
if isinstance(component_config, ConfigTree): component_list = self.parse_component_config(component_config.to_dict()) else: # Components were specified in a list rather than a tree. component_list = component_config component_list = _prep_components(component_li...
def get_components(self, component_config: Union[ConfigTree, List]) -> List
Extracts component specifications from configuration information and returns initialized components. Parameters ---------- component_config : A hierarchical component specification blob. This configuration information needs to be parsable into a full import path and a se...
4.161067
3.953768
1.052431
return _parse_component_config(component_config)
def parse_component_config(self, component_config: Dict[str, Union[Dict, List]]) -> List[str]
Parses a hierarchical component specification into a list of standardized component definitions. This default parser expects component configurations as a list of dicts. Each dict at the top level corresponds to a different package and has a single key. This key may be just the name of the package ...
7.506727
15.112566
0.496721
# We first split file into pieces searchunks = self._split_file() if searchunks: # And then we parse pieces into meaningful data usage = self._parse_file(searchunks) if 'CPU' in usage: return False self._sarinfo = usag...
def load_file(self)
Loads SAR format logfile in ASCII format (sarXX). :return: ``True`` if loading and parsing of file went fine, \ ``False`` if it failed (at any point)
14.161588
11.677051
1.212771
try: test = self._sarinfo["CPU"] del test except KeyError: file_parsed = self.load_file() if file_parsed: return self._sarinfo else: return False except: ### DEBUG trac...
def get_sar_info(self)
Returns parsed sar info :return: ``Dictionary``-style list of SAR data
7.60017
7.980131
0.952387
# Filename passed checks through __init__ if ((self.__filename and os.access(self.__filename, os.R_OK)) or data != ''): fhandle = None if data == '': try: fhandle = os.open(self.__filename, os.O_RDONLY) ...
def _split_file(self, data='')
Splits SAR output or SAR output file (in ASCII format) in order to extract info we need for it, in the format we want. :param data: Input data instead of file :type data: str. :return: ``List``-style of SAR file sections separated by the type of info they cont...
4.815315
4.700634
1.024397
usage = {} output = {} # If sar_parts is a list if type(sar_parts) is list: restart_pattern = re.compile(PATTERN_RESTART) for PATTERNSNAME in ALL_PATTERNS: patterns = ALL_...
def _parse_file(self, sar_parts)
Parses splitted file to get proper information from split parts. :param sar_parts: Array of SAR file parts :return: ``Dictionary``-style info (but still non-parsed) \ from SAR file, split into sections we want to check
4.375406
4.441741
0.985066
part_parts = part_first_line.split() ### DEBUG # print("Parts: %s" % (part_parts)) return_dict = {} counter = 0 for piece in part_parts: for colname in column_names: pattern_re = re.compile(colname) if pattern_re.sea...
def __find_column(self, column_names, part_first_line)
Finds the column for the column_name in sar type definition, and returns its index. :param column_names: Names of the column we look for (regex) put in the list :param part_first_line: First line of the SAR part :return: ``Dictionary`` of names => position, No...
4.376092
4.2696
1.024942
pattern = patterns['PATTERN'] if pattern == '': return False return_dict = {} pattern_re = re.compile(pattern) for part_line in info_part.split('\n'): if part_line.strip() != '' and not pattern_re.search(part_line): # Take ca...
def __split_info(self, info_part, patternsname, patterns)
Splits info from SAR parts into logical stuff :-) :param info_part: Part of SAR output we want to split into usable data :param patternsname: ??? :param patterns: ??? :return: ``List``-style info from SAR files, now finally \ completely parsed into meaningful data for further...
3.319307
3.269555
1.015217
if os.access(self.__filename, os.R_OK): # Read first line of the file try: sar_file = open(self.__filename, "r") except OSError: ### DEBUG traceback.print_exc() return False except: ...
def __get_filedate(self)
Parses (extracts) date of SAR data, from the SAR output file itself. :return: ISO-style (YYYY-MM-DD) date from SAR file
3.062851
2.984595
1.02622
if len(transition_set) == 0 or index.empty: return outputs, decisions = transition_set.choose_new_state(index) groups = _groupby_new_state(index, outputs, decisions) if groups: for output, affected_index in sorted(groups, key=lambda x: str(x[0])): if output == 'null_t...
def _next_state(index, event_time, transition_set, population_view)
Moves a population between different states using information from a `TransitionSet`. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. event_time : pandas.Timestamp When this transition is occurring. transition_set : TransitionSet ...
3.614018
3.512548
1.028888
output_map = {o: i for i, o in enumerate(outputs)} groups = pd.Series(index).groupby([output_map[d] for d in decisions]) results = [(outputs[i], pd.Index(sub_group.values)) for i, sub_group in groups] selected_outputs = [o for o, _ in results] for output in outputs: if output not in sel...
def _groupby_new_state(index, outputs, decisions)
Groups the simulants in the index by their new output state. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. outputs : iterable A list of possible output states. decisions : `pandas.Series` A series containing the name of the n...
3.090818
3.136615
0.985399
return _next_state(index, event_time, self.transition_set, population_view)
def next_state(self, index, event_time, population_view)
Moves a population between different states using information this state's `transition_set`. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. event_time : pandas.Timestamp When this transition is occurring. p...
6.300382
5.41988
1.162458
population_view.update(pd.Series(self.state_id, index=index)) self._transition_side_effect(index, event_time)
def transition_effect(self, index, event_time, population_view)
Updates the simulation state and triggers any side-effects associated with entering this state. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. event_time : pandas.Timestamp The time at which this transition occurs....
8.48208
7.10053
1.19457
t = Transition(self, output, probability_func=probability_func, triggered=triggered) self.transition_set.append(t) return t
def add_transition(self, output, probability_func=lambda index: np.ones(len(index), dtype=float), triggered=Trigger.NOT_TRIGGERED)
Builds a transition from this state to the given state. output : State The end state after the transition.
2.851377
4.146368
0.687681
builder.components.add_components(self.transitions) self.random = builder.randomness.get_stream(self.key)
def setup(self, builder)
Performs this component's simulation setup and return sub-components. Parameters ---------- builder : `engine.Builder` Interface to several simulation tools including access to common random number generation, in particular. Returns ------- itera...
17.610348
16.883606
1.043044
outputs, probabilities = zip(*[(transition.output_state, np.array(transition.probability(index))) for transition in self.transitions]) probabilities = np.transpose(probabilities) outputs, probabilities = self._normalize_probabilities(outputs, proba...
def choose_new_state(self, index)
Chooses a new state for each simulant in the index. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. Returns ------- outputs : list The possible end states of this set of transitions. decisio...
5.825729
5.372245
1.084412
outputs = list(outputs) total = np.sum(probabilities, axis=1) if self.allow_null_transition or not np.any(total): if np.any(total > 1+1e-08): # Accommodate rounding errors raise ValueError( "Null transition requested with un-normalized pr...
def _normalize_probabilities(self, outputs, probabilities)
Normalize probabilities to sum to 1 and add a null transition if desired. Parameters ---------- outputs : iterable List of possible end states corresponding to this containers transitions. probabilities : iterable of iterables A set of probability weights whose c...
4.894217
4.393651
1.11393
builder.components.add_components(self.states) self.population_view = builder.population.get_view([self.state_column])
def setup(self, builder)
Performs this component's simulation setup and return sub-components. Parameters ---------- builder : `engine.Builder` Interface to several simulation tools including access to common random number generation, in particular. Returns ------- itera...
15.068765
14.768433
1.020336
for state, affected in self._get_state_pops(index): if not affected.empty: state.next_state(affected.index, event_time, self.population_view.subview([self.state_column]))
def transition(self, index, event_time)
Finds the population in each state and moves them to the next state. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. event_time : pandas.Timestamp The time at which this transition occurs.
11.722946
9.224278
1.270879
from graphviz import Digraph dot = Digraph(format='png') for state in self.states: if isinstance(state, TransientState): dot.node(state.state_id, style='dashed') else: dot.node(state.state_id) for transition in state.tr...
def to_dot(self)
Produces a ball and stick graph of this state machine. Returns ------- `graphviz.Digraph` A ball and stick visualization of this state machine.
2.723697
2.807074
0.970297
from sar import parser sysstat_dir = '/var/log/sa' single_file = ('%s/%s' % (sysstat_dir, 'sar21')) # Single SAR file parsing insar = parser.Parser(single_file) print(("SAR file date: %s" % (insar.get_filedate()))) print("Content:\n") pprint.pprint(insar.get_sar_info()) print(("-"...
def main()
from sar import multiparser multi_file = ('./%s' % ('sarcombined')) inmulti = multiparser.Multiparser(multi_file) inmulti.load_file() print("Content:\n") pprint.pprint(inmulti.get_sar_info())
7.413745
4.184007
1.771925
self._managers = _setup_components(builder, self._managers, configuration) self._components = _setup_components(builder, self._components, configuration)
def setup_components(self, builder, configuration)
Apply component level configuration defaults to the global config and run setup methods on the components registering and setting up any child components generated in the process. Parameters ---------- builder: Interface to several simulation tools. configuration: ...
4.096301
4.928253
0.831187
filter_in = filter_in or {} filter_out = filter_out or {} catalog = read_catalog_obj(catalog) if filter_in or filter_out: filtered_datasets = [ dataset for dataset in catalog["dataset"] if _filter_dictionary(dataset, filter_in.get( "dataset"), filte...
def get_datasets(catalog, filter_in=None, filter_out=None, meta_field=None, exclude_meta_fields=None, only_time_series=False)
Devuelve una lista de datasets del catálogo o de uno de sus metadatos. Args: catalog (dict, str or DataJson): Representación externa/interna de un catálogo. Una representación _externa_ es un path local o una URL remota a un archivo con la metadata de un catálogo, en for...
2.198589
2.181374
1.007892
filter_in = filter_in or {} filter_out = filter_out or {} catalog = read_catalog_obj(catalog) distributions = [] for dataset in get_datasets(catalog, filter_in, filter_out): for distribution in dataset.get("distribution", []): # agrega el id del dataset distrib...
def get_distributions(catalog, filter_in=None, filter_out=None, meta_field=None, exclude_meta_fields=None, only_time_series=False)
Devuelve lista de distribuciones del catálogo o de uno de sus metadatos. Args: catalog (dict, str or DataJson): Representación externa/interna de un catálogo. Una representación _externa_ es un path local o una URL remota a un archivo con la metadata de un catálogo, en f...
2.413435
2.432263
0.992259
filter_in = filter_in or {} filter_out = filter_out or {} catalog = read_catalog_obj(catalog) # agrego atajos para filtros if distribution_identifier: if "distribution" not in filter_in: filter_in["distribution"] = {} filter_in["distribution"]["identifier"] = distr...
def get_fields(catalog, filter_in=None, filter_out=None, meta_field=None, only_time_series=False, distribution_identifier=None)
Devuelve lista de campos del catálogo o de uno de sus metadatos. Args: catalog (dict, str or DataJson): Representación externa/interna de un catálogo. Una representación _externa_ es un path local o una URL remota a un archivo con la metadata de un catálogo, en formato J...
2.687143
2.620255
1.025527
msg = "Se requiere un 'identifier' o 'title' para buscar el dataset." assert identifier or title, msg catalog = read_catalog_obj(catalog) # búsqueda optimizada por identificador if identifier: try: return _get_dataset_by_identifier(catalog, identifier) except BaseE...
def get_dataset(catalog, identifier=None, title=None)
Devuelve un Dataset del catálogo.
3.652771
3.412969
1.070262
msg = "Se requiere un 'identifier' o 'title' para buscar el distribution." assert identifier or title, msg catalog = read_catalog_obj(catalog) # 1. BUSCA las distribuciones en el catálogo # toma la distribution que tenga el id único # búsqueda optimizada por identificador if identifie...
def get_distribution(catalog, identifier=None, title=None, dataset_identifier=None)
Devuelve una Distribution del catálogo.
3.258279
3.10299
1.050045
msg = "Se requiere un 'id' o 'title' para buscar el field." assert identifier or title, msg # 1. BUSCA los fields en el catálogo # búsqueda optimizada por identificador if identifier: try: return _get_field_by_identifier(catalog, identifier) except BaseException: ...
def get_field(catalog, identifier=None, title=None, distribution_identifier=None)
Devuelve un Field del catálogo.
3.129733
2.948909
1.061319
exclude_meta_fields = exclude_meta_fields or [] catalog_dict_copy = catalog.copy() del catalog_dict_copy["dataset"] for excluded_meta_field in exclude_meta_fields: catalog_dict_copy.pop(excluded_meta_field, None) return catalog_dict_copy
def get_catalog_metadata(catalog, exclude_meta_fields=None)
Devuelve sólo la metadata de nivel catálogo.
2.431689
2.249717
1.080886
text_template = if "distribution" in dataset: distributions = "".join( map(distribution_to_markdown, dataset["distribution"])) else: distributions = "" text = text_template.format( title=dataset["title"], description=dataset.get("description", ""), ...
def dataset_to_markdown(dataset)
Genera texto en markdown a partir de los metadatos de una `dataset`. Args: dataset (dict): Diccionario con metadatos de una `dataset`. Returns: str: Texto que describe una `dataset`.
3.951792
4.041536
0.977795
text_template = if "field" in distribution: fields = "- " + \ "\n- ".join(map(field_to_markdown, distribution["field"])) else: fields = "" text = text_template.format( title=distribution["title"], description=distribution.get("description", ""), ...
def distribution_to_markdown(distribution)
Genera texto en markdown a partir de los metadatos de una `distribution`. Args: distribution (dict): Diccionario con metadatos de una `distribution`. Returns: str: Texto que describe una `distribution`.
3.694002
3.938336
0.93796
if "title" in field: field_title = "**{}**".format(field["title"]) else: raise Exception("Es necesario un `title` para describir un campo.") field_type = " ({})".format(field["type"]) if "type" in field else "" field_desc = ": {}".format( field["description"]) if "descripti...
def field_to_markdown(field)
Genera texto en markdown a partir de los metadatos de un `field`. Args: field (dict): Diccionario con metadatos de un `field`. Returns: str: Texto que describe un `field`.
2.978445
2.72649
1.09241
from ipywidgets import IntProgress, HTML, VBox from IPython.display import display is_iterator = False if size is None: try: size = len(sequence) except TypeError: is_iterator = True if size is not None: if every is None: if size <= 2...
def log_progress(sequence, every=None, size=None, name='Items')
Taken from https://github.com/alexanderkuk/log-progress
1.902398
1.863631
1.020802
try: datajson_file = sys.argv[1] dj_instance = DataJson() bool_res = dj_instance.is_valid_catalog(datajson_file) full_res = dj_instance.validate_catalog(datajson_file) pretty_full_res = json.dumps( full_res, indent=4, separators=(",", ": ")) logger.in...
def main()
Permite ejecutar el módulo por línea de comandos. Valida un path o url a un archivo data.json devolviendo True/False si es válido y luego el resultado completo. Example: python pydatajson.py http://181.209.63.71/data.json python pydatajson.py ~/github/pydatajson/tests/samples/full_data.jso...
4.328019
3.759573
1.151199
datasets_index = {} distributions_index = {} fields_index = {} # recorre todos los datasets for dataset_index, dataset in enumerate(self.datasets): if "identifier" in dataset: datasets_index[dataset["identifier"]] = { "da...
def _build_index(self)
Itera todos los datasets, distribucioens y fields indexandolos.
2.049918
1.758194
1.165922
catalog = catalog or self return validation.is_valid_catalog(catalog, validator=self.validator)
def is_valid_catalog(self, catalog=None)
Valida que un archivo `data.json` cumpla con el schema definido. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la estructura definida en el schema. Args: catalog (str o dict): Catálogo (dict, JSON...
6.502751
16.277836
0.399485
new_response = response.copy() # El status del catálogo entero será ERROR new_response["status"] = "ERROR" # Adapto la información del ValidationError recibido a los fines # del validador de DataJsons error_info = { # Error Code 1 para "campo obliga...
def _update_validation_response(error, response)
Actualiza la respuesta por default acorde a un error de validación.
5.039967
4.825168
1.044516
catalog = catalog or self return validation.validate_catalog( catalog, only_errors, fmt, export_path, validator=self.validator)
def validate_catalog(self, catalog=None, only_errors=False, fmt="dict", export_path=None)
Analiza un data.json registrando los errores que encuentra. Chequea que el data.json tiene todos los campos obligatorios y que tanto los campos obligatorios como los opcionales siguen la estructura definida en el schema. Args: catalog (str o dict): Catálogo (dict, JSON o XL...
4.563738
9.520445
0.479362
publisher_name = helpers.traverse_dict(dataset, ["publisher", "name"]) languages = cls._stringify_list(dataset.get("language")) super_themes = cls._stringify_list(dataset.get("superTheme")) themes = cls._stringify_list(dataset.get("theme")) def _stringify_distribution(...
def _dataset_report_helper(cls, dataset, catalog_homepage=None)
Toma un dict con la metadata de un dataset, y devuelve un dict coni los valores que dataset_report() usa para reportar sobre él. Args: dataset (dict): Diccionario con la metadata de un dataset. Returns: dict: Diccionario con los campos a nivel dataset que requiere ...
2.486974
2.530607
0.982758
fields = OrderedDict() fields["catalog_metadata_url"] = url fields["catalog_federation_id"] = catalog_id fields["catalog_federation_org"] = catalog_org fields["catalog_title"] = catalog.get("title") fields["catalog_description"] = catalog.get("description") ...
def _catalog_report_helper(catalog, catalog_validation, url, catalog_id, catalog_org)
Toma un dict con la metadata de un catálogo, y devuelve un dict con los valores que catalog_report() usa para reportar sobre él. Args: catalog (dict): Diccionario con la metadata de un catálogo. validation (dict): Resultado, únicamente a nivel catálogo, de la val...
2.965676
3.203364
0.925801
# hace un breve análisis de qa al dataset good_qa, notes = self._dataset_qa(dataset) dataset_report = OrderedDict(catalog_fields) dataset_report["valid_dataset_metadata"] = ( 1 if dataset_validation["status"] == "OK" else 0) dataset_report["dataset_index"] ...
def _dataset_report( self, dataset, dataset_validation, dataset_index, catalog_fields, harvest='none', report=None, catalog_homepage=None )
Genera una línea del `catalog_report`, correspondiente a un dataset de los que conforman el catálogo analizado.
3.101971
3.047539
1.017861
# 1. VALIDACIONES # chequea que haya por lo menos algún formato de datos reconocido has_data_format = helpers.dataset_has_data_distributions(dataset) # chequea que algunos campos tengan longitudes mínimas has_title = "title" in dataset has_description = "descri...
def _dataset_qa(self, dataset)
Chequea si el dataset tiene una calidad mínima para cosechar.
3.269149
2.975495
1.098691
url = catalog if isinstance(catalog, string_types) else None catalog = readers.read_catalog(catalog) validation = self.validate_catalog(catalog) catalog_validation = validation["error"]["catalog"] datasets_validations = validation["error"]["dataset"] catalog_f...
def catalog_report(self, catalog, harvest='none', report=None, catalog_id=None, catalog_homepage=None, catalog_org=None)
Genera un reporte sobre los datasets de un único catálogo. Args: catalog (dict, str o unicode): Representación externa (path/URL) o interna (dict) de un catálogo. harvest (str): Criterio de cosecha ('all', 'none', 'valid', 'report' o 'good'). Ret...
3.661453
3.573249
1.024684
# Si se pasa un único catálogo, genero una lista que lo contenga if isinstance(catalogs, string_types + (dict,)): catalogs = [catalogs] if harvest == 'report': if not report: raise ValueError() datasets_report = readers.read_table(re...
def generate_harvester_config(self, catalogs=None, harvest='valid', report=None, export_path=None)
Genera un archivo de configuración del harvester a partir de un reporte, o de un conjunto de catálogos y un criterio de cosecha (`harvest`). Args: catalogs (str, dict o list): Uno (str o dict) o varios (list de strs y/o dicts) catálogos. harvest (str): Cr...
4.217426
3.81368
1.105868