Skip to content

API reference

Reading data

eemkit.io.cary_eclipse.read_cary_eclipse

read_cary_eclipse(path: str | Path, em_grid: ndarray | None = None, tolerance: float = DEFAULT_TOLERANCE) -> xr.Dataset

Read one EEM exported by the Cary Eclipse software as CSV with log.

Parameters:

Name Type Description Default
path str | Path

CSV file with one emission scan per excitation wavelength.

required
em_grid ndarray | None

If given, each emission scan is linearly interpolated onto this grid (nm). If omitted, the native emission axis is kept, which requires all scans of the file to share it.

None
tolerance float

See :func:eemkit.core.grid.interp_on_grid; used only with em_grid.

DEFAULT_TOLERANCE

Returns:

Type Description
Dataset

intensity with dims (ex, em) in instrument units, coordinate scan_time(ex) and the instrument settings as attributes. Values are exactly as exported: no correction of any kind is applied.

eemkit.io.cary60.read_cary60

read_cary60(path: str | Path) -> xr.Dataset

Read one absorbance measurement (one or more cycles) from a Cary 60 CSV.

Returns:

Type Description
Dataset

absorbance with dims (cycle, wavelength), wavelength ascending (the instrument scans downwards), coordinate scan_time(cycle) and the instrument settings as attributes. Values are as exported: no blank subtraction, baseline or path-length normalisation.

eemkit.io.cary60.mean_cycles

mean_cycles(ds: Dataset) -> xr.Dataset

Average repeated cycles: returns absorbance and absorbance_sd (wavelength).

The standard deviation uses ddof=1 and is NaN for a single cycle.

eemkit.io.instruments

Readers for EEMs from fluorometers other than the Cary Eclipse, and plain absorbance files.

Every reader returns the same structure as :func:eemkit.io.cary_eclipse.read_cary_eclipse: intensity(ex, em) in instrument units, wavelengths ascending, the values exactly as in the file, and the file and instrument information as attributes. Two attributes matter for the corrections:

  • corrected_spectra: "On" when the file says the instrument already corrected the spectra (eemkit then refuses a second spectral correction); absent when the file does not say;
  • instrument_processing: text found in the file that describes processing done by the instrument software (e.g. Aqualog "Sample - Blank", "Normalized by 75.335"), and instrument_steps: the eemkit steps it implies (blank, inner_filter, raman), comma-separated. eemkit never repeats such a step and never skips one silently: the project must declare it in project.already_done (see :mod:eemkit.pipeline).

Formats (project.instrument):

======================== =================================================== aqualog Horiba Aqualog .dat export (excitation in columns) fluoromax Horiba Fluoromax .dat matrix (excitation in columns) hitachi_f7000 Hitachi F-7000 .TXT 3-D scan with header shimadzu Shimadzu .TXT blocks of (emission, intensity); the excitation wavelengths must be given matrix_csv any matrix: first row excitation, first column emission (or the transpose), comma, semicolon or tab separated ======================== ===================================================

Absorbance (project.absorbance_format): cary60 or two_column (:func:read_two_column_absorbance).

read_aqualog

read_aqualog(path: str | Path) -> xr.Dataset

Horiba Aqualog EEM exported as .dat (tab separated).

First row: a label (e.g. Sample - Blank) then the excitation wavelengths; then text rows (e.g. Normalized by 75.335) and one row per emission wavelength. The label and the text rows are kept in instrument_processing; a label mentioning a blank, an inner filter (IFE) or Raman units sets instrument_steps.

read_fluoromax

read_fluoromax(path: str | Path) -> xr.Dataset

Horiba Fluoromax .dat matrix (tab separated).

First row: a label then the excitation wavelengths; each following row an emission wavelength and its intensities. The file says nothing about the instrument's corrections, so corrected_spectra is not set.

read_hitachi_f7000

read_hitachi_f7000(path: str | Path) -> xr.Dataset

Hitachi F-7000 3-D scan exported as .TXT.

The header (key:<tab>value lines) is kept as attributes; the matrix follows Data Points with excitation in columns. The over-range value 9999.9, written where the detector saturated, becomes NaN and is counted in n_saturated with a warning. Corrected spectra: On is kept, so eemkit will not apply a second spectral correction.

read_shimadzu

read_shimadzu(path: str | Path, *, ex_start: float, ex_step: float) -> xr.Dataset

Shimadzu .TXT EEM: blocks of (emission, intensity) lines, one block per excitation.

The excitation wavelengths are not in the file: ex_start and ex_step (nm) must be given (no default), and the number of blocks in the file fixes how many there are. Each block must have the same emission wavelengths.

read_matrix_csv

read_matrix_csv(path: str | Path, *, orientation: str = 'em_rows') -> xr.Dataset

Any EEM matrix: first row and first column hold the wavelengths.

orientation="em_rows": first row = excitation, first column = emission (as Aqualog and Fluoromax); "ex_rows": the transpose. Separator: comma, semicolon or tab, detected from the first line. The top-left cell is ignored.

read_two_column_absorbance

read_two_column_absorbance(path: str | Path) -> xr.Dataset

Absorbance spectrum as two columns: wavelength (nm) and absorbance (decadic).

Comma, semicolon, tab or space separated; lines that are not two numbers (titles, units) are skipped. The wavelengths must not repeat. Returns absorbance(cycle, wavelength) with one cycle, like :func:eemkit.io.cary60.read_cary60, so the rest of eemkit treats both alike.

eemkit.corrections.instrument

Corrections already done by the instrument software.

Some instruments export EEMs that are already processed: an Aqualog export can be blank-subtracted ("Sample - Blank"), corrected for the inner filter or normalised. Correcting such data again would be wrong, and skipping a correction silently would be wrong too. So eemkit:

  • reads what each file says about its processing (attribute instrument_steps, see :mod:eemkit.io.instruments);
  • stops with an error when a file says a step was done that the project does not declare in project.already_done (:func:check_declared);
  • for each declared step, writes a history entry with the step's own name and done_by = "instrument software" instead of running it (:func:mark_done), so the record is complete and the step cannot be run a second time.

check_declared

check_declared(ds: Dataset, declared: list[str]) -> None

Raise :class:~eemkit.errors.SettingsError unless files and settings agree.

Every step a file states must be declared; a declared blank cannot have blank files paired; Raman units cannot be computed from a blank that the instrument already subtracted.

mark_done

mark_done(ds: Dataset, key: str) -> xr.Dataset

History entry for a step done by the instrument software (nothing is computed).

eemkit.io.discover.scan_folder

scan_folder(root: str | Path, *, blank_pattern: str = DEFAULT_BLANK_PATTERN, progress: Callable[[int, int], None] | None = None, instrument: str = 'cary_eclipse', absorbance_format: str = 'cary60', reader_options: dict | None = None) -> pd.DataFrame

Classify the measurement files below root (recursively); read-only.

With the default formats (Cary Eclipse and Cary 60) every *.csv is classified from its first two lines. For other instruments the files with the format's suffixes are read with its reader (:func:classify_with). Returns one row per file with :data:INVENTORY_COLUMNS; file is relative to root with forward slashes. first_x/last_x are the excitation range (EEM), the cycle numbers (Cary 60) or the wavelength range (two-column absorbance).

eemkit.io.discover.suggest_pairing

suggest_pairing(inventory: DataFrame) -> pd.DataFrame

Draft a pairing table from :func:scan_folder output, for a person to check.

One row per non-blank EEM. Suggestions, all marked as such:

  • abs_file: the non-blank absorbance file with the same sample name (ignoring case, spaces, _, - and .), preferring the EEM's folder; left empty if there is no single match;
  • eem_blank_file: the only blank EEM in the EEM's folder;
  • abs_blank_file: the only blank absorbance file in the absorbance file's folder;
  • eem_raman_file: left empty; fill it only when the blank is not water (e.g. methanol or ethanol), with a pure-water EEM measured in the same session for the Raman area.

Every row has include = no.

eemkit.io.pairing.read_pairing

read_pairing(path: str | Path, data_root: str | Path | None = None, check_files: bool = True) -> pd.DataFrame

Read and validate a pairing table.

Parameters:

Name Type Description Default
path str | Path

CSV file.

required
data_root str | Path | None

Folder the file paths are relative to; defaults to the table's folder.

None
check_files bool

Verify that every file referenced by an included row exists.

True

Returns:

Type Description
DataFrame

All rows (included or not), every column as text except include (bool). df.attrs holds source and data_root.

Raises:

Type Description
PairingError

Listing every problem found, not only the first.

eemkit.io.loader.load_dataset

load_dataset(pairing: str | Path | DataFrame, data_root: str | Path | None = None, em_grid: ndarray | None = None, wavelength_grid: ndarray | None = None, tolerance: float = DEFAULT_TOLERANCE, eem_format: str = 'cary_eclipse', abs_format: str = 'cary60', reader_options: dict | None = None) -> xr.Dataset

Read every included row of a pairing table into one dataset.

Parameters:

Name Type Description Default
pairing str | Path | DataFrame

Path to the pairing CSV, or a table already returned by :func:eemkit.io.pairing.read_pairing.

required
data_root str | Path | None

Folder the file paths are relative to (see read_pairing).

None
em_grid ndarray | None

Common emission grid for EEMs and wavelength grid for absorbance (nm). If omitted they are inferred with :func:eemkit.core.grid.infer_common_grid from all files read, and the choice is recorded in the history.

None
wavelength_grid ndarray | None

Common emission grid for EEMs and wavelength grid for absorbance (nm). If omitted they are inferred with :func:eemkit.core.grid.infer_common_grid from all files read, and the choice is recorded in the history.

None
tolerance float

Edge tolerance of the linear resampling (nm).

DEFAULT_TOLERANCE
eem_format str

File formats: a key of :data:READERS and of :data:ABS_READERS.

'cary_eclipse'
abs_format str

File formats: a key of :data:READERS and of :data:ABS_READERS.

'cary_eclipse'
reader_options dict | None

Keyword arguments for the EEM reader (e.g. ex_start and ex_step for Shimadzu files, orientation for matrix_csv).

None

Returns:

Type Description
Dataset

Dimensions sample, ex, em and, when any absorbance is paired, wavelength. Variables:

  • intensity (sample, ex, em): raw sample EEMs on em_grid
  • blank_intensity (sample, ex, em): the paired blank, NaN if none
  • raman_intensity (sample, ex, em): only when the table has an eem_raman_file column with a file in it: the pure-water EEM for the Raman area, NaN where none
  • absorbance, absorbance_sd (sample, wavelength): mean and SD of the instrument cycles, NaN if none
  • blank_absorbance (sample, wavelength)

All pairing-table columns become sample coordinates. File and instrument metadata are prefixed eem_, eem_blank_, eem_raman_, abs_ and abs_blank_.

eemkit.core.history.get_history

get_history(ds: Dataset | DataArray) -> list[dict[str, Any]]

Return the list of processing steps applied to ds, oldest first.

Corrections

eemkit.corrections

EEM corrections. Each is a separate, optional function recorded in the history.

Recommended order (each function refuses to run after a step that must follow it):

  1. :func:apply_spectral_correction (instrument response; optional)
  2. :func:subtract_absorbance_blank
  3. :func:correct_inner_filter (or :func:skip_inner_filter, with the reason, when there are no absorbance spectra)
  4. :func:subtract_blank
  5. :func:normalize_raman, then :func:correct_dilution (diluted samples) and :func:zap (regions removed by hand)
  6. :func:remove_scatter, then optionally :func:interpolate_missing
  7. :func:crop

With diluted samples, :func:match_absorbance_dilution goes between steps 2 and 3.

apply_spectral_correction

apply_spectral_correction(ds: Dataset, *, ex_factors: str | Path | tuple[ndarray, ndarray], em_factors: str | Path | tuple[ndarray, ndarray], variables: tuple[str, ...] = ('intensity', 'blank_intensity', 'raman_intensity'), convention: str = 'multiply') -> xr.Dataset

Multiply (or divide) EEMs by excitation and emission correction factors.

Factors are linearly interpolated onto the ex and em grids, which they must cover (no extrapolation). convention says what the files hold: "multiply" (correction factors) or "divide" (response spectra). The stored spectral_correction_ex/em variables are always the multipliers actually applied. Must precede every other correction.

read_correction_file

read_correction_file(path: str | Path) -> tuple[np.ndarray, np.ndarray]

Read wavelength, factor pairs; header lines and ,; or whitespace separators ok.

subtract_absorbance_blank

subtract_absorbance_blank(ds: Dataset, missing: str = 'error') -> xr.Dataset

Subtract the paired absorbance blank: absorbance - blank_absorbance.

Coordinate absorbance_blank_subtracted(sample) records which samples were corrected. missing as in :func:subtract_blank; samples without any absorbance are left alone.

match_absorbance_dilution

match_absorbance_dilution(ds: Dataset) -> xr.Dataset

Rescale each absorbance spectrum to the dilution of its EEM.

absorbance *= abs_dilution_factor / dilution_factor. Run after :func:~eemkit.corrections.subtract_absorbance_blank and before :func:~eemkit.corrections.correct_inner_filter. The coordinate absorbance_dilution(sample) records the dilution the absorbance now refers to, so the CDOM metrics can be reported for the undiluted sample.

correct_inner_filter

correct_inner_filter(ds: Dataset, *, absorbance_path_length_cm: float, fluorescence_path_length_cm: float, missing: str = 'error', max_a254: float = KOTHAWALA_MAX_A254) -> xr.Dataset

Correct intensity for inner-filter effects using the sample absorbance.

Parameters:

Name Type Description Default
absorbance_path_length_cm float

Path length of the cuvette the absorbance was measured in.

required
fluorescence_path_length_cm float

Path length of the fluorescence cuvette. Both are required: eemkit never assumes a cuvette.

required
missing str

Samples without absorbance: "error", "drop" or "keep".

'error'
max_a254 float

Samples whose A254 over the fluorescence path exceeds this value get a warning (Kothawala et al. 2013 recommend dilution above 1.5).

KOTHAWALA_MAX_A254
Notes

The absorbance must already be blank-corrected (:func:~eemkit.corrections.subtract_absorbance_blank). The applied factor is kept as the variable ife_factor(sample, ex, em).

skip_inner_filter

skip_inner_filter(ds: Dataset, *, reason: str) -> xr.Dataset

Record that the inner-filter correction is not applied, and why.

For data without absorbance spectra, e.g. from a fluorometer used on its own. The intensities are not changed: the step only writes a history entry with reason (so the processing record says the correction is missing), sets ife_corrected to False for every sample and prevents a later :func:correct_inner_filter. Without the correction, fluorescence is underestimated where the sample absorbs; it is commonly neglected only for samples of low absorbance or diluted to it (Kothawala et al. 2013), which is what reason should state.

subtract_blank

subtract_blank(ds: Dataset, missing: str = 'error') -> xr.Dataset

Subtract the paired blank EEM from each sample EEM.

intensity becomes intensity - blank_intensity; blank_intensity is kept unchanged (it is still needed for Raman normalisation). The coordinate blank_subtracted(sample) records which samples were corrected.

Parameters:

Name Type Description Default
missing str

What to do with samples that have no blank: "error" (default), "drop" them, or "keep" them uncorrected.

'error'

normalize_raman

normalize_raman(ds: Dataset, *, ex: float, em_range: tuple[float, float], baseline: bool = False, missing: str = 'error') -> xr.Dataset

Divide the EEMs by the Raman area of pure water measured with each sample.

The area is taken from the sample's water EEM (raman_intensity) when one is paired, otherwise from its blank (blank_intensity), which is then expected to be water. intensity, blank_intensity and raman_intensity are divided. The area (a.u. nm) is stored as the coordinate raman_area(sample) and the intensity units become R.U.; with raman_intensity present, raman_reference(sample) says where each area comes from (water EEM, blank or empty). missing controls samples with neither.

correct_dilution

correct_dilution(ds: Dataset) -> xr.Dataset

Multiply each EEM by its dilution_factor (the undiluted sample's fluorescence).

Run after :func:~eemkit.corrections.normalize_raman and before :func:~eemkit.corrections.remove_scatter. Only intensity is multiplied; the coordinate dilution_factor_applied(sample) records the factors.

raman_area

raman_area(blank: DataArray, *, ex: float, em_range: tuple[float, float], baseline: bool = False) -> xr.DataArray

Integrated water Raman peak of blank (dims ..., ex, em).

The spectrum at excitation ex (which must be measured) is treated as piecewise linear and integrated exactly from em_range[0] to em_range[1], so the limits need not be grid points. With baseline=True the straight line joining the spectrum at the two limits is subtracted first. Result in intensity units x nm; NaN for an all-NaN spectrum (no blank).

remove_scatter

remove_scatter(ds: Dataset, *, widths: Mapping[str, tuple[float, float]], raman_shift_cm1: float | None = None, zero_below_rayleigh: float | None = None, variables: tuple[str, ...] = ('intensity',)) -> xr.Dataset

Set scatter bands to NaN (and optionally the region below Rayleigh to 0).

Parameters:

Name Type Description Default
widths Mapping[str, tuple[float, float]]

{band: (below_nm, above_nm)} for the bands to remove; see module doc.

required
raman_shift_cm1 float | None

Raman shift of water, needed for Raman bands.

None
zero_below_rayleigh float | None

If given, intensities at em < ex - zero_below_rayleigh are set to 0 instead of NaN (applied after the bands, so it never overrides a band lying above that limit).

None
variables tuple[str, ...]

Data variables to process.

('intensity',)
Notes

The removed region is stored as scatter_mask(ex, em).

interpolate_missing

interpolate_missing(ds: Dataset, *, method: str, variables: tuple[str, ...] = ('intensity',), only: DataArray | None = None, what: str = 'all') -> xr.Dataset

Fill NaN gaps in each EEM by linear interpolation between measured points.

Parameters:

Name Type Description Default
method str

"em": along emission within each excitation scan; "ex": along excitation at each emission wavelength; "both": mean of the two estimates where both exist, otherwise whichever exists.

required
only DataArray | None

Boolean (sample, ex, em): fill only these cells, leave the other gaps missing (e.g. only the scatter bands, not the zapped regions).

None
what str

Label of the filled cells, recorded in the history.

'all'
Notes

Only gaps bracketed by measured values are filled; gaps at the edge of the EEM stay NaN. The coordinates n_interpolated(sample) and n_still_missing(sample) count filled and remaining values.

Indices

eemkit.indices

Fluorescence indices and peak picking.

==================== =============================================== ========================= index definition (defaults) reference ==================== =============================================== ========================= FI I(ex 370, em 470) / I(ex 370, em 520) Cory & McKnight 2005 HIX H / (H + L) at ex 254; H = area em 435-480, Ohno 2002 L = area em 300-345 BIX I(ex 310, em 380) / I(ex 310, em 430) Huguet et al. 2009 Coble peaks B 275/310, T 275/340, A 260/380-460, Coble 1996 M 312/380-420, C 350/420-480 (ex/em, nm); maximum over the emission range ==================== =============================================== =========================

Excitation wavelengths that are not on the measured grid (e.g. 254, 275 or 312 nm on a 10 nm grid) are handled by ex_method:

  • "linear": linear interpolation between the two neighbouring scans;
  • "nearest": the closest measured excitation;
  • "exact": refuse (raise) unless the excitation was measured.

Emission values off the grid are linearly interpolated; emission areas are trapezoidal integrals of the piecewise-linear spectrum between the exact limits. A value that needs a NaN point (e.g. removed scatter) is NaN and triggers a warning. In :func:compute_indices, an index the dataset cannot give at all (a wavelength outside the measured range) is left empty with a warning and its reason recorded, and the other indices are still computed. Ratios are unit-free; peaks are in the units of intensity. Indices depend on instrument spectral response (Cory et al. 2010), so the spectral-correction status travels with every result.

compute_indices

compute_indices(ds: Dataset, *, ex_method: str, fi: Mapping | None = None, hix: Mapping | None = None, bix: Mapping | None = None, peak_definitions: Mapping[str, tuple[float, tuple[float, float]]] | None = None, on_error: str = 'nan') -> pd.DataFrame

All indices in one table (one row per sample) with the settings in df.attrs.

fi, hix, bix are keyword overrides for the respective functions; peak_definitions defaults to :data:COBLE_1996. ex_method applies to every index and peak.

An index or peak that cannot be computed on this dataset (a wavelength outside the measured range, or an excitation that was not measured when ex_method="exact") does not stop the table: with on_error="nan" (default) its column is left empty (NaN), an :class:EEMKitWarning says why, and the reason is stored in df.attrs["settings"]["not_computed"] (and so in the JSON sidecar of :func:export_indices). With on_error="raise" the :class:IndexComputationError is raised instead.

fluorescence_index

fluorescence_index(ds: Dataset, *, ex: float = 370.0, em: tuple[float, float] = (470.0, 520.0), ex_method: str = 'exact') -> xr.DataArray

FI = I(ex, em[0]) / I(ex, em[1]) (Cory & McKnight 2005).

humification_index

humification_index(ds: Dataset, *, ex: float = 254.0, high: tuple[float, float] = (435.0, 480.0), low: tuple[float, float] = (300.0, 345.0), ex_method: str) -> xr.DataArray

HIX = H / (H + L) with emission areas H and L at ex (Ohno 2002).

ex_method has no default because the standard 254 nm is rarely on the measured grid and the choice must be explicit.

biological_index

biological_index(ds: Dataset, *, ex: float = 310.0, em_num: float = 380.0, em_den: float | tuple[float, float] = 430.0, ex_method: str = 'exact') -> xr.DataArray

BIX = I(ex, em_num) / I(ex, em_den) (Huguet et al. 2009).

If em_den is a (min, max) range, the denominator is the maximum over that range (as in the beta:alpha 'freshness' index).

peaks

peaks(ds: Dataset, definitions: Mapping[str, tuple[float, tuple[float, float]]], *, ex_method: str) -> xr.Dataset

Peak intensities: for each name, max over the emission range at the given excitation.

export_indices

export_indices(df: DataFrame, path: str | Path, ds: Dataset | None = None, metadata: tuple[str, ...] = ()) -> tuple[Path, Path]

Write the table as CSV plus a JSON sidecar (<name>.json) with all settings.

metadata lists sample coordinates of ds (e.g. river, site) to prepend as columns.

CDOM metrics

eemkit.absorbance

Chromophoric DOM (CDOM) metrics from absorbance spectra.

================= =================================================== ========================== metric definition (defaults) reference ================= =================================================== ========================== a254, a350 Napierian absorption coefficient a = ln(10) A / l Green & Blough 1994 (m^-1, path length l in m) S275_295 slope of ln a(lambda) against lambda, 275-295 nm Helms et al. 2008 S350_400 the same over 350-400 nm (nm^-1, reported positive) Helms et al. 2008 SR S275_295 / S350_400 Helms et al. 2008 E2_E3 A(250) / A(365) De Haan & De Boer 1987 SUVA254 A(254) / l (m^-1, decadic) / DOC (mg L^-1) Weishaar et al. 2003 ================= =================================================== ==========================

Before any metric, each spectrum is corrected for its baseline offset by subtracting its mean absorbance over baseline (default 680-700 nm, where CDOM does not absorb; Green & Blough 1994, Helms et al. 2008). The absorbance must already be blank-corrected (:func:~eemkit.corrections.subtract_absorbance_blank).

Low signal is never turned into a number: a metric that would need a non-positive absorbance, or a slope whose log-linear fit has R^2 below min_r2, is NaN, and the reason is written in the cdom_notes column.

compute_absorbance_metrics

compute_absorbance_metrics(ds: Dataset, *, absorbance_path_length_cm: float, baseline: tuple[float, float] | None = (680.0, 700.0), min_r2: float = 0.95, coefficients: Sequence[float] = COEFFICIENTS, slopes: dict[str, tuple[float, float]] | None = None, e2_e3: tuple[float, float] = E2_E3, doc: str | None = None) -> pd.DataFrame

CDOM metrics, one row per sample, with the settings in df.attrs.

Parameters:

Name Type Description Default
ds Dataset

Dataset with absorbance(sample, wavelength), blank-corrected.

required
absorbance_path_length_cm float

Path length of the absorbance cuvette. Required: eemkit never assumes a cuvette.

required
baseline tuple[float, float] | None

Wavelength range (nm) whose mean is subtracted from each spectrum; None for no baseline correction.

(680.0, 700.0)
min_r2 float

Smallest R^2 of the log-linear fit for a slope to be reported. This is an eemkit quality threshold, not a value from the literature; report the value used.

0.95
coefficients Sequence[float]

Wavelengths (nm) of the Napierian absorption coefficients a<nm>.

COEFFICIENTS
slopes dict[str, tuple[float, float]] | None

{name: (lo, hi)}; default :data:SLOPE_RANGES. SR is computed when both default ranges are present.

None
e2_e3 tuple[float, float]

The two wavelengths of the E2:E3 ratio.

E2_E3
doc str | None

Name of a sample coordinate holding DOC in mg L^-1; SUVA254 is computed only when it is given.

None
Notes

Values that cannot be computed are NaN and the reasons are joined in the cdom_notes column, so low-signal spectra are never reported as numbers.

baseline_corrected

baseline_corrected(absorbance: DataArray, baseline: tuple[float, float] | None) -> xr.DataArray

Each spectrum minus its mean over baseline (nm); unchanged if None.

spectral_slope

spectral_slope(a: ndarray, wl: ndarray, lo: float, hi: float, min_r2: float) -> tuple[float, float, str]

Slope S (nm^-1, positive for decreasing a) of ln a against wavelength on [lo, hi].

Linear least squares on the measured points in the range (Helms et al. 2008). Returns (S, R2, note); S is NaN with a note when a value in the range is not positive, when there are fewer than 3 points, or when R2 < min_r2.

PARAFAC

eemkit.parafac.model

Fitting PARAFAC models to an EEM dataset and packaging the result.

fit_parafac

fit_parafac(ds: Dataset, rank: int, *, n_init: int = 10, normalization: str | None = 'norm', tol: float = 1e-08, max_iter: int = 5000, random_state: int = 0, variable: str = 'intensity', n_jobs: int | None = None) -> xr.Dataset

Non-negative PARAFAC of ds[variable] (sample, ex, em), best of n_init starts.

Parameters:

Name Type Description Default
rank int

Number of components.

required
n_init int

Random starts (seeds random_state, random_state + 1, ...). The lowest-SSE fit is kept; all SSEs are stored to judge whether the solution is reproducible.

10
n_jobs int | None

Random starts run at the same time, in threads; None uses every processor, 1 runs them one after the other. Each start has its own seed, so the result does not depend on n_jobs.

None
normalization str | None

"norm": each sample is divided by its Frobenius norm before fitting and the scores are scaled back afterwards (Murphy et al. 2013); None: no scaling.

'norm'
tol float

Convergence: relative SSE change below tol.

1e-08
max_iter float

Convergence: relative SSE change below tol.

1e-08

Returns:

Type Description
Dataset

scores(sample, component) in the units of the data (after undoing the normalisation), ex_loadings(ex, component) and em_loadings(em, component) with unit Euclidean norm, fmax (sample, component) = maximum fluorescence of each component in each sample, leverages for every mode, per-sample residual SSE, and in attrs the fit statistics (SSE, explained variance, core consistency, iterations, all starts). Components are sorted by decreasing contribution to the modelled sum of squares.

fit_ranks

fit_ranks(ds: Dataset, ranks, **kwargs) -> dict[int, xr.Dataset]

:func:fit_parafac for each rank.

summary_table

summary_table(models: dict[int, Dataset])

One row per rank with the fit statistics.

model_eem

model_eem(model: Dataset) -> xr.DataArray

Modelled EEMs (sample, ex, em) in data units.

residuals

residuals(model: Dataset, ds: Dataset, variable: str = 'intensity') -> xr.DataArray

Data minus model (NaN where data are missing).

project_samples

project_samples(model: Dataset, ds: Dataset, variable: str = 'intensity') -> xr.Dataset

Scores of new samples on a fitted model, with its spectra kept fixed.

The excitation and emission loadings of model are not changed; for each sample of ds the scores are the non-negative least-squares fit of its observed (non-NaN) values (as drEEM's projectmodel and staRdom's A_missing). Dividing a sample by a constant divides its scores by the same constant, so the per-sample normalisation used to fit the model does not change the projected scores, which are in data units like the model's.

ds must be on the model's wavelengths (wider data are cut to them) and should be processed as the model's data were: a warning says when its processing history differs.

Returns scores, fmax, sse_sample and relative_sse (residual over data sum of squares) for every new sample, and outside_model_range: True when relative_sse is above the highest value among the samples used to fit the model, i.e. the model describes that sample worse than any sample it was built on. attrs hold that maximum and the model's main statistics.

eemkit.parafac.validation.split_half

split_half(ds: Dataset, rank: int, *, groups: ndarray | None = None, stratify: str | None = None, split_random_state: int = 0, threshold: float = 0.95, **fit_kwargs) -> xr.Dataset

Run the S4C6T3 split-half validation for one rank.

split_random_state seeds the division into groups; fit_kwargs (including random_state) go to :func:fit_parafac for every half. Returns a dataset with tcc_ex and tcc_em (test, component), the same for the shift- and shape-sensitive congruence ssc_ex, ssc_em (reported only; the decision uses TCC, as in Murphy et al. 2013), the half-model loadings (half, ex|em, component, aligned to the first half of each test), groups(sample) and attrs validated and min_tcc.

eemkit.parafac.compare

Comparing PARAFAC models and their components.

compare_models

compare_models(model1: Dataset, model2: Dataset) -> pd.DataFrame

Pair the components of two models and report how similar they are.

Components are paired by maximising the product of excitation and emission Tucker congruence (the models may have different ranks; the extra components of the larger one are listed unpaired). For each pair: tcc_ex, tcc_em (Tucker congruence) and ssc_ex, ssc_em (shift- and shape-sensitive congruence, :func:shift_shape_congruence). Wünsch et al. (2019) judge emission with SSC and excitation with TCC. The models must share the same wavelengths.

compare_ranks

compare_ranks(models: dict[int, Dataset]) -> pd.DataFrame

:func:compare_models between each rank and the next one.

Shows which components stay the same when one more is added and which split or change: a component that keeps TCC and SSC near 1 is stable.

component_correlations

component_correlations(model: Dataset, method: str = 'spearman') -> pd.DataFrame

Correlation between the Fmax of the components across samples.

Two components whose amounts always rise and fall together (|r| close to 1) may be one source split in two, or two sources that cannot be told apart in this dataset. method: "spearman" (rank correlation, default) or "pearson".

eemkit.parafac.outliers

Outlier diagnostics of a PARAFAC model: which samples and wavelengths fit badly.

Murphy et al. (2013) check every model for samples with high leverage (they pull the model towards themselves) and for samples or wavelengths with large residuals (the model does not describe them). These functions give the numbers; they set no threshold, because what counts as an outlier depends on the dataset: look at the samples at the top of the lists, at their residual EEMs (:func:eemkit.plot.residual_eems), and decide.

sample_labels

sample_labels(ds: Dataset) -> list[str]

Text columns that describe the samples (e.g. river, site, campaign).

File paths, instrument method names and the per-file metadata of the readers (eem_*, abs_*) are left out.

sample_diagnostics

sample_diagnostics(model: Dataset) -> pd.DataFrame

One row per sample: leverage, residual sums of squares and their ranks.

Columns: leverage; sse (data units squared); relative_sse (residual over the sample's data sum of squares, comparable between samples of different intensity); leverage_rank and residual_rank (1 = highest). Rows are sorted by the better of the two ranks, then by relative_sse, so the samples to inspect first come first. Sample columns of the model (e.g. river, campaign) are kept in front.

spectral_residuals

spectral_residuals(model: Dataset, ds: Dataset, variable: str = 'intensity') -> xr.Dataset

Residuals summed over samples, for each excitation and each emission wavelength.

sse_ex(ex) and sse_em(em): residual sum of squares over all samples and the other wavelength; relative_sse_ex and relative_sse_em: the same divided by the data sum of squares at that wavelength; bias_ex/bias_em: mean residual (data - model), which shows a systematic misfit (e.g. scatter left in the data) rather than noise; and the wavelength leverages of the model. Missing values are skipped. ds is the dataset the model was fitted to (the model's samples are taken from it).

eemkit.parafac.diagnostics

Model diagnostics: core consistency, leverage, congruence and component matching.

core_consistency

core_consistency(X: ndarray, A: ndarray, B: ndarray, C: ndarray) -> float

CORCONDIA in percent (Bro & Kiers 2003), computed as the N-way toolbox does.

Same computation as corcond of the N-way toolbox (Andersson & Bro 2000; version 2.01, the copy shipped with drEEM 2, called as drEEM's fitparafac calls it), so the values can be compared with drEEM's:

  1. each component's loading vectors are given the same norm, (|a_f| |b_f| |c_f|)^(1/3), so the result does not depend on how a component's size is split between the modes;
  2. the Tucker3 core G for these loadings is fitted by least squares to the observed cells only (missing values, e.g. scatter, are left out, not imputed);
  3. CC = 100 (1 - ||G - T||^2 / ||G||^2), with T the superdiagonal identity core.

Returns NaN, with a warning, if a loading matrix is rank-deficient (two components with the same profile in a mode); the N-way toolbox then changes the target core, which is not reproduced here.

leverage

leverage(M: ndarray) -> np.ndarray

Leverage of each row of a loading matrix: diag(M (M^T M)^-1 M^T).

tucker_congruence

tucker_congruence(P: ndarray, Q: ndarray) -> np.ndarray

Tucker's congruence coefficients between the columns of P and Q (F_P x F_Q).

shift_shape_congruence

shift_shape_congruence(P: ndarray, Q: ndarray, wavelengths: ndarray) -> np.ndarray

Shift- and shape-sensitive congruence between the columns of P and Q (F_P x F_Q).

SSC (Wünsch et al. 2019, Anal. Methods 11:888-893) lowers Tucker's congruence when two spectra peak at different wavelengths or have different widths, which TCC hardly notices::

SSC = TCC - alpha - beta
alpha = |wavelength of maximum(p) - wavelength of maximum(q)| / range
beta  = |area(p / max p) - area(q / max q)| / range

with range = last - first wavelength. The areas are trapezoidal integrals over wavelengths, so SSC does not depend on the wavelength step; staRdom's ssc sums the points instead, which on a 1 nm grid differs only by the half-weight of the two end points. Wünsch et al. compare emission spectra with SSC and excitation spectra with TCC.

eemqual

eemqual(model, split) -> dict[str, float]

EEMqual = fit x core consistency x split-half similarity (Bro & Vidal 2011).

Bro & Vidal (2011, Chemom. Intell. Lab. Syst. 106:86-92) rank PARAFAC models by the product of three numbers between 0 and 1. In eemkit they are:

  • fit: explained variance / 100;
  • core_consistency: core consistency / 100, negative values set to 0;
  • split_half: the lowest Tucker congruence of the split-half validation (split.attrs["min_tcc"], over every test, component and mode).

The split-half term is an eemkit choice: staRdom's eempf_eemqual uses the product of the best congruence of each component, which is never lower. EEMqual compares models fitted to the same data; it does not replace looking at the components.

match_components

match_components(ex1: ndarray, em1: ndarray, ex2: ndarray, em2: ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]

Pair components of two models by maximising the product of ex and em congruence.

Returns (order2, tcc_ex, tcc_em): model 2's component order2[f] matches model 1's component f, with the congruences of each pair.

eemkit.parafac.export.to_openfluor

to_openfluor(model: Dataset, path: str | Path, **metadata: str) -> Path

Write model's excitation and emission loadings for OpenFluor.

Loadings are scaled to a maximum of 1 per component (OpenFluor compares shapes). Unknown metadata are written as '?'; pass e.g. name=, creator=, doi=, description=. Fields derived from the model (unit, toolbox, date, nSample, constraints) are filled in unless given.

Rivers, sites and dates

eemkit.campaigns

Comparing sampling campaigns, sites and rivers.

Works on any per-sample table (indices, CDOM metrics, PARAFAC Fmax) with columns that name the group (e.g. river), the site and the time (e.g. campaign). The statistical unit is the mean of the replicates of one site at one time (:func:site_means), so replicates are never counted as independent samples.

  • :func:design_table and :func:confounding show which groups were sampled at which times, and say when group and time cannot be separated (for example rivers that were sampled in different months);
  • :func:compare_times: within each group, Kruskal-Wallis test between times (Kruskal & Wallis 1952) and Dunn's pairwise test (Dunn 1964) with Holm's correction (Holm 1979);
  • :func:spatial_trend: Spearman correlation with a site position (e.g. distance from the source), per group;
  • :func:covariate_correlations: Spearman correlation with covariates per group and time (e.g. discharge, rainfall);
  • :func:composition: the share of each PARAFAC component in total Fmax.

Optional tables are joined explicitly on their key columns (:func:join_sites, :func:join_covariates); rows that do not match are reported, never guessed.

site_means

site_means(df: DataFrame, values: Sequence[str], *, group: str, time: str, site: str | None = None) -> pd.DataFrame

Mean, standard deviation and coefficient of variation of the replicates.

One row per (group, site, time); n is the number of replicates. Without site all samples of a group at one time are pooled.

composition

composition(df: DataFrame, fmax_columns: Sequence[str]) -> pd.DataFrame

Percentage of each component in the summed Fmax of each sample.

design_table

design_table(units: DataFrame, *, group: str, time: str) -> pd.DataFrame

Number of units for every (time, group) combination.

confounding

confounding(units: DataFrame, *, group: str, time: str) -> list[str]

Plain-language warnings when group and time effects cannot be separated.

dunn

dunn(values: Sequence[float], labels: Sequence[str]) -> pd.DataFrame

Dunn's (1964) pairwise test after Kruskal-Wallis, with tie correction and Holm.

Returns one row per pair: mean ranks, z, two-sided p and Holm-adjusted p.

compare_times

compare_times(units: DataFrame, value: str, *, group: str, time: str) -> tuple[pd.DataFrame, pd.DataFrame]

Within each group, differences of value between times.

Returns (kruskal, pairwise): one Kruskal-Wallis row per group (H, degrees of freedom, p, number of units and times, or a note when the test cannot be run) and Dunn's pairwise comparisons with Holm-adjusted p.

spatial_trend

spatial_trend(units: DataFrame, value: str, position: str, *, group: str, time: str | None = None) -> pd.DataFrame

Spearman correlation between value and a site position within each group.

With time, also one row per (group, time). position is any number that orders the sites, e.g. distance from the source in km.

covariate_correlations

covariate_correlations(units: DataFrame, value: str, covariates: Sequence[str], *, group: str) -> pd.DataFrame

Spearman correlation between value and each covariate, per group and overall.

join_sites

join_sites(units: DataFrame, sites: DataFrame, *, group: str, site: str) -> tuple[pd.DataFrame, list[str]]

Add the columns of a site table (e.g. latitude, longitude, distance) by (group, site).

join_covariates

join_covariates(units: DataFrame, covariates: DataFrame, *, group: str, time: str) -> tuple[pd.DataFrame, list[str]]

Add the columns of a covariate table (e.g. discharge, rainfall) by (group, time).

The time values must be written exactly as in the sample table (e.g. 2024-05 for a campaign); no date matching is attempted.

Pipeline

eemkit.pipeline

The full processing chain, driven by one settings file.

The settings are a nested dictionary, stored as TOML, with the sections project, spectral, inner_filter, raman, scatter, crop, indices, absorbance, campaigns, parafac (with split_half and final), channels, missing and display. The same file drives scripts and the desktop application, so every analysis can be rerun from the command line.

Steps, in the enforced order of the corrections:

  1. :func:load - read the samples included in the pairing table;
  2. :func:correct_until_raman - optional instrument spectral correction, absorbance blank, inner filter, EEM blank, Raman units; :func:finish_corrections - scatter, optional interpolation, crop;
  3. :func:compute_indices - on the Raman-normalised EEMs, before scatter removal; :func:compute_absorbance - CDOM metrics;
  4. :func:explore - PARAFAC for a range of ranks with split-half validation; :func:fit_final - the chosen rank with tighter convergence;
  5. :func:campaign_analysis - differences between campaigns, along sites and with covariates, on any column of :func:sample_table;
  6. :func:export_results - tables, OpenFluor file, figures, settings and processing history; :func:export_campaigns for campaign analyses.

Defaults that are scientific choices are listed in :data:DEFAULTS with their source; values that depend on the measurement (cuvette path lengths) have no default and must be set.

default_settings

default_settings() -> dict

A fresh copy of :data:DEFAULTS.

load_settings

load_settings(path: str | Path) -> dict

Read a settings TOML; keys it does not set take :data:DEFAULTS.

dumps_settings

dumps_settings(settings: dict) -> str

Settings as TOML text. None values (unset) are written as comments.

load

load(settings: dict, base: str | Path | None = None) -> xr.Dataset

Read the included rows of project.pairing (paths relative to base).

reader_options

reader_options(settings: dict) -> dict

Keyword arguments for the EEM reader of project.instrument.

inner_filter_skip_reason

inner_filter_skip_reason(settings: dict) -> str | None

None if the inner-filter correction is applied, else the reason it is not.

Raises :class:~eemkit.errors.SettingsError when inner_filter.apply is false without a skip_reason: the correction is never left out silently.

correct_until_raman

correct_until_raman(ds: Dataset, settings: dict, base: str | Path | None = None) -> xr.Dataset

Spectral correction (if factor files are set), absorbance blank, inner filter (or, with inner_filter.apply = false, a history entry with the reason it is not applied), EEM blank and Raman units; then dilution (when the pairing table has dilution columns) and the regions of zap.regions. Factor files are relative to base. Steps listed in project.already_done were done by the instrument software: they are recorded, not repeated, and must agree with what the files say (:func:eemkit.corrections.instrument.check_declared).

finish_corrections

finish_corrections(ds: Dataset, settings: dict) -> xr.Dataset

Scatter removal, optional interpolation of the gaps, crop.

compute_indices

compute_indices(after_raman: Dataset, settings: dict) -> pd.DataFrame

FI, HIX, BIX and Coble peaks, with the sample metadata in front.

compute_absorbance

compute_absorbance(after_raman: Dataset, settings: dict) -> pd.DataFrame

CDOM metrics (a254, a350, spectral slopes, SR, E2:E3, SUVA254 with DOC).

parafac_input

parafac_input(corrected: Dataset, settings: dict) -> xr.Dataset

Drop excluded samples; add the split-half stratum coordinate.

explore

explore(ds: Dataset, settings: dict, *, progress: Progress | None = None, cancelled: Callable[[], bool] | None = None, n_jobs: int | None = None) -> Exploration

PARAFAC and split-half validation for every rank in parafac.ranks.

cancelled is polled between fits; when it returns True, :class:~eemkit.errors.Cancelled is raised. n_jobs: random starts run at the same time (see :func:eemkit.parafac.fit_parafac); it does not change the result.

fit_final

fit_final(ds: Dataset, settings: dict, *, progress: Progress | None = None, cancelled: Callable[[], bool] | None = None, n_jobs: int | None = None) -> tuple[xr.Dataset, xr.Dataset]

The rank in parafac.final.rank with its own convergence settings.

channel_specs

channel_specs(settings: dict) -> dict

The channels section as the argument of :func:eemkit.parafac.component_signals.

Each channel is {"ex": LED wavelength, "em": [filter low, filter high]} (nm); names may hold letters, digits, _ and - only (they are TOML keys and column labels). Raises :class:SettingsError for anything else.

channel_signals

channel_signals(model: Dataset, settings: dict, reduce: str = 'integral') -> xr.Dataset | None

Signal of each component in each channel of settings['channels'] (None if none).

See :func:eemkit.parafac.component_signals.

channel_tables

channel_tables(signals: Dataset) -> tuple[pd.DataFrame, pd.DataFrame]

signals as two tables: per sample, channel and component (signal, share), and the sensitivity of each channel to each component (rows = channels).

sample_table

sample_table(indices: DataFrame | None, model: Dataset | None = None) -> pd.DataFrame

Indices and CDOM metrics, plus Fmax and the share of each component if a model is given.

Samples left out of the model have no Fmax (empty cells).

campaign_analysis

campaign_analysis(table: DataFrame, value: str, settings: dict, base: str | Path | None = None) -> CampaignAnalysis

Differences of value between times, along sites and with covariates.

Uses settings["campaigns"]: group, time and optionally site, position (a column of the site table or of table) and the two optional tables (paths relative to base).

export_campaigns

export_campaigns(out_dir: str | Path, analysis: CampaignAnalysis, settings: dict, figures: bool = True) -> list[Path]

Tables (and figures) of one campaign analysis in out_dir.

export_results

export_results(out_dir: str | Path, settings: dict, *, corrected: Dataset | None = None, indices: DataFrame | None = None, exploration: Exploration | None = None, model: Dataset | None = None, split: Dataset | None = None, openfluor: dict | None = None, figures: bool = True, report: bool = False) -> list[Path]

Write whatever results are given; returns the paths written.

Always writes settings.toml and processing_record.json (versions, processing history, sample list) so the run can be repeated. With report=True also report.html (:func:eemkit.report.write_report); figures and report need matplotlib.

export_figures

export_figures(out: Path, settings: dict, exploration: Exploration | None, model: Dataset | None, split: Dataset | None) -> list[Path]

Rank diagnostics, components and leverage figures (needs matplotlib).

Figures

eemkit.plot

Publication figures for EEMs, PARAFAC models and indices (requires matplotlib).

Install with pip install eemkit[plot]. Every function draws on matplotlib axes and returns the figure, so figures can be adjusted before saving; :func:save writes a vector PDF and a 300 dpi PNG side by side.

Colour rules: EEM intensities use one sequential hue by default (light = low, :data:SEQUENTIAL); cmap="eclipse" gives instead the violet-to-red rainbow of the Cary Eclipse software (:data:ECLIPSE), familiar on screen but not perceptually ordered (Crameri et al. 2020). Groups and components use a fixed categorical order (:data:CATEGORICAL) and also differ in marker or line style, so identity never relies on colour alone. Missing cells (removed scatter) are shown in light grey.

style

style()

Context manager applying the eemkit figure style to matplotlib.

save

save(fig, path: str | Path, formats: Sequence[str] = ('pdf', 'png')) -> list[Path]

Save fig as path with each suffix in formats; returns the paths.

add_colorbar

add_colorbar(cs, ax, label: str = '')

A thin colour bar for cs beside ax (an axes or a list of axes).

eem

eem(ax, da: DataArray, *, vmax: float | None = None, levels: int = 16, colorbar: bool = True, label: str | None = None, cmap='blues')

Filled contours of one EEM (dims ex, em): emission on x, excitation on y.

The colour scale runs from 0 to vmax (default: the EEM maximum); values outside share the end colours, so a vmax below the scatter peaks keeps the fluorescence readable. NaN cells (removed scatter) stay grey. cmap is a name in :data:COLORMAPS or a matplotlib colour map. Returns the contour set.

eems

eems(panels: Mapping[str, DataArray], *, ncols: int = 3, shared_scale: bool = False, vmax: float | Mapping[str, float] | None = None, width: float = DOUBLE_COLUMN, cmap='blues')

Small multiples of EEMs, one titled panel per mapping entry.

vmax (one value, or one per panel title) caps the colour scale; shared_scale uses the largest maximum for every panel instead.

spectral_factors

spectral_factors(ds: Dataset, *, width: float = SINGLE_COLUMN)

The excitation and emission correction factors applied to ds.

Needs the spectral_correction_ex and spectral_correction_em variables written by :func:eemkit.corrections.apply_spectral_correction.

components

components(model: Dataset, split_half: Dataset | None = None, *, names: Sequence[str] | None = None, width: float = DOUBLE_COLUMN, cmap='blues')

One column per component: its EEM (top) and its loadings (bottom).

Loadings are scaled to a maximum of 1; with split_half, the loadings of every half-model are drawn as thin grey lines behind the final model.

channel_signals

channel_signals(signals: Dataset, model: Dataset | None = None, *, names: Sequence[str] | None = None, width: float = DOUBLE_COLUMN, cmap='blues')

What each LED and filter channel sees: where it sits, and which components it follows.

signals is the output of :func:eemkit.parafac.component_signals. Right panel: one bar per channel, split by the share of each component in its signal (mean over the samples; a component is also told apart by its hatch, not by colour alone). With model a left panel shows the mean modelled EEM with each channel on it: the LED excitation (vertical position) and the filter band (horizontal extent), so a channel that sits on the edge of a humic peak instead of the protein peak is visible at a glance.

rank_diagnostics

rank_diagnostics(table: DataFrame, *, threshold: float = 0.95, chosen: int | None = None, width: float = DOUBLE_COLUMN)

Explained variance, core consistency and split-half congruence against rank.

table is indexed by rank with columns explained_pct, core_consistency_pct and split_half_min_tcc (as written by :func:eemkit.parafac.summary_table plus the split-half results, e.g. :func:eemkit.pipeline.explore). One panel per measure: no shared y-axis between different quantities.

leverage

leverage(model: Dataset, *, by: str | None = None, n_label: int = 5, width: float = SINGLE_COLUMN)

Sample leverage against normalised residual sum of squares (outlier check).

The n_label samples furthest out (leverage and residual each scaled to their maximum) are labelled.

residual_eems

residual_eems(model: Dataset, ds: Dataset, samples: Sequence[str] | None = None, *, n: int = 3, variable: str = 'intensity', width: float = DOUBLE_COLUMN, cmap='blues')

Measured, modelled and residual EEM of a few samples (one column each).

Default: the n samples with the highest relative residual (:func:eemkit.parafac.sample_diagnostics). Measured and modelled share one colour scale per sample; the residual (data - model) uses a diverging scale centred on 0, so structure left in it (a peak, a scatter band) shows what the model misses.

spectral_residuals

spectral_residuals(residuals: Dataset, *, width: float = DOUBLE_COLUMN)

Relative residual and mean residual against excitation and emission wavelength.

residuals is the output of :func:eemkit.parafac.spectral_residuals. A wavelength with a high relative residual or a mean residual far from 0 is fitted badly in every sample: often a scatter band not fully removed, or the edge of the instrument's range.

campaign_series

campaign_series(units: DataFrame, value: str, *, group: str, time: str, width: float = SINGLE_COLUMN * 1.4)

value over time, one line per group: mean +/- SD across sites.

units holds one row per site and time (replicate means, as returned by :func:eemkit.campaigns.site_means); its points are drawn behind the means.

along_sites

along_sites(units: DataFrame, value: str, position: str, *, group: str, width: float = SINGLE_COLUMN * 1.4)

value against site position (e.g. distance from the source), one series per group.

composition

composition(units: DataFrame, pct_columns: Sequence[str], *, group: str, time: str, width: float = DOUBLE_COLUMN)

Mean share (%) of each PARAFAC component per time, one panel per group (stacked bars).

scores_over

scores_over(df: DataFrame, columns: Sequence[str], *, x: str, by: str, titles: Sequence[str] | None = None, ylabel: str = '', x_order: Sequence | None = None, x_labels: Mapping[str, str] | None = None, xlabel: str = '', width: float = DOUBLE_COLUMN, ncols: int | None = None)

Mean +/- standard deviation of each column per (x, by) group, one panel per column.

Typical use: Fmax or indices over sampling campaigns (x), one line per river (by). Replicates and sites are pooled in each group; individual samples are drawn as faint points behind the means. x_labels maps x values to shorter tick labels.

Report

eemkit.report.write_report

write_report(path: str | Path, settings: dict, *, corrected: Dataset | None = None, indices: DataFrame | None = None, exploration=None, model: Dataset | None = None, split: Dataset | None = None, title: str | None = None, n_residual_samples: int = 3) -> Path

Write the HTML report of an analysis; returns its path.

Every argument except path and settings is optional: the report contains the sections for the results given. corrected is the dataset after all corrections (the model's samples are taken from it for the residual figures); exploration is the result of :func:eemkit.pipeline.explore.

Command line

eemkit.cli.main

main(argv: list[str] | None = None) -> int