Metadata-Version: 2.4
Name: palkocat
Version: 1.0.0
Summary: PalkoCAT (Palkovitslab Calculation & Analysis Toolbox): convenient tools for everyday work in catalysis and electrochemistry labs
Author-email: Fabian Ketter <ketter@itmc.rwth-aachen.de>, Stefan Palkovits <stefan.palkovits@itmc.rwth-aachen.de>, Jens Heller <heller@itmc.rwth-aachen.de>, Lorenzo Cirillo <cirillo@itmc.rwth-aachen.de>, Regina Palkovits <palkovits@itmc.rwth-aachen.de>
Maintainer-email: Stefan Palkovits <stefan.palkovits@itmc.rwth-aachen.de>, Fabian Ketter <ketter@itmc.rwth-aachen.de>
License-Expression: MIT
Project-URL: Homepage, https://gitlab.git.nrw/rwth-itmc/palkovitslab/palkocat
Project-URL: Source, https://gitlab.git.nrw/rwth-itmc/palkovitslab/palkocat
Project-URL: Issues, https://gitlab.git.nrw/rwth-itmc/palkovitslab/palkocat/-/issues
Project-URL: Changelog, https://gitlab.git.nrw/rwth-itmc/palkovitslab/palkocat/-/blob/main/CHANGELOG.md
Project-URL: Documentation, https://gitlab.git.nrw/rwth-itmc/palkovitslab/palkocat/-/blob/main/README.md
Project-URL: Citation, https://doi.org/10.5281/zenodo.23835052
Keywords: chemistry,catalysis,electrochemistry,TPD,HPLC,lab tools,measurement data
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Chemistry
Requires-Python: <3.15,>=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.23
Requires-Dist: scipy>=1.10
Requires-Dist: pandas>=1.5
Requires-Dist: matplotlib>=3.6
Provides-Extra: styling
Requires-Dist: rwth_nb; extra == "styling"
Provides-Extra: tinkerforge
Requires-Dist: tinkerforge; extra == "tinkerforge"
Provides-Extra: interactive
Requires-Dist: ipywidgets>=8; extra == "interactive"
Dynamic: license-file

# PalkoCAT

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.23835052.svg)](https://doi.org/10.5281/zenodo.23835052)

**Palkovitslab Calculation & Analysis Toolbox**

A small Python library with convenient tools for everyday work in catalysis and
electrochemistry labs. It was developed in the
[PalkovitsLab](https://www.itmc.rwth-aachen.de/cms/itmc/das-institut/team/~mfon/regina-palkovits)
at RWTH Aachen University, but it is deliberately generic and offers helpful tools for multiple laboratory tasks.

You do **not** have to be a programmer to use it: if you have Python installed and
know how to run a python file or a Jupyter notebook, you are good to go. This README
aims to explain what the library does.

## What PalkoCAT does

The library provides *functions* for typical lab tasks and measurement data processing.
The package provides solutions for:

- **Reading measurement files** from the TPD, HPLC and Metrohm Autolab (NOVA) machines
  into a table (pandas calls it a *DataFrame* — think of an Excel sheet)
- **Fitting peaks and baselines** (Gaussian / multi-Gaussian curves, baseline correction)
  for your own data
- **Calculating common lab quantities**: ideal gas law, contact time, WHSV / GHSV,
  humidity-to-water-flow, ink and catalyst preparation for coating
- **Looking up chemicals** in a small built-in database (formula, semi-structural
  formula, multiple names/aliases, molar mass, density, CAS number)
- **Live-plotting pressure and temperature** with the optional Tinkerforge sensor apps

Just `import palkocat`. If you want the PalkoCAT plot look (font size, figure size,
inward ticks), call `palkocat.use_style()` once — this is opt-in and keeps the
default matplotlib colors; an optional institutional color palette (the RWTH
corporate design) is also available, see
[Plotting style](#plotting-style).

## Installation

Open a command prompt (Windows: press `Win` + `R`, type `cmd`, press Enter) and run:

```
pip install palkocat
```

All dependencies (numpy, pandas, scipy, matplotlib, ...) are installed automatically.

Optional extras:

| Extra | What it adds | Install |
|---|---|---|
| `styling` | Official RWTH-NB color cycle from the `rwth_nb` package | `pip install palkocat[styling]` |
| `tinkerforge` | Live-plotting apps for the Tinkerforge sensors (`python -m palkocat.tinkerforge_liveplot_pressure --uid ...`) | `pip install palkocat[tinkerforge]` |
| `interactive` | Jupyter widgets re-exported via `palkocat.basics` | `pip install palkocat[interactive]` |

For development, install from a clone with all extras:

```
git clone https://gitlab.git.nrw/rwth-itmc/palkovitslab/palkocat.git
cd palkocat
pip install -e ".[styling,tinkerforge,interactive]"
```

## Quick start

Create a **Jupyter notebook**, paste the code below into a cell and
press `Shift` + `Enter`. No files needed — this example uses synthetic
data, so it works directly after `pip install palkocat`.

```python
import numpy as np
import palkocat
from palkocat.curves import gauss, multi_gauss, baseline_als
from palkocat import helper_functions as hf

x = np.linspace(0, 10, 201)
y = multi_gauss(x, [2.0, 5.0, 1.0]) + 0.05 * x   # one peak on a slope
base = baseline_als(y)                            # estimate the baseline
peak = y - base                                   # baseline-corrected signal

p = hf.ideal_gas(V=1, n=0.05, T=298.15)           # pV = nRT, 0.05 mol in 1 L at 25 C
print(f"peak height ~ {peak.max():.2f}, p = {p:.0f} Pa = {p/1e5:.2f} bar")
```

**What you should see:** `peak height ~ 1.99, p = 123941 Pa = 1.24 bar`.
You generated a Gaussian peak, removed a baseline and solved the ideal gas
law — without downloading any measurement file.

To read your own measurement files, clone the repository for the bundled
`example_data/` (not shipped in the pip package, see
[Example data](#example-data)) and use the readers below.

### A quick tour through other functions

| What you want | Code |
|---|---|
| Load a TPD file | `data = tpd("my_file.TXT")` |
| Load an HPLC file | `results = hplc("my_file.txt")` (dict with `Name_ri`, `Conc_ri`, `Name_uv`, `Conc_uv`) |
| Load a NOVA file (Windows-only, needs the Autolab SDK, see below) | `data = nova("my_file.nox", sdk_path, adk_path)` |
| Turn NOVA data into a table | `df = cv2df(data)` (or `fra2df(data)` / `chrono2df(data)`) |
| List all chemicals in the database | `palkocat.db.print_database()` |
| Calculate the missing variable of `pV = nRT` (give 3 of the 4 values) | `p = palkocat.hf.ideal_gas(V=1, n=0.1, T=300)` |
| Apply the PalkoCAT plotting style | `palkocat.use_style()` |
| Use the RWTH corporate colors in plots | `palkocat.use_style(rwth=True)` |

Combine them the way you like, e.g.:

```python
import palkocat
from palkocat.imports import tpd
import matplotlib.pyplot as plt

data = tpd("example_data/tpd_ammonia_example.txt")
plt.plot(data["time"], data["temperature"])
plt.xlabel("time (s)")
plt.ylabel("temperature (°C)")
plt.show()
```

## Example data

The example measurement files used throughout this README live in the
`example_data/` folder inside the repository. They are intentionally **not**
shipped inside the pip package (the NOVA `.nox` binary files are large and
Windows-specific).

To get the files you can either:

1. **Clone the repository** (recommended for development), or
2. **Download the compact archive from [Zenodo](https://doi.org/10.5281/zenodo.23835052)**.
   Keeping the example data in a citable archive (instead of the pip package)
   also keeps every release small.

If you work from an installed package, simply point the readers at your own
measurement file or at a file extracted from the archive.

## Chemical database

`palkocat.chemical_database` is a small built-in catalogue of chemicals typically used
in the lab. Every entry can be found under **several names**: a primary name, extra
alternate names, aliases (synonyms and laboratory abbreviations), and the molecular
or semi-structural formula. All the preparation helpers (`solution_conc_*`,
`spray_ink`, `cast_ink`, `cat_synthesis`, ...) accept any of these forms:

```python
from palkocat import chemical_database as db

db.find('Methanol')              # primary name
db.find('MeOH')                  # laboratory abbreviation
db.find('CH3OH')                 # molecular formula
db.find('CH3-OH')                # semi-structural formula
```

All four lookups return the same `Chemical` object (methanol). The semi-structural
(condensed) formulas use the usual line notation, e.g. `CH3-CH2-OH` for ethanol or
`H-O-H` for water; ring compounds use a SMILES-style notation with ring-closure
digits, e.g. `O=C1CCCO1` for gamma-butyrolactone.

Each `Chemical` exposes `formula`, `semi_structural`, `names`, `name`, `aliases`,
`molar_mass`, `density`, `state_of_matter`, `cas_nr` and a `matches(query)` method.
List everything with `db.print_database()` or `db.chemical_identifiers()`.

## Helper functions — everyday calculations

Besides the file readers, the package bundles helper functions for calculations you
typically do in the lab: the ideal gas law, humidifier water flows, whsv/ghsv,
catalyst inks and catalyst preparation, and a small chemical database. Below are
**three examples from different areas** — run them in a Jupyter notebook cell, just
like the quick-start example. The calculation helpers live in
`palkocat.helper_functions` (we import them as `hf`) and the chemical database in
`palkocat.chemical_database` (`db`):

```python
import palkocat
from palkocat import helper_functions as hf
from palkocat import chemical_database as db
```

### 1. Gases — the ideal gas law `pV = nRT`

Give any **three** of the four variables (`p` in Pa, `V` in L, `n` in mol, `T` in K)
and `ideal_gas()` returns the missing one:

```python
p = hf.ideal_gas(V=1, n=0.05, T=298.15)    # 0.05 mol in 1 L at 25 °C — what pressure?
print(f"p = {p:.0f} Pa = {p/1e5:.2f} bar")
```

**What you should see:** `p = 123941 Pa = 1.24 bar`. In the same way,
`hf.ideal_gas(p=100000, n=0.05, T=298.15)` gives the volume back in litres.

### 2. Humidifier — water flow for a desired relative humidity

`water_flow()` calculates how much liquid water the saturator has to feed (in mL/min)
to a carrier gas flow (in mL/min) to reach a relative humidity `rH` (between 0 and 1)
at a given temperature `T` in °C:

```python
V_H2O = hf.water_flow(rH=0.7, T=20, gas_flow=100)    # 70 % rH, 100 mL/min at 20 °C
print(f"water flow = {V_H2O:.4f} mL/min")
```

**What you should see:** `water flow = 0.0012 mL/min` — only a tiny amount of water
is needed to saturate a small gas flow. (Pass `verbose=True` to also print the
intermediate saturation pressure `p_sat` and mole fraction `x_H2O`.)

### 3. Solution preparation — concentration calculations

Concentration calculations are needed all the time in the lab. `solution_conc_liquid()`
computes how much of a stock solution (or pure liquid) you need for a given final
volume and target concentration — it looks up the substance's molar mass and density
in the chemical database. For example: how much concentrated sulfuric acid (98 wt%) do
you need to prepare 500 mL of 0.5 mol/L H2SO4?

```python
print(db.H2SO4.name, "|", db.H2SO4.formula, "|", db.H2SO4.molar_mass, "g/mol")
# Sulfuric Acid | H2SO4 | 98.079 g/mol

sol = hf.solution_conc_liquid(volume=500, target=0.5, substance='H2SO4', stock_conc=98)
print(sol)
```

**What you should see:** a table with the required mass and volume of the 98 wt%
stock solution, the resulting molar concentration, the wt% and the mixture density —
e.g. `H2SO4 Stock Volume [mL] = 13.60` to make 500 mL of 0.5 mol/L H2SO4.

The same calculation for dissolving a solid works with `solution_conc_solid()`, e.g.
weighing out solid KOH for a 0.1 mol/L solution. You can also list the whole database
with `palkocat.db.print_database()` or get a compact list of names, formulas and
CAS numbers with `palkocat.db.chemical_identifiers()`.

## Reading NOVA `.nox` files (Windows only)

`palkocat.imports.nova()` imports measurement procedures from Metrohm Autolab `.nox`
files. **It works only on Windows** and needs three things that cannot be bundled
into the package itself:

1. **The Metrohm Autolab SDK**:
   <https://www.metrohm.com/service/software-center/autolab-sdk.html>.
   Install it, then note the path to these four files:

   - `Adk.x` (the ADK *executable*)
   - `EcoChemie.Autolab.Sdk.dll`
   - `EcoChemie.Shared100.dll`
   - `EcoChemie100.dll`

   These files are proprietary and therefore **not** shipped with palkocat. 

2. **The pythonnet bridge** used to talk to the `.NET` SDK:

   ```
   pip install pythonnet clr-loader
   ```

3. **The `.nox` measurement file** you want to read.

Example:

```python
from palkocat.imports import nova, cv2df, fra2df, chrono2df

data = nova(r"C:\Users\You\my_measurement.nox",
            sdk=r"C:\Program Files\Metrohm Autolab\EcoChemie.Autolab.Sdk.dll",
            adk=r"C:\Program Files\Metrohm Autolab\Adk.x")

df = cv2df(data)     # cyclic voltammetry
df = fra2df(data)    # impedance / FRA
df = chrono2df(data) # chronoamperometry
```

`nova()` returns a nested dictionary with one entry per measurement command. The
helpers in `palkocat.utils` convert a measurement into a pandas DataFrame:

- `cv2df(data)` — cyclic voltammetry (`CV staircase`)
- `fra2df(data)` — impedance spectra (`FRA measurement potentiostatic`)
- `chrono2df(data)` — chronoamperometry (`Record signals (>1 ms)`)

Ready-to-run example files live in `example_data/`:

- `nova_cv_example.nox` — cyclic voltammetry
- `nova_eis_example.nox` — impedance / FRA (Nyquist & Bode)
- `nova_chronoamperometry_example.nox` — chronoamperometry

For example: `df = fra2df(nova("example_data/nova_eis_example.nox", sdk, adk))`.

On Linux and macOS `nova()` raises an `OSError` (the Autolab SDK is
Windows-only); use the JSON conversion (e.g. `cv2df`) on data that was
previously exported on Windows. Pass `save_json=False` to skip writing the
`_data.json` sidecar file.
## Tinkerforge live-plotting apps

`palkocat/tinkerforge_liveplot_pressure.py` and
`palkocat/tinkerforge_liveplot_thermocouple.py` are small standalone apps that
live-log absolute pressure (Industrial Dual 0-20 mA Bricklet) or temperature
(Thermocouple V2 Bricklet) and save the data as timestamped CSV files.

They are **optional**. Install the extra (which also pulls in the Tinkerforge Python
bindings):

```
pip install palkocat[tinkerforge]
```

Then start a live plot via the module (the apps are only installed
with the `tinkerforge` extra, so there is no console script in a base install):

```
python -m palkocat.tinkerforge_liveplot_pressure --uid YOUR_UID
python -m palkocat.tinkerforge_liveplot_thermocouple --uid YOUR_UID --host 192.168.1.2 --port 4223
```

To talk to a different bricklet or daemon host without editing the source,
pass `--uid` / `--host` / `--port` (or set the `TINKERFORGE_UID`,
`TINKERFORGE_HOST`, `TINKERFORGE_PORT` environment variables):

```
python -m palkocat.tinkerforge_liveplot_pressure --uid YOUR_UID
python -m palkocat.tinkerforge_liveplot_thermocouple --uid YOUR_UID --host 192.168.1.2
```

Prerequisites:

- The Tinkerforge **Brick Daemon** (`brickd`) must be running on `localhost:4223`
  (or pass `--host` / `--port`)
- The bricklet UID must match your hardware: pass `--uid YOUR_UID` or set the
  `TINKERFORGE_UID` environment variable (no source edit needed)

The target folder for the CSV files can be chosen in the app and is remembered in a
per-app JSON config under `~/.palkocat/` (portable across Windows / Linux / macOS).

## Plotting style

Importing `palkocat` does **not** change any of your matplotlib or numpy settings.
If you want the PalkoCAT look (font size, figure size, inward ticks, thicker axes),
turn it on explicitly:

```python
import palkocat
palkocat.use_style()   # opt-in, idempotent — call once at the top of your notebook
```

By default the **matplotlib color cycle is untouched**, so `use_style()` always
works and looks the same everywhere — the package does not impose any particular
color scheme. Besides the matplotlib settings it also sets numpy's print options to
show **full arrays** instead of truncated ones (`np.set_printoptions(threshold=np.inf)`).

If you *do* want an institutional color scheme, PalkoCAT ships the RWTH
corporate-design palette as a built-in extra:

```python
palkocat.use_style(rwth=True)   # built-in RWTH color palette
```

If you installed the optional `styling` extra, you can instead use the official
RWTH-NB color cycle:

```python
palkocat.use_style(rwth_nb=True)   # needs: pip install palkocat[styling]
```

`palkocat.basics` re-exports `np`, `pd`, `sc`, `plt`, `fsolve` and `ipywidgets`, and
the RWTH color palette lives in `palkocat.basics.RWTH_COLORS`.

## API reference

Every function is documented in its docstring — in a notebook, `help(tpd)` shows it.
This section is just the map of *where* things live; the recommended imports are shown.

### `palkocat.imports` — file readers
| Function | Description |
|---|---|
| `tpd(filename, encoding=None)` | Read a TPD export file into a DataFrame with columns `time`, `temperature`, `event`, `injection`, `pressure`. |
| `hplc(filename)` | Read an HPLC LabSolutions export; returns a dict with `Name_ri`, `Conc_ri`, `Name_uv`, `Conc_uv`. |
| `nova(filepath, sdk, adk, save_json=True)` | Read a Metrohm Autolab `.nox` file into a dict of commands (Windows + SDK only; raises `OSError` elsewhere). |

### `palkocat.utils` — conversion helpers
- `cv2df(nova_dict)`, `fra2df(nova_dict)`, `chrono2df(nova_dict)` — turn NOVA
  measurement dicts into DataFrames.
- `parse_float`, `parse_columns`, `parse_columns_between` — internal text parsers
  (used by `hplc`, but public for reuse).

### `palkocat.curves` — peak fitting
- `baseline_als(y, lam=100000, p=0.0001, niter=10)` — asymmetric least-squares
  baseline correction (Eilers & Boelens 2005).
- `gauss(x, params)` — one Gaussian, `params = [height, center, width]`.
- `multi_gauss(x_data, *params)` — sum of Gaussians; pass the triplets flattened.

### `palkocat.helper_functions` — lab calculations
Grouped by purpose (all signatures are in the docstrings):

| Group | Functions |
|---|---|
| Data processing | `smooth`, `normalize`, `recalc_unit` |
| Gases | `ideal_gas`, `water_flow`, `contact_time_liq`, `whsv`, `ghsv` |
| Inks & coatings | `spray_ink`, `cast_ink`, `gde` |
| Catalyst preparation | `cat_synthesis` |
| Solutions | `solution_conc_liquid`, `solution_conc_solid` |
| Chemical arithmetic | `mol_to_mass`, `mass_to_mol` |
| Electrochemistry | `nernst`, `delta_g`, `faraday_galvanostatic`, `faraday_potentiostatic`, `process_ocp`, `process_cv`, `process_chronoamperometry`, `process_eis` |

### `palkocat.chemical_database` — chemical catalogue
- `Chemical` — one entry; `Chemical.matches(query)` matches names/aliases/formulas.
- `find(query)` — return the matching `Chemical` or `None`.
- `print_database()` / `print_chemicals()` / `chemical_identifiers()` — overviews.

### `palkocat.basics` — style and common imports
- `use_style(rwth=False, rwth_nb=False)` — apply the PalkoCAT matplotlib style
  (opt-in). The color cycle only changes when you ask for it: `rwth=True` for
  the built-in RWTH palette, `rwth_nb=True` for the official RWTH-NB cycle
  (needs the `styling` extra; wins over `rwth`). With `rwth_nb=True` the
  `rwth:blue`, `rwth:orange`, … names are also registered with Matplotlib and
  can be used directly, e.g. `plt.plot(x, y, color="rwth:blue")`.
- `RWTH_COLORS` — the built-in RWTH color palette (RWTH corporate design).
- Re-exported convenience imports: `np`, `pd`, `sc`, `plt`, `fsolve`,
  `interactive`, `SelectionSlider`, `interact`, `IntSlider`, `fixed`.

### Top level (`import palkocat`)
- `hf` — alias for `palkocat.helper_functions`
- `db` — alias for `palkocat.chemical_database`
- Convenience re-exports of the package's own functions: `tpd`, `hplc`,
  `nova`, `cv2df`, `fra2df`, `chrono2df`, `gauss`, `multi_gauss`,
  `baseline_als`, `use_style`, `RWTH_COLORS`, ...
- Third-party conveniences (`np`, `pd`, `plt`, ...) live in
  `palkocat.basics` and are intentionally **not** re-exported at the top
  level (import them via `from palkocat import basics` or plain
  `import numpy as np`).

## Development

The repository ships a [Ruff](https://docs.astral.sh/ruff/) configuration in
`pyproject.toml` (linting with `E`/`F`/`I`/`B`, line length 100) and a GitLab CI
pipeline that runs lint → tests → build. Locally:

```bash
pip install ruff
ruff check palkocat tests                # lint
ruff format palkocat tests               # apply formatting
python -m unittest discover -s tests -v  # run the test suite
```

Notable changes are documented in [CHANGELOG.md](CHANGELOG.md).

## Troubleshooting

| Message / symptom | What it means and what to do |
|---|---|
| `ModuleNotFoundError: No module named 'palkocat'` | The installation did not complete. Run `pip install palkocat` again and read the output for the actual error. |
| `ModuleNotFoundError: No module named 'rwth_nb'` | The RWTH-NB color cycle is optional: run `pip install palkocat[styling]`, or use the built-in RWTH palette via `palkocat.use_style(rwth=True)`. |
| `ModuleNotFoundError: No module named 'tinkerforge'` | The live-plot apps are optional: run `pip install palkocat[tinkerforge]`. |
| `ModuleNotFoundError: No module named 'clr'` (using `nova`) | The .NET bridge is missing on Windows: `pip install pythonnet clr-loader`, plus the Autolab SDK (see the NOVA section). |
| `FileNotFoundError: ... example_data ...` | Python looks for the file relative to your current working directory. Run your script from the project root, or give the full path, e.g. `tpd(r"C:\Users\YourName\Downloads\my_file.TXT")`. The example files ship only with the repository, not the pip package. |
| `ValueError: Substance '...' not found in the chemical database` | This name/alias/formula is not in the catalogue. Use `db.find('...')` or `db.print_database()` to check what is available. |
| No figure appears when plotting | matplotlib only draws the figure once you call `plt.show()` (in a notebook, closing the cell also works) — see the plot example above. |

## Authors

Fabian Ketter†, Stefan Palkovits†\*, Jens Heller, Lorenzo Cirillo, Regina Palkovits\*

- † These authors (Fabian Ketter, Stefan Palkovits) contributed equally to this work.
- \* Corresponding authors (Stefan Palkovits, Regina Palkovits).

## Citation

If you use *PalkoCAT* in academic work, please cite it as:

> F. Ketter, S. Palkovits, J. Heller, L. Cirillo, R. Palkovits (2026).
> *PalkoCAT* (Version 1.0.0) [Computer software]. Zenodo.
> <https://doi.org/10.5281/zenodo.23835052>.

A machine-readable `CITATION.cff` file is also included in the repository.

The equal-contribution (†) and corresponding-author (*) markings are documented
in the [Authors](#authors) section above.

## License

This project is licensed under the **MIT License** (see `LICENSE`).
