Skip to content

Commit

Permalink
Merge pull request #6 from rosalindfranklininstitute/bugfix-issue0005
Browse files Browse the repository at this point in the history
Bugfix issue #5
  • Loading branch information
elainehoml committed Nov 30, 2022
2 parents 7ec8c90 + 16e8854 commit dbd442a
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 23 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "quoll"
version = "0.0.1"
version = "0.0.2"
dependencies = [
"jpype1==0.7.5",
"pims==0.4.1",
Expand Down
35 changes: 35 additions & 0 deletions src/quoll/frc/frc_calibration_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Copyright 2022 Rosalind Franklin Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.


import numpy as np


""" When adding calibration functions here, ensure that your function starts
with `calibration_func` or else it will not be discovered in the CLI/Napari"""

def calibration_func_RFI(frequencies: list) -> list:
""" Calibration function to match 1 image FRC to 2 image FRC.
Redone for EM images.
Args:
frequencies (list): x-values in the FRC curve
Returns:
list: frequencies with correction factor applied
"""
correction = 2.066688385682453 + 0.09896293544729941 * np.log(0.08470690336138625 * frequencies)
corrected_frequencies = frequencies / correction
return corrected_frequencies
33 changes: 15 additions & 18 deletions src/quoll/frc/oneimg.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from miplib.data.io import read as miplibread
from miplib.processing import windowing
from quoll.io import reader, tiles
from quoll.frc import frc_calibration_functions as cf


def miplib_oneimg_FRC_calibrated(
Expand Down Expand Up @@ -98,27 +99,18 @@ def miplib_oneimg_FRC_calibrated(
return result


def calibration_func(frequencies: list) -> list:
""" Calibration function to match 1 image FRC to 2 image FRC.
Redone for EM images.
Args:
frequencies (list): x-values in the FRC curve
Returns:
list: frequencies with correction factor applied
"""
correction = 2.066688385682453 + 0.09896293544729941 * np.log(0.08470690336138625 * frequencies)
corrected_frequencies = frequencies / correction
return corrected_frequencies


def calc_frc_res(Image: reader.Image):
def calc_frc_res(
Image: reader.Image,
calibration_func: Optional[Callable] = None
):
"""Calculates one image FRC resolution for quoll Image object
Args:
Image (reader.Image): Quoll.io.reader.Image instance
calibration_func (callable): function that applies a correction factor to the
frequencies of the FRC curve to match the 1 img
FRC to the 2 img FRC. If None, no calibration is
applied.
Raises:
ValueError: if Image is not square
Expand All @@ -143,6 +135,7 @@ def calc_local_frc(
Image: reader.Image,
tile_size: int,
tiles_dir: str,
calibration_func: Optional[Callable] = None
):
""" Calculates local FRC on a quoll Image
Expand All @@ -152,6 +145,10 @@ def calc_local_frc(
Image (reader.Image): Quoll.io.reader.Image instance
tile_size (int): length of one side of the square tile in pixels
tiles_dir (str): path to directory holding tiles
calibration_func (callable): function that applies a correction factor to the
frequencies of the FRC curve to match the 1 img
FRC to the 2 img FRC. If None, no calibration is
applied.
Returns:
pandas DataFrame: df containing the resolutions in physical units
Expand All @@ -165,7 +162,7 @@ def calc_local_frc(
for tile in os.listdir(tiles_dir):
try:
Img = reader.Image(os.path.join(tiles_dir, tile))
result = calc_frc_res(Img)
result = calc_frc_res(Img, calibration_func)
resolutions["Resolution"][tile] = result.resolution["resolution"]
except:
resolutions["Resolution"][tile] = np.nan
Expand Down
42 changes: 41 additions & 1 deletion src/quoll/ui/frc_oneimg_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,29 @@

import argparse
import os
from inspect import getmembers

from matplotlib.pyplot import get
from quoll.frc import oneimg
from quoll.io import reader
from quoll.frc import frc_calibration_functions as cf


def get_calibration_functions() -> dict:
""" Gets a dict of available calibration functions in `frc.frc_calibration_functions`
Valid calibration functions all start with "calibration_func"
Returns:
dict: Dict of available calibration functions with keys = strings of the
calibration function and values = the functions themselves
"""
calibration_functions = {None: None}

for member in getmembers(cf):
if member[0].startswith("calibration_func"):
calibration_functions[member[0]] = member[1]

return calibration_functions


def get_args_oneimgFRC():
Expand All @@ -36,6 +57,19 @@ def get_args_oneimgFRC():
default="nm",
help="Physical unit of pixel size, default is nm"
)
parser.add_argument(
"-cf", "--calibration_func",
default=None,
choices=get_calibration_functions().keys(),
help="Function defining correction to match 1 image FRC to \
2 image FRC. This function is instrument specific, so only \
needs to be determined once for each instrument. \
Defaults to None (no calibration applied) \
This function applies a correction factor to return frequencies \
on the 1-img FRC curve to match the 2-img version. \
To set a custom calibration function please add your function to \
frc.frc_calibration_functions.py."
)
parser.add_argument(
"-ts", "--tile_size",
type=int,
Expand Down Expand Up @@ -83,8 +117,13 @@ def oneimgfrc():
unit=args.unit
)

cal_funcs = get_calibration_functions()

if args.tile_size == 0:
result = oneimg.calc_frc_res(Img)
result = oneimg.calc_frc_res(
Img,
calibration_func=cal_funcs[args.calibration_func]
)
print(f"Resolution of {Img.filename} is {result.resolution['resolution']} {Img.unit}")

if args.save_csv is True:
Expand All @@ -96,6 +135,7 @@ def oneimgfrc():
Img,
tile_size=args.tile_size,
tiles_dir=args.tiles_dir,
calibration_func=cal_funcs[args.calibration_func]
)

print(results_df.Resolution.describe())
Expand Down
54 changes: 51 additions & 3 deletions tests/test_frc_oneimg.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import miplib.ui.cli.miplib_entry_point_options as opts
from miplib.data.io import read as miplibread
from quoll.frc import oneimg
from quoll.frc import frc_calibration_functions as cf
from quoll.io import reader


Expand All @@ -40,7 +41,7 @@ def test_miplib_basic(self):
result = oneimg.miplib_oneimg_FRC_calibrated(
miplibImg,
args,
oneimg.calibration_func
calibration_func=None
)

self.assertIsNotNone(result)
Expand All @@ -50,7 +51,10 @@ def test_calc_frc_res(self):
Tests that the one-image FRC can be calculated from quoll.io.reader.Image
"""
Img = reader.Image("./data/042.tif")
result = oneimg.calc_frc_res(Img)
result = oneimg.calc_frc_res(
Image=Img,
calibration_func=cf.calibration_func_RFI
)
self.assertAlmostEqual(result.resolution["resolution"], 32.1159278)
self.assertIsNotNone(result)

Expand All @@ -72,7 +76,11 @@ def test_calc_local_frc(self):
unit="nm"
)

results_df = oneimg.calc_local_frc(Img, tile_size=512, tiles_dir="./data/tiles2/")
results_df = oneimg.calc_local_frc(
Img,
tile_size=512,
tiles_dir="./data/tiles2/",
calibration_func=cf.calibration_func_RFI)

# Check that tiles are created and saved
self.assertNotEqual(len(os.listdir("./data/tiles2")), 0)
Expand All @@ -93,3 +101,43 @@ def test_calc_local_frc(self):
# check that the resolution heatmap is not empty
self.assertGreater(np.mean(resolution_heatmap), 0)

def test_set_calibration_func(self):
"""
Tests that calibration function can be set to a custom function
In this test, calibration function is set to return the exact same
value, so the result should be equal to uncalibrated.
"""
Img = reader.Image("./data/042.tif")
result_calibrated = oneimg.calc_frc_res(
Image=Img,
calibration_func=lambda x: x # just return original value
)
result_uncalibrated = oneimg.calc_frc_res(
Image=Img,
calibration_func=None
)
self.assertAlmostEqual(
result_calibrated.resolution["resolution"],
result_uncalibrated.resolution["resolution"])
self.assertIsNotNone(result_calibrated.resolution["resolution"])
self.assertIsNotNone(result_uncalibrated.resolution["resolution"])
def test_set_calibration_func(self):
"""
Tests that calibration function can be set to a custom function
In this test, calibration function is set to return the exact same
value, so the result should be equal to uncalibrated.
"""
Img = reader.Image("./data/042.tif")
result_calibrated = oneimg.calc_frc_res(
Image=Img,
calibration_func=lambda x: x # just return original value
)
result_uncalibrated = oneimg.calc_frc_res(
Image=Img,
calibration_func=None
)
self.assertAlmostEqual(
result_calibrated.resolution["resolution"],
result_uncalibrated.resolution["resolution"])
self.assertIsNotNone(result_calibrated.resolution["resolution"])
self.assertIsNotNone(result_uncalibrated.resolution["resolution"])
16 changes: 16 additions & 0 deletions tests/test_frc_oneimg_cli_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,22 @@ def test_oneimgfrc_tiles_saveplots(self):
os.remove("./data/SerialFIB57_2048x2048_heatmap.tif")
shutil.rmtree("./data/tiles", ignore_errors=True)

@mock.patch(
'sys.argv',
["oneimgfrc",
"./data/042.tif",
"3.3724",
"-cf",
"calibration_func_RFI",
"--save_csv"],
)
def test_oneimgfrc_RFICalibrationFunc(self):
frc_oneimg_ui.oneimgfrc()
self.assertTrue(os.path.exists("./data/042_oneimgfrc.csv"))
with open("./data/042_oneimgfrc.csv", "r") as f:
self.assertAlmostEqual(float(f.read()), 32.11592783389754)
os.remove("./data/042_oneimgfrc.csv")


if __name__ == "__main__":
unittest.main()

0 comments on commit dbd442a

Please sign in to comment.