Skip to main content

About

filo is a Python 3 package for file management and analysis of file series. Its main purpose is to provide a FileSeries class to manage series of files (e.g. series of images or series of spectra from time-lapse experiments), possibly spread out across multiple folders, using a custom File class. In particular, file creation time is detected automatically and can be accessed as a pandas dataframe.

On top of that, the package provides:

  • Results storage: a ResultsBase base class to store analysis results and metadata and save/load them into/from files (with a ready-made single-file HDF5 backend, HDF5Results, and SingleFileResultsBase for other single-file formats;
  • Data series and analysis framework: DataSeries (raw data + metadata of a file series), AnalysisBase (base class to define analyses on data series), with supporting modules for reading raw files (readers), interactive viewing (viewers), analysis parameters (parameters), output formatting (formatters), and parallel processing (multiprocess);
  • Utilities: resampling of dataframes, csv/json file io, and misc file handling functions (list, move, rename files, ...).

See summary of functions and classes below, and associated docstrings for details. The notebooks ExampleDataSeries.ipynb, ExampleFileSeries.ipynb and ExampleResample.ipynb also provide interactive examples.

Install

pip install filo
pip install filo[hdf5]  # in case HDF5Results is used

Contents

  • FileSeries class: manage series of files (images, spectra, ...) potentially spread over multiple folders, with automatic creation-time tracking (File objects, info DataFrame)

  • Results classes: store experimental, simulation, or analysis data (+ metadata) and save/load them

    • ResultsBase: generic base class (custom file formats) for saving metadata and data to different files
    • SingleFileResultsBase / HDF5Results: subclasses to save to a single file backends (e.g., HDF5)
  • Data and data analysis: DataSeries, AnalysisBase, ...

  • Other modules: viewers, readers, parameters, formatters, multiprocess, json/csv I/O

  • Resampling: create_bins_centered_on(), resample_dataframe()

  • Misc. functions: list/move/rename files, csv line formatting, make_iterable

  • Tests

  • Requirements, Author, License

FileSeries class

Class to manage series of files of the same type (e.g. image series or spectra series from time-lapse experiments), possibly spread out across multiple folders. The main purpose of the class is to be subclassed in other modules specialized for analysis of specific experiment types, but it can be used as is, i.e. to extract timing info of series of files.

The main idea is that files are attributed a unique identifier (num) that starts at 0 in the first folder. Each file is described by an object of the File class that stores file path, identifier, and a time attribute.

Note: the time attribute is automatically extracted as the creation time of the file (st_mtime), but can be overwritten with external information, or can be defined differently by subclassing the _measure_times() method.

The list of file objects is accessed through the list FileSeries.files containing all filo.File objects (FileSeries.files[i] is the file object with identifier num=i). The correspondence between identifier, actual files, and file times is summarized in the FileSeries.info attribute, which is a pandas DataFrame tied to FileSeries.files, and which can be saved into a csv file. Loading options also exist to update file data using data stored in external files.

FileSeries Methods

  • save_info(): save info of files into csv file,
  • load_info(): load info of files from csv file (overwrites self.files),
  • load_time(): keep current file info but only update time from info in csv file.

FileSeries Attributes and properties

Regular attributes

  • folders: list of folders (pathlib.Path objects) across which the file series is spread,
  • files: list of files (filo.File objects, see below); self.files[num] is the file of identifier num,
  • savepath: directory in which data extracted/analyzed from files is saved, if applicable,
  • extension: extension of the files (str).

Read-only properties

(derived from regular attributes and methods)

  • info: pandas DataFrame containing info (number, folder, filename, time) time of files; re-calculated every time self.info is called and thus reflects changes in self.files.
  • duration: datetime.Timedelta object, time difference between last file and first file in the series

File objects

File objects listed in FileSeries.files have the following attributes:

  • path: Pathlib object of the file,
  • num: identifier of file within (int). In the series context, num starts at 0 in the first folder,
  • time: stores unix time (float, in seconds) when FileSeries.set_times() is called,

with the following additional read-only properties derived from the ones above for convenience

  • folder Pathlib object of the parent directory containing the file,
  • name: filename (str).

Examples

(See ExampleFileSeries.ipynb for examples with actual data).

from filo import FileSeries

# create series object of .png files located in 2 folders img1 and img2 ------
series = FileSeries(paths=['img1', 'img2'], savepath='analysis', extension='.png')

# Access individual files in the file series ---------------------------------
series.files[0]        # first file in the first folder
series.files[3].path   # actual pathlib object
series.files[55].num   # should always be equal to 55
series.files[10].time  # unix time of file creation

# Manage the infos DataFrame -------------------------------------------------
series.info         # see all file info in form of a pandas DataFrame
series.save_info()  # save info into 'FileFileSeries_Info.txt' (filename can be specified)

# Update FileSeries.files objects and FileSeries.info --------------------------------
series.load_info('Other_File_Info.txt')  # update all file data using data from external file
series.load_time('Other_File_Info.txt')   # update time information but keep other info
series.save_info('FileFileSeries_Info_New.txt')  # save updated info into new txt file

Results classes

ResultsBase

ResultsBase is a base class for objects that store analysis results (the data attribute, any Python object) together with metadata (the metadata attribute, a dict) and know how to save/load them to/from files.

The file handling is generic and driven by class attributes:

  • extensions and filename_adds: for each kind ('data', 'metadata'), which file extension(s) and filename additions to use - this allows e.g. one .tsv + one .json file (the defaults), or a single shared file (see SingleFileResultsBase below);
  • load_methods / save_methods: which methods to call for each kind.

To make a results class file-compatible, subclass it and redefine the four hooks (the filepath is computed for you from the attributes above):

  • _save_data(self, data, filepath): write self.data-shaped object to file
  • _load_data(self, filepath): read it back
  • _save_metadata(self, metadata, filepath): write metadata dict to file
  • _load_metadata(self, filepath): read it back

Minimal example (data as .npy, metadata as .json):

import json
import numpy as np
from filo import ResultsBase

class ArrayResults(ResultsBase):
    default_filename = "results"
    extensions = {"data": (".npy",), "metadata": (".json",)}
    filename_adds = {"data": ("_data",), "metadata": ("_meta",)}

    def default_data(self):
        return {"x": np.array([])}

    def default_metadata(self):
        return {"comment": ""}

    def _save_data(self, data, filepath):
        np.save(filepath, data["x"])

    def _load_data(self, filepath):
        return {"x": np.load(filepath)}

    def _save_metadata(self, metadata, filepath):
        with open(filepath, "w") as f:
            json.dump(metadata, f)

    def _load_metadata(self, filepath):
        with open(filepath) as f:
            return json.load(f)

res = ArrayResults(savepath=".")
res.data["x"] = np.linspace(0, 1, 5)
res.metadata["comment"] = "demo"
res.save("run")                              # writes run_data.npy + run_meta.json
res2 = ArrayResults.from_file("run", savepath=".")
res2.data["x"]                            # array([0. , 0.25, 0.5 , 0.75, 1. ])

Then it provides the following methods and attributes:

Methods

  • save(): save analysis data and metadata
  • load(): load analysis data and metadata from files (stores them in the data and metadata attributes; see below)
  • from_file(): classmethod; load a saved results object in one call
  • load_data(): load and return data loaded from file
  • load_metadata(): load and return dictionary of metadata loaded from file
  • save_data(): save only data
  • save_metadata(): save only metadata

Attributes

  • data, analysis data
  • metadata, analysis metadata
  • format_description, format_version: optional class attributes identifying the file format (e.g. written as root attributes of HDF5 files, checked with a warning on load)

HDF5Results (and SingleFileResultsBase)

SingleFileResultsBase is a ResultsBase variant that stores all kinds (data, metadata) in one single file instead of one file per kind. It is abstract: subclasses must set the extension class attribute (e.g. '.h5', or '.hdf5'); extensions/filename_adds are then derived automatically.

HDF5Results (requires pip install filo[hdf5]) is a ready-to-use HDF5 backend:

from filo import HDF5Results

class MyResults(HDF5Results):
    default_filename = "run"
    format_description = "my results"
    format_version = "1.0"
    # extension = ".hdf5"   # optional, default ".h5"

    def default_data(self):
        return {"simulation": {"times": []}, "analysis": {}}

    def default_metadata(self):
        return {"simulation": {}, "analysis": {}}

res = MyResults(savepath=".")
res.data["simulation"]["times"] = [0.0, 0.5, 1.0]
res.save("run")                            # writes run.h5 (single file)
res2 = MyResults.from_file("run", savepath=".")

File layout of the .h5 file: root attributes "format description" / "format version", a data/ group (dict -> group, list of equal-shaped arrays -> one matrix dataset) and a metadata/ group (dict -> group, scalar -> attribute, None stored as ""). Re-saving the same filename overwrites the written entries in place (other entries are kept).

Data and data analysis

See analysis.py and data_series modules, with classes

  • DataSeries()
  • AnalysisBase() etc.

(see e.g. ExampleDataSeries.ipynb)

Resampling

Functions:

  • create_bins_centered_on()
  • resample_dataframe()

(see ExampleResample.ipynb)

Other modules

  • viewers.py: DataViewerBase, AnalysisViewerBase, FormattedAnalysisViewerBase, KeyPressSlider: base classes and interactive matplotlib tools for inspection of data series and analysis results.

  • readers.py: DataSeriesReaderBase: base class to read raw experiment files into a DataSeries.

  • parameters.py: ParameterBase, TransformParameterBase, CorrectionParameterBase: base classes for parameters applied to file/image series and analysis.

  • formatters.py: FormatterBase, PandasFormatterBase: base classes to format analysis output (e.g., text / pandas).

  • multiprocess.py: Multiprocess: convenience tool to run analysis on file series in parallel.

  • fileio.py: load_json(), to_json() - json load/dump helpers (alongside load_csv, data_to_line, line_to_data).

Misc. Functions

# List files and folders -----------------------------------------------------
list_files(path='.', extension='')  # all files in a folder, sorted by name
list_all(path='.')  # all contents of a folder, sorted by name

# Move files and folders -----------------------------------------------------
move_files(src='.', dst='.', extension='')  # move only files with some suffix
move_all(src='.', dst='.')  # move everything

# Line formatting for csv ----------------------------------------------------
load_csv(file, sep='\t', skiprows=2)  # load csv into list of lists
data_to_line(data, sep='\t')  # iterable data to a line with \n, separated with separator sep.
line_to_data(line, sep='\t', dtype=float) # "Inverse of data_to_line(). Returns data as a tuple of type dtype.

# Misc -----------------------------------------------------------------------
batch_file_rename(name, newname, path='.')  # rename recursively files named name into newname
make_iterable(x):  # Transform non-iterables into a tuple, but keeps iterables unchanged

Note: extension is optional, to consider only files with a certain extension, e.g. '.txt'. If left blank, all files considered (excluding directories).

Tests

pip install filo[test]
python -m pytest

Requirements

(installed automatically by pip if necessary)

  • python >= 3.8
  • pandas (for managing data in FileSeries class)
  • matplotlib (for interactive inspection of series data)
  • importlib-metadata

Optional:

  • h5py (for the HDF5Results backend; pip install filo[hdf5])

Author

Olivier Vincent (ovinc.py@gmail.com)

License

3-clause BSD (see LICENSE file)

Metadata

Release files for filo 2.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for filo 2.3.0
File Size Uploaded Provenance Actions
filo-2.3.0.tar.gz 5.0 MB Without provenance Details for filo-2.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for filo 2.3.0
File Interpreter ABI Platform Actions
filo-2.3.0-py3-none-any.whl Python 3 none any Details for filo-2.3.0-py3-none-any.whl

Total release size: 10.0 MB

Release files / filo-2.3.0.tar.gz

Download URL filo-2.3.0.tar.gz
Size 5.0 MB
Tags Source
SHA-256 checksum
How to use checksums
054e8ac3b120f20b10aecf352887c069cb52ffcaf0ad29f4f459c1733b6ef8f7
BLAKE2b-256 checksum
How to use checksums
98884b3149808cd6bb9eeb99a31fbb47429d8794bae1bf0f4d8dd2a98791bb95
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.10.16

Release files / filo-2.3.0-py3-none-any.whl

Download URL filo-2.3.0-py3-none-any.whl
Size 5.0 MB
Tags Python 3
SHA-256 checksum
How to use checksums
bebe1a14dee335c4cdbc3174b18bc4a3b23d385d84e0c4519f6be049afd514e9
BLAKE2b-256 checksum
How to use checksums
65ed039bb31ddb7a0ae66866c47e93977a570074ab92d3a1bed59d602466a25a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.10.16

Security for filo 2.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page