Skip to content

I/O

load_assemblies(file_path)

Load assemblies and components from a YAML file.

Parameters:

Name Type Description Default
file_path PathLike | str

Path to the YAML file to load.

required

Returns:

Type Description
list[Assembly]

List of loaded assemblies.

Examples:

>>> from nasap_net import load_assemblies
>>> assemblies = load_assemblies('assemblies.yaml')
Source code in src/nasap_net/io/assemblies/loading.py
def load_assemblies(
        file_path: os.PathLike | str,
) -> list[Assembly]:
    """Load assemblies and components from a YAML file.

    Parameters
    ----------
    file_path : os.PathLike | str
        Path to the YAML file to load.

    Returns
    -------
    list[Assembly]
        List of loaded assemblies.

    Examples
    --------
    >>> from nasap_net import load_assemblies
    >>> assemblies = load_assemblies('assemblies.yaml')
    """
    file_path = Path(file_path)

    yaml_str = file_path.read_text(encoding="utf-8")
    assemblies = load_assemblies_from_str(yaml_str)
    logger.info('Loaded %d assemblies from "%s"', len(assemblies), str(file_path))
    return assemblies

load_reactions(file_path, assemblies, *, assembly_id_type='str', component_id_type='str', site_id_type='str', reaction_id_type='str', has_index_column=False)

Load reactions from a CSV file and convert to Reaction objects.

Parameters:

Name Type Description Default
file_path PathLike | str

Path to the CSV file to load.

required
assemblies Iterable[Assembly]

Assemblies referenced by the reactions. Must have unique IDs.

required
assembly_id_type (str, int)

Type to cast assembly IDs to. Default is 'str'.

'str'
component_id_type (str, int)

Type to cast component IDs to. Default is 'str'.

'str'
site_id_type (str, int)

Type to cast site IDs to. Default is 'str'.

'str'
reaction_id_type (str, int)

Type to cast reaction IDs to. Default is 'str'.

'str'
has_index_column bool

If True, the first column is treated as a row index. Default is False.

False

Returns:

Type Description
list[Reaction]

List of loaded reactions.

Examples:

>>> from nasap_net import load_reactions
>>> reactions = load_reactions('reactions.csv', assemblies=assemblies)
Source code in src/nasap_net/io/reactions/loading.py
def load_reactions(
        file_path: os.PathLike | str,
        assemblies: Iterable[Assembly],
        *,
        assembly_id_type: Literal['str', 'int'] = 'str',
        component_id_type: Literal['str', 'int'] = 'str',
        site_id_type: Literal['str', 'int'] = 'str',
        reaction_id_type: Literal['str', 'int'] = 'str',
        has_index_column: bool = False,
) -> list[Reaction]:
    """Load reactions from a CSV file and convert to Reaction objects.

    Parameters
    ----------
    file_path : os.PathLike | str
        Path to the CSV file to load.
    assemblies : Iterable[Assembly]
        Assemblies referenced by the reactions. Must have unique IDs.
    assembly_id_type : {'str', 'int'}, optional
        Type to cast assembly IDs to. Default is ``'str'``.
    component_id_type : {'str', 'int'}, optional
        Type to cast component IDs to. Default is ``'str'``.
    site_id_type : {'str', 'int'}, optional
        Type to cast site IDs to. Default is ``'str'``.
    reaction_id_type : {'str', 'int'}, optional
        Type to cast reaction IDs to. Default is ``'str'``.
    has_index_column : bool, optional
        If True, the first column is treated as a row index. Default is False.

    Returns
    -------
    list[Reaction]
        List of loaded reactions.

    Examples
    --------
    >>> from nasap_net import load_reactions
    >>> reactions = load_reactions('reactions.csv', assemblies=assemblies)
    """
    validate_unique_ids(assemblies)
    id_to_assembly = {assembly.id_: assembly for assembly in assemblies}

    file_path = Path(file_path)
    if not file_path.exists():
        raise FileNotFoundError(f'File "{str(file_path)}" does not exist.')

    df = pd.read_csv(
        file_path,
        index_col=0 if has_index_column else None,
    )
    df = df.astype(object).where(pd.notnull(df), None)  # type: ignore[call-overload]

    types = {'int': int, 'str': str}

    reaction_rows = [
        ReactionRow.from_dict(
            row,
            assembly_id_type=types[assembly_id_type],
            component_id_type=types[component_id_type],
            site_id_type=types[site_id_type],
            reaction_id_type=types[reaction_id_type],
        )
        for row in df.to_dict(orient="records")
    ]

    reactions = [
        reaction_row_to_reaction(reaction_row, id_to_assembly)
        for reaction_row in reaction_rows
    ]

    logger.info('Loaded %d reactions from "%s"', len(reactions), str(file_path))

    return reactions

save_assemblies(assemblies, file_path, *, overwrite=False)

Dump assemblies and components into a YAML file.

Parameters:

Name Type Description Default
assemblies Iterable[Assembly]

Assemblies to dump.

required
file_path PathLike | str

Path to the YAML file to write.

required
overwrite bool

If True, overwrite the file if it already exists. If False, raise an error if the file already exists. Default is False.

False

Examples:

>>> from nasap_net import save_assemblies
>>> save_assemblies(assemblies, 'assemblies.yaml')
>>> save_assemblies(assemblies, 'assemblies.yaml', overwrite=True)
Source code in src/nasap_net/io/assemblies/saving.py
def save_assemblies(
        assemblies: Iterable[Assembly],
        file_path: os.PathLike | str,
        *,
        overwrite: bool = False,
        ) -> None:
    """Dump assemblies and components into a YAML file.

    Parameters
    ----------
    assemblies : Iterable[Assembly]
        Assemblies to dump.
    file_path : os.PathLike | str
        Path to the YAML file to write.
    overwrite : bool, optional
        If True, overwrite the file if it already exists.
        If False, raise an error if the file already exists.
        Default is False.

    Examples
    --------
    >>> from nasap_net import save_assemblies
    >>> save_assemblies(assemblies, 'assemblies.yaml')
    >>> save_assemblies(assemblies, 'assemblies.yaml', overwrite=True)
    """
    file_path = Path(file_path)
    if file_path.exists() and not overwrite:
        raise FileExistsError(
            f'File "{str(file_path)}" already exists. '
            'Use `overwrite=True` to overwrite it.'
        )

    assemblies = list(assemblies)

    file_path.parent.mkdir(parents=True, exist_ok=True)
    yaml_str = dump_assemblies_to_str(assemblies)
    file_path.write_text(yaml_str, encoding="utf-8")
    logger.info('Saved %d assemblies to "%s"', len(assemblies), str(file_path))

save_reactions(reactions, file_path, *, overwrite=False, index=False)

Save reactions to a CSV file.

Resulting CSV columns:

  • init_assem_id : str | int
  • entering_assem_id : str | int | None
  • product_assem_id : str | int
  • leaving_assem_id : str | int | None
  • metal_bs_component : str | int
  • metal_bs_site : str | int
  • leaving_bs_component : str | int
  • leaving_bs_site : str | int
  • entering_bs_component : str | int
  • entering_bs_site : str | int
  • duplicate_count : int
  • id : str | int | None

Parameters:

Name Type Description Default
reactions Iterable[Reaction]

Reactions to save.

required
file_path PathLike | str

Path to the CSV file to write.

required
overwrite bool

If True, overwrite the file if it already exists. If False, raise an error if the file already exists. Default is False.

False
index bool

If True, write row names (index). Default is False.

False

Examples:

>>> from nasap_net import save_reactions
>>> save_reactions(reactions, 'reactions.csv')
>>> save_reactions(reactions, 'reactions.csv', overwrite=True)
Source code in src/nasap_net/io/reactions/saving.py
def save_reactions(
        reactions: Iterable[Reaction],
        file_path: os.PathLike | str,
        *,
        overwrite: bool = False,
        index: bool = False,
        ) -> None:
    """Save reactions to a CSV file.

    Resulting CSV columns:

    - init_assem_id : str | int
    - entering_assem_id : str | int | None
    - product_assem_id : str | int
    - leaving_assem_id : str | int | None
    - metal_bs_component : str | int
    - metal_bs_site : str | int
    - leaving_bs_component : str | int
    - leaving_bs_site : str | int
    - entering_bs_component : str | int
    - entering_bs_site : str | int
    - duplicate_count : int
    - id : str | int | None

    Parameters
    ----------
    reactions : Iterable[Reaction]
        Reactions to save.
    file_path : os.PathLike | str
        Path to the CSV file to write.
    overwrite : bool, optional
        If True, overwrite the file if it already exists.
        If False, raise an error if the file already exists.
        Default is False.
    index : bool, optional
        If True, write row names (index). Default is False.

    Examples
    --------
    >>> from nasap_net import save_reactions
    >>> save_reactions(reactions, 'reactions.csv')
    >>> save_reactions(reactions, 'reactions.csv', overwrite=True)
    """
    file_path = Path(file_path)
    if file_path.exists() and not overwrite:
        raise FileExistsError(
            f'File "{str(file_path)}" already exists. '
            'Use `overwrite=True` to overwrite it.'
        )

    reactions = list(reactions)
    df = reactions_to_df(reactions)

    file_path.parent.mkdir(parents=True, exist_ok=True)
    df.to_csv(file_path, index=index)
    logger.info('Saved %d reactions to "%s"', len(reactions), str(file_path))

save_classification_result(reaction_to_class, file_path, *, overwrite=False, index=False)

Save the classification result to a CSV file.

Resulting CSV columns:

  • init_assem_id : str | int
  • entering_assem_id : str | int | None
  • product_assem_id : str | int
  • leaving_assem_id : str | int | None
  • metal_bs_component : str | int
  • metal_bs_site : str | int
  • leaving_bs_component : str | int
  • leaving_bs_site : str | int
  • entering_bs_component : str | int
  • entering_bs_site : str | int
  • duplicate_count : int
  • id : str | int | None
  • reaction_class : str

Parameters:

Name Type Description Default
reaction_to_class Mapping[Reaction, str]

Mapping from Reaction objects to their corresponding class labels.

required
file_path PathLike | str

Path to the CSV file to write.

required
overwrite bool

If True, overwrite the file if it already exists. If False, raise an error if the file already exists. Default is False.

False
index bool

If True, write row names (index). Default is False.

False

Examples:

>>> from nasap_net import save_classification_result
>>> save_classification_result(reaction_to_class, 'classification.csv')
Source code in src/nasap_net/io/classification_result/saving.py
def save_classification_result(
        reaction_to_class: Mapping[Reaction, str],
        file_path: os.PathLike | str,
        *,
        overwrite: bool = False,
        index: bool = False,
        ) -> None:
    """Save the classification result to a CSV file.

    Resulting CSV columns:

    - init_assem_id : str | int
    - entering_assem_id : str | int | None
    - product_assem_id : str | int
    - leaving_assem_id : str | int | None
    - metal_bs_component : str | int
    - metal_bs_site : str | int
    - leaving_bs_component : str | int
    - leaving_bs_site : str | int
    - entering_bs_component : str | int
    - entering_bs_site : str | int
    - duplicate_count : int
    - id : str | int | None
    - reaction_class : str

    Parameters
    ----------
    reaction_to_class : Mapping[Reaction, str]
        Mapping from Reaction objects to their corresponding class labels.
    file_path : os.PathLike | str
        Path to the CSV file to write.
    overwrite : bool, optional
        If True, overwrite the file if it already exists.
        If False, raise an error if the file already exists.
        Default is False.
    index : bool, optional
        If True, write row names (index). Default is False.

    Examples
    --------
    >>> from nasap_net import save_classification_result
    >>> save_classification_result(reaction_to_class, 'classification.csv')
    """
    file_path = Path(file_path)
    if file_path.exists() and not overwrite:
        raise FileExistsError(
            f'File "{str(file_path)}" already exists. '
            'Use `overwrite=True` to overwrite it.'
        )

    df = classification_result_to_df(reaction_to_class)

    file_path.parent.mkdir(parents=True, exist_ok=True)
    df.to_csv(file_path, index=index)
    logger.info(
        'Saved %d reactions to "%s"',
        len(reaction_to_class),
        str(file_path)
    )