_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q15500 | line_starts_subpgm | train | def line_starts_subpgm(line: str) -> Tuple[bool, Optional[str]]:
"""
Indicates whether a line in the program is the first line of a subprogram
definition.
Args:
line
Returns:
(True, f_name) if line begins a definition for subprogram f_name;
(False, None) if line does not begin a subprogram definition.
"""
match = RE_SUB_START.match(line)
| python | {
"resource": ""
} |
q15501 | program_unit_name | train | def program_unit_name(line:str) -> str:
"""Given a line that starts a program unit, i.e., a program, module,
subprogram, or | python | {
"resource": ""
} |
q15502 | prepend | train | def prepend(x: T, xs: Iterable[T]) -> Iterator[T]:
""" Prepend a value to an iterable.
Parameters
----------
x
An element of type T.
xs
An iterable of elements of type T.
Returns
-------
Iterator
An iterator that yields *x* followed by elements | python | {
"resource": ""
} |
q15503 | append | train | def append(x: T, xs: Iterable[T]) -> Iterator[T]:
""" Append a value to an iterable.
Parameters
----------
x
An element of type T.
xs
An iterable of elements of type T.
Returns
-------
Iterator
An iterator that yields elements of *xs*, then | python | {
"resource": ""
} |
q15504 | flatten | train | def flatten(xs: Union[List, Tuple]) -> List:
""" Flatten a nested list or tuple. """
return (
sum(map(flatten, xs), [])
| python | {
"resource": ""
} |
q15505 | iterate | train | def iterate(f: Callable[[T], T], x: T) -> Iterator[T]:
""" Makes infinite iterator that returns the result of successive
applications of a function to an element
.. math::
iterate(f, x) = [x, f(x), f(f(x)), f(f(f(x))), ...]
Examples
--------
>>> from delphi.utils.fp import iterate, | python | {
"resource": ""
} |
q15506 | ptake | train | def ptake(n: int, xs: Iterable[T]) -> Iterable[T]:
""" take with a tqdm progress bar. | python | {
"resource": ""
} |
q15507 | ltake | train | def ltake(n: int, xs: Iterable[T]) -> List[T]:
""" A non-lazy version of | python | {
"resource": ""
} |
q15508 | compose | train | def compose(*fs: Any) -> Callable:
""" Compose functions from left to right. | python | {
"resource": ""
} |
q15509 | rcompose | train | def rcompose(*fs: Any) -> Callable:
""" Compose functions from right to left. | python | {
"resource": ""
} |
q15510 | flatMap | train | def flatMap(f: Callable, xs: Iterable) -> List:
""" Map | python | {
"resource": ""
} |
q15511 | process_climis_crop_production_data | train | def process_climis_crop_production_data(data_dir: str):
""" Process CliMIS crop production data """
climis_crop_production_csvs = glob(
"{data_dir}/Climis South Sudan Crop Production Data/"
"Crops_EstimatedProductionConsumptionBalance*.csv"
)
state_county_df = pd.read_csv(
f"{data_dir}/ipc_data.csv", skipinitialspace=True
)
combined_records = []
for f in climis_crop_production_csvs:
year = int(f.split("/")[-1].split("_")[2].split(".")[0])
df = pd.read_csv(f).dropna()
for i, r in df.iterrows():
record = {
"Year": year,
"Month": None,
"Source": "CliMIS",
"Country": "South Sudan",
}
region = r["State/County"].strip()
| python | {
"resource": ""
} |
q15512 | AnalysisGraph.assign_uuids_to_nodes_and_edges | train | def assign_uuids_to_nodes_and_edges(self):
""" Assign uuids to nodes and edges. """
for node in self.nodes(data=True):
node[1]["id"] = str(uuid4())
| python | {
"resource": ""
} |
q15513 | AnalysisGraph.from_statements_file | train | def from_statements_file(cls, file: str):
""" Construct an AnalysisGraph object from a pickle file containing a
list of INDRA statements. """
| python | {
"resource": ""
} |
q15514 | AnalysisGraph.from_text | train | def from_text(cls, text: str):
""" Construct an AnalysisGraph object from text, using Eidos to perform
machine reading. """
| python | {
"resource": ""
} |
q15515 | AnalysisGraph.from_uncharted_json_file | train | def from_uncharted_json_file(cls, file):
""" Construct an AnalysisGraph object from a file containing INDRA
statements serialized exported by Uncharted's CauseMos webapp.
"""
| python | {
"resource": ""
} |
q15516 | AnalysisGraph.from_uncharted_json_serialized_dict | train | def from_uncharted_json_serialized_dict(
cls, _dict, minimum_evidence_pieces_required: int = 1
):
""" Construct an AnalysisGraph object from a dict of INDRA statements
exported by Uncharted's CauseMos webapp. """
sts = _dict["statements"]
G = nx.DiGraph()
for s in sts:
if len(s["evidence"]) >= minimum_evidence_pieces_required:
subj, obj = s["subj"], s["obj"]
if (
subj["db_refs"]["concept"] is not None
and obj["db_refs"]["concept"] is not None
):
subj_name, obj_name = [
"/".join(s[x]["db_refs"]["concept"].split("/")[:])
for x in ["subj", "obj"]
]
G.add_edge(subj_name, obj_name)
subj_delta = s["subj_delta"]
obj_delta = s["obj_delta"]
for delta in (subj_delta, obj_delta):
# TODO : Ensure that all the statements provided by
# Uncharted have unambiguous polarities.
if delta["polarity"] is None:
delta["polarity"] = 1
influence_stmt = Influence(
Concept(subj_name, db_refs=subj["db_refs"]),
Concept(obj_name, db_refs=obj["db_refs"]),
subj_delta=s["subj_delta"],
obj_delta=s["obj_delta"],
evidence=[
INDRAEvidence(
source_api=ev["source_api"],
annotations=ev["annotations"],
text=ev["text"],
| python | {
"resource": ""
} |
q15517 | AnalysisGraph.sample_observed_state | train | def sample_observed_state(self, s: pd.Series) -> Dict:
""" Sample observed state vector. This is the implementation of the
emission function.
Args:
s: Latent state vector.
Returns:
Observed state vector.
"""
return {
n[0]: {
| python | {
"resource": ""
} |
q15518 | AnalysisGraph.sample_from_likelihood | train | def sample_from_likelihood(self, n_timesteps=10):
""" Sample a collection of observed state sequences from the likelihood
model given a collection of transition matrices.
Args:
n_timesteps: The number of timesteps for the sequences.
"""
self.latent_state_sequences = lmap(
lambda A: ltake(
n_timesteps,
iterate(
lambda s: | python | {
"resource": ""
} |
q15519 | AnalysisGraph.get_timeseries_values_for_indicators | train | def get_timeseries_values_for_indicators(
self, resolution: str = "month", months: Iterable[int] = range(6, 9)
):
""" Attach timeseries to indicators, for performing Bayesian inference.
"""
if resolution == "month":
funcs = [
partial(get_indicator_value, month=month) for month in months
]
else:
raise NotImplementedError(
"Currently, only the 'month' resolution is supported."
| python | {
"resource": ""
} |
q15520 | AnalysisGraph.sample_from_posterior | train | def sample_from_posterior(self, A: pd.DataFrame) -> None:
""" Run Bayesian inference - sample from the posterior distribution."""
self.sample_from_proposal(A)
self.set_latent_state_sequence(A)
self.update_log_prior(A)
self.update_log_likelihood()
candidate_log_joint_probability = self.log_prior + self.log_likelihood
| python | {
"resource": ""
} |
q15521 | AnalysisGraph.create_bmi_config_file | train | def create_bmi_config_file(self, filename: str = "bmi_config.txt") -> None:
""" Create a BMI config file to initialize the model.
Args:
filename: The filename with which the config file should be saved.
| python | {
"resource": ""
} |
q15522 | AnalysisGraph.export_node | train | def export_node(self, n) -> Dict[str, Union[str, List[str]]]:
""" Return dict suitable for exporting to JSON.
Args:
n: A dict representing the data in a networkx AnalysisGraph node.
Returns:
The node dict with additional fields for name, units, dtype, and
arguments.
"""
node_dict = {
"name": n[0],
"units": _get_units(n[0]),
"dtype": _get_dtype(n[0]),
"arguments": list(self.predecessors(n[0])),
}
if not n[1].get("indicators") is None:
for indicator in n[1]["indicators"].values():
| python | {
"resource": ""
} |
q15523 | AnalysisGraph.map_concepts_to_indicators | train | def map_concepts_to_indicators(
self, n: int = 1, min_temporal_res: Optional[str] = None
):
""" Map each concept node in the AnalysisGraph instance to one or more
tangible quantities, known as 'indicators'.
Args:
n: Number of matches to keep
min_temporal_res: Minimum temporal resolution that the indicators
must have data for.
"""
for node in self.nodes(data=True):
query_parts = [
"select Indicator from concept_to_indicator_mapping",
f"where `Concept` like '{node[0]}'",
]
# TODO May need to delve into SQL/database stuff a bit more deeply
# for this. Foreign keys perhaps?
query = " ".join(query_parts)
results = engine.execute(query)
if min_temporal_res is not None:
if min_temporal_res not in ["month"]:
raise ValueError("min_temporal_res must be 'month'")
vars_with_required_temporal_resolution = [
| python | {
"resource": ""
} |
q15524 | AnalysisGraph.parameterize | train | 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 function that will be called to perform the
aggregation if there are multiple matches.
"""
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: | python | {
"resource": ""
} |
q15525 | AnalysisGraph.delete_nodes | train | def delete_nodes(self, nodes: Iterable[str]):
""" Iterate over a set of nodes and remove the ones that are present in
the graph. """
| python | {
"resource": ""
} |
q15526 | AnalysisGraph.delete_node | train | def delete_node(self, node: str):
""" Removes a node if it | python | {
"resource": ""
} |
q15527 | AnalysisGraph.delete_edge | train | def delete_edge(self, source: str, target: str):
""" Removes an edge if | python | {
"resource": ""
} |
q15528 | AnalysisGraph.delete_edges | train | 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. """
| python | {
"resource": ""
} |
q15529 | AnalysisGraph.merge_nodes | train | 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
"""
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.has_edge(p, n2):
self.add_edge(p, n2)
self[p][n2]["InfluenceStatements"] = self[p][n1][
"InfluenceStatements"
]
else:
self[p][n2]["InfluenceStatements"] += self[p][n1][
"InfluenceStatements"
]
for s in self.successors(n1):
for st in self.edges[n1, s]["InfluenceStatements"]: | python | {
"resource": ""
} |
q15530 | AnalysisGraph.get_subgraph_for_concept | train | 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.
Setting this to False (default) will search for upstream causal
influences, and setting it to True will search for
downstream causal influences. | python | {
"resource": ""
} |
q15531 | create_pgm_dict | train | 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. """
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.function_defs[-1]
pgm["source"] = [[get_path(file_name, "source")]]
# dateCreated stores the date and time on which the lambda and PGM file was created.
# It is stored | python | {
"resource": ""
} |
q15532 | filter_and_process_statements | train | 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. """
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 score threshold cutoff
if not s.belief > belief_score_cutoff:
continue
| python | {
"resource": ""
} |
q15533 | create_CAG_with_indicators | train | def create_CAG_with_indicators(input, output, filename="CAG_with_indicators.pdf"):
""" Create a CAG with mapped indicators """
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",
| python | {
"resource": ""
} |
q15534 | ComputationalGraph.run | train | 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 GrFN, one for every set of
inputs.
"""
# Set input values
for i in self.inputs:
| python | {
"resource": ""
} |
q15535 | GroundedFunctionNetwork.traverse_nodes | train | 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.
"""
tab = " "
result = list()
for n in node_set:
repr = (
| python | {
"resource": ""
} |
q15536 | GroundedFunctionNetwork.from_json_and_lambdas | train | 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:
| python | {
"resource": ""
} |
q15537 | GroundedFunctionNetwork.from_python_file | train | def from_python_file(
cls, python_file, lambdas_path, json_filename: str, stem: str
):
"""Builds GrFN object from Python file."""
with open(python_file, "r") as f:
| python | {
"resource": ""
} |
q15538 | GroundedFunctionNetwork.from_python_src | train | def from_python_src(
cls,
pySrc,
lambdas_path,
json_filename: str,
stem: str,
save_file: bool = False,
):
"""Builds GrFN object from Python source code."""
| python | {
"resource": ""
} |
q15539 | GroundedFunctionNetwork.from_fortran_file | train | def from_fortran_file(cls, fortran_file: str, tmpdir: str = "."):
"""Builds GrFN object from a Fortran program."""
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 open(fortran_file, "r") as f:
inputLines = f.readlines()
with open(preprocessed_fortran_file, "w") as f:
f.write(preprocessor.process(inputLines))
xml_string = sp.run(
[
"java",
"fortran.ofp.FrontEnd",
"--class",
"fortran.ofp.XMLPrinter",
"--verbosity",
"0",
| python | {
"resource": ""
} |
q15540 | GroundedFunctionNetwork.from_fortran_src | train | 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!) Defaults to
the current directory.
Returns:
A GroundedFunctionNetwork instance
| python | {
"resource": ""
} |
q15541 | GroundedFunctionNetwork.clear | train | def clear(self):
"""Clear variable nodes for next computation."""
for n in self.nodes():
if self.nodes[n]["type"] == "variable": | python | {
"resource": ""
} |
q15542 | GroundedFunctionNetwork.to_FIB | train | 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.
"""
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):
return [v for v in graph.nodes() if shortname in v]
this_var_nodes = [
shortname(n)
for (n, d) in self.nodes(data=True)
if d["type"] == "variable"
]
other_var_nodes = [
| python | {
"resource": ""
} |
q15543 | GroundedFunctionNetwork.to_agraph | train | def to_agraph(self):
""" Export to a PyGraphviz AGraph object. """
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]
for n in self.nodes(data=True)
if n[1]["parent"] == cluster_name
]
root_graph.add_nodes_from(subgraph_nodes)
subgraph = root_graph.add_subgraph(
| python | {
"resource": ""
} |
q15544 | GroundedFunctionNetwork.to_CAG_agraph | train | 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.
"""
CAG = self.to_CAG()
A = nx.nx_agraph.to_agraph(CAG)
| python | {
"resource": ""
} |
q15545 | GroundedFunctionNetwork.to_call_agraph | train | def to_call_agraph(self):
""" Build a PyGraphviz AGraph object corresponding to a call graph of
functions. """
A = nx.nx_agraph.to_agraph(self.call_graph)
| python | {
"resource": ""
} |
q15546 | ForwardInfluenceBlanket.S2_surface | train | 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.
presets: Set of standard values for GrFN inputs.
Returns:
Tuple:
Tuple: The names of the two variables that were selected
Tuple: The X, Y vectors of eval values
Z: The numpy matrix of output evaluations
"""
args = self.inputs
Si = self.sobol_analysis(
num_samples,
{
"num_vars": len(args),
| python | {
"resource": ""
} |
q15547 | XMLToJSONTranslator.process_direct_map | train | 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."""
| python | {
"resource": ""
} |
q15548 | XMLToJSONTranslator.parseTree | train | 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.
Returns:
ast: A JSON ast that defines the structure of the Fortran file.
"""
| python | {
"resource": ""
} |
q15549 | XMLToJSONTranslator.loadFunction | train | 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 | python | {
"resource": ""
} |
q15550 | XMLToJSONTranslator.analyze | train | def analyze(
self, trees: List[ET.ElementTree], comments: OrderedDict
) -> Dict:
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 format that can be used to generate Python statements.
for tree in trees:
ast += self.parseTree(tree, ParseState())
"""
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, all the functions and subroutines of the
program are listed and included as the possible entry point.
"""
if self.entryPoint:
entry = {"program": self.entryPoint[0]}
else:
| python | {
"resource": ""
} |
q15551 | construct_FAO_ontology | train | def construct_FAO_ontology():
""" Construct FAO variable ontology for use with Eidos. """
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()))
| python | {
"resource": ""
} |
q15552 | inspect_edge | train | 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
| python | {
"resource": ""
} |
q15553 | _get_edge_sentences | train | 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.
| python | {
"resource": ""
} |
q15554 | get_node_type | train | def get_node_type(type_str):
"""Returns the NodeType given a name of a JSON function object."""
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": | python | {
"resource": ""
} |
q15555 | list_output_formats | train | 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."""
out_format_list = []
for type_item | python | {
"resource": ""
} |
q15556 | list_data_type | train | 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."""
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":
| python | {
"resource": ""
} |
q15557 | Format.read_line | train | def read_line(self, line):
"""
Match a line of input according to the format specified and return a
tuple of the resulting values
"""
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 = self._divisors[i]
cvt_fn = self._in_cvt_fns[i]
match_str = match.group(i + 1)
match0 = re.match(cvt_re, match_str)
if match0 is not None:
if cvt_fn == "float":
if "." in match_str:
val = float(match_str)
else:
| python | {
"resource": ""
} |
q15558 | Format.write_line | train | def write_line(self, values):
"""
Process a list of values according to the format specified to generate
a line of output.
"""
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._out_gen_fmt[i]
out_width = self._out_widths[i]
out_val = out_fmt.format(values[i])
| python | {
"resource": ""
} |
q15559 | get_variable_and_source | train | def get_variable_and_source(x: str):
""" Process the variable name to make it more human-readable. """
xs = x.replace("\/", "|").split("/")
xs = [x.replace("|", "/") for x in xs]
if | python | {
"resource": ""
} |
q15560 | construct_concept_to_indicator_mapping | train | 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.
"""
df = pd.read_sql_table("concept_to_indicator_mapping", con=engine)
| python | {
"resource": ""
} |
q15561 | Mortality.base_mortality_rate | train | 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.
| python | {
"resource": ""
} |
q15562 | Mortality.determine_deaths | train | 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.
"""
effective_rate | python | {
"resource": ""
} |
q15563 | _prep_components | train | 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.
| python | {
"resource": ""
} |
q15564 | ComponentConfigurationParser.get_components | train | 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 set of initialization arguments by the ``parse_component_config``
method.
Returns
-------
List
A list of initialized components.
| python | {
"resource": ""
} |
q15565 | ComponentConfigurationParser.parse_component_config | train | 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
or a Python style import path to the module in which components live. The values of the top level dicts
are a list of dicts or strings. If dicts, the keys are another step along the import path. If strings,
the strings are representations of calls to the class constructor of components to be generated. This
pattern may be arbitrarily nested. | python | {
"resource": ""
} |
q15566 | _next_state | train | 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
A set of potential transitions available to the simulants.
population_view : vivarium.framework.population.PopulationView
A view of the internal state of the simulation.
"""
if len(transition_set) == 0 or index.empty:
| python | {
"resource": ""
} |
q15567 | _groupby_new_state | train | 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 next state for each simulant in the index.
Returns
-------
iterable of 2-tuples
The first item in each tuple is the name of an output state and the second item
is a `pandas.Index` representing the simulants to transition into that state.
"""
output_map = {o: | python | {
"resource": ""
} |
q15568 | State.next_state | train | 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 | python | {
"resource": ""
} |
q15569 | State.transition_effect | train | 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. | python | {
"resource": ""
} |
q15570 | State.add_transition | train | 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 | python | {
"resource": ""
} |
q15571 | TransitionSet.choose_new_state | train | 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.
decisions: `pandas.Series`
A series containing the name of the next state for each simulant in the index.
"""
outputs, probabilities = zip(*[(transition.output_state, np.array(transition.probability(index)))
| python | {
"resource": ""
} |
q15572 | TransitionSet._normalize_probabilities | train | 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 columns correspond to the end states in `outputs`
and whose rows correspond to each simulant undergoing the transition.
Returns
-------
outputs: list
The original output list expanded to include a null transition (a transition back | python | {
"resource": ""
} |
q15573 | Machine.transition | train | 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.
| python | {
"resource": ""
} |
q15574 | Machine.to_dot | train | 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.
"""
from graphviz import Digraph
| python | {
"resource": ""
} |
q15575 | ComponentManager.setup_components | train | 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.
| python | {
"resource": ""
} |
q15576 | field_to_markdown | train | 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`.
"""
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 | python | {
"resource": ""
} |
q15577 | DataJson._build_index | train | def _build_index(self):
"""Itera todos los datasets, distribucioens y fields indexandolos."""
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"]] = {
"dataset_index": dataset_index
}
# recorre las distribuciones del dataset
for distribution_index, distribution in enumerate(
dataset.get("distribution", [])):
if "identifier" in distribution:
distributions_index[distribution["identifier"]] = {
| python | {
"resource": ""
} |
q15578 | import_by_path | train | def import_by_path(path: str) -> Callable:
"""Import a class or function given it's absolute path.
Parameters
| python | {
"resource": ""
} |
q15579 | _set_default_value | train | def _set_default_value(dict_obj, keys, value):
"""Setea valor en diccionario anidado, siguiendo lista de keys.
Args:
dict_obj (dict): Un diccionario anidado.
keys (list): Una lista de keys para navegar el diccionario.
value (any): Un valor para | python | {
"resource": ""
} |
q15580 | _make_contact_point | train | def _make_contact_point(dataset):
"""De estar presentes las claves necesarias, genera el diccionario
"contactPoint" de un dataset."""
keys = [k for k in | python | {
"resource": ""
} |
q15581 | _read_csv_table | train | def _read_csv_table(path):
"""Lee un CSV a una lista de diccionarios."""
with | python | {
"resource": ""
} |
q15582 | _read_xlsx_table | train | def _read_xlsx_table(path):
"""Lee la hoja activa de un archivo XLSX a una lista de diccionarios."""
workbook = pyxl.load_workbook(path)
| python | {
"resource": ""
} |
q15583 | validate_model_specification_file | train | def validate_model_specification_file(file_path: str) -> str:
"""Ensures the provided file is a yaml file"""
if not os.path.isfile(file_path):
raise ConfigurationError('If you provide a model specification file, it must be a file. ' | python | {
"resource": ""
} |
q15584 | ConfigNode.get_value_with_source | train | def get_value_with_source(self, layer=None):
"""Returns a tuple of the value's source and the value at the specified
layer. If no layer is specified then the outer layer is used.
Parameters
----------
layer : str
Name of the layer to use. If None then the outermost where the value
exists will be used.
Raises
------
KeyError
If the value is not set for | python | {
"resource": ""
} |
q15585 | ConfigNode.metadata | train | def metadata(self):
"""Returns all values and associated metadata for this node as a dict.
The value which would be selected if the node's value was requested
is indicated by the `default` flag.
"""
result = []
for layer in self._layers:
if layer in self._values:
result.append({
'layer': layer,
| python | {
"resource": ""
} |
q15586 | ConfigNode.set_value | train | def set_value(self, value, layer=None, source=None):
"""Set a value for a particular layer with optional metadata about source.
Parameters
----------
value : str
Data to store in the node.
layer : str
Name of the layer to use. If None then the outermost where the value
exists will be used.
source : str
Metadata indicating the source of this value (e.g. a file path)
Raises
------
| python | {
"resource": ""
} |
q15587 | ConfigTree.freeze | train | def freeze(self):
"""Causes the ConfigTree to become read only.
This is useful for loading and then freezing configurations that should not be modified at runtime.
"""
| python | {
"resource": ""
} |
q15588 | ConfigTree.get_from_layer | train | def get_from_layer(self, name, layer=None):
"""Get a configuration value from the named layer.
Parameters
----------
name : str
The name of the value to retrieve
layer: str
The name of the layer to retrieve the value from. If it is not supplied
then the outermost layer in which the key is defined will be used.
"""
if name not in self._children:
if self._frozen:
| python | {
"resource": ""
} |
q15589 | ConfigTree._set_with_metadata | train | def _set_with_metadata(self, name, value, layer=None, source=None):
"""Set a value in the named layer with the given source.
Parameters
----------
name : str
The name of the value
value
The value to store
layer : str, optional
The name of the layer to store the value in. If none is supplied
then the value will be stored in the outermost layer.
source : str, optional
The source to attribute the value to.
| python | {
"resource": ""
} |
q15590 | ConfigTree.update | train | def update(self, data: Union[Mapping, str, bytes], layer: str=None, source: str=None):
"""Adds additional data into the ConfigTree.
Parameters
----------
data :
source data
layer :
layer to load data into. If none is supplied the outermost one is used
source :
Source to attribute the values to
See Also
--------
read_dict
"""
if isinstance(data, dict):
self._read_dict(data, layer, source)
elif isinstance(data, ConfigTree):
# TODO: set this to parse the other config tree including layer and source info. Maybe.
self._read_dict(data.to_dict(), layer, source)
elif isinstance(data, str):
if data.endswith(('.yaml', '.yml')):
source = source if source else data
self._load(data, layer, source)
else:
try:
| python | {
"resource": ""
} |
q15591 | ConfigTree._read_dict | train | def _read_dict(self, data_dict, layer=None, source=None):
"""Load a dictionary into the ConfigTree. If the dict contains nested dicts
then the values will be added recursively. See module docstring for example code.
Parameters
----------
data_dict : dict
source data
layer : str
layer to load data into. If none is supplied the outermost one is | python | {
"resource": ""
} |
q15592 | ConfigTree._loads | train | def _loads(self, data_string, layer=None, source=None):
"""Load data from a yaml formatted string.
Parameters
----------
data_string : str
yaml formatted string. The root element of the document should be | python | {
"resource": ""
} |
q15593 | ConfigTree._load | train | def _load(self, f, layer=None, source=None):
"""Load data from a yaml formatted file.
Parameters
----------
f : str or file like object
If f is a string then it is interpreted as a path to the file to load
If it is a file like object then data is read directly from it.
layer : str
layer to load data into. If none is supplied the outermost one is used
source : str
Source to attribute the values to | python | {
"resource": ""
} |
q15594 | ConfigTree.metadata | train | def metadata(self, name):
"""Return value and metadata associated with the named value
Parameters
----------
name : str
name to retrieve. If the name contains '.'s it will be retrieved recursively
Raises
------
KeyError
if name is not defined in the ConfigTree
"""
if name in self._children:
return self._children[name].metadata()
| python | {
"resource": ""
} |
q15595 | ConfigTree.unused_keys | train | def unused_keys(self):
"""Lists all keys which are present in the ConfigTree but which have not been accessed."""
unused = set()
for k, c in self._children.items():
if isinstance(c, ConfigNode):
if not c.has_been_accessed():
| python | {
"resource": ""
} |
q15596 | create_validator | train | def create_validator(schema_filename=None, schema_dir=None):
"""Crea el validador necesario para inicializar un objeto DataJson.
Para poder resolver referencias inter-esquemas, un Validador requiere
que se especifique un RefResolver (Resolvedor de Referencias) con el
directorio base (absoluto) y el archivo desde el que se referencia el
directorio.
Para poder validar formatos, un Validador requiere que se provea
explícitamente un FormatChecker. Actualmente se usa el default de la
librería, jsonschema.FormatChecker().
Args:
schema_filename (str): Nombre del archivo que contiene el esquema
validador "maestro".
schema_dir (str): Directorio (absoluto) donde se encuentra el
esquema validador maestro y sus referencias, de tenerlas.
Returns:
Draft4Validator: Un validador de JSONSchema Draft #4. El validador
se crea con un RefResolver que resuelve referencias de
| python | {
"resource": ""
} |
q15597 | initialize_simulation | train | def initialize_simulation(components: List, input_config: Mapping=None,
plugin_config: Mapping=None) -> InteractiveContext:
"""Construct a simulation from a list of components, component
configuration, and a plugin configuration.
The simulation context returned by this method still needs to be setup by
calling its setup method. It is mostly useful for testing and debugging.
Parameters
----------
components
A list of initialized simulation components. Corresponds to the
components block of a model specification.
input_config
A nested dictionary with any additional simulation configuration
information needed. Corresponds to the configuration block of a model
specification.
plugin_config
A dictionary containing a description of any simulation plugins to | python | {
"resource": ""
} |
q15598 | setup_simulation | train | def setup_simulation(components: List, input_config: Mapping=None,
plugin_config: Mapping=None) -> InteractiveContext:
"""Construct a simulation from a list of components and call its setup
method.
Parameters
----------
components
A list of initialized simulation components. Corresponds to the
components block of a model specification.
input_config
A nested dictionary with any additional simulation configuration
information needed. Corresponds to the configuration block of a model
specification.
plugin_config
A dictionary containing a description of any simulation plugins to
include in the simulation. If you're using this argument, you're either
| python | {
"resource": ""
} |
q15599 | initialize_simulation_from_model_specification | train | def initialize_simulation_from_model_specification(model_specification_file: str) -> InteractiveContext:
"""Construct a simulation from a model specification file.
The simulation context returned by this method still needs to be setup by
calling its setup method. It is mostly useful for testing and debugging.
Parameters
----------
model_specification_file
The path to a model specification file.
Returns
-------
An initialized (but not set up) simulation context.
"""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.