Skip to content

Commit

Permalink
Remove more unused code
Browse files Browse the repository at this point in the history
  • Loading branch information
adamltyson committed Dec 15, 2023
1 parent c3e3597 commit 1e81929
Show file tree
Hide file tree
Showing 16 changed files with 1 addition and 619 deletions.
111 changes: 1 addition & 110 deletions brainglobe_utils/cells/cells.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,15 @@
Based on https://github.com/SainsburyWellcomeCentre/niftynet_cell_count by
Christian Niedworok (https://github.com/cniedwor).
"""
import logging
import math
import os
import re
from collections import defaultdict
from functools import total_ordering
from typing import Any, DefaultDict, Dict, List, Optional, Tuple, Union
from typing import Any, DefaultDict, Dict, List, Tuple, Union
from xml.etree import ElementTree
from xml.etree.ElementTree import Element as EtElement

import numpy.typing as npt


@total_ordering
class Cell:
Expand Down Expand Up @@ -250,112 +247,6 @@ def pos_from_file_name(file_name: str) -> List[float]:
return [int(p) for p in (x[-1][1:], y[-1][1:], z[-1][1:])]


def transform(
cell: Cell,
deformation_field: npt.NDArray[Any],
field_scales: Tuple[float, float, float],
scales: Tuple[float, float, float],
) -> Optional[Cell]:
"""
Transforms cell position from one space, to another (defined by a
deformation field)
:param cell: Cells in original space
:param deformation_field: Deformation field
(shape (len(x), len(y), len(z), 3). For each spatial position, there is a
vector mapping onto a new coordinate space.
:param field_scales: Scaling of the deformation field values (in mm) into
voxel space (e.g. 100,100,100)
:param scales: Scale of cell x, y and z positions onto deformation
field (e.g. 0.2, 0.2, 0.5)
:return: Cell in the new space
"""
scaled_x = int(round(cell.x * scales[0]))
scaled_y = int(round(cell.y * scales[1]))
scaled_z = int(round(cell.z * scales[2]))

try:
new_x = int(
round(
field_scales[0]
* deformation_field[scaled_x, scaled_y, scaled_z, 0, 0]
)
)
new_y = int(
round(
field_scales[1]
* deformation_field[scaled_x, scaled_y, scaled_z, 0, 1]
)
)
new_z = int(
round(
field_scales[2]
* deformation_field[scaled_x, scaled_y, scaled_z, 0, 2]
)
)

# if any new coordinates are negative
if any(position < 0 for position in [new_x, new_y, new_z]):
warn_outside_target_space(cell)

else:
cell.x = new_x
cell.y = new_y
cell.z = new_z
return cell

except IndexError:
warn_outside_target_space(cell)
return None


def warn_outside_target_space(cell: Cell) -> None:
logging.warning(
"Position x:{}, y:{}, z{} is outside the target "
"coordinate space, skipping. If this happens for many "
"cells, something may be up.".format(cell.x, cell.y, cell.z)
)


def transform_cell_positions(
cells: List[Cell],
deformation_field: npt.NDArray[Any],
field_scales: Tuple[float, float, float] = (100, 100, 100),
scales: Tuple[float, float, float] = (1, 1, 1),
) -> List[Cell]:
"""
Transforms cell positions from one space, to another (defined by a
deformation field)
:param cells: List of cells in original space
:param deformation_field: Deformation field
(shape (len(x), len(y), len(z), 3). For each spatial position, there is a
vector mapping onto a new coordinate space.
:param field_scales: Scaling of the deformation field values (in mm) into
voxel space (e.g. 100,100,100)
:param scales: Scale of cell x, y and z positions onto deformation
field (e.g. 0.2, 0.2, 0.5)
:return: list of cells in the new space
"""
# TODO: parallelise (maybe not needed, very quick anyway)
# TODO: clarify this transformation, and the existing transformed_x
# property of the cells used for other things (e.g. summaries)
transformed_cells = [
transform(cell, deformation_field, field_scales, scales)
for cell in cells
]

# Remove None's from list (where cell couldn't be transformed)
transformed_cells_no_none = [
cell for cell in transformed_cells if cell is not None
]
cells_not_transformed = len(cells) - len(transformed_cells_no_none)
logging.warning(
"{} cells were not transformed to standard space".format(
cells_not_transformed
)
)
return transformed_cells_no_none


def group_cells_by_z(cells: List[Cell]) -> DefaultDict[float, List[Cell]]:
"""
For a list of Cells return a dict of lists of cells, grouped by plane.
Expand Down
58 changes: 0 additions & 58 deletions brainglobe_utils/cells/utils.py

This file was deleted.

5 changes: 0 additions & 5 deletions brainglobe_utils/general/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,3 @@ def __init__(self, message):

def __str__(self):
return str(self.message)


class ArgumentError(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
36 changes: 0 additions & 36 deletions brainglobe_utils/general/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,39 +10,3 @@ def remove_empty_string(str_list):
def unique_elements_lists(list_in):
"""return the unique elements in a list"""
return list(dict.fromkeys(list_in))


def strip_spaces_list(list_in, strip_method="all"):
"""
Remove spaces from all items in a list
:param list_in:
:param strip_method: Default: 'all' for leading and trailing spaces.
Can also be 'leading' or 'trailing'
:return: List with items stripped of spaces
"""

if strip_method == "all":
list_out = [item.strip() for item in list_in]
elif strip_method == "leading":
list_out = [item.rstrip() for item in list_in]
elif strip_method == "trailing":
list_out = [item.lstrip() for item in list_in]
else:
raise NotImplementedError(
'Strip method: "{}" is not implemented. Please use "all", '
'"leading" or "trailing"'.format(strip_method)
)
return list_out


def split_list(input_list):
"""
Splits a list in half (assumes even length)
:param input_list:
:return: Tuple of the first and second halves of the list
"""
if len(input_list) % 2 == 0:
half = len(input_list) // 2
return input_list[:half], input_list[half:]
else:
raise NotImplementedError("split_list requires a list of even length")
27 changes: 0 additions & 27 deletions brainglobe_utils/general/numerical.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import argparse
import decimal


def is_even(num):
Expand Down Expand Up @@ -61,29 +60,3 @@ def check_positive_int(value, none_allowed=True):
raise argparse.ArgumentTypeError("%s is an invalid value." % value)

return ivalue


def get_decimal_places(x):
"""
Returns the number of decimal places of a number
:param float x: Input number
:return: Number of decimal places
"""
d = decimal.Decimal(str(x))
return abs(d.as_tuple().exponent)


def round_updown_to_x(num_in, x, direction="up"):
"""
Rounds a given value (num_in) to the nearest multiple of x, in a given
direction (up or down)
:param num_in: Input value
:param x: Value to round to a multiple of
:param direction: Round up or down. Default: 'up'
:return: Rounded number
"""
if direction == "down":
num_out = int(num_in) - int(num_in) % int(x)
else:
num_out = num_in + (x - num_in) % int(x)
return num_out
64 changes: 0 additions & 64 deletions brainglobe_utils/general/parsing.py

This file was deleted.

35 changes: 0 additions & 35 deletions brainglobe_utils/general/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,25 +352,6 @@ class SafeExecuteCommandError(Exception):
pass


def delete_temp(directory, paths, prefix="tmp__"):
"""
Removes all temp files (properties of an object starting with "tmp__")
:param directory: Directory to delete tmp files from
:param paths: Paths object with temp paths.
:param prefix: String that temporary files (to be deleted) begin with.
"""
for path_name, path in paths.__dict__.items():
if path_name.startswith(prefix):
if check_path_in_dir(path, directory):
try:
os.remove(path)
except FileNotFoundError:
logging.debug(
f"File: {path} not found, not deleting. "
f"Proceeding anyway."
)


def delete_directory_contents(directory, progress=False):
"""
Removes all contents of a directory
Expand All @@ -383,19 +364,3 @@ def delete_directory_contents(directory, progress=False):
else:
for f in files:
os.remove(os.path.join(directory, f))


def filename_from_path(path, remove_extension=False):
"""
Takes a filepath and returns only the filename, optionally removes the
file extension
:param path: Filepath
:param remove_extension: If True, remove the file extension too.
Default: False
:return: filename
"""

filename = os.path.basename(path)
if remove_extension:
filename = os.path.splitext(filename)[0]
return filename
Loading

0 comments on commit 1e81929

Please sign in to comment.