code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _package_location(root_path, name="pipeline.yaml"):
"""
Look for a src/{package-name}/pipeline.yaml relative to root_path
Parameters
----------
root_path : str or pathlib.Path
Looks for a package relative to this
name : str, default='pipeline.yaml'
YAML spec to search for
... |
Look for a src/{package-name}/pipeline.yaml relative to root_path
Parameters
----------
root_path : str or pathlib.Path
Looks for a package relative to this
name : str, default='pipeline.yaml'
YAML spec to search for
Returns
-------
str
Path to package. None i... | _package_location | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def entry_point_with_name(root_path=None, name=None):
"""Search for an entry point with a given name
Parameters
----------
name : str, default=None
If None, searchs for a pipeline.yaml file otherwise for a
file with such name
"""
filename = name or "pipeline.yaml"
# first, ... | Search for an entry point with a given name
Parameters
----------
name : str, default=None
If None, searchs for a pipeline.yaml file otherwise for a
file with such name
| entry_point_with_name | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def entry_point(root_path=None):
"""
Determines the default YAML specentry point. It first determines the
project root. If the project isn't a package, it returns
project_root/pipeline.yaml, otherwise src/*/pipeline.yaml. If the
ENTRY_POINT environment variable is set, it looks for a file with
s... |
Determines the default YAML specentry point. It first determines the
project root. If the project isn't a package, it returns
project_root/pipeline.yaml, otherwise src/*/pipeline.yaml. If the
ENTRY_POINT environment variable is set, it looks for a file with
such name (e.g., project_root/{ENTRY_POIN... | entry_point | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def try_to_find_entry_point():
"""Try to find the default entry point. Returns None if it isn't possible"""
# check if it's a dotted path
type_ = try_to_find_entry_point_type(os.environ.get("ENTRY_POINT"))
if type_ == EntryPoint.DottedPath:
return os.environ.get("ENTRY_POINT")
# entry_poi... | Try to find the default entry point. Returns None if it isn't possible | try_to_find_entry_point | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def entry_point_relative(name=None):
"""
Returns a relative path to the entry point with the given name.
Raises
------
DAGSpecInvalidError
If cannot locate the requested file
Notes
-----
This is used by Soopervisor when loading dags. We must ensure it gets
a relative path s... |
Returns a relative path to the entry point with the given name.
Raises
------
DAGSpecInvalidError
If cannot locate the requested file
Notes
-----
This is used by Soopervisor when loading dags. We must ensure it gets
a relative path since such file is used for loading the spec ... | entry_point_relative | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def try_to_find_env_yml(path_to_spec):
"""
The purpose of this function is to check whether there are env files
ending with .yml format. It will return that file if it does exist,
otherwise return None.
This function will only be called right after path_to_env_from_spec.
"""
# FIXME: dele... |
The purpose of this function is to check whether there are env files
ending with .yml format. It will return that file if it does exist,
otherwise return None.
This function will only be called right after path_to_env_from_spec.
| try_to_find_env_yml | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def path_to_env_from_spec(path_to_spec):
"""
It first looks up the PLOOMBER_ENV_FILENAME env var, it if exists, it uses
the filename defined there. If not, it looks for an env.yaml file. Prefers
a file in the working directory, otherwise, one relative to the spec's
parent. If the appropriate env.ya... |
It first looks up the PLOOMBER_ENV_FILENAME env var, it if exists, it uses
the filename defined there. If not, it looks for an env.yaml file. Prefers
a file in the working directory, otherwise, one relative to the spec's
parent. If the appropriate env.yaml file does not exist, returns None.
If pat... | path_to_env_from_spec | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def _path_to_filename_in_cwd_or_with_parent(filename, path_to_parent, raise_):
"""
Looks for a file with filename in the current working directory, if it
doesn't exist, it looks for the file under parent directory again
For example:
project/
pipeline.yaml
another/ <- assume this is ... |
Looks for a file with filename in the current working directory, if it
doesn't exist, it looks for the file under parent directory again
For example:
project/
pipeline.yaml
another/ <- assume this is the current working directory
env.yaml <- this gets loaded
And:
p... | _path_to_filename_in_cwd_or_with_parent | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def extract_name(path):
"""
Extract name from a path whose filename is something.{name}.{extension}.
Returns none if the file doesn't follow the naming convention
"""
name = Path(path).name
parts = name.split(".")
if len(parts) < 3:
return None
else:
return parts[1] |
Extract name from a path whose filename is something.{name}.{extension}.
Returns none if the file doesn't follow the naming convention
| extract_name | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def find_file_recursively(name, max_levels_up=6, starting_dir=None):
"""
Find a file by looking into the current folder and parent folders,
returns None if no file was found otherwise pathlib.Path to the file
Parameters
----------
name : str
Filename
Returns
-------
path : ... |
Find a file by looking into the current folder and parent folders,
returns None if no file was found otherwise pathlib.Path to the file
Parameters
----------
name : str
Filename
Returns
-------
path : str
Absolute path to the file
levels : int
How many leve... | find_file_recursively | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def find_root_recursively(starting_dir=None, filename=None, check_parents=True):
"""
Finds a project root by looking recursively for pipeline.yaml or a setup.py
file. Ignores pipeline.yaml if located in src/*/pipeline.yaml.
Parameters
---------
starting_dir : str or pathlib.Path
The dir... |
Finds a project root by looking recursively for pipeline.yaml or a setup.py
file. Ignores pipeline.yaml if located in src/*/pipeline.yaml.
Parameters
---------
starting_dir : str or pathlib.Path
The directory to start the search
Raises
------
DAGSpecInvalidError
If fa... | find_root_recursively | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def find_package_name(starting_dir=None):
"""
Find package name for this project. Raises an error if it cannot determine
a valid root path
"""
root = find_root_recursively(starting_dir=starting_dir)
pkg = _package_location(root_path=root)
if not pkg:
raise ValueError(
"C... |
Find package name for this project. Raises an error if it cannot determine
a valid root path
| find_package_name | python | ploomber/ploomber | src/ploomber/util/default.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/default.py | Apache-2.0 |
def load_dotted_path(dotted_path, raise_=True, reload=False):
"""Load an object/function/module by passing a dotted path
Parameters
----------
dotted_path : str
Dotted path to a module, e.g. ploomber.tasks.NotebookRunner
raise_ : bool, default=True
If True, an exception is raised if... | Load an object/function/module by passing a dotted path
Parameters
----------
dotted_path : str
Dotted path to a module, e.g. ploomber.tasks.NotebookRunner
raise_ : bool, default=True
If True, an exception is raised if the module can't be imported,
otherwise return None if that ... | load_dotted_path | python | ploomber/ploomber | src/ploomber/util/dotted_path.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/dotted_path.py | Apache-2.0 |
def load_callable_dotted_path(dotted_path, raise_=True, reload=False):
"""
Like load_dotted_path but verifies the loaded object is a callable
"""
loaded_object = load_dotted_path(
dotted_path=dotted_path, raise_=raise_, reload=reload
)
if not callable(loaded_object):
raise TypeE... |
Like load_dotted_path but verifies the loaded object is a callable
| load_callable_dotted_path | python | ploomber/ploomber | src/ploomber/util/dotted_path.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/dotted_path.py | Apache-2.0 |
def call_dotted_path(dotted_path, raise_=True, reload=False, kwargs=None):
"""
Load dotted path (using load_callable_dotted_path), and call it with
kwargs arguments, raises an exception if returns None
Parameters
----------
dotted_path : str
Dotted path to call
kwargs : dict, defaul... |
Load dotted path (using load_callable_dotted_path), and call it with
kwargs arguments, raises an exception if returns None
Parameters
----------
dotted_path : str
Dotted path to call
kwargs : dict, default=None
Keyword arguments to call the dotted path
| call_dotted_path | python | ploomber/ploomber | src/ploomber/util/dotted_path.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/dotted_path.py | Apache-2.0 |
def locate_dotted_path(dotted_path):
"""
Locates a dotted path, returns the spec for the module where the attribute
is defined
"""
tokens = dotted_path.split(".")
module = ".".join(tokens[:-1])
# NOTE: if importing a sub-module (e.g., something.another), this will
# import some modules (... |
Locates a dotted path, returns the spec for the module where the attribute
is defined
| locate_dotted_path | python | ploomber/ploomber | src/ploomber/util/dotted_path.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/dotted_path.py | Apache-2.0 |
def locate_dotted_path_root(dotted_path):
"""
Returns the module spec for a given dotted path.
e.g. module.sub.another, checks that module exists
"""
tokens = dotted_path.split(".")
spec = importlib.util.find_spec(tokens[0])
if spec is None:
raise ModuleNotFoundError(f"Module {token... |
Returns the module spec for a given dotted path.
e.g. module.sub.another, checks that module exists
| locate_dotted_path_root | python | ploomber/ploomber | src/ploomber/util/dotted_path.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/dotted_path.py | Apache-2.0 |
def lazily_locate_dotted_path(dotted_path):
"""
Locates a dotted path, but unlike importlib.util.find_spec, it does not
import submodules
"""
_validate_dotted_path(dotted_path)
parts = dotted_path.split(".")
module_name = ".".join(parts[:-1])
first, middle, mod, symbol = parts[0], parts... |
Locates a dotted path, but unlike importlib.util.find_spec, it does not
import submodules
| lazily_locate_dotted_path | python | ploomber/ploomber | src/ploomber/util/dotted_path.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/dotted_path.py | Apache-2.0 |
def create_intermediate_modules(module_parts):
"""
Creates the folder structure needed for a module specified
by the parts of its name
Parameters
----------
module_parts : list
A list of strings with the module elements.
Example: ['module', 'sub_module']
Raises
------
... |
Creates the folder structure needed for a module specified
by the parts of its name
Parameters
----------
module_parts : list
A list of strings with the module elements.
Example: ['module', 'sub_module']
Raises
------
ValueError
If the module already exists
... | create_intermediate_modules | python | ploomber/ploomber | src/ploomber/util/dotted_path.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/dotted_path.py | Apache-2.0 |
def lazily_load_entry_point(starting_dir=None, reload=False):
"""
Lazily loads entry point by recursively looking in starting_dir directory
and parent directories.
"""
generator = _lazily_load_entry_point_generator(
starting_dir=starting_dir, reload=reload
)
_ = next(generator)
r... |
Lazily loads entry point by recursively looking in starting_dir directory
and parent directories.
| lazily_load_entry_point | python | ploomber/ploomber | src/ploomber/util/loader.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/loader.py | Apache-2.0 |
def _default_spec_load_generator(starting_dir=None, lazy_import=False, reload=False):
"""
Similar to _default_spec_load but this one returns a generator. The
first element is the path to the entry point and the second one
the spec, the path to spec parent and the path to the spec
"""
root_path =... |
Similar to _default_spec_load but this one returns a generator. The
first element is the path to the entry point and the second one
the spec, the path to spec parent and the path to the spec
| _default_spec_load_generator | python | ploomber/ploomber | src/ploomber/util/loader.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/loader.py | Apache-2.0 |
def markdown_to_html(md):
"""
Convert markdown to HTML with syntax highlighting, works with old and
new versions of mistune
"""
if mistune_recent:
class HighlightRenderer(mistune.HTMLRenderer):
def block_code(self, code, lang=None):
if lang:
l... |
Convert markdown to HTML with syntax highlighting, works with old and
new versions of mistune
| markdown_to_html | python | ploomber/ploomber | src/ploomber/util/markup.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/markup.py | Apache-2.0 |
def callback_check(fn, available, allow_default=True):
"""
Check if a callback function signature requests available parameters
Parameters
----------
fn : callable
Callable (e.g. a function) to check
available : dict
All available params
allow_default : bool, optional
... |
Check if a callback function signature requests available parameters
Parameters
----------
fn : callable
Callable (e.g. a function) to check
available : dict
All available params
allow_default : bool, optional
Whether allow arguments with default values in "fn" or not... | callback_check | python | ploomber/ploomber | src/ploomber/util/util.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/util.py | Apache-2.0 |
def signature_check(fn, params, task_name):
"""
Verify if the function signature used as source in a PythonCallable
task matches available params
"""
params = set(params)
parameters = inspect.signature(fn).parameters
required = {
name for name, param in parameters.items() if param.... |
Verify if the function signature used as source in a PythonCallable
task matches available params
| signature_check | python | ploomber/ploomber | src/ploomber/util/util.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/util.py | Apache-2.0 |
def call_with_dictionary(fn, kwargs):
"""
Call a function by passing elements from a dictionary that appear in the
function signature
"""
parameters = inspect.signature(fn).parameters
common = set(parameters) & set(kwargs)
sub_kwargs = {k: kwargs[k] for k in common}
return fn(**sub_kwarg... |
Call a function by passing elements from a dictionary that appear in the
function signature
| call_with_dictionary | python | ploomber/ploomber | src/ploomber/util/util.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/util.py | Apache-2.0 |
def chdir_code(path):
"""
Returns a string with valid code to chdir to the passed path
"""
path = Path(path).resolve()
if isinstance(path, WindowsPath):
path = str(path).replace("\\", "\\\\")
return f'os.chdir("{path}")' |
Returns a string with valid code to chdir to the passed path
| chdir_code | python | ploomber/ploomber | src/ploomber/util/util.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/util.py | Apache-2.0 |
def _python_bin():
"""
Get the path to the Python executable, return 'python' if unable to get it
"""
executable = sys.executable
return executable if executable else "python" |
Get the path to the Python executable, return 'python' if unable to get it
| _python_bin | python | ploomber/ploomber | src/ploomber/util/_sys.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/util/_sys.py | Apache-2.0 |
def validate_task_class_name(value):
"""
Validates if a string is a valid Task class name (e.g., SQLScipt).
Raises a ValueError if not.
"""
if value not in _KEY2CLASS_TASKS:
suggestion = get_suggestion(value, mapping=_NORMALIZED_TASKS)
msg = f"{value!r} is not a valid Task class name... |
Validates if a string is a valid Task class name (e.g., SQLScipt).
Raises a ValueError if not.
| validate_task_class_name | python | ploomber/ploomber | src/ploomber/validators/string.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/validators/string.py | Apache-2.0 |
def validate_product_class_name(value):
"""
Validates if a string is a valid Product class name (e.g., File).
Raises a ValueError if not.
"""
if value not in _KEY2CLASS_PRODUCTS:
suggestion = get_suggestion(value, mapping=_NORMALIZED_PRODUCTS)
msg = f"{value!r} is not a valid Product... |
Validates if a string is a valid Product class name (e.g., File).
Raises a ValueError if not.
| validate_product_class_name | python | ploomber/ploomber | src/ploomber/validators/string.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/validators/string.py | Apache-2.0 |
def validate_schema(assert_, data, schema, optional=None, on_unexpected_cols="raise"):
"""Check if a data frame complies with a schema
Parameters
----------
data : pandas.DataFrame
Data frame to test
schema : list or dict
List with column names (will only validate names)
or ... | Check if a data frame complies with a schema
Parameters
----------
data : pandas.DataFrame
Data frame to test
schema : list or dict
List with column names (will only validate names)
or dict with column names as keys, dtypes as values (will validate
names and dtypes)
... | validate_schema | python | ploomber/ploomber | src/ploomber/validators/validators.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/validators/validators.py | Apache-2.0 |
def data_frame_validator(df, validators):
"""
Examples
--------
>>> from ploomber.validators import data_frame_validator
>>> from ploomber.validators import validate_schema, validate_values
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'x': np.random.rand(3), 'y'... |
Examples
--------
>>> from ploomber.validators import data_frame_validator
>>> from ploomber.validators import validate_schema, validate_values
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'x': np.random.rand(3), 'y': np.random.rand(3),
... '... | data_frame_validator | python | ploomber/ploomber | src/ploomber/validators/validators.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber/validators/validators.py | Apache-2.0 |
def scaffold(name, conda, package, entry_point, empty):
"""
Create a new project and task source files
Step 1. Create new project
$ ploomber scaffold myproject
$ cd myproject
Step 2. Add tasks to the pipeline.yaml file
Step 3. Create source files
$ ploomber scaffold
Need... |
Create a new project and task source files
Step 1. Create new project
$ ploomber scaffold myproject
$ cd myproject
Step 2. Add tasks to the pipeline.yaml file
Step 3. Create source files
$ ploomber scaffold
Need help? https://ploomber.io/community
| scaffold | python | ploomber/ploomber | src/ploomber_cli/cli.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber_cli/cli.py | Apache-2.0 |
def examples(name, force, branch, output):
"""
Download examples
Step 1. List examples
$ ploomber examples
Step 2. Download an example
$ ploomber examples -n templates/ml-basic -o my-pipeline
Need help? https://ploomber.io/community
"""
click.echo("Loading examples...")
... |
Download examples
Step 1. List examples
$ ploomber examples
Step 2. Download an example
$ ploomber examples -n templates/ml-basic -o my-pipeline
Need help? https://ploomber.io/community
| examples | python | ploomber/ploomber | src/ploomber_cli/cli.py | https://github.com/ploomber/ploomber/blob/master/src/ploomber_cli/cli.py | Apache-2.0 |
def tmp_directory_local(tmp_path):
"""
Pretty much the same as tmp_directory, but it uses pytest tmp_path,
which creates the path in a pre-determined location depending on the test,
TODO: replace the logic in tmp_directory with this one
"""
old = os.getcwd()
os.chdir(tmp_path)
yield tmp... |
Pretty much the same as tmp_directory, but it uses pytest tmp_path,
which creates the path in a pre-determined location depending on the test,
TODO: replace the logic in tmp_directory with this one
| tmp_directory_local | python | ploomber/ploomber | tests/conftest.py | https://github.com/ploomber/ploomber/blob/master/tests/conftest.py | Apache-2.0 |
def sqlite_client_and_tmp_dir():
"""
Creates a sqlite db with sample data and yields initialized client
along with a temporary directory location
"""
old = os.getcwd()
tmp_dir = Path(tempfile.mkdtemp())
os.chdir(str(tmp_dir))
client = SQLAlchemyClient("sqlite:///" + str(tmp_dir / "my_db.... |
Creates a sqlite db with sample data and yields initialized client
along with a temporary directory location
| sqlite_client_and_tmp_dir | python | ploomber/ploomber | tests/conftest.py | https://github.com/ploomber/ploomber/blob/master/tests/conftest.py | Apache-2.0 |
def pg_client_and_schema():
"""
Creates a temporary schema for the testing session, drops everything
at the end
"""
db = _load_db_credentials()
# set a new schema for this session, otherwise if two test sessions
# are run at the same time, tests might conflict with each other
# NOTE: av... |
Creates a temporary schema for the testing session, drops everything
at the end
| pg_client_and_schema | python | ploomber/ploomber | tests/conftest.py | https://github.com/ploomber/ploomber/blob/master/tests/conftest.py | Apache-2.0 |
def no_sys_modules_cache():
"""
Removes modules from sys.modules that didn't exist before the test
"""
mods = set(sys.modules)
yield
current = set(sys.modules)
to_remove = current - mods
for a_module in to_remove:
del sys.modules[a_module] |
Removes modules from sys.modules that didn't exist before the test
| no_sys_modules_cache | python | ploomber/ploomber | tests/conftest.py | https://github.com/ploomber/ploomber/blob/master/tests/conftest.py | Apache-2.0 |
def set_terminal_output_columns(num_cols: int, monkeypatch):
"""
Sets the number of columns for terminalwriter
Usefult for ci where the number of columns is inconsistent
"""
# countaract lines in sep() of terminalwriter.py that removes a col from
# the width if on windows
if sys.platform == ... |
Sets the number of columns for terminalwriter
Usefult for ci where the number of columns is inconsistent
| set_terminal_output_columns | python | ploomber/ploomber | tests/tests_util.py | https://github.com/ploomber/ploomber/blob/master/tests/tests_util.py | Apache-2.0 |
def test_manager_initialization(tmp_directory):
"""
There some weird stuff in the Jupyter contents manager base class that
causses the initialization to break if we modify the __init__ method
in PloomberContentsManager. We add this to check that values are
correctly initialized
"""
dir_ = Pa... |
There some weird stuff in the Jupyter contents manager base class that
causses the initialization to break if we modify the __init__ method
in PloomberContentsManager. We add this to check that values are
correctly initialized
| test_manager_initialization | python | ploomber/ploomber | tests/test_jupyter.py | https://github.com/ploomber/ploomber/blob/master/tests/test_jupyter.py | Apache-2.0 |
def test_ignores_tasks_whose_source_is_not_a_file(
monkeypatch, capsys, tmp_directory, no_sys_modules_cache
):
"""
Context: jupyter extension only applies to tasks whose source is a script,
otherwise it will break, trying to get the source location. This test
checks that a SQLUpload (whose source is... |
Context: jupyter extension only applies to tasks whose source is a script,
otherwise it will break, trying to get the source location. This test
checks that a SQLUpload (whose source is a data file) task is ignored
from the extension
| test_ignores_tasks_whose_source_is_not_a_file | python | ploomber/ploomber | tests/test_jupyter.py | https://github.com/ploomber/ploomber/blob/master/tests/test_jupyter.py | Apache-2.0 |
def test_jupyter_workflow_with_functions(
backup_spec_with_functions, no_sys_modules_cache
):
"""
Tests a typical workflow with a pieline where some tasks are functions
"""
cm = PloomberContentsManager()
def get_names(out):
return {model["name"] for model in out["content"]}
assert ... |
Tests a typical workflow with a pieline where some tasks are functions
| test_jupyter_workflow_with_functions | python | ploomber/ploomber | tests/test_jupyter.py | https://github.com/ploomber/ploomber/blob/master/tests/test_jupyter.py | Apache-2.0 |
def features(upstream, product):
"""Generate new features from existing columns"""
data = pd.read_parquet(str(upstream["get"]))
ft = data["1"] * data["2"]
df = pd.DataFrame({"feature": ft, "another": ft**2})
df.to_parquet(str(product)) | Generate new features from existing columns | features | python | ploomber/ploomber | tests/assets/simple/tasks_simple.py | https://github.com/ploomber/ploomber/blob/master/tests/assets/simple/tasks_simple.py | Apache-2.0 |
def join(upstream, product):
"""Join raw data with generated features"""
a = pd.read_parquet(str(upstream["get"]))
b = pd.read_parquet(str(upstream["features"]))
df = a.join(b)
df.to_parquet(str(product)) | Join raw data with generated features | join | python | ploomber/ploomber | tests/assets/simple/tasks_simple.py | https://github.com/ploomber/ploomber/blob/master/tests/assets/simple/tasks_simple.py | Apache-2.0 |
def test_cli_does_not_import_main_package(monkeypatch):
"""
ploomber_cli.cli should NOT import ploomber since it's a heavy package
and we want the CLI to be responsive. imports should happen inside each
command
"""
out = subprocess.check_output(
[
"python",
"-c",
... |
ploomber_cli.cli should NOT import ploomber since it's a heavy package
and we want the CLI to be responsive. imports should happen inside each
command
| test_cli_does_not_import_main_package | python | ploomber/ploomber | tests/cli/test_custom.py | https://github.com/ploomber/ploomber/blob/master/tests/cli/test_custom.py | Apache-2.0 |
def test_task_command_does_not_force_dag_render(tmp_nbs, monkeypatch):
"""
Make sure the force flag is only used in task.render and not dag.render
because we don't want to override the status of other tasks
"""
args = ["task", "load", "--force"]
monkeypatch.setattr(sys, "argv", args)
class ... |
Make sure the force flag is only used in task.render and not dag.render
because we don't want to override the status of other tasks
| test_task_command_does_not_force_dag_render | python | ploomber/ploomber | tests/cli/test_custom.py | https://github.com/ploomber/ploomber/blob/master/tests/cli/test_custom.py | Apache-2.0 |
def test_dagspec_initialization_from_yaml(tmp_nbs_nested, monkeypatch):
"""
DAGSpec can be initialized with a path to a spec or a dictionary, but
they have a slightly different behavior. This checks that we initialize
with the path
"""
mock = Mock(wraps=parsers.DAGSpec)
monkeypatch.setattr(... |
DAGSpec can be initialized with a path to a spec or a dictionary, but
they have a slightly different behavior. This checks that we initialize
with the path
| test_dagspec_initialization_from_yaml | python | ploomber/ploomber | tests/cli/test_customparser.py | https://github.com/ploomber/ploomber/blob/master/tests/cli/test_customparser.py | Apache-2.0 |
def test_dagspec_initialization_from_yaml_and_env(tmp_nbs, monkeypatch):
"""
DAGSpec can be initialized with a path to a spec or a dictionary, but
they have a slightly different behavior. This ensure the cli passes
the path, instead of a dictionary
"""
mock_DAGSpec = Mock(wraps=parsers.DAGSpec)
... |
DAGSpec can be initialized with a path to a spec or a dictionary, but
they have a slightly different behavior. This ensure the cli passes
the path, instead of a dictionary
| test_dagspec_initialization_from_yaml_and_env | python | ploomber/ploomber | tests/cli/test_customparser.py | https://github.com/ploomber/ploomber/blob/master/tests/cli/test_customparser.py | Apache-2.0 |
def test_ploomber_scaffold(tmp_directory, monkeypatch, args, conda, package, empty):
"""
Testing cli args are correctly routed to the function
"""
mock = Mock()
monkeypatch.setattr(cli.scaffold_project, "cli", mock)
runner = CliRunner()
result = runner.invoke(scaffold, args=args, catch_exce... |
Testing cli args are correctly routed to the function
| test_ploomber_scaffold | python | ploomber/ploomber | tests/cli/test_scaffold.py | https://github.com/ploomber/ploomber/blob/master/tests/cli/test_scaffold.py | Apache-2.0 |
def test_ploomber_scaffold_task_template(file_, extract_flag, tmp_directory):
"""Test scaffold when project already exists (add task templates)"""
sample_spec = {
"meta": {"extract_upstream": extract_flag, "extract_product": extract_flag}
}
task = {"source": file_}
if not extract_flag:
... | Test scaffold when project already exists (add task templates) | test_ploomber_scaffold_task_template | python | ploomber/ploomber | tests/cli/test_scaffold.py | https://github.com/ploomber/ploomber/blob/master/tests/cli/test_scaffold.py | Apache-2.0 |
def monkeypatch_plot(monkeypatch):
"""
Monkeypatch logic for making the DAG.plot() work without calling
pygraphviz and checking calls are done with the right arguments
"""
image_out = object()
mock_Image = Mock(return_value=image_out)
mock_to_agraph = Mock()
def touch(*args, **kwargs):
... |
Monkeypatch logic for making the DAG.plot() work without calling
pygraphviz and checking calls are done with the right arguments
| monkeypatch_plot | python | ploomber/ploomber | tests/dag/test_dag.py | https://github.com/ploomber/ploomber/blob/master/tests/dag/test_dag.py | Apache-2.0 |
def test_forced_render_does_not_call_is_outdated(monkeypatch):
"""
For products whose metadata is stored remotely, checking status is an
expensive operation. Make dure forced render does not call
Product._is_oudated
"""
dag = DAG()
t1 = PythonCallable(touch_root, File("1.txt"), dag, name=1)
... |
For products whose metadata is stored remotely, checking status is an
expensive operation. Make dure forced render does not call
Product._is_oudated
| test_forced_render_does_not_call_is_outdated | python | ploomber/ploomber | tests/dag/test_dag.py | https://github.com/ploomber/ploomber/blob/master/tests/dag/test_dag.py | Apache-2.0 |
def test_dag_functions_do_not_fetch_metadata(
function_name, executor, tmp_directory, monkeypatch_plot
):
"""
these function should not look up metadata, since the products do not
exist, the status can be determined without it
"""
product = File("1.txt")
dag = DAG(executor=executor)
Pyth... |
these function should not look up metadata, since the products do not
exist, the status can be determined without it
| test_dag_functions_do_not_fetch_metadata | python | ploomber/ploomber | tests/dag/test_dag.py | https://github.com/ploomber/ploomber/blob/master/tests/dag/test_dag.py | Apache-2.0 |
def test_dag_task_status_life_cycle(executor, tmp_directory):
"""
Check dag and task status along calls to DAG.render and DAG.build.
Although DAG and Task status are automatically updated and propagated
downstream upon calls to render and build, we have to parametrize this
over executors since the o... |
Check dag and task status along calls to DAG.render and DAG.build.
Although DAG and Task status are automatically updated and propagated
downstream upon calls to render and build, we have to parametrize this
over executors since the object that gets updated might not be the same
one that we declare... | test_dag_task_status_life_cycle | python | ploomber/ploomber | tests/dag/test_dag.py | https://github.com/ploomber/ploomber/blob/master/tests/dag/test_dag.py | Apache-2.0 |
def test_logging_handler(executor, tmp_directory):
"""
Note: this test is a bit weird, when executed in isolation it fails,
but when executing the whole file, it works. Not sure why.
Also, this only works on windows/mac when tasks are executed in the same
process. For it to work, we'd have to ensur... |
Note: this test is a bit weird, when executed in isolation it fails,
but when executing the whole file, it works. Not sure why.
Also, this only works on windows/mac when tasks are executed in the same
process. For it to work, we'd have to ensure that the logging objects
are re-configured again in ... | test_logging_handler | python | ploomber/ploomber | tests/dag/test_dagconfigurator.py | https://github.com/ploomber/ploomber/blob/master/tests/dag/test_dagconfigurator.py | Apache-2.0 |
def test_render_checks_outdated_status_once(monkeypatch, tmp_directory):
"""
_check_is_outdated is an expensive operation and it should only run
once per task
"""
def _make_dag():
dag = DAG(executor=Serial(build_in_subprocess=False))
t1 = PythonCallable(touch_root, File("one.txt"), ... |
_check_is_outdated is an expensive operation and it should only run
once per task
| test_render_checks_outdated_status_once | python | ploomber/ploomber | tests/dag/test_render.py | https://github.com/ploomber/ploomber/blob/master/tests/dag/test_render.py | Apache-2.0 |
def color_mapping():
"""Returns a utility class which can replace keys in strings in the form
"{NAME}"
by their equivalent ASCII codes in the terminal.
Used by tests which check the actual colors output by pytest.
"""
class ColorMapping:
COLORS = {
"red": "\x1b[31m",
... | Returns a utility class which can replace keys in strings in the form
"{NAME}"
by their equivalent ASCII codes in the terminal.
Used by tests which check the actual colors output by pytest.
| color_mapping | python | ploomber/ploomber | tests/io_mod/test_terminalwriter.py | https://github.com/ploomber/ploomber/blob/master/tests/io_mod/test_terminalwriter.py | Apache-2.0 |
def test_task_with_client_and_metaproduct_isnt_outdated_rtrns_waiting_download(
operation, tmp_directory, tmp_path
):
"""
Checking MetaProduct correctly forwards WaitingDownload when calling
MetaProduct._is_outdated
"""
dag = _make_dag_with_metaproduct(with_client=True)
dag.build()
# si... |
Checking MetaProduct correctly forwards WaitingDownload when calling
MetaProduct._is_outdated
| test_task_with_client_and_metaproduct_isnt_outdated_rtrns_waiting_download | python | ploomber/ploomber | tests/products/test_file.py | https://github.com/ploomber/ploomber/blob/master/tests/products/test_file.py | Apache-2.0 |
def test_task_with_client_and_metaproduct_with_some_missing_products(
operation, tmp_directory, tmp_path
):
"""
If local MetaProduct content isn't consistent, it should execute instead of
download
"""
dag = _make_dag_with_metaproduct(with_client=True)
dag.build()
# simulate *some* local... |
If local MetaProduct content isn't consistent, it should execute instead of
download
| test_task_with_client_and_metaproduct_with_some_missing_products | python | ploomber/ploomber | tests/products/test_file.py | https://github.com/ploomber/ploomber/blob/master/tests/products/test_file.py | Apache-2.0 |
def test_task_with_client_and_metaproduct_with_some_missing_remote_products(
operation, tmp_directory, tmp_path
):
"""
If remote MetaProduct content isn't consistent, it should execute instead
of download
"""
dag = _make_dag_with_metaproduct(with_client=True)
dag.build()
# simulate *som... |
If remote MetaProduct content isn't consistent, it should execute instead
of download
| test_task_with_client_and_metaproduct_with_some_missing_remote_products | python | ploomber/ploomber | tests/products/test_file.py | https://github.com/ploomber/ploomber/blob/master/tests/products/test_file.py | Apache-2.0 |
def test_interface(concrete_class):
"""
Look for unnecessary implemeneted methods/attributes in MetaProduct,
this helps us keep the API up-to-date if the Product interface changes
"""
allowed_mapping = {
"SQLRelation": {"schema", "name", "kind", "client"},
"SQLiteRelation": {"schema"... |
Look for unnecessary implemeneted methods/attributes in MetaProduct,
this helps us keep the API up-to-date if the Product interface changes
| test_interface | python | ploomber/ploomber | tests/products/test_product.py | https://github.com/ploomber/ploomber/blob/master/tests/products/test_product.py | Apache-2.0 |
def tmp_nbs_ipynb(tmp_nbs):
"""Modifies the nbs example to have one task with ipynb format"""
# modify the spec so it has one ipynb task
with open("pipeline.yaml") as f:
spec = yaml.safe_load(f)
spec["tasks"][0]["source"] = "load.ipynb"
Path("pipeline.yaml").write_text(yaml.dump(spec))
... | Modifies the nbs example to have one task with ipynb format | tmp_nbs_ipynb | python | ploomber/ploomber | tests/sources/test_notebooksource.py | https://github.com/ploomber/ploomber/blob/master/tests/sources/test_notebooksource.py | Apache-2.0 |
def test_unmodified_function(fn_name, remove_trailing_newline, backup_test_pkg):
"""
This test makes sure the file is not modified if we don't change the
notebook because whitespace is tricky
"""
fn = getattr(functions, fn_name)
path_to_file = Path(inspect.getfile(fn))
content = path_to_fil... |
This test makes sure the file is not modified if we don't change the
notebook because whitespace is tricky
| test_unmodified_function | python | ploomber/ploomber | tests/sources/test_python_interact.py | https://github.com/ploomber/ploomber/blob/master/tests/sources/test_python_interact.py | Apache-2.0 |
def test_develop_spec_with_local_functions(
task_name, backup_spec_with_functions, no_sys_modules_cache
):
"""
Check we can develop functions defined locally, the sample project includes
relative imports, which should work when generating the temporary notebook
"""
dag = DAGSpec("pipeline.yaml")... |
Check we can develop functions defined locally, the sample project includes
relative imports, which should work when generating the temporary notebook
| test_develop_spec_with_local_functions | python | ploomber/ploomber | tests/sources/test_python_interact.py | https://github.com/ploomber/ploomber/blob/master/tests/sources/test_python_interact.py | Apache-2.0 |
def test_interface(concrete_class):
"""
Check that Source concrete classes do not have any extra methods
that are not declared in the Source abstract class
"""
if concrete_class in {PythonCallableSource, NotebookSource}:
# FIXME: these two have a lot of extra methods
pytest.xfail()
... |
Check that Source concrete classes do not have any extra methods
that are not declared in the Source abstract class
| test_interface | python | ploomber/ploomber | tests/sources/test_sources.py | https://github.com/ploomber/ploomber/blob/master/tests/sources/test_sources.py | Apache-2.0 |
def test_init_from_file_resolves_source_location(tmp_directory, spec, base, cwd):
"""
DAGSpec resolves sources and products to absolute values, this process
should be independent of the current working directory and ignore the
existence of other pipeline.yaml in parent directories
"""
Path("dir"... |
DAGSpec resolves sources and products to absolute values, this process
should be independent of the current working directory and ignore the
existence of other pipeline.yaml in parent directories
| test_init_from_file_resolves_source_location | python | ploomber/ploomber | tests/spec/test_dagspec.py | https://github.com/ploomber/ploomber/blob/master/tests/spec/test_dagspec.py | Apache-2.0 |
def test_spec_with_functions(
lazy_import,
backup_spec_with_functions,
add_current_to_sys_path,
no_sys_modules_cache,
):
"""
Check we can create pipeline where the task is a function defined in a
local file
"""
spec = DAGSpec("pipeline.yaml", lazy_import=lazy_import)
spec.to_dag(... |
Check we can create pipeline where the task is a function defined in a
local file
| test_spec_with_functions | python | ploomber/ploomber | tests/spec/test_dagspec.py | https://github.com/ploomber/ploomber/blob/master/tests/spec/test_dagspec.py | Apache-2.0 |
def test_spec_with_functions_fails(
lazy_import,
backup_spec_with_functions_no_sources,
add_current_to_sys_path,
no_sys_modules_cache,
):
"""
Check we can create pipeline where the task is a function defined in a
local file but the sources do not exist. Since it is trying to load the
sou... |
Check we can create pipeline where the task is a function defined in a
local file but the sources do not exist. Since it is trying to load the
source scripts thanks to lazy_import being bool, it should fail (True
imports the function, while False does not but it checks that it exists)
| test_spec_with_functions_fails | python | ploomber/ploomber | tests/spec/test_dagspec.py | https://github.com/ploomber/ploomber/blob/master/tests/spec/test_dagspec.py | Apache-2.0 |
def test_spec_with_sourceless_functions(
backup_spec_with_functions_no_sources, add_current_to_sys_path, no_sys_modules_cache
):
"""
Check we can create pipeline where the task is a function defined in a
deep hierarchical structure where the source does not exists
"""
assert DAGSpec("pipeline.ya... |
Check we can create pipeline where the task is a function defined in a
deep hierarchical structure where the source does not exists
| test_spec_with_sourceless_functions | python | ploomber/ploomber | tests/spec/test_dagspec.py | https://github.com/ploomber/ploomber/blob/master/tests/spec/test_dagspec.py | Apache-2.0 |
def test_import_tasks_from_does_not_resolve_dotted_paths(tmp_nbs):
"""
Sources defined in a file used in "import_tasks_from" are resolved
if they're paths to files but dotted paths should remain the same
"""
some_tasks = [
{"source": "extra_task.py", "product": "extra.ipynb"},
{"sour... |
Sources defined in a file used in "import_tasks_from" are resolved
if they're paths to files but dotted paths should remain the same
| test_import_tasks_from_does_not_resolve_dotted_paths | python | ploomber/ploomber | tests/spec/test_dagspec.py | https://github.com/ploomber/ploomber/blob/master/tests/spec/test_dagspec.py | Apache-2.0 |
def test_resolve_client(tmp_directory, tmp_imports, product_class, arg):
"""
Test tries to use task-level client, then dag-level client
"""
Path("my_testing_client.py").write_text(
"""
def get():
return 1
"""
)
task = product_class(arg, client=DottedPath("my_testing_client.get"))
... |
Test tries to use task-level client, then dag-level client
| test_resolve_client | python | ploomber/ploomber | tests/tasks/test_client.py | https://github.com/ploomber/ploomber/blob/master/tests/tasks/test_client.py | Apache-2.0 |
def test_interface(concrete_class):
"""
Look for unnecessary implemented methods/attributes in Tasks concrete
classes, this helps us keep the API up-to-date
"""
allowed_mapping = {
"Input": {"_true", "_null_update_metadata"},
"Link": {"_false"},
"PythonCallable": {"load", "_i... |
Look for unnecessary implemented methods/attributes in Tasks concrete
classes, this helps us keep the API up-to-date
| test_interface | python | ploomber/ploomber | tests/tasks/test_task.py | https://github.com/ploomber/ploomber/blob/master/tests/tasks/test_task.py | Apache-2.0 |
def test_task_init_source_with_placeholder_obj(Task, prod, source):
"""
Testing we can initialize a task with a Placeholder as the source argument
"""
dag = DAG()
dag.clients[Task] = Mock()
dag.clients[type(prod)] = Mock()
Task(Placeholder(source), prod, dag, name="task") |
Testing we can initialize a task with a Placeholder as the source argument
| test_task_init_source_with_placeholder_obj | python | ploomber/ploomber | tests/tasks/test_tasks.py | https://github.com/ploomber/ploomber/blob/master/tests/tasks/test_tasks.py | Apache-2.0 |
def fixture_backup(source):
"""
Similar to fixture_tmp_dir but backups the content instead
"""
def decorator(function):
@wraps(function)
def wrapper():
old = os.getcwd()
backup = tempfile.mkdtemp()
root = _path_to_tests() / "assets" / source
... |
Similar to fixture_tmp_dir but backups the content instead
| fixture_backup | python | ploomber/ploomber | testutils/testutils.py | https://github.com/ploomber/ploomber/blob/master/testutils/testutils.py | Apache-2.0 |
def fixture_tmp_dir(source, **kwargs):
"""
A lot of our fixtures are copying a few files into a temporary location,
making that location the current working directory and deleting after
the test is done. This decorator allows us to build such fixture
"""
# NOTE: I tried not making this a decora... |
A lot of our fixtures are copying a few files into a temporary location,
making that location the current working directory and deleting after
the test is done. This decorator allows us to build such fixture
| fixture_tmp_dir | python | ploomber/ploomber | testutils/testutils.py | https://github.com/ploomber/ploomber/blob/master/testutils/testutils.py | Apache-2.0 |
def set_outflow_BC(self, pores, mode='add'):
r"""
Adds outflow boundary condition to the selected pores
Parameters
----------
pores : array_like
The pore indices where the condition should be applied
mode : str, optional
Controls how the boundary ... |
Adds outflow boundary condition to the selected pores
Parameters
----------
pores : array_like
The pore indices where the condition should be applied
mode : str, optional
Controls how the boundary conditions are applied. The default value
is ... | set_outflow_BC | python | PMEAL/OpenPNM | openpnm/algorithms/_advection_diffusion.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_advection_diffusion.py | MIT |
def _apply_BCs(self):
r"""
Applies Dirichlet, Neumann, and outflow BCs in order
"""
# Apply Dirichlet and rate BCs
super()._apply_BCs()
if 'pore.bc.outflow' not in self.keys():
return
# Apply outflow BC
diag = self.A.diagonal()
ind = np... |
Applies Dirichlet, Neumann, and outflow BCs in order
| _apply_BCs | python | PMEAL/OpenPNM | openpnm/algorithms/_advection_diffusion.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_advection_diffusion.py | MIT |
def iterative_props(self):
r"""
Finds and returns properties that need to be iterated while
running the algorithm.
"""
import networkx as nx
phase = self.project[self.settings.phase]
# Generate global dependency graph
dg = nx.compose_all([x.models.dependen... |
Finds and returns properties that need to be iterated while
running the algorithm.
| iterative_props | python | PMEAL/OpenPNM | openpnm/algorithms/_algorithm.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_algorithm.py | MIT |
def _update_iterative_props(self, iterative_props=None):
"""
Regenerates phase, geometries, and physics objects using the
current value of ``quantity``.
Notes
-----
The algorithm directly writes the value of 'quantity' into the
phase, which is against one of the ... |
Regenerates phase, geometries, and physics objects using the
current value of ``quantity``.
Notes
-----
The algorithm directly writes the value of 'quantity' into the
phase, which is against one of the OpenPNM rules of objects not
being able to write into each o... | _update_iterative_props | python | PMEAL/OpenPNM | openpnm/algorithms/_algorithm.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_algorithm.py | MIT |
def set_BC(self, pores=None, bctype=[], bcvalues=[], mode='add'):
r"""
The main method for setting and adjusting boundary conditions.
This method is called by other more convenient wrapper functions like
``set_value_BC``.
Parameters
----------
pores : array_like... |
The main method for setting and adjusting boundary conditions.
This method is called by other more convenient wrapper functions like
``set_value_BC``.
Parameters
----------
pores : array_like
The pores where the boundary conditions should be applied. If
... | set_BC | python | PMEAL/OpenPNM | openpnm/algorithms/_algorithm.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_algorithm.py | MIT |
def reset(self):
r"""
Resets the algorithm's main results so that it can be re-run
"""
self['pore.invaded'] = False
self['throat.invaded'] = False
# self['pore.residual'] = False
# self['throat.residual'] = False
self['pore.trapped'] = False
self['... |
Resets the algorithm's main results so that it can be re-run
| reset | python | PMEAL/OpenPNM | openpnm/algorithms/_drainage.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_drainage.py | MIT |
def run(self, pressures=25):
r"""
Runs the simulation for the pressure points
Parameters
----------
pressures : int or ndarray
The number of pressue steps to apply, or an array of specific
points
"""
if isinstance(pressures, int):
... |
Runs the simulation for the pressure points
Parameters
----------
pressures : int or ndarray
The number of pressue steps to apply, or an array of specific
points
| run | python | PMEAL/OpenPNM | openpnm/algorithms/_drainage.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_drainage.py | MIT |
def apply_trapping(self):
r"""
Adjusts the invasion history of pores and throats that are trapped.
Returns
-------
This function returns nothing, but the following adjustments are made
to the data on the object for trapped pores and throats:
* ``'pore/throat.tra... |
Adjusts the invasion history of pores and throats that are trapped.
Returns
-------
This function returns nothing, but the following adjustments are made
to the data on the object for trapped pores and throats:
* ``'pore/throat.trapped'`` is set to ``True``
* `... | apply_trapping | python | PMEAL/OpenPNM | openpnm/algorithms/_drainage.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_drainage.py | MIT |
def set_inlet_BC(self, pores=None, mode='add'):
r"""
Specifies which pores are treated as inlets for the invading phase
Parameters
----------
pores : ndarray
The indices of the pores from which the invading fluid invasion
should start
mode : str o... |
Specifies which pores are treated as inlets for the invading phase
Parameters
----------
pores : ndarray
The indices of the pores from which the invading fluid invasion
should start
mode : str or list of str, optional
Controls how the boundar... | set_inlet_BC | python | PMEAL/OpenPNM | openpnm/algorithms/_invasion_percolation.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_invasion_percolation.py | MIT |
def run(self):
r"""
Performs the algorithm for the given number of steps
"""
# Setup arrays and info
# TODO: This should be called conditionally so that it doesn't
# overwrite existing data when doing a few steps at a time
self._run_setup()
n_steps = np.i... |
Performs the algorithm for the given number of steps
| run | python | PMEAL/OpenPNM | openpnm/algorithms/_invasion_percolation.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_invasion_percolation.py | MIT |
def pc_curve(self):
r"""
Get the percolation data as the non-wetting phase saturation vs the
capillary pressure.
"""
net = self.project.network
pvols = net[self.settings['pore_volume']]
tvols = net[self.settings['throat_volume']]
tot_vol = np.sum(pvols) +... |
Get the percolation data as the non-wetting phase saturation vs the
capillary pressure.
| pc_curve | python | PMEAL/OpenPNM | openpnm/algorithms/_invasion_percolation.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_invasion_percolation.py | MIT |
def apply_trapping(self):
r"""
Adjusts the invasion sequence of pores and throats that are trapped.
This method uses the reverse invasion percolation procedure outlined
by Masson [1].
Returns
-------
This function does not return anything. It adjusts the
... |
Adjusts the invasion sequence of pores and throats that are trapped.
This method uses the reverse invasion percolation procedure outlined
by Masson [1].
Returns
-------
This function does not return anything. It adjusts the
``'pore.invasion_sequence'`` and ``'t... | apply_trapping | python | PMEAL/OpenPNM | openpnm/algorithms/_invasion_percolation.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_invasion_percolation.py | MIT |
def _run_accelerated(t_start, t_sorted, t_order, t_inv, p_inv, p_inv_t,
conns, idx, indptr, n_steps): # pragma: no cover
r"""
Numba-jitted run method for InvasionPercolation class.
Notes
-----
``idx`` and ``indptr`` are properties are the network's incidence
matrix, and ar... |
Numba-jitted run method for InvasionPercolation class.
Notes
-----
``idx`` and ``indptr`` are properties are the network's incidence
matrix, and are used to quickly find neighbor throats.
Numba doesn't like foreign data types (i.e. Network), and so
``find_neighbor_throats`` method cannot ... | _run_accelerated | python | PMEAL/OpenPNM | openpnm/algorithms/_invasion_percolation.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_invasion_percolation.py | MIT |
def set_source(self, pores, propname, mode="add"):
r"""
Applies a given source term to the specified pores
Parameters
----------
pores : array_like
The pore indices where the source term should be applied.
propname : str
The property name of the s... |
Applies a given source term to the specified pores
Parameters
----------
pores : array_like
The pore indices where the source term should be applied.
propname : str
The property name of the source term model to be applied.
mode : str
... | set_source | python | PMEAL/OpenPNM | openpnm/algorithms/_reactive_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_reactive_transport.py | MIT |
def _apply_sources(self):
"""
Updates ``A`` and ``b``, applying source terms to specified pores.
Notes
-----
Phase and physics objects are also updated before applying source
terms to ensure that source terms values are associated with the
current value of 'quant... |
Updates ``A`` and ``b``, applying source terms to specified pores.
Notes
-----
Phase and physics objects are also updated before applying source
terms to ensure that source terms values are associated with the
current value of 'quantity'.
| _apply_sources | python | PMEAL/OpenPNM | openpnm/algorithms/_reactive_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_reactive_transport.py | MIT |
def _run_special(self, solver, x0, verbose=None):
r"""
Repeatedly updates ``A``, ``b``, and the solution guess within
according to the applied source term then calls ``_solve`` to
solve the resulting system of linear equations.
Stops when the max-norm of the residual drops by at... |
Repeatedly updates ``A``, ``b``, and the solution guess within
according to the applied source term then calls ``_solve`` to
solve the resulting system of linear equations.
Stops when the max-norm of the residual drops by at least
``f_rtol``:
``norm(R_n) < norm(R_0... | _run_special | python | PMEAL/OpenPNM | openpnm/algorithms/_reactive_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_reactive_transport.py | MIT |
def _get_progress(self, res):
"""
Returns an approximate value for completion percent of Newton iterations.
"""
if not hasattr(self, "_f0_norm"):
self._f0_norm = norm(res)
f_rtol = self.settings.f_rtol
norm_reduction = norm(res) / self._f0_norm / f_rtol
... |
Returns an approximate value for completion percent of Newton iterations.
| _get_progress | python | PMEAL/OpenPNM | openpnm/algorithms/_reactive_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_reactive_transport.py | MIT |
def _get_residual(self, x=None):
r"""
Calculates solution residual based on the given ``x`` based on the
following formula:
``R = A * x - b``
"""
if x is None:
x = self.x
return self.A * x - self.b |
Calculates solution residual based on the given ``x`` based on the
following formula:
``R = A * x - b``
| _get_residual | python | PMEAL/OpenPNM | openpnm/algorithms/_reactive_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_reactive_transport.py | MIT |
def interpolate(self, x):
"""
Interpolates solution at point 'x'.
Parameters
----------
x : float
Point at which the solution is to be interpolated
Returns
-------
ndarray
Solution interpolated at the given point 'x'
"""
... |
Interpolates solution at point 'x'.
Parameters
----------
x : float
Point at which the solution is to be interpolated
Returns
-------
ndarray
Solution interpolated at the given point 'x'
| interpolate | python | PMEAL/OpenPNM | openpnm/algorithms/_solution.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_solution.py | MIT |
def run(self, x0, tspan, saveat=None, integrator=None):
"""
Runs the transient algorithm and returns the solution.
Parameters
----------
x0 : ndarray or float
Array (or scalar) containing initial condition values.
tspan : array_like
Tuple (or arra... |
Runs the transient algorithm and returns the solution.
Parameters
----------
x0 : ndarray or float
Array (or scalar) containing initial condition values.
tspan : array_like
Tuple (or array) containing the integration time span.
saveat : array_lik... | run | python | PMEAL/OpenPNM | openpnm/algorithms/_transient_reactive_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_transient_reactive_transport.py | MIT |
def _build_rhs(self):
"""
Returns a function handle, which calculates dy/dt = rhs(y, t).
Notes
-----
``y`` is the variable that the algorithms solves for, e.g., for
``TransientFickianDiffusion``, it would be concentration.
"""
def ode_func(t, y):
... |
Returns a function handle, which calculates dy/dt = rhs(y, t).
Notes
-----
``y`` is the variable that the algorithms solves for, e.g., for
``TransientFickianDiffusion``, it would be concentration.
| _build_rhs | python | PMEAL/OpenPNM | openpnm/algorithms/_transient_reactive_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_transient_reactive_transport.py | MIT |
def _build_A(self):
"""
Builds the coefficient matrix based on throat conductance values.
Notes
-----
The conductance to use is specified in stored in the algorithm's
settings under ``alg.settings['conductance']``.
"""
gvals = self.settings['conductance'... |
Builds the coefficient matrix based on throat conductance values.
Notes
-----
The conductance to use is specified in stored in the algorithm's
settings under ``alg.settings['conductance']``.
| _build_A | python | PMEAL/OpenPNM | openpnm/algorithms/_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_transport.py | MIT |
def _build_b(self):
"""Initializes the RHS vector, b, with zeros."""
b = np.zeros(self.Np, dtype=float)
self._pure_b = b
self.b = self._pure_b.copy() | Initializes the RHS vector, b, with zeros. | _build_b | python | PMEAL/OpenPNM | openpnm/algorithms/_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_transport.py | MIT |
def b(self):
"""The right-hand-side (RHS) vector, b (in Ax = b)"""
if self._b is None:
self._build_b()
return self._b | The right-hand-side (RHS) vector, b (in Ax = b) | b | python | PMEAL/OpenPNM | openpnm/algorithms/_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_transport.py | MIT |
def _apply_BCs(self):
"""Applies specified boundary conditions by modifying A and b."""
if 'pore.bc.rate' in self.keys():
# Update b
ind = np.isfinite(self['pore.bc.rate'])
self.b[ind] = self['pore.bc.rate'][ind]
if 'pore.bc.value' in self.keys():
... | Applies specified boundary conditions by modifying A and b. | _apply_BCs | python | PMEAL/OpenPNM | openpnm/algorithms/_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_transport.py | MIT |
def run(self, solver=None, x0=None, verbose=False):
"""
Builds the A and b matrices, and calls the solver specified in the
``settings`` attribute.
This method stores the solution in the algorithm's ``soln``
attribute as a ``SolutionContainer`` object. The solution itself
... |
Builds the A and b matrices, and calls the solver specified in the
``settings`` attribute.
This method stores the solution in the algorithm's ``soln``
attribute as a ``SolutionContainer`` object. The solution itself
is stored in the ``x`` attribute of the algorithm as a NumPy a... | run | python | PMEAL/OpenPNM | openpnm/algorithms/_transport.py | https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_transport.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.