SPM Modules

For decoding and loading .spm AFM file format into Python Numpy arrays.

get_spm_channels(file_path: Path | str) -> list

Get the list of channels available in the .spm file.

Parameters:

Name Type Description Default
file_path Path or str

Path to the .spm file.

required

Returns:

Type Description
list

List of available channels.

Source code in AFMReader/spm.py
def get_spm_channels(file_path: Path | str) -> list:
    """
    Get the list of channels available in the .spm file.

    Parameters
    ----------
    file_path : Path or str
        Path to the .spm file.

    Returns
    -------
    list
        List of available channels.
    """
    labels = []
    file_path = Path(file_path)
    filename = file_path.stem
    try:
        scan = pySPM.Bruker(file_path)
    except FileNotFoundError:
        logger.error(f"[{filename}] File not found : {file_path}")
        raise
    for channel_option in [layer[b"@2:Image Data"][0] for layer in scan.layers]:
        channel_name = channel_option.decode("latin1").split('"')[1]
        labels.append(channel_name)
    return labels

load_spm(file_path: Path | str, channel: str) -> AFMScan

Extract image and pixel to nm scaling from the Bruker .spm file.

Parameters:

Name Type Description Default
file_path Path or str

Path to the .spm file.

required
channel str

Channel name to extract from the .spm file.

required

Returns:

Type Description
AFMScan

An AFMScan object containing the image, its pixel to nanometre scaling value, and z-axis units.

Raises:

Type Description
FileNotFoundError

If the file is not found.

ValueError

If the channel is not found in the .spm file.

Examples:

Load the image and pixel to nanometre scaling factor, available channels are 'Height', 'ZSensor' and 'Height Sensor'.

>>> from AFMReader.spm import load_spm
>>> afm_scan = load_spm(file_path="path/to/file.spm", channel="Height")
>>> image = afm_scan.image
>>> pixel_to_nm = afm_scan.pixel_to_nanometre_scaling
>>> z_units = afm_scan.z_units
```
Source code in AFMReader/spm.py
def load_spm(file_path: Path | str, channel: str) -> AFMScan:
    """
    Extract image and pixel to nm scaling from the Bruker .spm file.

    Parameters
    ----------
    file_path : Path or str
        Path to the .spm file.
    channel : str
        Channel name to extract from the .spm file.

    Returns
    -------
    AFMScan
        An AFMScan object containing the image, its pixel to nanometre scaling value, and z-axis units.

    Raises
    ------
    FileNotFoundError
        If the file is not found.
    ValueError
        If the channel is not found in the .spm file.

    Examples
    --------
    Load the image and pixel to nanometre scaling factor, available channels are 'Height', 'ZSensor' and 'Height
    Sensor'.

    >>> from AFMReader.spm import load_spm
    >>> afm_scan = load_spm(file_path="path/to/file.spm", channel="Height")
    >>> image = afm_scan.image
    >>> pixel_to_nm = afm_scan.pixel_to_nanometre_scaling
    >>> z_units = afm_scan.z_units
    ```
    """
    logger.info(f"Loading image from : {file_path}")
    file_path = Path(file_path)
    filename = file_path.stem
    try:
        scan = pySPM.Bruker(file_path)
        logger.info(f"[{filename}] : Loaded image from : {file_path}")
        channel_data = scan.get_channel(channel)
        logger.info(f"[{filename}] : Extracted channel {channel}")
        unit = channel_data.zscale
        image = np.flipud(np.array(channel_data.pixels))
    except FileNotFoundError:
        logger.error(f"[{filename}] File not found : {file_path}")
        raise
    except Exception as e:
        if "Channel" in str(e) and "not found" in str(e):
            # trying to return the error with options of possible channel values
            labels = []
            for channel_option in [layer[b"@2:Image Data"][0] for layer in scan.layers]:
                channel_name = channel_option.decode("latin1").split('"')[1]
                labels.append(channel_name)
            logger.error(f"[{filename}] : '{channel}' not in {file_path.suffix} channel list: {labels}")
            raise ValueError(f"'{channel}' not in {file_path.suffix} channel list: {labels}") from e
        raise e

    return AFMScan(
        image=image,
        pixel_to_nanometre_scaling=spm_pixel_to_nm_scaling(filename, channel_data),
        z_units=unit,
    )

spm_pixel_to_nm_scaling(filename: str, channel_data: pySPM.SPM.SPM_image) -> float

Extract pixel to nm scaling from the SPM image metadata.

Parameters:

Name Type Description Default
filename str

File name.

required
channel_data SPM_image

Channel data from PySPM.

required

Returns:

Type Description
float

Pixel to nm scaling factor.

Source code in AFMReader/spm.py
def spm_pixel_to_nm_scaling(filename: str, channel_data: pySPM.SPM.SPM_image) -> float:
    """
    Extract pixel to nm scaling from the SPM image metadata.

    Parameters
    ----------
    filename : str
        File name.
    channel_data : pySPM.SPM.SPM_image
        Channel data from PySPM.

    Returns
    -------
    float
        Pixel to nm scaling factor.
    """
    unit_dict = {
        "pm": 1e-3,
        "nm": 1,
        "um": 1e3,
        "mm": 1e6,
    }
    px_to_real = channel_data.pxs()
    # Has potential for non-square pixels but not yet implimented
    pixel_to_nm_scaling = (
        px_to_real[0][0] * unit_dict[px_to_real[0][1]],
        px_to_real[1][0] * unit_dict[px_to_real[1][1]],
    )[0]
    # ns-rse : Perhaps just switch to _always_ using the parameters from channel_data.size to calculate scaling?
    if px_to_real[0][0] == 0 and px_to_real[1][0] == 0:
        logger.info(
            f"[{filename}] : Pixel to nm scaling not directly available, calculating from 'channel_data.size['real']' "
            "and 'channel_data.size['pixels']'."
        )
        pixel_to_nm_scaling = (
            (channel_data.size["real"]["x"] / channel_data.size["pixels"]["x"])
            / unit_dict[channel_data.size["real"]["unit"]],
            (channel_data.size["real"]["y"] / channel_data.size["pixels"]["y"])
            / unit_dict[channel_data.size["real"]["unit"]],
        )[0]
    logger.info(f"[{filename}] : Pixel to nm scaling : {pixel_to_nm_scaling}")
    return pixel_to_nm_scaling