repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
ml4ai/delphi
delphi/utils/fp.py
foldl
def foldl(f: Callable[[T, U], T], x: T, xs: Iterable[U]) -> T: """ Returns the accumulated result of a binary function applied to elements of an iterable. .. math:: foldl(f, x_0, [x_1, x_2, x_3]) = f(f(f(f(x_0, x_1), x_2), x_3) Examples -------- >>> from delphi.utils.fp import foldl ...
python
def foldl(f: Callable[[T, U], T], x: T, xs: Iterable[U]) -> T: """ Returns the accumulated result of a binary function applied to elements of an iterable. .. math:: foldl(f, x_0, [x_1, x_2, x_3]) = f(f(f(f(x_0, x_1), x_2), x_3) Examples -------- >>> from delphi.utils.fp import foldl ...
Returns the accumulated result of a binary function applied to elements of an iterable. .. math:: foldl(f, x_0, [x_1, x_2, x_3]) = f(f(f(f(x_0, x_1), x_2), x_3) Examples -------- >>> from delphi.utils.fp import foldl >>> foldl(lambda x, y: x + y, 10, range(5)) 20
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L146-L161
ml4ai/delphi
delphi/utils/fp.py
foldl1
def foldl1(f: Callable[[T, T], T], xs: Iterable[T]) -> T: """ Returns the accumulated result of a binary function applied to elements of an iterable. .. math:: foldl1(f, [x_0, x_1, x_2, x_3]) = f(f(f(f(x_0, x_1), x_2), x_3) Examples -------- >>> from delphi.utils.fp import foldl1 ...
python
def foldl1(f: Callable[[T, T], T], xs: Iterable[T]) -> T: """ Returns the accumulated result of a binary function applied to elements of an iterable. .. math:: foldl1(f, [x_0, x_1, x_2, x_3]) = f(f(f(f(x_0, x_1), x_2), x_3) Examples -------- >>> from delphi.utils.fp import foldl1 ...
Returns the accumulated result of a binary function applied to elements of an iterable. .. math:: foldl1(f, [x_0, x_1, x_2, x_3]) = f(f(f(f(x_0, x_1), x_2), x_3) Examples -------- >>> from delphi.utils.fp import foldl1 >>> foldl1(lambda x, y: x + y, range(5)) 10
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L164-L179
ml4ai/delphi
delphi/utils/fp.py
flatten
def flatten(xs: Union[List, Tuple]) -> List: """ Flatten a nested list or tuple. """ return ( sum(map(flatten, xs), []) if (isinstance(xs, list) or isinstance(xs, tuple)) else [xs] )
python
def flatten(xs: Union[List, Tuple]) -> List: """ Flatten a nested list or tuple. """ return ( sum(map(flatten, xs), []) if (isinstance(xs, list) or isinstance(xs, tuple)) else [xs] )
Flatten a nested list or tuple.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L182-L188
ml4ai/delphi
delphi/utils/fp.py
iterate
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, tak...
python
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, tak...
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, take >>> list(take(5, iterate(lambda x: x*2, 1))) [1, 2, 4...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L191-L204
ml4ai/delphi
delphi/utils/fp.py
ptake
def ptake(n: int, xs: Iterable[T]) -> Iterable[T]: """ take with a tqdm progress bar. """ return tqdm(take(n, xs), total=n)
python
def ptake(n: int, xs: Iterable[T]) -> Iterable[T]: """ take with a tqdm progress bar. """ return tqdm(take(n, xs), total=n)
take with a tqdm progress bar.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L211-L213
ml4ai/delphi
delphi/utils/fp.py
ltake
def ltake(n: int, xs: Iterable[T]) -> List[T]: """ A non-lazy version of take. """ return list(take(n, xs))
python
def ltake(n: int, xs: Iterable[T]) -> List[T]: """ A non-lazy version of take. """ return list(take(n, xs))
A non-lazy version of take.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L216-L218
ml4ai/delphi
delphi/utils/fp.py
compose
def compose(*fs: Any) -> Callable: """ Compose functions from left to right. e.g. compose(f, g)(x) = f(g(x)) """ return foldl1(lambda f, g: lambda *x: f(g(*x)), fs)
python
def compose(*fs: Any) -> Callable: """ Compose functions from left to right. e.g. compose(f, g)(x) = f(g(x)) """ return foldl1(lambda f, g: lambda *x: f(g(*x)), fs)
Compose functions from left to right. e.g. compose(f, g)(x) = f(g(x))
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L221-L226
ml4ai/delphi
delphi/utils/fp.py
rcompose
def rcompose(*fs: Any) -> Callable: """ Compose functions from right to left. e.g. rcompose(f, g)(x) = g(f(x)) """ return foldl1(lambda f, g: lambda *x: g(f(*x)), fs)
python
def rcompose(*fs: Any) -> Callable: """ Compose functions from right to left. e.g. rcompose(f, g)(x) = g(f(x)) """ return foldl1(lambda f, g: lambda *x: g(f(*x)), fs)
Compose functions from right to left. e.g. rcompose(f, g)(x) = g(f(x))
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L229-L234
ml4ai/delphi
delphi/utils/fp.py
flatMap
def flatMap(f: Callable, xs: Iterable) -> List: """ Map a function onto an iterable and flatten the result. """ return flatten(lmap(f, xs))
python
def flatMap(f: Callable, xs: Iterable) -> List: """ Map a function onto an iterable and flatten the result. """ return flatten(lmap(f, xs))
Map a function onto an iterable and flatten the result.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L237-L239
ml4ai/delphi
delphi/utils/fp.py
grouper
def grouper(xs: Iterable, n: int, fillvalue=None): """Collect data into fixed-length chunks or blocks. >>> from delphi.utils.fp import grouper >>> list(grouper('ABCDEFG', 3, 'x')) [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')] """ args = [iter(xs)] * n return zip_longest(*args, fillvalu...
python
def grouper(xs: Iterable, n: int, fillvalue=None): """Collect data into fixed-length chunks or blocks. >>> from delphi.utils.fp import grouper >>> list(grouper('ABCDEFG', 3, 'x')) [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')] """ args = [iter(xs)] * n return zip_longest(*args, fillvalu...
Collect data into fixed-length chunks or blocks. >>> from delphi.utils.fp import grouper >>> list(grouper('ABCDEFG', 3, 'x')) [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')]
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L254-L261
ml4ai/delphi
scripts/process_climis_unicef_ieconomics_data.py
process_climis_crop_production_data
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"{da...
python
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"{da...
Process CliMIS crop production data
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/scripts/process_climis_unicef_ieconomics_data.py#L154-L205
ml4ai/delphi
scripts/process_climis_unicef_ieconomics_data.py
process_climis_livestock_data
def process_climis_livestock_data(data_dir: str): """ Process CliMIS livestock data. """ records = [] livestock_data_dir = f"{data_dir}/Climis South Sudan Livestock Data" for filename in glob( f"{livestock_data_dir}/Livestock Body Condition/*2017.csv" ): records += process_file_wi...
python
def process_climis_livestock_data(data_dir: str): """ Process CliMIS livestock data. """ records = [] livestock_data_dir = f"{data_dir}/Climis South Sudan Livestock Data" for filename in glob( f"{livestock_data_dir}/Livestock Body Condition/*2017.csv" ): records += process_file_wi...
Process CliMIS livestock data.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/scripts/process_climis_unicef_ieconomics_data.py#L208-L353
ml4ai/delphi
delphi/translators/for2py/preprocessor.py
separate_trailing_comments
def separate_trailing_comments(lines: List[str]) -> List[Tuple[int, str]]: """Given a list of numbered Fortran source code lines, i.e., pairs of the form (n, code_line) where n is a line number and code_line is a line of code, separate_trailing_comments() behaves as follows: for each pair (n, c...
python
def separate_trailing_comments(lines: List[str]) -> List[Tuple[int, str]]: """Given a list of numbered Fortran source code lines, i.e., pairs of the form (n, code_line) where n is a line number and code_line is a line of code, separate_trailing_comments() behaves as follows: for each pair (n, c...
Given a list of numbered Fortran source code lines, i.e., pairs of the form (n, code_line) where n is a line number and code_line is a line of code, separate_trailing_comments() behaves as follows: for each pair (n, code_line) where code_line can be broken into two parts -- a code portion co...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/preprocessor.py#L39-L61
ml4ai/delphi
delphi/translators/for2py/preprocessor.py
merge_continued_lines
def merge_continued_lines(lines): """Given a list of numered Fortran source code lines, i.e., pairs of the form (n, code_line) where n is a line number and code_line is a line of code, merge_continued_lines() merges sequences of lines that are indicated to be continuation lines. """ # ...
python
def merge_continued_lines(lines): """Given a list of numered Fortran source code lines, i.e., pairs of the form (n, code_line) where n is a line number and code_line is a line of code, merge_continued_lines() merges sequences of lines that are indicated to be continuation lines. """ # ...
Given a list of numered Fortran source code lines, i.e., pairs of the form (n, code_line) where n is a line number and code_line is a line of code, merge_continued_lines() merges sequences of lines that are indicated to be continuation lines.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/preprocessor.py#L64-L106
ml4ai/delphi
delphi/translators/for2py/preprocessor.py
type_of_line
def type_of_line(line): """Given a line of code, type_of_line() returns a string indicating what kind of code it is.""" if line_is_comment(line): return "comment" elif line_is_executable(line): return "exec_stmt" elif line_is_pgm_unit_end(line): return "pgm_unit_end" ...
python
def type_of_line(line): """Given a line of code, type_of_line() returns a string indicating what kind of code it is.""" if line_is_comment(line): return "comment" elif line_is_executable(line): return "exec_stmt" elif line_is_pgm_unit_end(line): return "pgm_unit_end" ...
Given a line of code, type_of_line() returns a string indicating what kind of code it is.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/preprocessor.py#L140-L154
ml4ai/delphi
delphi/translators/for2py/preprocessor.py
extract_comments
def extract_comments( lines: List[Tuple[int, str]] ) -> Tuple[List[Tuple[int, str]], Dict[str, List[str]]]: """Given a list of numbered lines from a Fortran file where comments internal to subprogram bodies have been moved out into their own lines, extract_comments() extracts comments into a dicti...
python
def extract_comments( lines: List[Tuple[int, str]] ) -> Tuple[List[Tuple[int, str]], Dict[str, List[str]]]: """Given a list of numbered lines from a Fortran file where comments internal to subprogram bodies have been moved out into their own lines, extract_comments() extracts comments into a dicti...
Given a list of numbered lines from a Fortran file where comments internal to subprogram bodies have been moved out into their own lines, extract_comments() extracts comments into a dictionary and replaces each comment internal to subprogram bodies with a marker statement. It returns a pair ...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/preprocessor.py#L157-L250
ml4ai/delphi
delphi/translators/for2py/preprocessor.py
split_trailing_comment
def split_trailing_comment(line: str) -> str: """Takes a line and splits it into two parts (code_part, comment_part) where code_part is the line up to but not including any trailing comment (the '!' comment character and subsequent characters to the end of the line), while comment_part is the trailing c...
python
def split_trailing_comment(line: str) -> str: """Takes a line and splits it into two parts (code_part, comment_part) where code_part is the line up to but not including any trailing comment (the '!' comment character and subsequent characters to the end of the line), while comment_part is the trailing c...
Takes a line and splits it into two parts (code_part, comment_part) where code_part is the line up to but not including any trailing comment (the '!' comment character and subsequent characters to the end of the line), while comment_part is the trailing comment. Args: line: A line of Fortran so...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/preprocessor.py#L262-L303
ml4ai/delphi
delphi/translators/for2py/preprocessor.py
process
def process(inputLines: List[str]) -> str: """process() provides the interface used by an earlier version of this preprocessor.""" lines = separate_trailing_comments(inputLines) merge_continued_lines(lines) (lines, comments) = extract_comments(lines) actual_lines = [ line[1] f...
python
def process(inputLines: List[str]) -> str: """process() provides the interface used by an earlier version of this preprocessor.""" lines = separate_trailing_comments(inputLines) merge_continued_lines(lines) (lines, comments) = extract_comments(lines) actual_lines = [ line[1] f...
process() provides the interface used by an earlier version of this preprocessor.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/preprocessor.py#L306-L317
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.assign_uuids_to_nodes_and_edges
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()) for edge in self.edges(data=True): edge[2]["id"] = str(uuid4())
python
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()) for edge in self.edges(data=True): edge[2]["id"] = str(uuid4())
Assign uuids to nodes and edges.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L67-L73
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.from_statements_file
def from_statements_file(cls, file: str): """ Construct an AnalysisGraph object from a pickle file containing a list of INDRA statements. """ with open(file, "rb") as f: sts = pickle.load(f) return cls.from_statements(sts)
python
def from_statements_file(cls, file: str): """ Construct an AnalysisGraph object from a pickle file containing a list of INDRA statements. """ with open(file, "rb") as f: sts = pickle.load(f) return cls.from_statements(sts)
Construct an AnalysisGraph object from a pickle file containing a list of INDRA statements.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L80-L87
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.from_statements
def from_statements( cls, sts: List[Influence], assign_default_polarities: bool = True ): """ Construct an AnalysisGraph object from a list of INDRA statements. Unknown polarities are set to positive by default. Args: sts: A list of INDRA Statements Returns: ...
python
def from_statements( cls, sts: List[Influence], assign_default_polarities: bool = True ): """ Construct an AnalysisGraph object from a list of INDRA statements. Unknown polarities are set to positive by default. Args: sts: A list of INDRA Statements Returns: ...
Construct an AnalysisGraph object from a list of INDRA statements. Unknown polarities are set to positive by default. Args: sts: A list of INDRA Statements Returns: An AnalysisGraph instance constructed from a list of INDRA statements.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L90-L126
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.from_text
def from_text(cls, text: str): """ Construct an AnalysisGraph object from text, using Eidos to perform machine reading. """ eidosProcessor = process_text(text) return cls.from_statements(eidosProcessor.statements)
python
def from_text(cls, text: str): """ Construct an AnalysisGraph object from text, using Eidos to perform machine reading. """ eidosProcessor = process_text(text) return cls.from_statements(eidosProcessor.statements)
Construct an AnalysisGraph object from text, using Eidos to perform machine reading.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L129-L134
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.from_uncharted_json_file
def from_uncharted_json_file(cls, file): """ Construct an AnalysisGraph object from a file containing INDRA statements serialized exported by Uncharted's CauseMos webapp. """ with open(file, "r") as f: _dict = json.load(f) return cls.from_uncharted_json_serialized_dic...
python
def from_uncharted_json_file(cls, file): """ Construct an AnalysisGraph object from a file containing INDRA statements serialized exported by Uncharted's CauseMos webapp. """ with open(file, "r") as f: _dict = json.load(f) return cls.from_uncharted_json_serialized_dic...
Construct an AnalysisGraph object from a file containing INDRA statements serialized exported by Uncharted's CauseMos webapp.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L151-L157
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.from_uncharted_json_serialized_dict
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...
python
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...
Construct an AnalysisGraph object from a dict of INDRA statements exported by Uncharted's CauseMos webapp.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L160-L228
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.assemble_transition_model_from_gradable_adjectives
def assemble_transition_model_from_gradable_adjectives(self): """ Add probability distribution functions constructed from gradable adjective data to the edges of the analysis graph data structure. Args: adjective_data res """ df = pd.read_sql_table("grad...
python
def assemble_transition_model_from_gradable_adjectives(self): """ Add probability distribution functions constructed from gradable adjective data to the edges of the analysis graph data structure. Args: adjective_data res """ df = pd.read_sql_table("grad...
Add probability distribution functions constructed from gradable adjective data to the edges of the analysis graph data structure. Args: adjective_data res
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L276-L303
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.sample_from_prior
def sample_from_prior(self): """ Sample elements of the stochastic transition matrix from the prior distribution, based on gradable adjectives. """ # simple_path_dict caches the results of the graph traversal that finds # simple paths between pairs of nodes, so that it doesn't have to b...
python
def sample_from_prior(self): """ Sample elements of the stochastic transition matrix from the prior distribution, based on gradable adjectives. """ # simple_path_dict caches the results of the graph traversal that finds # simple paths between pairs of nodes, so that it doesn't have to b...
Sample elements of the stochastic transition matrix from the prior distribution, based on gradable adjectives.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L314-L354
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.sample_observed_state
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
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]: { ...
Sample observed state vector. This is the implementation of the emission function. Args: s: Latent state vector. Returns: Observed state vector.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L356-L373
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.sample_from_likelihood
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 =...
python
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 =...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L375-L396
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.sample_from_proposal
def sample_from_proposal(self, A: pd.DataFrame) -> None: """ Sample a new transition matrix from the proposal distribution, given a current candidate transition matrix. In practice, this amounts to the in-place perturbation of an element of the transition matrix currently being used by t...
python
def sample_from_proposal(self, A: pd.DataFrame) -> None: """ Sample a new transition matrix from the proposal distribution, given a current candidate transition matrix. In practice, this amounts to the in-place perturbation of an element of the transition matrix currently being used by t...
Sample a new transition matrix from the proposal distribution, given a current candidate transition matrix. In practice, this amounts to the in-place perturbation of an element of the transition matrix currently being used by the sampler. Args
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L398-L412
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.get_timeseries_values_for_indicators
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, ...
python
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, ...
Attach timeseries to indicators, for performing Bayesian inference.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L414-L434
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.sample_from_posterior
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_prob...
python
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_prob...
Run Bayesian inference - sample from the posterior distribution.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L436-L457
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.infer_transition_matrix_coefficient_from_data
def infer_transition_matrix_coefficient_from_data( self, source: str, target: str, state: Optional[str] = None, crop: Optional[str] = None, ): """ Infer the distribution of a particular transition matrix coefficient from data. Args: source...
python
def infer_transition_matrix_coefficient_from_data( self, source: str, target: str, state: Optional[str] = None, crop: Optional[str] = None, ): """ Infer the distribution of a particular transition matrix coefficient from data. Args: source...
Infer the distribution of a particular transition matrix coefficient from data. Args: source: The source of the edge corresponding to the matrix element to infer. target: The target of the edge corresponding to the matrix element to infer. ...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L459-L491
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.create_bmi_config_file
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. """ s0 = self.construct_default_initial_state() s0.to_csv(filena...
python
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. """ s0 = self.construct_default_initial_state() s0.to_csv(filena...
Create a BMI config file to initialize the model. Args: filename: The filename with which the config file should be saved.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L497-L504
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.default_update_function
def default_update_function(self, n: Tuple[str, dict]) -> List[float]: """ The default update function for a CAG node. n: A 2-tuple containing the node name and node data. Returns: A list of values corresponding to the distribution of the value of the real-valued var...
python
def default_update_function(self, n: Tuple[str, dict]) -> List[float]: """ The default update function for a CAG node. n: A 2-tuple containing the node name and node data. Returns: A list of values corresponding to the distribution of the value of the real-valued var...
The default update function for a CAG node. n: A 2-tuple containing the node name and node data. Returns: A list of values corresponding to the distribution of the value of the real-valued variable representing the node.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L506-L518
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.initialize
def initialize( self, config_file: str = "bmi_config.txt", initialize_indicators=True ): """ Initialize the executable AnalysisGraph with a config file. Args: config_file Returns: AnalysisGraph """ self.t = 0.0 if not os.path.isfile(c...
python
def initialize( self, config_file: str = "bmi_config.txt", initialize_indicators=True ): """ Initialize the executable AnalysisGraph with a config file. Args: config_file Returns: AnalysisGraph """ self.t = 0.0 if not os.path.isfile(c...
Initialize the executable AnalysisGraph with a config file. Args: config_file Returns: AnalysisGraph
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L520-L556
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.update
def update(self, τ: float = 1.0, update_indicators=True, dampen=False): """ Advance the model by one time step. """ for n in self.nodes(data=True): n[1]["next_state"] = n[1]["update_function"](n) for n in self.nodes(data=True): n[1]["rv"].dataset = n[1]["next_state"] ...
python
def update(self, τ: float = 1.0, update_indicators=True, dampen=False): """ Advance the model by one time step. """ for n in self.nodes(data=True): n[1]["next_state"] = n[1]["update_function"](n) for n in self.nodes(data=True): n[1]["rv"].dataset = n[1]["next_state"] ...
Advance the model by one time step.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L558-L581
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.export_node
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 ar...
python
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 ar...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L623-L653
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.to_dict
def to_dict(self) -> Dict: """ Export the CAG to a dict that can be serialized to JSON. """ return { "name": self.name, "dateCreated": str(self.dateCreated), "variables": lmap( lambda n: self.export_node(n), self.nodes(data=True) ), ...
python
def to_dict(self) -> Dict: """ Export the CAG to a dict that can be serialized to JSON. """ return { "name": self.name, "dateCreated": str(self.dateCreated), "variables": lmap( lambda n: self.export_node(n), self.nodes(data=True) ), ...
Export the CAG to a dict that can be serialized to JSON.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L655-L665
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.map_concepts_to_indicators
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:...
python
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:...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L675-L719
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.parameterize
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, ...
python
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...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L721-L764
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.delete_nodes
def delete_nodes(self, nodes: Iterable[str]): """ Iterate over a set of nodes and remove the ones that are present in the graph. """ for n in nodes: if self.has_node(n): self.remove_node(n)
python
def delete_nodes(self, nodes: Iterable[str]): """ Iterate over a set of nodes and remove the ones that are present in the graph. """ for n in nodes: if self.has_node(n): self.remove_node(n)
Iterate over a set of nodes and remove the ones that are present in the graph.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L775-L780
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.delete_node
def delete_node(self, node: str): """ Removes a node if it is in the graph. """ if self.has_node(node): self.remove_node(node)
python
def delete_node(self, node: str): """ Removes a node if it is in the graph. """ if self.has_node(node): self.remove_node(node)
Removes a node if it is in the graph.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L782-L785
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.delete_edge
def delete_edge(self, source: str, target: str): """ Removes an edge if it is in the graph. """ if self.has_edge(source, target): self.remove_edge(source, target)
python
def delete_edge(self, source: str, target: str): """ Removes an edge if it is in the graph. """ if self.has_edge(source, target): self.remove_edge(source, target)
Removes an edge if it is in the graph.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L787-L790
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.delete_edges
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. """ for edge in edges: if self.has_edge(*edge): self.remove_edge(*edge)
python
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. """ for edge in edges: if self.has_edge(*edge): self.remove_edge(*edge)
Iterate over a set of edges and remove the ones that are present in the graph.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L792-L797
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.prune
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: ...
python
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: ...
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...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L799-L823
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.merge_nodes
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]...
python
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]...
Merge node n1 into node n2, with the option to specify relative polarity. Args: n1 n2 same_polarity
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L825-L868
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.get_subgraph_for_concept
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...
python
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...
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. ...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L874-L903
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.get_subgraph_for_concept_pair
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 """ paths = nx.all_simple_p...
python
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 """ paths = nx.all_simple_p...
Get subgraph comprised of simple paths between the source and the target. Args: source target cutoff
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L905-L917
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.get_subgraph_for_concept_pairs
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 """ path_generator = ( nx.all_simple...
python
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 """ path_generator = ( nx.all_simple...
Get subgraph comprised of simple paths between the source and the target. Args: concepts cutoff
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L919-L934
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.to_sql
def to_sql(self, app=None, last_known_value_date: Optional[date] = None): """ Inserts the model into the SQLite3 database associated with Delphi, for use with the ICM REST API. """ from delphi.apps.rest_api import create_app, db self.assign_uuids_to_nodes_and_edges() icm_metada...
python
def to_sql(self, app=None, last_known_value_date: Optional[date] = None): """ Inserts the model into the SQLite3 database associated with Delphi, for use with the ICM REST API. """ from delphi.apps.rest_api import create_app, db self.assign_uuids_to_nodes_and_edges() icm_metada...
Inserts the model into the SQLite3 database associated with Delphi, for use with the ICM REST API.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L940-L1060
ml4ai/delphi
delphi/AnalysisGraph.py
AnalysisGraph.to_agraph
def to_agraph( self, indicators: bool = False, indicator_values: bool = False, nodes_to_highlight=None, *args, **kwargs, ): """ Exports the CAG as a pygraphviz AGraph for visualization. Args: indicators: Whether to display indicators in th...
python
def to_agraph( self, indicators: bool = False, indicator_values: bool = False, nodes_to_highlight=None, *args, **kwargs, ): """ Exports the CAG as a pygraphviz AGraph for visualization. Args: indicators: Whether to display indicators in th...
Exports the CAG as a pygraphviz AGraph for visualization. Args: indicators: Whether to display indicators in the AGraph indicator_values: Whether to display indicator values in the AGraph nodes_to_highlight: Nodes to highlight in the AGraph. Returns: A Py...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L1062-L1217
ml4ai/delphi
delphi/translators/for2py/genPGM.py
dump
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...
python
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...
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...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/genPGM.py#L1375-L1424
ml4ai/delphi
delphi/translators/for2py/genPGM.py
create_pgm_dict
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) ...
python
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) ...
Create a Python dict representing the PGM, with additional metadata for JSON output.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/genPGM.py#L1622-L1655
ml4ai/delphi
scripts/evaluations/create_reference_CAG.py
filter_and_process_statements
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): ...
python
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): ...
Filter preassembled statements according to certain rules.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/scripts/evaluations/create_reference_CAG.py#L7-L63
ml4ai/delphi
scripts/evaluations/create_CAG_with_indicators.py
create_CAG_with_indicators
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 Ave...
python
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 Ave...
Create a CAG with mapped indicators
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/scripts/evaluations/create_CAG_with_indicators.py#L5-L18
ml4ai/delphi
delphi/GrFN/networks.py
ComputationalGraph.run
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...
python
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...
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...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L87-L124
ml4ai/delphi
delphi/GrFN/networks.py
ComputationalGraph.to_CAG
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.""" G = nx.DiGraph() for (name, attrs) in self.nodes(data=True): if attrs["type"] == ...
python
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.""" G = nx.DiGraph() for (name, attrs) in self.nodes(data=True): if attrs["type"] == ...
Export to a Causal Analysis Graph (CAG) PyGraphviz AGraph object. The CAG shows the influence relationships between the variables and elides the function nodes.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L126-L152
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.traverse_nodes
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...
python
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...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L186-L210
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.from_json_and_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. """ with open(fi...
python
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. """ with open(fi...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L213-L227
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.from_dict
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 ...
python
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 ...
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: ...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L230-L356
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.from_python_file
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: pySrc = f.read() return cls.from_python_src(pySrc, lambdas_path, json_filename, stem)
python
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: pySrc = f.read() return cls.from_python_src(pySrc, lambdas_path, json_filename, stem)
Builds GrFN object from Python file.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L359-L365
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.from_python_src
def from_python_src( cls, pySrc, lambdas_path, json_filename: str, stem: str, save_file: bool = False, ): """Builds GrFN object from Python source code.""" asts = [ast.parse(pySrc)] pgm_dict = genPGM.create_pgm_dict( lambdas_path, ...
python
def from_python_src( cls, pySrc, lambdas_path, json_filename: str, stem: str, save_file: bool = False, ): """Builds GrFN object from Python source code.""" asts = [ast.parse(pySrc)] pgm_dict = genPGM.create_pgm_dict( lambdas_path, ...
Builds GrFN object from Python source code.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L368-L385
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.from_fortran_file
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}_preproc...
python
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}_preproc...
Builds GrFN object from a Fortran program.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L390-L425
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.from_fortran_src
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 ...
python
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 ...
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...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L428-L446
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.clear
def clear(self): """Clear variable nodes for next computation.""" 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
python
def clear(self): """Clear variable nodes for next computation.""" 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
Clear variable nodes for next computation.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L448-L454
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.to_FIB
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 u...
python
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 u...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L550-L590
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.to_agraph
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...
python
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...
Export to a PyGraphviz AGraph object.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L592-L618
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.to_CAG_agraph
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) A.graph_attr.update({"dpi": 227...
python
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) A.graph_attr.update({"dpi": 227...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L620-L639
ml4ai/delphi
delphi/GrFN/networks.py
GroundedFunctionNetwork.to_call_agraph
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) A.graph_attr.update({"dpi": 227, "fontsize": 20, "fontname": "Menlo"}) A.node_attr.update( {"shape": "rectangle"...
python
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) A.graph_attr.update({"dpi": 227, "fontsize": 20, "fontname": "Menlo"}) A.node_attr.update( {"shape": "rectangle"...
Build a PyGraphviz AGraph object corresponding to a call graph of functions.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L641-L651
ml4ai/delphi
delphi/GrFN/networks.py
ForwardInfluenceBlanket.run
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: in...
python
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: in...
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...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L745-L768
ml4ai/delphi
delphi/GrFN/networks.py
ForwardInfluenceBlanket.S2_surface
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: Tup...
python
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: Tup...
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...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/networks.py#L806-L862
ml4ai/delphi
delphi/translators/for2py/translate.py
XMLToJSONTranslator.process_direct_map
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.""" val = {"tag": root.tag, "args": []} for node in root: val["args"] +=...
python
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.""" val = {"tag": root.tag, "args": []} for node in root: val["args"] +=...
Handles tags that are mapped directly from xml to IR with no additional processing other than recursive translation of any child nodes.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/translate.py#L629-L637
ml4ai/delphi
delphi/translators/for2py/translate.py
XMLToJSONTranslator.parseTree
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 stat...
python
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 stat...
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. ...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/translate.py#L738-L763
ml4ai/delphi
delphi/translators/for2py/translate.py
XMLToJSONTranslator.loadFunction
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 i...
python
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 i...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/translate.py#L765-L780
ml4ai/delphi
delphi/translators/for2py/translate.py
XMLToJSONTranslator.analyze
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) ...
python
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) ...
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...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/translate.py#L782-L823
ml4ai/delphi
delphi/apps/cli.py
main
def main(): """Run the CLI.""" 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, h...
python
def main(): """Run the CLI.""" 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, h...
Run the CLI.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/apps/cli.py#L93-L155
ml4ai/delphi
scripts/data_processing/process_FAO_and_WDI_data.py
construct_FAO_ontology
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)]}...
python
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)]}...
Construct FAO variable ontology for use with Eidos.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/scripts/data_processing/process_FAO_and_WDI_data.py#L96-L119
ml4ai/delphi
delphi/inspection.py
inspect_edge
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 """ return create_statement_inspection_table( G[source][target]["...
python
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 """ return create_statement_inspection_table( G[source][target]["...
'Drill down' into an edge in the analysis graph and inspect its provenance. This function prints the provenance. Args: G source target
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/inspection.py#L13-L25
ml4ai/delphi
delphi/inspection.py
_get_edge_sentences
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. """ return chain.from_iterable( [ ...
python
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. """ return chain.from_iterable( [ ...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/inspection.py#L28-L44
ml4ai/delphi
delphi/GrFN/utils.py
get_node_type
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 == "condit...
python
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 == "condit...
Returns the NodeType given a name of a JSON function object.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/GrFN/utils.py#L51-L64
ml4ai/delphi
delphi/translators/for2py/format.py
list_output_formats
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 in type_list: item_format = default_output_format(type_item) out_format_list.ap...
python
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 in type_list: item_format = default_output_format(type_item) out_format_list.ap...
This function takes a list of type names and returns a list of format specifiers for list-directed output of values of those types.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L405-L413
ml4ai/delphi
delphi/translators/for2py/format.py
list_data_type
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]...
python
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]...
This function takes a list of format specifiers and returns a list of data types represented by the format specifiers.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L421-L448
ml4ai/delphi
delphi/translators/for2py/format.py
Format.init_read_line
def init_read_line(self): """init_read_line() initializes fields relevant to input matching""" 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._r...
python
def init_read_line(self): """init_read_line() initializes fields relevant to input matching""" 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._r...
init_read_line() initializes fields relevant to input matching
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L73-L87
ml4ai/delphi
delphi/translators/for2py/format.py
Format.init_write_line
def init_write_line(self): """init_write_line() initializes fields relevant to output generation""" 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 ou...
python
def init_write_line(self): """init_write_line() initializes fields relevant to output generation""" 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 ou...
init_write_line() initializes fields relevant to output generation
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L89-L96
ml4ai/delphi
delphi/translators/for2py/format.py
Format.read_line
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 m...
python
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 m...
Match a line of input according to the format specified and return a tuple of the resulting values
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L99-L138
ml4ai/delphi
delphi/translators/for2py/format.py
Format.write_line
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:...
python
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:...
Process a list of values according to the format specified to generate a line of output.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L140-L167
ml4ai/delphi
delphi/translators/for2py/format.py
Format.match_input_fmt
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.""" rexp_list = [] for fmt in fmt_list: rexp_list.ext...
python
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.""" rexp_list = [] for fmt in fmt_list: rexp_list.ext...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L178-L187
ml4ai/delphi
delphi/translators/for2py/format.py
Format.match_input_fmt_1
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: ...
python
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: ...
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...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L189-L258
ml4ai/delphi
delphi/translators/for2py/format.py
Format.gen_output_fmt
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.""" rexp_list = [] for fmt in fmt_list: rexp_lis...
python
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.""" rexp_list = [] for fmt in fmt_list: rexp_lis...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L266-L275
ml4ai/delphi
delphi/translators/for2py/format.py
Format.gen_output_fmt_1
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 forma...
python
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 forma...
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 ...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/format.py#L277-L358
ml4ai/delphi
delphi/assembly.py
constructConditionalPDF
def constructConditionalPDF( gb, rs: np.ndarray, e: Tuple[str, str, Dict] ) -> gaussian_kde: """ Construct a conditional probability density function for a particular AnalysisGraph edge. """ adjective_response_dict = {} all_θs = [] # Setting σ_X and σ_Y that are in Eq. 1.21 of the model docume...
python
def constructConditionalPDF( gb, rs: np.ndarray, e: Tuple[str, str, Dict] ) -> gaussian_kde: """ Construct a conditional probability density function for a particular AnalysisGraph edge. """ adjective_response_dict = {} all_θs = [] # Setting σ_X and σ_Y that are in Eq. 1.21 of the model docume...
Construct a conditional probability density function for a particular AnalysisGraph edge.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/assembly.py#L24-L89
ml4ai/delphi
delphi/assembly.py
get_variable_and_source
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 xs[0] == "FAO": return " ".join(xs[2:]), xs[0] else: return xs[-1], xs[0]
python
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 xs[0] == "FAO": return " ".join(xs[2:]), xs[0] else: return xs[-1], xs[0]
Process the variable name to make it more human-readable.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/assembly.py#L96-L103
ml4ai/delphi
delphi/assembly.py
construct_concept_to_indicator_mapping
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....
python
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....
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/assembly.py#L106-L123
ihmeuw/vivarium
src/vivarium/examples/disease_model/mortality.py
Mortality.setup
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. Para...
python
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. Para...
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 : ...
https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/examples/disease_model/mortality.py#L25-L43
ihmeuw/vivarium
src/vivarium/examples/disease_model/mortality.py
Mortality.base_mortality_rate
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 ------- ...
python
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 ------- ...
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.
https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/examples/disease_model/mortality.py#L45-L58
ihmeuw/vivarium
src/vivarium/examples/disease_model/mortality.py
Mortality.determine_deaths
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. ...
python
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. ...
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.
https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/examples/disease_model/mortality.py#L60-L74
ihmeuw/vivarium
src/vivarium/framework/components/parser.py
_prep_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 ------- Lis...
python
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 ------- Lis...
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.
https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/components/parser.py#L100-L117
ihmeuw/vivarium
src/vivarium/framework/components/parser.py
ComponentConfigurationParser.get_components
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 con...
python
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 con...
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...
https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/components/parser.py#L35-L55
ihmeuw/vivarium
src/vivarium/framework/components/parser.py
ComponentConfigurationParser.parse_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 ...
python
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 ...
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 ...
https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/components/parser.py#L57-L79
casastorta/python-sar
sar/parser.py
Parser.load_file
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) """ # We first split file into pieces searchunks = self._split_file() i...
python
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) """ # We first split file into pieces searchunks = self._split_file() i...
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)
https://github.com/casastorta/python-sar/blob/e6d8bb86524102d677f37e985302fad34e3297c1/sar/parser.py#L39-L62