Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
8e822bf
Few changes to auxiallry scripts
nrhorner Jun 16, 2020
8c9c045
updated qc script
nrhorner Jun 26, 2020
de77ff7
New script for parallelising pairwise populaiton average
nrhorner Jun 30, 2020
dceb155
Added stage startgets options
nrhorner Jul 2, 2020
f79d767
Was importing a file from local system. Most it to lama project
nrhorner Jul 2, 2020
f4999c6
Removed deprecated pandas .ix calls
nrhorner Jul 2, 2020
53d9caa
Updated label overlay qc
nrhorner Jul 3, 2020
73e090e
Stats memory cleanup for Iterator
antshp-vc Jul 7, 2020
ecb99e5
Finally fixed the bug in the pairwise aberage code
nrhorner Jul 8, 2020
4b7a5a5
Rewrite of parallel avergae script. Using status files to control int…
nrhorner Jul 9, 2020
a419cac
More pairwise script fixes
nrhorner Jul 10, 2020
8fbba75
Updated utils
nrhorner Jul 17, 2020
c348407
Updated qc and setup.py
nrhorner Aug 10, 2020
991a9d4
?
nrhorner Aug 10, 2020
61c0f17
QC inverted lables: added multiple slices taken from within mask boun…
nrhorner Aug 10, 2020
cce9797
Qc script
nrhorner Aug 11, 2020
a25d4d5
QC
nrhorner Aug 11, 2020
6055398
Switched off histogram matching in qc images as red cyan overlays wer…
nrhorner Aug 13, 2020
342b144
Switched off histogram matching in qc images as red cyan overlays wer…
nrhorner Aug 13, 2020
39c70b8
Data cleanup scrpt
nrhorner Aug 13, 2020
766ba36
Updated data cleanup script
nrhorner Aug 14, 2020
d6f1d4c
Updated data cleanup script
nrhorner Aug 14, 2020
6025df4
Create dicom_to_nrrd.sh
dorkylever Aug 18, 2020
3d23642
bit of qc stuff
nrhorner Aug 19, 2020
0b68f04
Added optional image height to collate_qc
nrhorner Aug 21, 2020
32ad360
Added option to interactive_qc to just dump the images in compressed …
nrhorner Aug 21, 2020
3125738
updated qc script
nrhorner Aug 21, 2020
6e37f9b
Coulple of minor things
nrhorner Aug 28, 2020
4f0213b
Permutation stats reports t-statistics
nrhorner Sep 10, 2020
e46076c
Updated qc script
nrhorner Sep 11, 2020
c042db3
Got permutation test working again.
nrhorner Sep 22, 2020
24b8940
Some qc small changes
nrhorner Sep 24, 2020
81c7dfb
Added scatter plots for non-permutation based organ vol stats
nrhorner Sep 24, 2020
919a45e
Added cohens D and mean vol differnces to permutation stats results csvs
nrhorner Oct 9, 2020
6b6386b
Penetrance/expressivity plots now output for organ volume permutation…
nrhorner Oct 10, 2020
c20e840
Some Qc stuff
nrhorner Oct 13, 2020
46648f3
Fixed paths on interactive qc
nrhorner Oct 23, 2020
24c2730
Updated qc script
nrhorner Oct 28, 2020
bea08e2
Merge pull request #18 from Dorky-Lever/patch-7
nrhorner Oct 28, 2020
fe3942b
Merge branch 'anton-merge' into dev
nrhorner Oct 28, 2020
5649374
Merge pull request #15 from antshp-vc/dev
nrhorner Oct 28, 2020
112a024
Edit of a test
nrhorner Oct 28, 2020
03a1484
Merge branch 'anton-merge' into dev
nrhorner Oct 28, 2020
244f3c7
Some qc changes
nrhorner Nov 12, 2020
8691b41
Added folding reprt for each organ
nrhorner Nov 18, 2020
0034b99
Updates on folding correction
nrhorner Nov 19, 2020
792c9d7
Fixed bug in deformation code
nrhorner Nov 19, 2020
e1c9299
Updated pipeline to put pyramid images in seperate dir. And to ignore…
nrhorner Nov 20, 2020
3b86223
Fixed type error in folding report
nrhorner Nov 25, 2020
8458c13
Added check for inversion skipping when embryo_volume staging is True…
nrhorner Nov 25, 2020
9ecc38b
Require affine or simlarity stage for embryo vvolume calculation. Fix…
nrhorner Nov 25, 2020
ea19eb0
Added check for filenames woth spaces. Fixes #49
nrhorner Nov 25, 2020
c530013
Final fix for images with spaces in filenames
nrhorner Nov 25, 2020
8acc0d3
Update dicom_to_nrrd.sh
dorkylever Dec 1, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions install_elastix_R.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ sudo apt install python3-pip
sudo apt install r-base

# Install elastix
wget https://github.com/SuperElastix/elastix/releases/download/4.9.0/elastix-4.9.0-linux.tar.bz2
wget https://github.com/SuperElastix/elastix/releases/download/5.0.0/elastix-5.0.0-linux.tar.bz2
mkdir ~/elastix
tar xjf elastix-4.9.0-linux.tar.bz2 -C ~/elastix
tar xjf elastix-5.0.0-linux.tar.bz2 -C ~/elastix

home=~/
echo -e "\n# paths added by my LAMA installation" >> ~/.bashrc
Expand Down
2 changes: 1 addition & 1 deletion lama/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
warnings.filterwarnings("ignore")


matplotlib.use('Agg')
#matplotlib.use('Agg')
72 changes: 50 additions & 22 deletions lama/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@

ORGAN_VOLUME_CSV_FILE = 'organ_volumes.csv'
STAGING_INFO_FILENAME = 'staging_info_volume.csv'
FOLDING_FILE_NAME = 'folding_report.csv'

lama_root_dir = Path(lama.__file__).parent

Expand Down Expand Up @@ -116,7 +117,7 @@ def excepthook_overide(exctype, value, traceback):


def command_line_agrs():
return ', '.join(sys.argv)
return ' '.join(sys.argv)


def touch(file_: Path):
Expand Down Expand Up @@ -238,7 +239,7 @@ def write_array(array: np.ndarray, path: Union[str, Path], compressed=True, ras=
img = sitk.GetImageFromArray(array)
if ras:
img.SetDirection((-1, 0, 0, 0, -1, 0, 0, 0, 1))
sitk.WriteImage(sitk.GetImageFromArray(array), path, compressed)
sitk.WriteImage(img, path, compressed)


def read_array( path: Union[str, Path]):
Expand Down Expand Up @@ -373,7 +374,7 @@ def mkdir_if_not_exists(dir_: Union[str, Path]):


def get_file_paths(folder: Union[str, Path], extension_tuple=('.nrrd', '.tiff', '.tif', '.nii', '.bmp', 'jpg', 'mnc', 'vtk', 'bin', 'npy'),
pattern: str = None, ignore_folder: str = "") -> Union[List[str], List[Path]]:
pattern: str = None, ignore_folders: Union[List, str] = []) -> Union[List[str], List[Path]]:
"""
Given a directory return all image paths within all sibdirectories.

Expand All @@ -385,8 +386,8 @@ def get_file_paths(folder: Union[str, Path], extension_tuple=('.nrrd', '.tiff',
Select only images with these extensions
pattern
Do a simple `pattern in filename` filter on filenames
ignore_folder
do not look in folder with this name
ignore_folders
do not look in folder with these names

Notes
-----
Expand All @@ -395,32 +396,33 @@ def get_file_paths(folder: Union[str, Path], extension_tuple=('.nrrd', '.tiff',

Do not include hidden filenames
"""
paths = []

if not os.path.isdir(folder):
return False
else:
paths = []
if isinstance(ignore_folders, str):
ignore_folders = [ignore_folders]

for root, subfolders, files in os.walk(folder):

if ignore_folder in subfolders:
subfolders.remove(ignore_folder)
for root, subfolders, files in os.walk(folder):

for filename in files:
for f in ignore_folders:
if f in subfolders:
subfolders.remove(f)

if filename.lower().endswith(extension_tuple) and not filename.startswith('.'):
for filename in files:

if pattern:
if filename.lower().endswith(extension_tuple) and not filename.startswith('.'):

if pattern and pattern not in filename:
continue
if pattern:

paths.append(os.path.abspath(os.path.join(root, filename)))
if pattern and pattern not in filename:
continue

if isinstance(folder, str):
return paths
else:
return [Path(x) for x in paths]
paths.append(os.path.abspath(os.path.join(root, filename)))

if isinstance(folder, str):
return paths
else:
return [Path(x) for x in paths]


def check_config_entry_path(dict_, key):
Expand Down Expand Up @@ -466,6 +468,14 @@ def getfile_endswith(dir_: Path, suffix: str):
raise FileNotFoundError(f'cannot find path file ending with {suffix} in {dir_}') from e


def getfile_startswith_endswith(dir_: Path, prefix: str, suffix: str):
try:
return [x for x in dir_.iterdir() if x.name.endswith(suffix) and x.name.startswith(prefix)][0]
except IndexError as e:
raise FileNotFoundError(f'cannot find path starting with {prefix} and ending with {suffix} in {dir_}') from e



def get_inputs_from_file_list(file_list_path, config_dir):
"""
Gte the input files
Expand Down Expand Up @@ -956,3 +966,21 @@ def cfg_load(cfg) -> Dict:

else:
raise ValueError('Config file should end in .toml or .yaml')


def bytesToGb(numberOfBytes, precision = 3):
return round(numberOfBytes / (1024 ** 3), precision)

def logMemoryUsageInfo():
proc = psutil.Process(os.getpid())

procMemInfo = proc.memory_info()
globalMemInfo = psutil.virtual_memory()

totalMem = bytesToGb(globalMemInfo.total, 5)
totalMemAvailable = bytesToGb(globalMemInfo.available, 5)
procMemRSS = bytesToGb(procMemInfo.rss, 5)
procMemVMS = bytesToGb(procMemInfo.vms, 5)
procMemData = bytesToGb(procMemInfo.data, 5)

logging.info(f"Memory: Process Resident: {procMemRSS}, Process Virtual: {procMemVMS}, Process data: {procMemData}. Total Available: {totalMemAvailable}")
3 changes: 2 additions & 1 deletion lama/elastix/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@
VOLUME_CALCULATIONS_FILENAME = "organvolumes.csv"
INVERT_CONFIG = 'invert.yaml'
REG_DIR_ORDER = 'reg_order.txt'
IGNORE_FOLDER = 'resolution_images' # When reading images from dir and subdirs, ignore images in this folder
RESOLUTION_IMGS_DIR = 'resolution_images' # When reading images from dir and subdirs, ignore images in this folder
TRANSFORMIX_OUT = 'result.nrrd' # This will not be correct if filetype is not nrrd
IMG_PYRAMID_DIR = 'pyramid_images'
49 changes: 40 additions & 9 deletions lama/elastix/deformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,40 @@
TRANSFORMIX_LOG = 'transformix.log'


def make_deformations_at_different_scales(config: Union[LamaConfig, dict]):
def make_deformations_at_different_scales(config: Union[LamaConfig, dict]) -> Union[None, np.array]:
"""
Generate jacobian determinants ans optionaly defromation vectors
Generate jacobian determinants and optionaly defromation vectors

Parameters
----------
config:
LamaConfig object if running from other lama module
Path to config file if running this module independently

Notes
-----
How to generate the hacobian determinants is defined by the config['generate_deformation_fields'] entry.

toml representation from the LAMA config:

[generate_deformation_fields]
192_to_10 = [ "deformable_192_to_10",]

This will create a set of jacobian determinants and optional deformation fields called 192_to_10 and using the
the named regisrtation stages in the list.

Multiple sets of key/value pairs are allowed so that diffrent jacobians determinatnts might be made. For eaxmple
you may want to include the affine transformation in the jacobians, which would look like so:

affine_192_to_10 = [ "affine", "deformable_192_to_10"]

Returns
-------
jacobian array if there are any negative values
"""
if isinstance(config, Path):
config = LamaConfig(config)

if isinstance(config, (str, Path)):
config = LamaConfig(Path(config))

if not config['generate_deformation_fields']:
return
Expand Down Expand Up @@ -76,8 +98,9 @@ def make_deformations_at_different_scales(config: Union[LamaConfig, dict]):
log_jacobians_scale_dir = log_jacobians_dir / deformation_id
log_jacobians_scale_dir.mkdir()

generate_deformation_fields(reg_stage_dirs, resolutions, deformation_scale_dir, jacobians_scale_dir,
neg_jac_arr = generate_deformation_fields(reg_stage_dirs, resolutions, deformation_scale_dir, jacobians_scale_dir,
log_jacobians_scale_dir, make_vectors, threads=config['threads'], filetype=config['filetype'])
return neg_jac_arr


def generate_deformation_fields(registration_dirs: List,
Expand Down Expand Up @@ -150,8 +173,9 @@ def generate_deformation_fields(registration_dirs: List,
# Copy the tp files into the temp directory and then modify to add initail transform

# pass in the last tp file [-1] as the other tp files are intyernally referenced
get_deformations(transform_params[-1], deformation_dir, jacobian_dir, log_jacobians_dir, filetype, specimen_id,
neg_jac_array = get_deformations(transform_params[-1], deformation_dir, jacobian_dir, log_jacobians_dir, filetype, specimen_id,
threads, jacmat, get_vectors)
return neg_jac_array


def _modfy_tforms(tforms: List):
Expand All @@ -166,7 +190,7 @@ def _modfy_tforms(tforms: List):
for i, tp in enumerate(tforms[1:]):
initial_tp = tforms[i]

with open(tp, 'rb') as fh:
with open(tp, 'r') as fh:
lines = []
for line in fh:
if line.startswith('(InitialTransformParametersFileName'):
Expand All @@ -175,7 +199,7 @@ def _modfy_tforms(tforms: List):

previous_tp_str = '(InitialTransformParametersFileName "{}")'.format(initial_tp)
lines.insert(0, previous_tp_str + '\n')
with open(tp, 'wb') as wh:
with open(tp, 'w') as wh:
for line in lines:
wh.write(line)

Expand All @@ -188,9 +212,13 @@ def get_deformations(tform: Path,
specimen_id: str,
threads: int,
make_jacmat: bool,
get_vectors: bool = False):
get_vectors: bool = False) -> Union[None, np.array]:
"""
Generate spatial jacobians and optionally deformation files.

Returns
-------
the jacobian array if there are any values < 0
"""

cmd = ['transformix',
Expand Down Expand Up @@ -265,5 +293,8 @@ def get_deformations(tform: Path,

logging.info('Finished generating deformation fields')

if jac_min <=0:
return jac_arr



Loading