Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add topostats file helper class #945

Draft
wants to merge 11 commits into
base: main
Choose a base branch
from
141 changes: 141 additions & 0 deletions notebooks/topostats_file_helper_example.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Import needed libraries\n",
"import numpy as np\n",
"from topostats.io import TopoFileHelper\n",
"from IPython.display import clear_output\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load topostats file"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Load topostats file\n",
"file = \"../tests/resources/file.topostats\"\n",
"helper = TopoFileHelper(file)\n",
"# Clear logging output\n",
"clear_output(wait=False)\n",
"print(\"File loaded\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Print the structure of the file"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Print the structure of the file\n",
"helper.pretty_print_structure()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Find data within the file"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Find the name of the data we want, we know it contains \"ordered_trace_heights\" and we want grain 2, but don't know\n",
"# what keys precede it\n",
"helper.find_data([\"ordered_trace_heights\", \"2\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Retrieve data from the file"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Get some data from the file\n",
"cropped_image = helper.get_data(\"grain_trace_data/above/cropped_images/2\")\n",
"ordered_trace_heights = helper.get_data(\"grain_trace_data/above/ordered_trace_heights/2\")\n",
"cumulative_distances = helper.get_data(\"grain_trace_data/above/ordered_trace_cumulative_distances/2\")\n",
"ordered_traces = helper.get_data(\"grain_trace_data/above/ordered_traces/2\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use the retrieved data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Plot the image\n",
"plt.imshow(cropped_image)\n",
"# Create a basic colour scale for the moleucle trace\n",
"c = np.arange(0, len(ordered_traces))\n",
"# Plot the molecule trace\n",
"plt.scatter(ordered_traces[:, 1], ordered_traces[:, 0], c=c, s=10)\n",
"plt.show()\n",
"# Plot the height of the molecule trace against the cumulative distance in nanometres\n",
"plt.plot(cumulative_distances, ordered_trace_heights)\n",
"plt.xlabel(\"Cumulative distance (nm)\")\n",
"plt.ylabel(\"Height (nm)\")\n",
"plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "topo-unet",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.9"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
41 changes: 41 additions & 0 deletions tests/test_io.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Tests of IO."""

from __future__ import annotations

import argparse
import json
import logging
Expand All @@ -15,6 +17,7 @@

from topostats.io import (
LoadScans,
TopoFileHelper,
convert_basename_to_relative_paths,
dict_to_hdf5,
dict_to_json,
Expand Down Expand Up @@ -1379,3 +1382,41 @@ def test_dict_to_json(dictionary: dict, target: dict, tmp_path: Path) -> None:

with outfile.open("r", encoding="utf-8") as f:
assert target == json.load(f)


class TestTopoFileHelper:
"""Test the TopoFileHelper class."""

@pytest.mark.parametrize(
("file_path_or_string"),
[
pytest.param(
"tests/resources/file.topostats",
id="String file path",
),
pytest.param(
Path("tests/resources/file.topostats"),
id="Path object path",
),
],
)
def test_init(self, file_path_or_string: Path | str) -> None:
"""Test the __init__ method of the TopoFileHelper class."""
topo_file_helper = TopoFileHelper(file_path_or_string)
assert isinstance(topo_file_helper, TopoFileHelper)
assert isinstance(topo_file_helper.data, dict)

def test_get_data(self) -> None:
"""Test the get_data method of the TopoFileHelper class."""
topo_file_helper = TopoFileHelper("tests/resources/file.topostats")
cropped_image = topo_file_helper.get_data("grain_trace_data/above/cropped_images/2")
assert isinstance(cropped_image, np.ndarray)


# This test only works when not part of the TestTopoFileHelper class
def test_pretty_print_structure(caplog) -> None:
"""Test the pretty_print_structure method of the TopoFileHelper class."""
topo_file_helper = TopoFileHelper("tests/resources/file.topostats")
topo_file_helper.pretty_print_structure()
assert "filename" in caplog.text
assert "keys with numpy arrays as values" in caplog.text
Loading
Loading