Skip to content

# file.py

# `` create_dir

    create_dir(dir: str) -> str

Try to create an output directory if one doesn't exist.

Throws an exception if the directory cannot be created. Returns quietly if the directory already exists.

Parameters:

- ## `dir`

  (`str`) –

  name of directory

Returns:

- `str` –

  path to directory.

Source code in `.venv/lib/python3.14/site-packages/langevin/base/file.py`

    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    def create_dir(dir: str) -> str:
        """
        Try to create an output directory if one doesn't exist.

        Throws an exception if the directory cannot be created.
        Returns quietly if the directory already exists.

        Args:
            dir:
                name of directory

        Returns:
            path to directory.
        """
        try:
            if not exists(dir):
                mkdir(dir)
            else:
                return dir
        except OSError:
            print(f'Cannot create directory "{realpath(dir)}"')
            raise
        except Exception:
            print(Exception)
            raise
        return dir

# `` create_directories

    create_directories(
        results_path: Sequence = ("..", "experiments"),
        results_dir: str = "Demo",
        do_clean: bool = False,
    ) -> str

Create results parent and target directory.

Parameters:

- ## `results_path`

  (`Sequence`, default: `('..', 'experiments')` ) –

  path to parent results directory (to be created if necessary)

- ## `results_dir`

  (`str`, default: `'Demo'` ) –

  target results directory (to be created)

Returns:

- `str` –

  path to target results directory.

Source code in `.venv/lib/python3.14/site-packages/langevin/base/file.py`

    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    def create_directories(
            results_path: Sequence = ("..", "experiments",),
            results_dir: str = "Demo",
            do_clean: bool=False,
        ) -> str:
        """
        Create results parent and target directory.

        Args:
            results_path: path to parent results directory
                (to be created if necessary)
            results_dir: target results directory (to be created)

        Returns:
            path to target results directory.
        """
        results_path_ = ["."] + list(results_path)
        create_dir(join(*results_path_))
        results_dir_ = results_path_ + [results_dir]
        if do_clean and exists(join(*results_dir_)):
            rmtree(join(*results_dir_))
        return create_dir(join(*results_dir_))

# `` export_info

    export_info(
        info_dir: str,
        file_name: str,
        source_dict: dict,
        module: Any,
        suffix: str | None = None,
        encoding: str = "utf-8",
    ) -> tuple[dict, str]

Export results dictionary to JSON file.

Tries to ensure all dictionary entries are serializable by running `latex` on keys and converting values to floats.

Parameters:

- ## `info_dir`

  (`str`) –

  target parent folder

- ## `file_name`

  (`str`) –

  name of output JSON file

- ## `module`

  (`Any`) –

  dplvn or other class module

- ## `source_dict`

  (`dict`) –

  dictionary of results, possibly requiring conversion from latex form such that serialization into a JSON file is possible

- ## `suffix`

  (`str | None`, default: `None` ) –

  to append to filename prior to addition of '.json' extension

Returns:

- `tuple[dict, str]` –

  serialized dictionary and the file path string

Source code in `.venv/lib/python3.14/site-packages/langevin/base/file.py`

    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    def export_info(
            info_dir: str,
            file_name: str,
            source_dict: dict,
            module: Any,
            suffix: str | None = None,
            encoding: str = "utf-8", #"latin-1"
        ) -> tuple[dict, str]:
        """
        Export results dictionary to JSON file.

        Tries to ensure all dictionary entries are
        serializable by running `latex`
        on keys and converting values to floats.

        Args:
            info_dir: target parent folder
            file_name: name of output JSON file
            module: dplvn or other class module
            source_dict: dictionary of results, possibly requiring conversion
                from latex form such that serialization into a JSON file
                is possible
            suffix: to append to filename prior to addition of '.json' extension

        Returns:
            serialized dictionary and the file path string
        """
        # A bit of recursion for a change
        def render_serializable(source, module,) -> dict:
            serialized: dict = {}
            for item_ in source.items():
                if type(item_[1]) is dict:
                    serialized.update(
                        {item_[0]: render_serializable(item_[1], module,)}
                    )
                else:
                    serialized.update(
                        {item_[0]: to_serializable(item_[1], module,)}
                    )
            return serialized

        serializable_dict: dict = render_serializable(source_dict, module,)
        info_path = [str(info_dir)] + [
            str(file_name) + ("_"+suffix if suffix is not None else "") + ".json"
        ]

        file: TextIOWrapper
        with open(join(*info_path), "w", encoding=encoding,) as file:
            logging.info(join(*info_path))
            dump(serializable_dict, file, indent=4, ensure_ascii=False,) #separators=(", \n", ": ")
        return (serializable_dict, info_dir,)

# `` export_plot

    export_plot(
        fig_name: str,
        fig: Any,
        results_dir: str,
        file_type: str = "pdf",
        suffix: str = "",
        dpi: int | None = None,
    ) -> None

Export plot to PDF or other format file.

Parameters:

- ## `fig_name`

  (`str`) –

  name to be used for file (extension auto-appended)

- ## `fig`

  (`Any`) –

  figure object

- ## `results_dir`

  (`str`) –

  name of output directory

- ## `file_type`

  (`str`, default: `'pdf'` ) –

  file format

- ## `suffix`

  (`str`, default: `''` ) –

  filename suffix

- ## `dpi`

  (`int | None`, default: `None` ) –

  output image resolution

Source code in `.venv/lib/python3.14/site-packages/langevin/base/file.py`

    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    def export_plot(
            fig_name: str,
            fig: Any,
            results_dir: str,
            file_type: str = "pdf",
            suffix: str = "",
            dpi: int | None = None,
        ) -> None:
        """
        Export plot to PDF or other format file.

        Args:
            fig_name: name to be used for file (extension auto-appended)
            fig: figure object
            results_dir: name of output directory
            file_type: file format
            suffix: filename suffix
            dpi: output image resolution
        """
        fig_name_ = f"{fig_name}{suffix}.{file_type.lower()}"
        # print(f"{fig_name_} exists: {exists(join(results_dir, fig_name_))}")
        try:
            # logging.info(f'dpi={dpi}')
            fig.savefig(
                join(results_dir, fig_name_),
                bbox_inches="tight",
                pad_inches=0.05,
                dpi=dpi,
                format=file_type,
            )
            logging.info(f'export_plot: Exported "{fig_name_}"')
        except OSError:
            logging.info(
                f'export_plot: Failed to export figure "{fig_name_}"'
            )
            raise
        except:
            raise

# `` export_plots

    export_plots(
        fig_dict: dict,
        results_dir: str,
        file_types: list[str] | tuple[str] | str = "png",
        suffix: str = "",
        dpi: int = 150,
        do_verbose: bool = False,
    ) -> str

Export plots to PDF or other format files.

Parameters:

- ## `fig_dict`

  (`dict`) –

  dictionary of figures

- ## `results_dir`

  (`str`) –

  name of output directory

- ## `file_types`

  (`list[str] | tuple[str] | str`, default: `'png'` ) –

  file format (or list of file formats)

- ## `suffix`

  (`str`, default: `''` ) –

  filename suffix

- ## `dpi`

  (`int`, default: `150` ) –

  output image resolution

- ## `do_verbose`

  (`bool`, default: `False` ) –

  use tqdm progress bar to track

Returns:

- `str` –

  the supplied export directory

Source code in `.venv/lib/python3.14/site-packages/langevin/base/file.py`

    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    def export_plots(
            fig_dict: dict,
            results_dir: str,
            file_types: list[str] | tuple[str] | str = "png",
            suffix: str = "",
            dpi: int = 150,
            do_verbose: bool=False,
        ) -> str:
        """
        Export plots to PDF or other format files.

        Args:
            fig_dict: dictionary of figures
            results_dir: name of output directory
            file_types: file format (or list of file formats)
            suffix: filename suffix
            dpi: output image resolution
            do_verbose: use tqdm progress bar to track

        Returns:
            the supplied export directory
        """
        results_path: str = realpath(results_dir)
        logging.info(
            "gmplib.save.export_plots:\n   " + f'Writing to dir: "{results_path}"'
        )
        file_types_: List[str] = (
            file_types if isinstance(file_types, list) else [str(file_types)]
        )
        progress_bar: Callable = (
            progress if do_verbose else progress_disabled
        )
        for file_type in file_types_:
            # logging.info(f'Image file type: "{file_type}"')
            for fig_name, fig in progress_bar(fig_dict.items(),):
                export_plot(
                    fig_name, fig,
                    results_path,
                    file_type=file_type,
                    suffix=suffix,
                    dpi=dpi,
                )
        return results_dir

# `` import_info

    import_info(info_dir: str, file_name: str, module: Any) -> dict

Read and adapt parameters specified in a JSON file.

Parameters:

- ## `info_dir`

  (`str`) –

  parent folder of JSON file

- ## `file_name`

  (`str`) –

  JSON file name.

- ## `module`

  (`Any`) –

  dplvn or other class module

Returns: info as dictionary.

Source code in `.venv/lib/python3.14/site-packages/langevin/base/file.py`

     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    def import_info(
            info_dir: str,
            file_name: str,
            module: Any,
            # encoding: str = "utf-8",
        ) -> dict:
        """
        Read and adapt parameters specified in a JSON file.

        Args:
            info_dir: parent folder of JSON file
            file_name:  JSON file name.
            module: dplvn or other class module

        Returns: info as dictionary.
        """
        file: TextIOWrapper
        raw_info: dict
        info_path = [str(info_dir)] + [f"{file_name}.json"]
        with open(join(*info_path), "rb",) as file:
            raw_info = load(file)
        parameters: dict = {}
        for item_ in raw_info["Parameters"].items():
            parameters.update({item_[0]: from_serializable(item_[1], module)})
        info: dict = {
            "Analysis": raw_info["Analysis"],
            "Parameters": parameters,
            "Misc":  raw_info["Misc"]
        }
        return info

# `` read_info

    read_info(path: Sequence[str], module: Any) -> tuple[str, dict]

Wrapper around method to import info dictionary.

Parameters:

- ## `path`

  (`Sequence[str]`) –

  to info JSON file.

- ## `module`

  (`Any`) –

  dplvn or other class module

Returns:

- `tuple[str, dict]` –

  path to file and imported dictionary

Source code in `.venv/lib/python3.14/site-packages/langevin/base/file.py`

    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    def read_info(
            path: Sequence[str],
            module: Any,
            # encoding: str = "utf-8",
        ) -> tuple[str, dict]:
        """
        Wrapper around method to import info dictionary.

        Args:
            path: to info JSON file.
            module: dplvn or other class module

        Returns:
            path to file and imported dictionary
        """
        full_path: str = join(*path,)
        info: dict = import_info(full_path, "Info", module,)
        return (full_path, info,)