Skip to content

asaf.isotherm

Provides the Isotherm class to store, manipulate, plot and save adsorption isotherm data.

Isotherm

Isotherm(
    data: DataFrame | None = None,
    saturation_fugacity: float | None = None,
    saturation_pressure: float | None = None,
    metadata: dict[str, Any] | None = None,
    fugacity_unit: str = "Pa",
    uptake_unit: str = "molecules/unitcell",
)

Isotherm class to store, recalculate and save the adsorption isotherm.

Parameters:

  • data (DataFrame | None, default: None ) –

    A pandas DataFrame containing the adsorption data. Should contain 'pressure' and 'uptake' columns.

  • saturation_fugacity (float | None, default: None ) –

    The saturation fugacity at given conditions. Used to calculate relative fugacity (f/f0).

  • saturation_pressure (float | None, default: None ) –

    The saturation pressure at given conditions. Used to calculate relative pressure (p/p0).

  • metadata (dict[str, Any] | None, default: None ) –

    A dictionary with the simulation metadata.

  • uptake_unit (str, default: 'molecules/unitcell' ) –

    Units at which uptake is stored. Default value is 'molecules/unitcell'.

Source code in src/asaf/isotherm.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def __init__(
    self,
    data: pd.DataFrame | None = None,
    saturation_fugacity: float | None = None,
    saturation_pressure: float | None = None,
    metadata: dict[str, Any] | None = None,
    fugacity_unit: str = "Pa",
    uptake_unit: str = "molecules/unitcell",
) -> None:
    """Initialize the Isotherm object.

    Parameters
    ----------
    data
        A pandas DataFrame containing the adsorption data. Should contain 'pressure' and 'uptake' columns.
    saturation_fugacity
        The saturation fugacity at given conditions. Used to calculate relative fugacity (f/f0).
    saturation_pressure
        The saturation pressure at given conditions. Used to calculate relative pressure (p/p0).
    metadata
        A dictionary with the simulation metadata.
    uptake_unit
        Units at which uptake is stored. Default value is 'molecules/unitcell'.
    """
    self.dataframe = data
    self._metadata = {}
    self.metadata = metadata
    self._pressure_unit = fugacity_unit
    self._uptake_unit = uptake_unit
    self.saturation_fugacity = saturation_fugacity
    self.saturation_pressure = saturation_pressure

amount_adsorbed property

amount_adsorbed: Series

Return the uptake column.

dataframe property writable

dataframe: DataFrame

Return dataframe with isotherm data.

fugacity property

fugacity: Series | None

Return the fugacity column.

metadata property writable

metadata: dict[str, Any]

Return the metadata dictionary.

metastable_gas property

metastable_gas: Series | None

Return the metastable gas column, if it exists.

metastable_liq property

metastable_liq: Series | None

Return the metastable liquid column, if it exists.

pressure property writable

pressure: Series | None

Return the pressure column.

pressure_unit property

pressure_unit: str

Return the current pressure unit.

saturation_fugacity property writable

saturation_fugacity: float | None

Return the saturation fugacity.

saturation_pressure property writable

saturation_pressure: float | None

Return the saturation pressure.

uptake_unit property

uptake_unit: str

Return the current uptake unit.

plot

plot(
    label: str | None = None,
    fig: Figure | None = None,
    x_axis: str = "auto",
    y_axis: str | None = None,
    trace_kwargs: dict[str, Any] | None = None,
    layout_kwargs: dict[str, Any] | None = None,
    uptake_conversion_factor: float | None = None,
    show: bool = False,
) -> Figure

Plot an isotherm (stable + metastable gas and / or liquid) and group all traces under a single legend entry.

You can pass any kwargs through trace_kwargs or layout_kwargs; missing values will be filled in by defaults.

Source code in src/asaf/isotherm.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
def plot(
    self,
    label: str | None = None,
    fig: Figure | None = None,
    x_axis: str = "auto",
    y_axis: str | None = None,
    trace_kwargs: dict[str, Any] | None = None,
    layout_kwargs: dict[str, Any] | None = None,
    uptake_conversion_factor: float | None = None,
    show: bool = False,
) -> Figure:
    """Plot an isotherm (stable + metastable gas and / or liquid) and group all traces under a single legend entry.

    You can pass any kwargs through `trace_kwargs` or `layout_kwargs`; missing values will be filled in by defaults.
    """
    import plotly.colors as pc
    import plotly.graph_objects as go

    if fig is None:
        fig = go.Figure()

    trace_kwargs = trace_kwargs or {}
    layout_kwargs = layout_kwargs or {}

    # look for an explicit color in trace_kwargs
    explicit_color = None
    if "line" in trace_kwargs and isinstance(trace_kwargs["line"], dict):
        explicit_color = trace_kwargs["line"].get("color")

    if explicit_color:
        color = explicit_color
    else:
        default_colors = pc.qualitative.Vivid
        calls = getattr(fig, "_plot_calls", 0)
        color = default_colors[calls % len(default_colors)]
        fig._plot_calls = calls + 1

    x_vals, x_title = self._resolve_x_axis(x_axis)
    y_axis = y_axis or self.uptake_unit
    y_factor = self._uptake_conversion_factor(y_axis, uptake_conversion_factor)

    legend_name = label or "Uptake"
    legendgroup = f"asaf-isotherm-{getattr(fig, '_asaf_isotherm_groups', 0)}"
    fig._asaf_isotherm_groups = getattr(fig, "_asaf_isotherm_groups", 0) + 1
    lg = dict(legendgroup=legendgroup)

    default_stable = {
        "x": x_vals,
        "y": self.amount_adsorbed * y_factor,
        "mode": "lines+markers",
        "name": legend_name,
        "line": dict(color=color),
        "marker": dict(
            color=color,
            symbol=trace_kwargs.get("marker", {}).get("symbol", "circle"),
        ),
        **lg,
    }

    user_line = trace_kwargs.get("line", {})
    user_marker = trace_kwargs.get("marker", {})

    stable_line = {**default_stable["line"], **user_line}
    stable_marker = {**default_stable["marker"], **user_marker}

    merged_stable = {
        **default_stable,
        **trace_kwargs,
        "line": stable_line,
        "marker": stable_marker,
    }

    fig.add_trace(go.Scatter(**merged_stable))

    # metastable defaults: just dashed line, no markers, and no extra legend entry
    default_meta = {
        "x": x_vals,
        "mode": "lines",
        "name": legend_name,
        "line": dict(color=color, dash="dash"),
        "showlegend": False,
        **lg,
    }

    meta_trace_kwargs = {**default_meta, **trace_kwargs}

    if self.metastable_gas is not None:
        gas_line = {**default_meta["line"], **user_line, "dash": "dash"}
        fig.add_trace(
            go.Scatter(
                y=self.metastable_gas * y_factor,
                **{**meta_trace_kwargs, "line": gas_line},
            )
        )
    if self.metastable_liq is not None:
        liq_line = {**default_meta["line"], **user_line, "dash": "dot"}
        fig.add_trace(
            go.Scatter(
                y=self.metastable_liq * y_factor,
                **{**meta_trace_kwargs, "line": liq_line},
            )
        )

    base_layout = dict(
        font=dict(family="Helvetica Neue", size=14, color="black"),
        xaxis=dict(
            showline=True,
            linewidth=1,
            linecolor="black",
            gridcolor="lightgrey",
            mirror=True,
            zeroline=False,
            ticks="inside",
            title=x_title,
        ),
        yaxis=dict(
            showline=True,
            linewidth=1,
            linecolor="black",
            gridcolor="lightgrey",
            mirror=True,
            zeroline=False,
            ticks="inside",
            title=f"Uptake ({y_axis})",
        ),
        plot_bgcolor="white",
        width=700,
        height=500,
        margin=dict(l=30, r=30, t=30, b=30),
        legend=dict(traceorder="grouped"),
    )
    fig.update_layout(**{**base_layout, **layout_kwargs})

    if show:
        fig.show()

    return fig

set_pressure_unit

set_pressure_unit(
    target_unit: str, conversion_factor: float
) -> None

Convert the pressure column to the target unit using the provided conversion factor.

Source code in src/asaf/isotherm.py
136
137
138
139
140
141
142
143
def set_pressure_unit(self, target_unit: str, conversion_factor: float) -> None:
    """Convert the pressure column to the target unit using the provided conversion factor."""
    if self.pressure is None:
        raise ValueError(
            "Cannot convert pressure units: no 'pressure' column found."
        )
    self.pressure = self.pressure * conversion_factor
    self._pressure_unit = target_unit

set_uptake_unit

set_uptake_unit(
    target_unit: str, conversion_factor: float | None = None
) -> None

Convert the uptake column to the target unit.

Source code in src/asaf/isotherm.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def set_uptake_unit(
    self, target_unit: str, conversion_factor: float | None = None
) -> None:
    """Convert the uptake column to the target unit."""
    conversion_factor = self._uptake_conversion_factor(
        target_unit, conversion_factor
    )

    self.dataframe["uptake"] = self.dataframe["uptake"] * conversion_factor
    if self.metastable_gas is not None:
        self.dataframe["metastable_gas"] = (
            self.dataframe["metastable_gas"] * conversion_factor
        )
    if self.metastable_liq is not None:
        self.dataframe["metastable_liq"] = (
            self.dataframe["metastable_liq"] * conversion_factor
        )

    self._uptake_unit = target_unit

to_aif

to_aif(
    filename: str,
    user_key_mapper: dict[str, Any] | None = None,
) -> None

Save the isotherm in an AIF file format.

Parameters:

  • filename (str) –

    The name of the file to be saved.

  • user_key_mapper (dict[str, Any] | None, default: None ) –

    A dictionary based on which keys from the metadata are transformed into keys according to aifdictionary.json. Required format: {'_AIF_key': 'metadata_key'}.

Returns:

  • None
Source code in src/asaf/isotherm.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
def to_aif(
    self, filename: str, user_key_mapper: dict[str, Any] | None = None
) -> None:
    """Save the isotherm in an AIF file format.

    Parameters
    ----------
    filename
        The name of the file to be saved.
    user_key_mapper
        A dictionary based on which keys from the metadata are transformed into keys
        according to aifdictionary.json. Required format: {'_AIF_key': 'metadata_key'}.

    Returns
    -------
    None
    """
    from gemmi import cif

    metadata = self.metadata
    key_mapper = {
        "_exptl_temperature": "temperature",
        "_units_temperature": "temperature_units",
        "_adsnt_material_id": "framework_name",
        "_exptl_adsorptive_name": "molecule_name",
        "_simltn_code": "code_name",
        "_simltn_date": "simulation_date",
        "_simltn_size": "system_size",
        "_simltn_forcefield_adsorptive": "molecule_force_field",
        "_simltn_forcefield_adsorbent": "framework_force_field",
        "_units_pressure": "pressure_units",
        "_units_fugacity": "fugacity_units",
        "_units_loading": "loading_units",
    }

    if user_key_mapper:
        key_mapper.update(user_key_mapper)

    doc = cif.Document()
    doc.add_new_block("isotherm")
    block = doc.sole_block()

    if metadata:
        for key, value in key_mapper.items():
            if value in metadata.keys():
                if isinstance(metadata[value], (int, float)):
                    block.set_pair(key, str(metadata[value]))
                else:
                    block.set_pair(key, quote(metadata[value]))

    block.set_pair("_units_loading", quote(self.uptake_unit))
    block.set_pair("_audit_aif_version", quote("63df4e8"))

    df = self.dataframe.copy()
    column_map = (
        ("pressure", "pressure"),
        ("fugacity", "fugacity"),
        ("p/p0", "relative_pressure"),
        ("f/f0", "relative_fugacity"),
        ("relative_humidity", "relative_humidity"),
        ("relative humidity", "relative_humidity"),
        ("RH", "relative_humidity"),
        ("rh", "relative_humidity"),
        ("metastable_gas", "amount_metastable_gas"),
        ("metastable_liq", "amount_metastable_liq"),
    )

    loop_columns = []
    loop_tags = []
    for column, tag in column_map:
        if column in df.columns:
            loop_columns.append(column)
            loop_tags.append(tag)

    if self.saturation_pressure is not None and "pressure" in df.columns:
        df["saturation_pressure"] = self.saturation_pressure
        loop_columns.append("saturation_pressure")
        loop_tags.append("p0")

    if self.saturation_fugacity is not None and "fugacity" in df.columns:
        df["saturation_fugacity"] = self.saturation_fugacity
        loop_columns.append("saturation_fugacity")
        loop_tags.append("f0")

    if "uptake" not in loop_columns:
        loop_columns.append("uptake")
        loop_tags.append("amount")

    if len(loop_columns) == 1:
        raise ValueError(
            "AIF export requires at least one pressure-related column in addition to 'uptake'."
        )

    loop_ads = block.init_loop("_adsorp_", loop_tags)
    loop_ads.set_all_values(
        [list(df[column].values.astype(str)) for column in loop_columns]
    )

    if filename.endswith(".aif"):
        filename = filename[:-4]
    doc.write_file(f"{filename}.aif")

to_csv

to_csv(filename: str) -> None

Save the isotherm data to a CSV file.

Source code in src/asaf/isotherm.py
539
540
541
def to_csv(self, filename: str) -> None:
    """Save the isotherm data to a CSV file."""
    self.dataframe.to_csv(filename, index=False)

options: filters: ["!^_"]