Metadata-Version: 2.4
Name: filo
Version: 2.3.0
Summary: Managing files and file series
Author-email: Olivier Vincent <ovinc.py@gmail.com>
License: BSD 3-Clause License
Project-URL: Homepage, https://github.com/ovinc/filo
Project-URL: Documentation, https://github.com/ovinc/filo/README.md
Project-URL: Repository, https://github.com/ovinc/filo.git
Keywords: files,management,file,series
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: License :: OSI Approved :: BSD License
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: importlib-metadata
Requires-Dist: pandas
Requires-Dist: matplotlib
Provides-Extra: hdf5
Requires-Dist: h5py; extra == "hdf5"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: h5py; extra == "test"
Dynamic: license-file

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
=======

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

Contents
========

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

- [Results classes](#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](#data-and-data-analysis): `DataSeries`, `AnalysisBase`, ...

- [Other modules](#other-modules): viewers, readers, parameters, formatters, multiprocess, json/csv I/O

- [Resampling](#resampling): `create_bins_centered_on()`, `resample_dataframe()`

- [Misc. functions](#misc-functions): list/move/rename files, csv line formatting, `make_iterable`

- [Tests](#tests)

- [Requirements](#requirements), [Author](#author), [License](#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).

```python
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`):

```python
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:

```python
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
===============

```python
# 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
=====

```bash
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)
