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
Valassis-Digital-Media/spylon
spylon/common.py
as_iterable
def as_iterable(iterable_or_scalar): """Utility for converting an object to an iterable. Parameters ---------- iterable_or_scalar : anything Returns ------- l : iterable If `obj` was None, return the empty tuple. If `obj` was not iterable returns a 1-tuple containing `obj`....
python
def as_iterable(iterable_or_scalar): """Utility for converting an object to an iterable. Parameters ---------- iterable_or_scalar : anything Returns ------- l : iterable If `obj` was None, return the empty tuple. If `obj` was not iterable returns a 1-tuple containing `obj`....
Utility for converting an object to an iterable. Parameters ---------- iterable_or_scalar : anything Returns ------- l : iterable If `obj` was None, return the empty tuple. If `obj` was not iterable returns a 1-tuple containing `obj`. Otherwise return `obj` Notes ...
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/common.py#L30-L69
Valassis-Digital-Media/spylon
spylon/spark/utils.py
SparkJVMHelpers.classloader
def classloader(self): """Returns the private class loader that spark uses. This is needed since jars added with --jars are not easily resolvable by py4j's classloader """ return self.jvm.org.apache.spark.util.Utils.getContextOrSparkClassLoader()
python
def classloader(self): """Returns the private class loader that spark uses. This is needed since jars added with --jars are not easily resolvable by py4j's classloader """ return self.jvm.org.apache.spark.util.Utils.getContextOrSparkClassLoader()
Returns the private class loader that spark uses. This is needed since jars added with --jars are not easily resolvable by py4j's classloader
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/utils.py#L68-L73
Valassis-Digital-Media/spylon
spylon/spark/utils.py
SparkJVMHelpers.get_java_container
def get_java_container(self, package_name=None, object_name=None, java_class_instance=None): """Convenience method to get the container that houses methods we wish to call a method on. """ if package_name is not None: jcontainer = self.import_scala_package_object(package_name) ...
python
def get_java_container(self, package_name=None, object_name=None, java_class_instance=None): """Convenience method to get the container that houses methods we wish to call a method on. """ if package_name is not None: jcontainer = self.import_scala_package_object(package_name) ...
Convenience method to get the container that houses methods we wish to call a method on.
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/utils.py#L75-L87
Valassis-Digital-Media/spylon
spylon/spark/utils.py
SparkJVMHelpers.wrap_function_cols
def wrap_function_cols(self, name, package_name=None, object_name=None, java_class_instance=None, doc=""): """Utility method for wrapping a scala/java function that returns a spark sql Column. This assumes that the function that you are wrapping takes a list of spark sql Column objects as its arguments...
python
def wrap_function_cols(self, name, package_name=None, object_name=None, java_class_instance=None, doc=""): """Utility method for wrapping a scala/java function that returns a spark sql Column. This assumes that the function that you are wrapping takes a list of spark sql Column objects as its arguments...
Utility method for wrapping a scala/java function that returns a spark sql Column. This assumes that the function that you are wrapping takes a list of spark sql Column objects as its arguments.
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/utils.py#L89-L104
Valassis-Digital-Media/spylon
spylon/spark/utils.py
SparkJVMHelpers.wrap_spark_sql_udf
def wrap_spark_sql_udf(self, name, package_name=None, object_name=None, java_class_instance=None, doc=""): """Wraps a scala/java spark user defined function """ def _(*cols): jcontainer = self.get_java_container(package_name=package_name, object_name=object_name, java_class_instance=java_cla...
python
def wrap_spark_sql_udf(self, name, package_name=None, object_name=None, java_class_instance=None, doc=""): """Wraps a scala/java spark user defined function """ def _(*cols): jcontainer = self.get_java_container(package_name=package_name, object_name=object_name, java_class_instance=java_cla...
Wraps a scala/java spark user defined function
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/utils.py#L106-L117
Valassis-Digital-Media/spylon
update_spark_params.py
_save_documentation
def _save_documentation(version, base_url="https://spark.apache.org/docs"): """ Write the spark property documentation to a file """ target_dir = join(dirname(__file__), 'spylon', 'spark') with open(join(target_dir, "spark_properties_{}.json".format(version)), 'w') as fp: all_props = _fetch_...
python
def _save_documentation(version, base_url="https://spark.apache.org/docs"): """ Write the spark property documentation to a file """ target_dir = join(dirname(__file__), 'spylon', 'spark') with open(join(target_dir, "spark_properties_{}.json".format(version)), 'w') as fp: all_props = _fetch_...
Write the spark property documentation to a file
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/update_spark_params.py#L16-L25
Valassis-Digital-Media/spylon
spylon/spark/progress.py
_pretty_time_delta
def _pretty_time_delta(td): """Creates a string representation of a time delta. Parameters ---------- td : :class:`datetime.timedelta` Returns ------- pretty_formatted_datetime : str """ seconds = td.total_seconds() sign_string = '-' if seconds < 0 else '' seconds = abs(int...
python
def _pretty_time_delta(td): """Creates a string representation of a time delta. Parameters ---------- td : :class:`datetime.timedelta` Returns ------- pretty_formatted_datetime : str """ seconds = td.total_seconds() sign_string = '-' if seconds < 0 else '' seconds = abs(int...
Creates a string representation of a time delta. Parameters ---------- td : :class:`datetime.timedelta` Returns ------- pretty_formatted_datetime : str
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/progress.py#L34-L59
Valassis-Digital-Media/spylon
spylon/spark/progress.py
_format_stage_info
def _format_stage_info(bar_width, stage_info, duration, timedelta_formatter=_pretty_time_delta): """Formats the Spark stage progress. Parameters ---------- bar_width : int Width of the progressbar to print out. stage_info : :class:`pyspark.status.StageInfo` Information about the run...
python
def _format_stage_info(bar_width, stage_info, duration, timedelta_formatter=_pretty_time_delta): """Formats the Spark stage progress. Parameters ---------- bar_width : int Width of the progressbar to print out. stage_info : :class:`pyspark.status.StageInfo` Information about the run...
Formats the Spark stage progress. Parameters ---------- bar_width : int Width of the progressbar to print out. stage_info : :class:`pyspark.status.StageInfo` Information about the running stage stage_id : int Unique ID of the stage duration : :class:`datetime.timedelta` ...
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/progress.py#L62-L95
Valassis-Digital-Media/spylon
spylon/spark/progress.py
start
def start(sc, timedelta_formatter=_pretty_time_delta, bar_width=20, sleep_time=0.5): """Creates a :class:`ProgressPrinter` that polls the SparkContext for information about active stage progress and prints that information to stderr. The printer runs in a thread and is useful for showing text-based pro...
python
def start(sc, timedelta_formatter=_pretty_time_delta, bar_width=20, sleep_time=0.5): """Creates a :class:`ProgressPrinter` that polls the SparkContext for information about active stage progress and prints that information to stderr. The printer runs in a thread and is useful for showing text-based pro...
Creates a :class:`ProgressPrinter` that polls the SparkContext for information about active stage progress and prints that information to stderr. The printer runs in a thread and is useful for showing text-based progress bars in interactive environments (e.g., REPLs, Jupyter Notebooks). This function ...
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/progress.py#L205-L238
Valassis-Digital-Media/spylon
spylon/spark/progress.py
ProgressPrinter.resume
def resume(self): """Resume progress updates.""" with self.condition: self.paused = False self.condition.notify_all()
python
def resume(self): """Resume progress updates.""" with self.condition: self.paused = False self.condition.notify_all()
Resume progress updates.
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/progress.py#L146-L150
Valassis-Digital-Media/spylon
spylon/spark/progress.py
ProgressPrinter.run
def run(self): """Run the progress printing loop.""" last_status = '' # lambda is used to avoid http://bugs.python.org/issue30473 in py36 start_times = defaultdict(lambda: datetime.datetime.now()) max_stage_id = -1 status = self.sc.statusTracker() while True: ...
python
def run(self): """Run the progress printing loop.""" last_status = '' # lambda is used to avoid http://bugs.python.org/issue30473 in py36 start_times = defaultdict(lambda: datetime.datetime.now()) max_stage_id = -1 status = self.sc.statusTracker() while True: ...
Run the progress printing loop.
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/progress.py#L152-L199
Valassis-Digital-Media/spylon
spylon/spark/yarn_launcher.py
create_conda_env
def create_conda_env(sandbox_dir, env_name, dependencies, options=()): """ Create a conda environment inside the current sandbox for the given list of dependencies and options. Parameters ---------- sandbox_dir : str env_name : str dependencies : list List of conda specs options...
python
def create_conda_env(sandbox_dir, env_name, dependencies, options=()): """ Create a conda environment inside the current sandbox for the given list of dependencies and options. Parameters ---------- sandbox_dir : str env_name : str dependencies : list List of conda specs options...
Create a conda environment inside the current sandbox for the given list of dependencies and options. Parameters ---------- sandbox_dir : str env_name : str dependencies : list List of conda specs options List of additional options to pass to conda. Things like ["-c", "conda-fo...
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/yarn_launcher.py#L46-L72
Valassis-Digital-Media/spylon
spylon/spark/yarn_launcher.py
archive_dir
def archive_dir(env_dir): """ Compresses the directory and writes to its parent Parameters ---------- env_dir : str Returns ------- str """ output_filename = env_dir + ".zip" log.info("Archiving conda environment: %s -> %s", env_dir, output_filename) subprocess.check_ca...
python
def archive_dir(env_dir): """ Compresses the directory and writes to its parent Parameters ---------- env_dir : str Returns ------- str """ output_filename = env_dir + ".zip" log.info("Archiving conda environment: %s -> %s", env_dir, output_filename) subprocess.check_ca...
Compresses the directory and writes to its parent Parameters ---------- env_dir : str Returns ------- str
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/yarn_launcher.py#L75-L90
Valassis-Digital-Media/spylon
spylon/spark/yarn_launcher.py
prepare_pyspark_yarn_interactive
def prepare_pyspark_yarn_interactive(env_name, env_archive, spark_conf): """ This ASSUMES that you have a compatible python environment running on the other side. WARNING: Injects "PYSPARK_DRIVER_PYTHON" and "PYSPARK_PYTHON" as environmental variables into your current environment Parameters -...
python
def prepare_pyspark_yarn_interactive(env_name, env_archive, spark_conf): """ This ASSUMES that you have a compatible python environment running on the other side. WARNING: Injects "PYSPARK_DRIVER_PYTHON" and "PYSPARK_PYTHON" as environmental variables into your current environment Parameters -...
This ASSUMES that you have a compatible python environment running on the other side. WARNING: Injects "PYSPARK_DRIVER_PYTHON" and "PYSPARK_PYTHON" as environmental variables into your current environment Parameters ---------- env_name : str env_archive : str spark_conf : SparkConfiguratio...
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/yarn_launcher.py#L94-L158
Valassis-Digital-Media/spylon
spylon/spark/yarn_launcher.py
run_pyspark_yarn_cluster
def run_pyspark_yarn_cluster(env_dir, env_name, env_archive, args): """ Initializes the requires spark command line options on order to start a python job with the given python environment. Parameters ---------- env_dir : str env_name : str env_archive : str args : list Returns ...
python
def run_pyspark_yarn_cluster(env_dir, env_name, env_archive, args): """ Initializes the requires spark command line options on order to start a python job with the given python environment. Parameters ---------- env_dir : str env_name : str env_archive : str args : list Returns ...
Initializes the requires spark command line options on order to start a python job with the given python environment. Parameters ---------- env_dir : str env_name : str env_archive : str args : list Returns ------- This call will spawn a child process and block until that is comple...
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/yarn_launcher.py#L204-L241
Valassis-Digital-Media/spylon
spylon/spark/yarn_launcher.py
launcher
def launcher(deploy_mode, args, working_dir=".", cleanup=True): """Initializes arguments and starts up pyspark with the correct deploy mode and environment. Parameters ---------- deploy_mode : {"client", "cluster"} args : list Arguments to pass onwards to spark submit. working_dir : str...
python
def launcher(deploy_mode, args, working_dir=".", cleanup=True): """Initializes arguments and starts up pyspark with the correct deploy mode and environment. Parameters ---------- deploy_mode : {"client", "cluster"} args : list Arguments to pass onwards to spark submit. working_dir : str...
Initializes arguments and starts up pyspark with the correct deploy mode and environment. Parameters ---------- deploy_mode : {"client", "cluster"} args : list Arguments to pass onwards to spark submit. working_dir : str, optional Path to working directory to use for creating conda ...
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/yarn_launcher.py#L299-L360
Valassis-Digital-Media/spylon
spylon/spark/yarn_launcher.py
_extract_local_archive
def _extract_local_archive(working_dir, cleanup_functions, env_name, local_archive): """Helper internal function for extracting a zipfile and ensure that a cleanup is queued. Parameters ---------- working_dir : str cleanup_functions : List[() -> NoneType] env_name : str local_archive : str ...
python
def _extract_local_archive(working_dir, cleanup_functions, env_name, local_archive): """Helper internal function for extracting a zipfile and ensure that a cleanup is queued. Parameters ---------- working_dir : str cleanup_functions : List[() -> NoneType] env_name : str local_archive : str ...
Helper internal function for extracting a zipfile and ensure that a cleanup is queued. Parameters ---------- working_dir : str cleanup_functions : List[() -> NoneType] env_name : str local_archive : str
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/yarn_launcher.py#L363-L392
Valassis-Digital-Media/spylon
spylon/spark/launcher.py
keyfilter
def keyfilter(predicate, d, factory=dict): """ Filter items in dictionary by key >>> iseven = lambda x: x % 2 == 0 >>> d = {1: 2, 2: 3, 3: 4, 4: 5} >>> keyfilter(iseven, d) {2: 3, 4: 5} See Also: valfilter itemfilter keymap """ rv = factory() for k, v in ite...
python
def keyfilter(predicate, d, factory=dict): """ Filter items in dictionary by key >>> iseven = lambda x: x % 2 == 0 >>> d = {1: 2, 2: 3, 3: 4, 4: 5} >>> keyfilter(iseven, d) {2: 3, 4: 5} See Also: valfilter itemfilter keymap """ rv = factory() for k, v in ite...
Filter items in dictionary by key >>> iseven = lambda x: x % 2 == 0 >>> d = {1: 2, 2: 3, 3: 4, 4: 5} >>> keyfilter(iseven, d) {2: 3, 4: 5} See Also: valfilter itemfilter keymap
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/launcher.py#L77-L94
Valassis-Digital-Media/spylon
spylon/spark/launcher.py
with_spark_context
def with_spark_context(application_name, conf=None): """Context manager for a spark context Parameters ---------- application_name : string conf : string, optional Returns ------- sc : SparkContext Examples -------- Used within a context manager >>> with with_spark_con...
python
def with_spark_context(application_name, conf=None): """Context manager for a spark context Parameters ---------- application_name : string conf : string, optional Returns ------- sc : SparkContext Examples -------- Used within a context manager >>> with with_spark_con...
Context manager for a spark context Parameters ---------- application_name : string conf : string, optional Returns ------- sc : SparkContext Examples -------- Used within a context manager >>> with with_spark_context("MyApplication") as sc: ... # Your Code here ...
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/launcher.py#L552-L580
Valassis-Digital-Media/spylon
spylon/spark/launcher.py
with_sql_context
def with_sql_context(application_name, conf=None): """Context manager for a spark context Returns ------- sc : SparkContext sql_context: SQLContext Examples -------- Used within a context manager >>> with with_sql_context("MyApplication") as (sc, sql_context): ... import py...
python
def with_sql_context(application_name, conf=None): """Context manager for a spark context Returns ------- sc : SparkContext sql_context: SQLContext Examples -------- Used within a context manager >>> with with_sql_context("MyApplication") as (sc, sql_context): ... import py...
Context manager for a spark context Returns ------- sc : SparkContext sql_context: SQLContext Examples -------- Used within a context manager >>> with with_sql_context("MyApplication") as (sc, sql_context): ... import pyspark ... # Do stuff ... pass
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/launcher.py#L584-L610
Valassis-Digital-Media/spylon
spylon/spark/launcher.py
_SparkConfHelper.set_if_unset
def set_if_unset(self, key, value): """Set a particular spark property by the string key name if it hasn't already been set. This method allows chaining so that i can provide a similar feel to the standard Scala way of setting multiple configurations Parameters ---------- ...
python
def set_if_unset(self, key, value): """Set a particular spark property by the string key name if it hasn't already been set. This method allows chaining so that i can provide a similar feel to the standard Scala way of setting multiple configurations Parameters ---------- ...
Set a particular spark property by the string key name if it hasn't already been set. This method allows chaining so that i can provide a similar feel to the standard Scala way of setting multiple configurations Parameters ---------- key : string value : string ...
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/launcher.py#L297-L314
Valassis-Digital-Media/spylon
spylon/spark/launcher.py
SparkConfiguration._repr_pretty_
def _repr_pretty_(self, p, cycle): """Pretty printer for the spark cnofiguration""" from IPython.lib.pretty import RepresentationPrinter assert isinstance(p, RepresentationPrinter) p.begin_group(1, "SparkConfiguration(") def kv(k, v, do_comma=True): p.text(k) ...
python
def _repr_pretty_(self, p, cycle): """Pretty printer for the spark cnofiguration""" from IPython.lib.pretty import RepresentationPrinter assert isinstance(p, RepresentationPrinter) p.begin_group(1, "SparkConfiguration(") def kv(k, v, do_comma=True): p.text(k) ...
Pretty printer for the spark cnofiguration
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/launcher.py#L350-L369
Valassis-Digital-Media/spylon
spylon/spark/launcher.py
SparkConfiguration._set_launcher_property
def _set_launcher_property(self, driver_arg_key, spark_property_key): """Handler for a special property that exists in both the launcher arguments and the spark conf dictionary. This will use the launcher argument if set falling back to the spark conf argument. If neither are set this is a noo...
python
def _set_launcher_property(self, driver_arg_key, spark_property_key): """Handler for a special property that exists in both the launcher arguments and the spark conf dictionary. This will use the launcher argument if set falling back to the spark conf argument. If neither are set this is a noo...
Handler for a special property that exists in both the launcher arguments and the spark conf dictionary. This will use the launcher argument if set falling back to the spark conf argument. If neither are set this is a noop (which means that the standard spark defaults will be used). Since `sp...
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/launcher.py#L411-L432
Valassis-Digital-Media/spylon
spylon/spark/launcher.py
SparkConfiguration._set_environment_variables
def _set_environment_variables(self): """Initializes the correct environment variables for spark""" cmd = [] # special case for driver JVM properties. self._set_launcher_property("driver-memory", "spark.driver.memory") self._set_launcher_property("driver-library-path", "spark.dr...
python
def _set_environment_variables(self): """Initializes the correct environment variables for spark""" cmd = [] # special case for driver JVM properties. self._set_launcher_property("driver-memory", "spark.driver.memory") self._set_launcher_property("driver-library-path", "spark.dr...
Initializes the correct environment variables for spark
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/launcher.py#L434-L460
Valassis-Digital-Media/spylon
spylon/spark/launcher.py
SparkConfiguration._init_spark
def _init_spark(self): """Initializes spark so that pyspark is importable. This also sets up the required environment variables """ global _SPARK_INITIALIZED spark_home = self.spark_home python_path = self._python_path if use_findspark: if _SPARK_INITIALIZED...
python
def _init_spark(self): """Initializes spark so that pyspark is importable. This also sets up the required environment variables """ global _SPARK_INITIALIZED spark_home = self.spark_home python_path = self._python_path if use_findspark: if _SPARK_INITIALIZED...
Initializes spark so that pyspark is importable. This also sets up the required environment variables
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/launcher.py#L462-L483
Valassis-Digital-Media/spylon
spylon/spark/launcher.py
SparkConfiguration.spark_context
def spark_context(self, application_name): """Create a spark context given the parameters configured in this class. The caller is responsible for calling ``.close`` on the resulting spark context Parameters ---------- application_name : string Returns ------- ...
python
def spark_context(self, application_name): """Create a spark context given the parameters configured in this class. The caller is responsible for calling ``.close`` on the resulting spark context Parameters ---------- application_name : string Returns ------- ...
Create a spark context given the parameters configured in this class. The caller is responsible for calling ``.close`` on the resulting spark context Parameters ---------- application_name : string Returns ------- sc : SparkContext
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/launcher.py#L497-L522
Valassis-Digital-Media/spylon
spylon/spark/launcher.py
SparkConfiguration.sql_context
def sql_context(self, application_name): """Create a spark context given the parameters configured in this class. The caller is responsible for calling ``.close`` on the resulting spark context Parameters ---------- application_name : string Returns ------- ...
python
def sql_context(self, application_name): """Create a spark context given the parameters configured in this class. The caller is responsible for calling ``.close`` on the resulting spark context Parameters ---------- application_name : string Returns ------- ...
Create a spark context given the parameters configured in this class. The caller is responsible for calling ``.close`` on the resulting spark context Parameters ---------- application_name : string Returns ------- sc : SparkContext
https://github.com/Valassis-Digital-Media/spylon/blob/ac00e285fa1c790674606b793819c3e5baee0d48/spylon/spark/launcher.py#L524-L540
wepay/Python-SDK
wepay/api.py
WePay.call
def call(self, uri, params=None, token=None, risk_token=None, client_ip=None): """ Calls wepay.com/v2/``uri`` with ``params`` and returns the JSON response as a python dict. The optional token parameter will override the instance's access_token if it is set. :param str uri: The ...
python
def call(self, uri, params=None, token=None, risk_token=None, client_ip=None): """ Calls wepay.com/v2/``uri`` with ``params`` and returns the JSON response as a python dict. The optional token parameter will override the instance's access_token if it is set. :param str uri: The ...
Calls wepay.com/v2/``uri`` with ``params`` and returns the JSON response as a python dict. The optional token parameter will override the instance's access_token if it is set. :param str uri: The URI on the API endpoint to call. :param dict params: The parameters to pass to the URI. ...
https://github.com/wepay/Python-SDK/blob/26b2d81a61215e17442583120f2bace4ae0c38f8/wepay/api.py#L34-L75
wepay/Python-SDK
wepay/api.py
WePay.get_authorization_url
def get_authorization_url(self, redirect_uri, client_id, options=None, scope=None): """ Returns a URL to send the user to in order to get authorization. After getting authorization the user will return to redirect_uri. Optionally, scope can be set to limit p...
python
def get_authorization_url(self, redirect_uri, client_id, options=None, scope=None): """ Returns a URL to send the user to in order to get authorization. After getting authorization the user will return to redirect_uri. Optionally, scope can be set to limit p...
Returns a URL to send the user to in order to get authorization. After getting authorization the user will return to redirect_uri. Optionally, scope can be set to limit permissions, and the options dict can be loaded with any combination of state, user_name or user_email. :param...
https://github.com/wepay/Python-SDK/blob/26b2d81a61215e17442583120f2bace4ae0c38f8/wepay/api.py#L77-L104
wepay/Python-SDK
wepay/api.py
WePay.get_token
def get_token( self, redirect_uri, client_id, client_secret, code, callback_uri=None): """ Calls wepay.com/v2/oauth2/token to get an access token. Sets the access_token for the WePay instance and returns the entire response as a dict. Should only be called after t...
python
def get_token( self, redirect_uri, client_id, client_secret, code, callback_uri=None): """ Calls wepay.com/v2/oauth2/token to get an access token. Sets the access_token for the WePay instance and returns the entire response as a dict. Should only be called after t...
Calls wepay.com/v2/oauth2/token to get an access token. Sets the access_token for the WePay instance and returns the entire response as a dict. Should only be called after the user returns from being sent to get_authorization_url. :param str redirect_uri: The same URI specified in the ...
https://github.com/wepay/Python-SDK/blob/26b2d81a61215e17442583120f2bace4ae0c38f8/wepay/api.py#L106-L142
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.figure
def figure(bgcolor=(1,1,1), size=(1000,1000)): """Create a blank figure. Parameters ---------- bgcolor : (3,) float Color of the background with values in [0,1]. size : (2,) int Width and height of the figure in pixels. """ Visualizer3D._sce...
python
def figure(bgcolor=(1,1,1), size=(1000,1000)): """Create a blank figure. Parameters ---------- bgcolor : (3,) float Color of the background with values in [0,1]. size : (2,) int Width and height of the figure in pixels. """ Visualizer3D._sce...
Create a blank figure. Parameters ---------- bgcolor : (3,) float Color of the background with values in [0,1]. size : (2,) int Width and height of the figure in pixels.
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L32-L44
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.show
def show(animate=False, axis=np.array([0.,0.,1.]), clf=True, **kwargs): """Display the current figure and enable interaction. Parameters ---------- animate : bool Whether or not to animate the scene. axis : (3,) float or None If present, the animation wil...
python
def show(animate=False, axis=np.array([0.,0.,1.]), clf=True, **kwargs): """Display the current figure and enable interaction. Parameters ---------- animate : bool Whether or not to animate the scene. axis : (3,) float or None If present, the animation wil...
Display the current figure and enable interaction. Parameters ---------- animate : bool Whether or not to animate the scene. axis : (3,) float or None If present, the animation will rotate about the given axis in world coordinates. Otherwise, the anim...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L48-L72
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.render
def render(n_frames=1, axis=np.array([0.,0.,1.]), clf=True, **kwargs): """Render frames from the viewer. Parameters ---------- n_frames : int Number of frames to render. If more than one, the scene will animate. axis : (3,) float or None If present, the a...
python
def render(n_frames=1, axis=np.array([0.,0.,1.]), clf=True, **kwargs): """Render frames from the viewer. Parameters ---------- n_frames : int Number of frames to render. If more than one, the scene will animate. axis : (3,) float or None If present, the a...
Render frames from the viewer. Parameters ---------- n_frames : int Number of frames to render. If more than one, the scene will animate. axis : (3,) float or None If present, the animation will rotate about the given axis in world coordinates. Otherw...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L76-L106
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.save
def save(filename, n_frames=1, axis=np.array([0.,0.,1.]), clf=True, **kwargs): """Save frames from the viewer out to a file. Parameters ---------- filename : str The filename in which to save the output image. If more than one frame, should have extension .gif. ...
python
def save(filename, n_frames=1, axis=np.array([0.,0.,1.]), clf=True, **kwargs): """Save frames from the viewer out to a file. Parameters ---------- filename : str The filename in which to save the output image. If more than one frame, should have extension .gif. ...
Save frames from the viewer out to a file. Parameters ---------- filename : str The filename in which to save the output image. If more than one frame, should have extension .gif. n_frames : int Number of frames to render. If more than one, the scene ...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L110-L143
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.save_loop
def save_loop(filename, framerate=30, time=3.0, axis=np.array([0.,0.,1.]), clf=True, **kwargs): """Off-screen save a GIF of one rotation about the scene. Parameters ---------- filename : str The filename in which to save the output image (should have extension .gif) ...
python
def save_loop(filename, framerate=30, time=3.0, axis=np.array([0.,0.,1.]), clf=True, **kwargs): """Off-screen save a GIF of one rotation about the scene. Parameters ---------- filename : str The filename in which to save the output image (should have extension .gif) ...
Off-screen save a GIF of one rotation about the scene. Parameters ---------- filename : str The filename in which to save the output image (should have extension .gif) framerate : int The frame rate at which to animate motion. time : float The...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L146-L170
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.clf
def clf(): """Clear the current figure """ Visualizer3D._scene = Scene(background_color=Visualizer3D._scene.background_color) Visualizer3D._scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], strength=1.0)
python
def clf(): """Clear the current figure """ Visualizer3D._scene = Scene(background_color=Visualizer3D._scene.background_color) Visualizer3D._scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], strength=1.0)
Clear the current figure
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L173-L177
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.points
def points(points, T_points_world=None, color=np.array([0,1,0]), scale=0.01, n_cuts=20, subsample=None, random=False, name=None): """Scatter a point cloud in pose T_points_world. Parameters ---------- points : autolab_core.BagOfPoints or (n,3) float The point set to visualiz...
python
def points(points, T_points_world=None, color=np.array([0,1,0]), scale=0.01, n_cuts=20, subsample=None, random=False, name=None): """Scatter a point cloud in pose T_points_world. Parameters ---------- points : autolab_core.BagOfPoints or (n,3) float The point set to visualiz...
Scatter a point cloud in pose T_points_world. Parameters ---------- points : autolab_core.BagOfPoints or (n,3) float The point set to visualize. T_points_world : autolab_core.RigidTransform Pose of points, specified as a transformation from point frame to world f...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L209-L287
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.mesh
def mesh(mesh, T_mesh_world=RigidTransform(from_frame='obj', to_frame='world'), style='surface', smooth=False, color=(0.5,0.5,0.5), name=None): """Visualize a 3D triangular mesh. Parameters ---------- mesh : trimesh.Trimesh The mesh to visualize. T_mesh_...
python
def mesh(mesh, T_mesh_world=RigidTransform(from_frame='obj', to_frame='world'), style='surface', smooth=False, color=(0.5,0.5,0.5), name=None): """Visualize a 3D triangular mesh. Parameters ---------- mesh : trimesh.Trimesh The mesh to visualize. T_mesh_...
Visualize a 3D triangular mesh. Parameters ---------- mesh : trimesh.Trimesh The mesh to visualize. T_mesh_world : autolab_core.RigidTransform The pose of the mesh, specified as a transformation from mesh frame to world frame. style : str Tria...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L290-L325
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.mesh_stable_pose
def mesh_stable_pose(mesh, T_obj_table, T_table_world=RigidTransform(from_frame='table', to_frame='world'), style='wireframe', smooth=False, color=(0.5,0.5,0.5), dim=0.15, plot_table=True, plot_com=False, name=None): """Visualize a mesh ...
python
def mesh_stable_pose(mesh, T_obj_table, T_table_world=RigidTransform(from_frame='table', to_frame='world'), style='wireframe', smooth=False, color=(0.5,0.5,0.5), dim=0.15, plot_table=True, plot_com=False, name=None): """Visualize a mesh ...
Visualize a mesh in a stable pose. Parameters ---------- mesh : trimesh.Trimesh The mesh to visualize. T_obj_table : autolab_core.RigidTransform Pose of object relative to table. T_table_world : autolab_core.RigidTransform Pose of table relati...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L329-L371
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.pose
def pose(T_frame_world, alpha=0.1, tube_radius=0.005, center_scale=0.01): """Plot a 3D pose as a set of axes (x red, y green, z blue). Parameters ---------- T_frame_world : autolab_core.RigidTransform The pose relative to world coordinates. alpha : float ...
python
def pose(T_frame_world, alpha=0.1, tube_radius=0.005, center_scale=0.01): """Plot a 3D pose as a set of axes (x red, y green, z blue). Parameters ---------- T_frame_world : autolab_core.RigidTransform The pose relative to world coordinates. alpha : float ...
Plot a 3D pose as a set of axes (x red, y green, z blue). Parameters ---------- T_frame_world : autolab_core.RigidTransform The pose relative to world coordinates. alpha : float Length of plotted x,y,z axes. tube_radius : float Radius of plott...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L374-L398
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.table
def table(T_table_world=RigidTransform(from_frame='table', to_frame='world'), dim=0.16, color=(0,0,0)): """Plot a table mesh in 3D. Parameters ---------- T_table_world : autolab_core.RigidTransform Pose of table relative to world. dim : float The side-len...
python
def table(T_table_world=RigidTransform(from_frame='table', to_frame='world'), dim=0.16, color=(0,0,0)): """Plot a table mesh in 3D. Parameters ---------- T_table_world : autolab_core.RigidTransform Pose of table relative to world. dim : float The side-len...
Plot a table mesh in 3D. Parameters ---------- T_table_world : autolab_core.RigidTransform Pose of table relative to world. dim : float The side-length for the table. color : 3-tuple Color tuple.
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L401-L421
BerkeleyAutomation/visualization
visualization/visualizer3d.py
Visualizer3D.plot3d
def plot3d(points, color=(0.5, 0.5, 0.5), tube_radius=0.005, n_components=30, name=None): """Plot a 3d curve through a set of points using tubes. Parameters ---------- points : (n,3) float A series of 3D points that define a curve in space. color : (3,) float ...
python
def plot3d(points, color=(0.5, 0.5, 0.5), tube_radius=0.005, n_components=30, name=None): """Plot a 3d curve through a set of points using tubes. Parameters ---------- points : (n,3) float A series of 3D points that define a curve in space. color : (3,) float ...
Plot a 3d curve through a set of points using tubes. Parameters ---------- points : (n,3) float A series of 3D points that define a curve in space. color : (3,) float The color of the tube. tube_radius : float Radius of tube representing curve...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L424-L468
BerkeleyAutomation/visualization
visualization/visualizer2d.py
Visualizer2D.figure
def figure(size=(8,8), *args, **kwargs): """ Creates a figure. Parameters ---------- size : 2-tuple size of the view window in inches args : list args of mayavi figure kwargs : list keyword args of mayavi figure Returns -...
python
def figure(size=(8,8), *args, **kwargs): """ Creates a figure. Parameters ---------- size : 2-tuple size of the view window in inches args : list args of mayavi figure kwargs : list keyword args of mayavi figure Returns -...
Creates a figure. Parameters ---------- size : 2-tuple size of the view window in inches args : list args of mayavi figure kwargs : list keyword args of mayavi figure Returns ------- pyplot figure the current ...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L14-L31
BerkeleyAutomation/visualization
visualization/visualizer2d.py
Visualizer2D.show
def show(filename=None, *args, **kwargs): """ Show the current figure. Parameters ---------- filename : :obj:`str` filename to save the image to, for auto-saving """ if filename is None: plt.show(*args, **kwargs) else: plt.save...
python
def show(filename=None, *args, **kwargs): """ Show the current figure. Parameters ---------- filename : :obj:`str` filename to save the image to, for auto-saving """ if filename is None: plt.show(*args, **kwargs) else: plt.save...
Show the current figure. Parameters ---------- filename : :obj:`str` filename to save the image to, for auto-saving
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L34-L45
BerkeleyAutomation/visualization
visualization/visualizer2d.py
Visualizer2D.imshow
def imshow(image, auto_subplot=False, **kwargs): """ Displays an image. Parameters ---------- image : :obj:`perception.Image` image to display auto_subplot : bool whether or not to automatically subplot for multi-channel images e.g. rgbd """ ...
python
def imshow(image, auto_subplot=False, **kwargs): """ Displays an image. Parameters ---------- image : :obj:`perception.Image` image to display auto_subplot : bool whether or not to automatically subplot for multi-channel images e.g. rgbd """ ...
Displays an image. Parameters ---------- image : :obj:`perception.Image` image to display auto_subplot : bool whether or not to automatically subplot for multi-channel images e.g. rgbd
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L118-L151
BerkeleyAutomation/visualization
visualization/visualizer2d.py
Visualizer2D.box
def box(b, line_width=2, color='g', style='-'): """ Draws a box on the current plot. Parameters ---------- b : :obj:`autolab_core.Box` box to draw line_width : int width of lines on side of box color : :obj:`str` color of box s...
python
def box(b, line_width=2, color='g', style='-'): """ Draws a box on the current plot. Parameters ---------- b : :obj:`autolab_core.Box` box to draw line_width : int width of lines on side of box color : :obj:`str` color of box s...
Draws a box on the current plot. Parameters ---------- b : :obj:`autolab_core.Box` box to draw line_width : int width of lines on side of box color : :obj:`str` color of box style : :obj:`str` style of lines to draw
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L154-L191
BerkeleyAutomation/visualization
visualization/visualizer2d.py
Visualizer2D.contour
def contour(c, subsample=1, size=10, color='g'): """ Draws a contour on the current plot by scattering points. Parameters ---------- c : :obj:`autolab_core.Contour` contour to draw subsample : int subsample rate for boundary pixels size : int ...
python
def contour(c, subsample=1, size=10, color='g'): """ Draws a contour on the current plot by scattering points. Parameters ---------- c : :obj:`autolab_core.Contour` contour to draw subsample : int subsample rate for boundary pixels size : int ...
Draws a contour on the current plot by scattering points. Parameters ---------- c : :obj:`autolab_core.Contour` contour to draw subsample : int subsample rate for boundary pixels size : int size of scattered points color : :obj:`str` ...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L194-L212
BerkeleyAutomation/visualization
visualization/visualizer2d.py
Visualizer2D.grasp
def grasp(grasp, width=None, color='r', arrow_len=4, arrow_head_len = 2, arrow_head_width = 3, arrow_width = 1, jaw_len=3, jaw_width = 1.0, grasp_center_size=1, grasp_center_thickness=2.5, grasp_center_style='+', grasp_axis_width=1, grasp_axis_style='--', line_wid...
python
def grasp(grasp, width=None, color='r', arrow_len=4, arrow_head_len = 2, arrow_head_width = 3, arrow_width = 1, jaw_len=3, jaw_width = 1.0, grasp_center_size=1, grasp_center_thickness=2.5, grasp_center_style='+', grasp_axis_width=1, grasp_axis_style='--', line_wid...
Plots a 2D grasp with arrow and jaw style using matplotlib Parameters ---------- grasp : :obj:`Grasp2D` 2D grasp to plot width : float width, in pixels, of the grasp (overrides Grasp2D.width_px) color : :obj:`str` color of plotted gras...
https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L215-L308
ml4ai/delphi
delphi/translators/for2py/arrays.py
all_subs
def all_subs(bounds): """given a list of tuples specifying the bounds of an array, all_subs() returns a list of all the tuples of subscripts for that array.""" idx_list = [] for i in range(len(bounds)): this_dim = bounds[i] lo,hi = this_dim[0],this_dim[1] # bounds for this dimension...
python
def all_subs(bounds): """given a list of tuples specifying the bounds of an array, all_subs() returns a list of all the tuples of subscripts for that array.""" idx_list = [] for i in range(len(bounds)): this_dim = bounds[i] lo,hi = this_dim[0],this_dim[1] # bounds for this dimension...
given a list of tuples specifying the bounds of an array, all_subs() returns a list of all the tuples of subscripts for that array.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/arrays.py#L152-L162
ml4ai/delphi
delphi/translators/for2py/arrays.py
idx2subs
def idx2subs(idx_list): """Given a list idx_list of index values for each dimension of an array, idx2subs() returns a list of the tuples of subscripts for all of the array elements specified by those index values. Note: This code adapted from that posted by jfs at https://stackoverflo...
python
def idx2subs(idx_list): """Given a list idx_list of index values for each dimension of an array, idx2subs() returns a list of the tuples of subscripts for all of the array elements specified by those index values. Note: This code adapted from that posted by jfs at https://stackoverflo...
Given a list idx_list of index values for each dimension of an array, idx2subs() returns a list of the tuples of subscripts for all of the array elements specified by those index values. Note: This code adapted from that posted by jfs at https://stackoverflow.com/questions/533905/get-the-...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/arrays.py#L165-L176
ml4ai/delphi
delphi/translators/for2py/arrays.py
array_values
def array_values(expr): """Given an expression expr denoting a list of values, array_values(expr) returns a list of values for that expression.""" if isinstance(expr, Array): return expr.get_elems(all_subs(expr._bounds)) elif isinstance(expr, list): vals = [array_values(x) for x in e...
python
def array_values(expr): """Given an expression expr denoting a list of values, array_values(expr) returns a list of values for that expression.""" if isinstance(expr, Array): return expr.get_elems(all_subs(expr._bounds)) elif isinstance(expr, list): vals = [array_values(x) for x in e...
Given an expression expr denoting a list of values, array_values(expr) returns a list of values for that expression.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/arrays.py#L179-L188
ml4ai/delphi
delphi/translators/for2py/arrays.py
array_subscripts
def array_subscripts(expr): """Given a subscript expression expr (i.e., an expression that denotes the set of elements of some array that are to be accessed), array_subscripts() returns a list of the elements denoted by expr.""" if isinstance(expr, Array): return all_subs(expr._bounds) ...
python
def array_subscripts(expr): """Given a subscript expression expr (i.e., an expression that denotes the set of elements of some array that are to be accessed), array_subscripts() returns a list of the elements denoted by expr.""" if isinstance(expr, Array): return all_subs(expr._bounds) ...
Given a subscript expression expr (i.e., an expression that denotes the set of elements of some array that are to be accessed), array_subscripts() returns a list of the elements denoted by expr.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/arrays.py#L191-L201
ml4ai/delphi
delphi/translators/for2py/arrays.py
flatten
def flatten(in_list): """given a list of values in_list, flatten returns the list obtained by flattening the top-level elements of in_list.""" out_list = [] for val in in_list: if isinstance(val, list): out_list.extend(val) else: out_list.append(val) retu...
python
def flatten(in_list): """given a list of values in_list, flatten returns the list obtained by flattening the top-level elements of in_list.""" out_list = [] for val in in_list: if isinstance(val, list): out_list.extend(val) else: out_list.append(val) retu...
given a list of values in_list, flatten returns the list obtained by flattening the top-level elements of in_list.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/arrays.py#L210-L220
ml4ai/delphi
delphi/translators/for2py/arrays.py
implied_loop_expr
def implied_loop_expr(expr, start, end, delta): """given the parameters of an implied loop -- namely, the start and end values together with the delta per iteration -- implied_loop_expr() returns a list of values of the lambda expression expr applied to successive values of the implied loop....
python
def implied_loop_expr(expr, start, end, delta): """given the parameters of an implied loop -- namely, the start and end values together with the delta per iteration -- implied_loop_expr() returns a list of values of the lambda expression expr applied to successive values of the implied loop....
given the parameters of an implied loop -- namely, the start and end values together with the delta per iteration -- implied_loop_expr() returns a list of values of the lambda expression expr applied to successive values of the implied loop.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/arrays.py#L223-L236
ml4ai/delphi
delphi/translators/for2py/arrays.py
Array._mk_uninit_array
def _mk_uninit_array(self, bounds): """ given a list of bounds for the N dimensions of an array, _mk_uninit_array() creates and returns an N-dimensional array of the size specified by the bounds with each element set to the value None.""" if len(bounds) == 0: ...
python
def _mk_uninit_array(self, bounds): """ given a list of bounds for the N dimensions of an array, _mk_uninit_array() creates and returns an N-dimensional array of the size specified by the bounds with each element set to the value None.""" if len(bounds) == 0: ...
given a list of bounds for the N dimensions of an array, _mk_uninit_array() creates and returns an N-dimensional array of the size specified by the bounds with each element set to the value None.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/arrays.py#L34-L52
ml4ai/delphi
delphi/translators/for2py/arrays.py
Array._posn
def _posn(self, bounds, idx): """given bounds = (lo,hi) and an index value idx, _posn(bounds, idx) returns the position in a 0-based array corresponding to idx in the (lo,hi)-based array. It generates an error if idx < lo or idx > hi.""" lo,hi = bounds[0],bounds[1] ...
python
def _posn(self, bounds, idx): """given bounds = (lo,hi) and an index value idx, _posn(bounds, idx) returns the position in a 0-based array corresponding to idx in the (lo,hi)-based array. It generates an error if idx < lo or idx > hi.""" lo,hi = bounds[0],bounds[1] ...
given bounds = (lo,hi) and an index value idx, _posn(bounds, idx) returns the position in a 0-based array corresponding to idx in the (lo,hi)-based array. It generates an error if idx < lo or idx > hi.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/arrays.py#L75-L84
ml4ai/delphi
delphi/translators/for2py/arrays.py
Array._access
def _access(self, subs, acc_type, val): """_access(subs, acc_type, val) accesses the array element specified by the tuple of subscript values, subs. If acc_type == _GET_ it returns the value of this element; else it sets this element to the value of the argument val.""" ...
python
def _access(self, subs, acc_type, val): """_access(subs, acc_type, val) accesses the array element specified by the tuple of subscript values, subs. If acc_type == _GET_ it returns the value of this element; else it sets this element to the value of the argument val.""" ...
_access(subs, acc_type, val) accesses the array element specified by the tuple of subscript values, subs. If acc_type == _GET_ it returns the value of this element; else it sets this element to the value of the argument val.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/arrays.py#L87-L111
ml4ai/delphi
delphi/translators/for2py/arrays.py
Array.set_elems
def set_elems(self, subs, vals): """set_elems(subs, vals) sets the array elements specified by the list of subscript values subs (each element of subs is a tuple of subscripts identifying an array element) to the corresponding value in vals.""" if isinstance(vals, (int,...
python
def set_elems(self, subs, vals): """set_elems(subs, vals) sets the array elements specified by the list of subscript values subs (each element of subs is a tuple of subscripts identifying an array element) to the corresponding value in vals.""" if isinstance(vals, (int,...
set_elems(subs, vals) sets the array elements specified by the list of subscript values subs (each element of subs is a tuple of subscripts identifying an array element) to the corresponding value in vals.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/arrays.py#L133-L143
ml4ai/delphi
delphi/utils/misc.py
multiple_replace
def multiple_replace(d: Dict[str, str], text: str) -> str: """ Performs string replacement from dict in a single pass. Taken from https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html """ # Create a regular expression from all of the dictionary keys regex = re.compile("|".join(m...
python
def multiple_replace(d: Dict[str, str], text: str) -> str: """ Performs string replacement from dict in a single pass. Taken from https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html """ # Create a regular expression from all of the dictionary keys regex = re.compile("|".join(m...
Performs string replacement from dict in a single pass. Taken from https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/misc.py#L30-L38
ml4ai/delphi
scripts/evaluations/create_parameterized_CAG.py
create_parameterized_CAG
def create_parameterized_CAG(input, output, filename="CAG_with_indicators_and_values.pdf"): """ Create a CAG with mapped and parameterized indicators """ with open(input, "rb") as f: G = pickle.load(f) G.parameterize(year=2017, month=4) G.get_timeseries_values_for_indicators() with open(outp...
python
def create_parameterized_CAG(input, output, filename="CAG_with_indicators_and_values.pdf"): """ Create a CAG with mapped and parameterized indicators """ with open(input, "rb") as f: G = pickle.load(f) G.parameterize(year=2017, month=4) G.get_timeseries_values_for_indicators() with open(outp...
Create a CAG with mapped and parameterized indicators
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/scripts/evaluations/create_parameterized_CAG.py#L5-L12
ml4ai/delphi
delphi/utils/indra.py
get_concepts
def get_concepts(sts: List[Influence]) -> Set[str]: """ Get a set of all unique concepts in the list of INDRA statements. """ return set(flatMap(nameTuple, sts))
python
def get_concepts(sts: List[Influence]) -> Set[str]: """ Get a set of all unique concepts in the list of INDRA statements. """ return set(flatMap(nameTuple, sts))
Get a set of all unique concepts in the list of INDRA statements.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L12-L14
ml4ai/delphi
delphi/utils/indra.py
get_valid_statements_for_modeling
def get_valid_statements_for_modeling(sts: List[Influence]) -> List[Influence]: """ Select INDRA statements that can be used to construct a Delphi model from a given list of statements. """ return [ s for s in sts if is_grounded_statement(s) and (s.subj_delta["polarity"] is ...
python
def get_valid_statements_for_modeling(sts: List[Influence]) -> List[Influence]: """ Select INDRA statements that can be used to construct a Delphi model from a given list of statements. """ return [ s for s in sts if is_grounded_statement(s) and (s.subj_delta["polarity"] is ...
Select INDRA statements that can be used to construct a Delphi model from a given list of statements.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L17-L27
ml4ai/delphi
delphi/utils/indra.py
_
def _(s: Influence) -> bool: """ Check if an Influence statement is grounded """ return is_grounded(s.subj) and is_grounded(s.obj)
python
def _(s: Influence) -> bool: """ Check if an Influence statement is grounded """ return is_grounded(s.subj) and is_grounded(s.obj)
Check if an Influence statement is grounded
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L78-L80
ml4ai/delphi
delphi/utils/indra.py
is_grounded_statement
def is_grounded_statement(s: Influence) -> bool: """ Check if an Influence statement is grounded """ return is_grounded_concept(s.subj) and is_grounded_concept(s.obj)
python
def is_grounded_statement(s: Influence) -> bool: """ Check if an Influence statement is grounded """ return is_grounded_concept(s.subj) and is_grounded_concept(s.obj)
Check if an Influence statement is grounded
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L91-L93
ml4ai/delphi
delphi/utils/indra.py
_
def _(c: Concept, cutoff: float = 0.7) -> bool: """Check if a concept has a high grounding score. """ return is_grounded(c) and (top_grounding_score(c) >= cutoff)
python
def _(c: Concept, cutoff: float = 0.7) -> bool: """Check if a concept has a high grounding score. """ return is_grounded(c) and (top_grounding_score(c) >= cutoff)
Check if a concept has a high grounding score.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L102-L105
ml4ai/delphi
delphi/utils/indra.py
_
def _(s: Influence, cutoff: float = 0.7) -> bool: """ Returns true if both subj and obj are grounded to the UN ontology. """ return all(map(lambda c: is_well_grounded(c, cutoff), s.agent_list()))
python
def _(s: Influence, cutoff: float = 0.7) -> bool: """ Returns true if both subj and obj are grounded to the UN ontology. """ return all(map(lambda c: is_well_grounded(c, cutoff), s.agent_list()))
Returns true if both subj and obj are grounded to the UN ontology.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L109-L112
ml4ai/delphi
delphi/utils/indra.py
is_well_grounded_concept
def is_well_grounded_concept(c: Concept, cutoff: float = 0.7) -> bool: """Check if a concept has a high grounding score. """ return is_grounded(c) and (top_grounding_score(c) >= cutoff)
python
def is_well_grounded_concept(c: Concept, cutoff: float = 0.7) -> bool: """Check if a concept has a high grounding score. """ return is_grounded(c) and (top_grounding_score(c) >= cutoff)
Check if a concept has a high grounding score.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L115-L118
ml4ai/delphi
delphi/utils/indra.py
is_well_grounded_statement
def is_well_grounded_statement(s: Influence, cutoff: float = 0.7) -> bool: """ Returns true if both subj and obj are grounded to the UN ontology. """ return all( map(lambda c: is_well_grounded_concept(c, cutoff), s.agent_list()) )
python
def is_well_grounded_statement(s: Influence, cutoff: float = 0.7) -> bool: """ Returns true if both subj and obj are grounded to the UN ontology. """ return all( map(lambda c: is_well_grounded_concept(c, cutoff), s.agent_list()) )
Returns true if both subj and obj are grounded to the UN ontology.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L121-L126
ml4ai/delphi
delphi/utils/indra.py
is_grounded_to_name
def is_grounded_to_name(c: Concept, name: str, cutoff=0.7) -> bool: """ Check if a concept is grounded to a given name. """ return (top_grounding(c) == name) if is_well_grounded(c, cutoff) else False
python
def is_grounded_to_name(c: Concept, name: str, cutoff=0.7) -> bool: """ Check if a concept is grounded to a given name. """ return (top_grounding(c) == name) if is_well_grounded(c, cutoff) else False
Check if a concept is grounded to a given name.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L129-L131
ml4ai/delphi
delphi/utils/indra.py
contains_relevant_concept
def contains_relevant_concept( s: Influence, relevant_concepts: List[str], cutoff=0.7 ) -> bool: """ Returns true if a given Influence statement has a relevant concept, and false otherwise. """ return any( map(lambda c: contains_concept(s, c, cutoff=cutoff), relevant_concepts) )
python
def contains_relevant_concept( s: Influence, relevant_concepts: List[str], cutoff=0.7 ) -> bool: """ Returns true if a given Influence statement has a relevant concept, and false otherwise. """ return any( map(lambda c: contains_concept(s, c, cutoff=cutoff), relevant_concepts) )
Returns true if a given Influence statement has a relevant concept, and false otherwise.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L143-L151
ml4ai/delphi
delphi/utils/indra.py
top_grounding
def top_grounding(c: Concept) -> str: """ Return the top-scoring grounding from the UN ontology. """ return c.db_refs["UN"][0][0] if "UN" in c.db_refs else c.name
python
def top_grounding(c: Concept) -> str: """ Return the top-scoring grounding from the UN ontology. """ return c.db_refs["UN"][0][0] if "UN" in c.db_refs else c.name
Return the top-scoring grounding from the UN ontology.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L154-L156
ml4ai/delphi
delphi/utils/indra.py
nameTuple
def nameTuple(s: Influence) -> Tuple[str, str]: """ Returns a 2-tuple consisting of the top groundings of the subj and obj of an Influence statement. """ return top_grounding(s.subj), top_grounding(s.obj)
python
def nameTuple(s: Influence) -> Tuple[str, str]: """ Returns a 2-tuple consisting of the top groundings of the subj and obj of an Influence statement. """ return top_grounding(s.subj), top_grounding(s.obj)
Returns a 2-tuple consisting of the top groundings of the subj and obj of an Influence statement.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/indra.py#L163-L166
ml4ai/delphi
delphi/apps/rest_api/api.py
createNewICM
def createNewICM(): """ Create a new ICM""" data = json.loads(request.data) G = AnalysisGraph.from_uncharted_json_serialized_dict(data) G.assemble_transition_model_from_gradable_adjectives() G.sample_from_prior() G.to_sql(app=current_app) _metadata = ICMMetadata.query.filter_by(id=G.id).firs...
python
def createNewICM(): """ Create a new ICM""" data = json.loads(request.data) G = AnalysisGraph.from_uncharted_json_serialized_dict(data) G.assemble_transition_model_from_gradable_adjectives() G.sample_from_prior() G.to_sql(app=current_app) _metadata = ICMMetadata.query.filter_by(id=G.id).firs...
Create a new ICM
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/apps/rest_api/api.py#L36-L45
ml4ai/delphi
delphi/apps/rest_api/api.py
getICMByUUID
def getICMByUUID(uuid: str): """ Fetch an ICM by UUID""" _metadata = ICMMetadata.query.filter_by(id=uuid).first().deserialize() del _metadata["model_id"] return jsonify(_metadata)
python
def getICMByUUID(uuid: str): """ Fetch an ICM by UUID""" _metadata = ICMMetadata.query.filter_by(id=uuid).first().deserialize() del _metadata["model_id"] return jsonify(_metadata)
Fetch an ICM by UUID
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/apps/rest_api/api.py#L55-L59
ml4ai/delphi
delphi/apps/rest_api/api.py
deleteICM
def deleteICM(uuid: str): """ Deletes an ICM""" _metadata = ICMMetadata.query.filter_by(id=uuid).first() db.session.delete(_metadata) db.session.commit() return ("", 204)
python
def deleteICM(uuid: str): """ Deletes an ICM""" _metadata = ICMMetadata.query.filter_by(id=uuid).first() db.session.delete(_metadata) db.session.commit() return ("", 204)
Deletes an ICM
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/apps/rest_api/api.py#L63-L68
ml4ai/delphi
delphi/apps/rest_api/api.py
getICMPrimitives
def getICMPrimitives(uuid: str): """ returns all ICM primitives (TODO - needs filter support)""" primitives = [ p.deserialize() for p in CausalPrimitive.query.filter_by(model_id=uuid).all() ] for p in primitives: del p["model_id"] return jsonify(primitives)
python
def getICMPrimitives(uuid: str): """ returns all ICM primitives (TODO - needs filter support)""" primitives = [ p.deserialize() for p in CausalPrimitive.query.filter_by(model_id=uuid).all() ] for p in primitives: del p["model_id"] return jsonify(primitives)
returns all ICM primitives (TODO - needs filter support)
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/apps/rest_api/api.py#L78-L86
ml4ai/delphi
delphi/apps/rest_api/api.py
getEvidenceForID
def getEvidenceForID(uuid: str, prim_id: str): """ returns evidence for a causal primitive (needs pagination support)""" evidences = [ evidence.deserialize() for evidence in Evidence.query.filter_by( causalrelationship_id=prim_id ).all() ] for evidence in evidences: ...
python
def getEvidenceForID(uuid: str, prim_id: str): """ returns evidence for a causal primitive (needs pagination support)""" evidences = [ evidence.deserialize() for evidence in Evidence.query.filter_by( causalrelationship_id=prim_id ).all() ] for evidence in evidences: ...
returns evidence for a causal primitive (needs pagination support)
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/apps/rest_api/api.py#L116-L127
ml4ai/delphi
delphi/apps/rest_api/api.py
createExperiment
def createExperiment(uuid: str): """ Execute an experiment over the model""" data = request.get_json() G = DelphiModel.query.filter_by(id=uuid).first().model if os.environ.get("TRAVIS") is not None: config_file="bmi_config.txt" else: if not os.path.exists("/tmp/delphi"): ...
python
def createExperiment(uuid: str): """ Execute an experiment over the model""" data = request.get_json() G = DelphiModel.query.filter_by(id=uuid).first().model if os.environ.get("TRAVIS") is not None: config_file="bmi_config.txt" else: if not os.path.exists("/tmp/delphi"): ...
Execute an experiment over the model
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/apps/rest_api/api.py#L187-L279
ml4ai/delphi
delphi/apps/rest_api/api.py
getExperiments
def getExperiments(uuid: str): """ list active (running or completed) experiments""" return jsonify([x.deserialize() for x in Experiment.query.all()])
python
def getExperiments(uuid: str): """ list active (running or completed) experiments""" return jsonify([x.deserialize() for x in Experiment.query.all()])
list active (running or completed) experiments
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/apps/rest_api/api.py#L283-L285
ml4ai/delphi
delphi/apps/rest_api/api.py
getExperiment
def getExperiment(uuid: str, exp_id: str): """ Fetch experiment results""" experimentResult = ForwardProjectionResult.query.filter_by( id=exp_id ).first() return jsonify(experimentResult.deserialize())
python
def getExperiment(uuid: str, exp_id: str): """ Fetch experiment results""" experimentResult = ForwardProjectionResult.query.filter_by( id=exp_id ).first() return jsonify(experimentResult.deserialize())
Fetch experiment results
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/apps/rest_api/api.py#L289-L294
ml4ai/delphi
delphi/jupyter_tools.py
create_statement_inspection_table
def create_statement_inspection_table(sts: List[Influence]): """ Display an HTML representation of a table with INDRA statements to manually inspect for validity. Args: sts: A list of INDRA statements to be manually inspected for validity. """ columns = [ "un_groundings", "...
python
def create_statement_inspection_table(sts: List[Influence]): """ Display an HTML representation of a table with INDRA statements to manually inspect for validity. Args: sts: A list of INDRA statements to be manually inspected for validity. """ columns = [ "un_groundings", "...
Display an HTML representation of a table with INDRA statements to manually inspect for validity. Args: sts: A list of INDRA statements to be manually inspected for validity.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/jupyter_tools.py#L20-L69
ml4ai/delphi
delphi/jupyter_tools.py
get_python_shell
def get_python_shell(): """Determine python shell get_python_shell() returns 'shell' (started python on command line using "python") 'ipython' (started ipython on command line using "ipython") 'ipython-notebook' (e.g., running in Spyder or started with "ipython qtconsole") 'jupyter-notebook' (...
python
def get_python_shell(): """Determine python shell get_python_shell() returns 'shell' (started python on command line using "python") 'ipython' (started ipython on command line using "ipython") 'ipython-notebook' (e.g., running in Spyder or started with "ipython qtconsole") 'jupyter-notebook' (...
Determine python shell get_python_shell() returns 'shell' (started python on command line using "python") 'ipython' (started ipython on command line using "ipython") 'ipython-notebook' (e.g., running in Spyder or started with "ipython qtconsole") 'jupyter-notebook' (running in a Jupyter notebook) ...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/jupyter_tools.py#L103-L127
ml4ai/delphi
scripts/evaluations/create_precipitation_centered_CAG.py
create_precipitation_centered_CAG
def create_precipitation_centered_CAG(input, output): """ Get a CAG that examines the downstream effects of changes in precipitation. """ with open(input, "rb") as f: G = pickle.load(f) G = G.get_subgraph_for_concept( "UN/events/weather/precipitation", depth=2, reverse=False ) G.pru...
python
def create_precipitation_centered_CAG(input, output): """ Get a CAG that examines the downstream effects of changes in precipitation. """ with open(input, "rb") as f: G = pickle.load(f) G = G.get_subgraph_for_concept( "UN/events/weather/precipitation", depth=2, reverse=False ) G.pru...
Get a CAG that examines the downstream effects of changes in precipitation.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/scripts/evaluations/create_precipitation_centered_CAG.py#L6-L22
ml4ai/delphi
delphi/translators/for2py/pyTranslate.py
index_modules
def index_modules(root) -> Dict: """ Counts the number of modules in the Fortran file including the program file. Each module is written out into a separate Python file. """ module_index_dict = { node["name"]: (node.get("tag"), index) for index, node in enumerate(root) if node.get(...
python
def index_modules(root) -> Dict: """ Counts the number of modules in the Fortran file including the program file. Each module is written out into a separate Python file. """ module_index_dict = { node["name"]: (node.get("tag"), index) for index, node in enumerate(root) if node.get(...
Counts the number of modules in the Fortran file including the program file. Each module is written out into a separate Python file.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/pyTranslate.py#L1244-L1254
ml4ai/delphi
delphi/translators/for2py/pyTranslate.py
PythonCodeGenerator.printArray
def printArray(self, node, printState: PrintState): """ Prints out the array declaration in a format of Array class object declaration. 'arrayName = Array(Type, [bounds])' """ if ( self.nameMapper[node["name"]] not in printState.definedVars and self.nameMapper...
python
def printArray(self, node, printState: PrintState): """ Prints out the array declaration in a format of Array class object declaration. 'arrayName = Array(Type, [bounds])' """ if ( self.nameMapper[node["name"]] not in printState.definedVars and self.nameMapper...
Prints out the array declaration in a format of Array class object declaration. 'arrayName = Array(Type, [bounds])'
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/pyTranslate.py#L1151-L1199
ml4ai/delphi
delphi/analysis/comparison/utils.py
draw_graph
def draw_graph(G: nx.DiGraph, filename: str): """ Draw a networkx graph with Pygraphviz. """ A = to_agraph(G) A.graph_attr["rankdir"] = "LR" A.draw(filename, prog="dot")
python
def draw_graph(G: nx.DiGraph, filename: str): """ Draw a networkx graph with Pygraphviz. """ A = to_agraph(G) A.graph_attr["rankdir"] = "LR" A.draw(filename, prog="dot")
Draw a networkx graph with Pygraphviz.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/analysis/comparison/utils.py#L6-L10
ml4ai/delphi
delphi/analysis/comparison/utils.py
get_input_nodes
def get_input_nodes(G: nx.DiGraph) -> List[str]: """ Get all input nodes from a network. """ return [n for n, d in G.in_degree() if d == 0]
python
def get_input_nodes(G: nx.DiGraph) -> List[str]: """ Get all input nodes from a network. """ return [n for n, d in G.in_degree() if d == 0]
Get all input nodes from a network.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/analysis/comparison/utils.py#L13-L15
ml4ai/delphi
delphi/analysis/comparison/utils.py
get_output_nodes
def get_output_nodes(G: nx.DiGraph) -> List[str]: """ Get all output nodes from a network. """ return [n for n, d in G.out_degree() if d == 0]
python
def get_output_nodes(G: nx.DiGraph) -> List[str]: """ Get all output nodes from a network. """ return [n for n, d in G.out_degree() if d == 0]
Get all output nodes from a network.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/analysis/comparison/utils.py#L18-L20
ml4ai/delphi
delphi/analysis/comparison/utils.py
nx_graph_from_dotfile
def nx_graph_from_dotfile(filename: str) -> nx.DiGraph: """ Get a networkx graph from a DOT file, and reverse the edges. """ return nx.DiGraph(read_dot(filename).reverse())
python
def nx_graph_from_dotfile(filename: str) -> nx.DiGraph: """ Get a networkx graph from a DOT file, and reverse the edges. """ return nx.DiGraph(read_dot(filename).reverse())
Get a networkx graph from a DOT file, and reverse the edges.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/analysis/comparison/utils.py#L23-L25
ml4ai/delphi
delphi/analysis/comparison/utils.py
to_dotfile
def to_dotfile(G: nx.DiGraph, filename: str): """ Output a networkx graph to a DOT file. """ A = to_agraph(G) A.write(filename)
python
def to_dotfile(G: nx.DiGraph, filename: str): """ Output a networkx graph to a DOT file. """ A = to_agraph(G) A.write(filename)
Output a networkx graph to a DOT file.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/analysis/comparison/utils.py#L28-L31
ml4ai/delphi
delphi/analysis/comparison/utils.py
get_shared_nodes
def get_shared_nodes(G1: nx.DiGraph, G2: nx.DiGraph) -> List[str]: """Get all the nodes that are common to both networks.""" return list(set(G1.nodes()).intersection(set(G2.nodes())))
python
def get_shared_nodes(G1: nx.DiGraph, G2: nx.DiGraph) -> List[str]: """Get all the nodes that are common to both networks.""" return list(set(G1.nodes()).intersection(set(G2.nodes())))
Get all the nodes that are common to both networks.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/analysis/comparison/utils.py#L34-L36
ml4ai/delphi
delphi/translators/for2py/syntax.py
line_is_comment
def line_is_comment(line: str) -> bool: """ From FORTRAN Language Reference (https://docs.oracle.com/cd/E19957-01/805-4939/z40007332024/index.html): A line with a c, C, *, d, D, or ! in column one is a comment line, except that if the -xld option is set, then the lines starting with D or d are ...
python
def line_is_comment(line: str) -> bool: """ From FORTRAN Language Reference (https://docs.oracle.com/cd/E19957-01/805-4939/z40007332024/index.html): A line with a c, C, *, d, D, or ! in column one is a comment line, except that if the -xld option is set, then the lines starting with D or d are ...
From FORTRAN Language Reference (https://docs.oracle.com/cd/E19957-01/805-4939/z40007332024/index.html): A line with a c, C, *, d, D, or ! in column one is a comment line, except that if the -xld option is set, then the lines starting with D or d are compiled as debug lines. The d, D, and ! are nonstan...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/syntax.py#L12-L42
ml4ai/delphi
delphi/translators/for2py/syntax.py
line_starts_subpgm
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...
python
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...
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.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/syntax.py#L125-L147
ml4ai/delphi
delphi/translators/for2py/syntax.py
program_unit_name
def program_unit_name(line:str) -> str: """Given a line that starts a program unit, i.e., a program, module, subprogram, or function, this function returns the name associated with that program unit.""" match = RE_PGM_UNIT_START.match(line) assert match != None return match.group(2)
python
def program_unit_name(line:str) -> str: """Given a line that starts a program unit, i.e., a program, module, subprogram, or function, this function returns the name associated with that program unit.""" match = RE_PGM_UNIT_START.match(line) assert match != None return match.group(2)
Given a line that starts a program unit, i.e., a program, module, subprogram, or function, this function returns the name associated with that program unit.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/syntax.py#L160-L166
ml4ai/delphi
delphi/translators/for2py/syntax.py
line_is_continuation
def line_is_continuation(line: str) -> bool: """ Args: line Returns: True iff line is a continuation line, else False. """ llstr = line.lstrip() return len(llstr) > 0 and llstr[0] == "&"
python
def line_is_continuation(line: str) -> bool: """ Args: line Returns: True iff line is a continuation line, else False. """ llstr = line.lstrip() return len(llstr) > 0 and llstr[0] == "&"
Args: line Returns: True iff line is a continuation line, else False.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/syntax.py#L168-L177
ml4ai/delphi
delphi/translators/for2py/syntax.py
line_is_executable
def line_is_executable(line: str) -> bool: """line_is_executable() returns True iff the line can start an executable statement in a program.""" if line_is_comment(line): return False if re.match(RE_TYPE_NAMES, line): return False for exp in EXECUTABLE_CODE_START: if re....
python
def line_is_executable(line: str) -> bool: """line_is_executable() returns True iff the line can start an executable statement in a program.""" if line_is_comment(line): return False if re.match(RE_TYPE_NAMES, line): return False for exp in EXECUTABLE_CODE_START: if re....
line_is_executable() returns True iff the line can start an executable statement in a program.
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/translators/for2py/syntax.py#L191-L205
ml4ai/delphi
delphi/utils/fp.py
prepend
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 of *xs*. Exa...
python
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 of *xs*. Exa...
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 of *xs*. Examples -------- >>> from delphi.utils.fp import pre...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L30-L53
ml4ai/delphi
delphi/utils/fp.py
append
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 yields *x*. Exa...
python
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 yields *x*. Exa...
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 yields *x*. Examples -------- >>> from delphi.utils.fp import app...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L56-L80
ml4ai/delphi
delphi/utils/fp.py
scanl
def scanl(f: Callable[[T, U], T], x: T, xs: Iterable[U]) -> Iterator[T]: """ Make an iterator that returns accumulated results of a binary function applied to elements of an iterable. .. math:: scanl(f, x_0, [x_1, x_2, ...]) = [x_0, f(x_0, x_1), f(f(x_0, x_1), x_2), ...] Parameters -------...
python
def scanl(f: Callable[[T, U], T], x: T, xs: Iterable[U]) -> Iterator[T]: """ Make an iterator that returns accumulated results of a binary function applied to elements of an iterable. .. math:: scanl(f, x_0, [x_1, x_2, ...]) = [x_0, f(x_0, x_1), f(f(x_0, x_1), x_2), ...] Parameters -------...
Make an iterator that returns accumulated results of a binary function applied to elements of an iterable. .. math:: scanl(f, x_0, [x_1, x_2, ...]) = [x_0, f(x_0, x_1), f(f(x_0, x_1), x_2), ...] Parameters ---------- f A binary function of two arguments of type T. x An ...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L83-L113
ml4ai/delphi
delphi/utils/fp.py
scanl1
def scanl1(f: Callable[[T, T], T], xs: Iterable[T]) -> Iterator[T]: """ Make an iterator that returns accumulated results of a binary function applied to elements of an iterable. .. math:: scanl1(f, [x_0, x_1, x_2, ...]) = [x_0, f(x_0, x_1), f(f(x_0, x_1), x_2), ...] Parameters ---------- ...
python
def scanl1(f: Callable[[T, T], T], xs: Iterable[T]) -> Iterator[T]: """ Make an iterator that returns accumulated results of a binary function applied to elements of an iterable. .. math:: scanl1(f, [x_0, x_1, x_2, ...]) = [x_0, f(x_0, x_1), f(f(x_0, x_1), x_2), ...] Parameters ---------- ...
Make an iterator that returns accumulated results of a binary function applied to elements of an iterable. .. math:: scanl1(f, [x_0, x_1, x_2, ...]) = [x_0, f(x_0, x_1), f(f(x_0, x_1), x_2), ...] Parameters ---------- f A binary function of two arguments of type T. xs A...
https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L116-L143