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 python algebra test #853

Merged
merged 36 commits into from
Feb 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
d47dcac
added python tests for SIRF DataContainer Algebra
paskino Jan 21, 2021
19eb336
remove comment
paskino Jan 21, 2021
6265575
added test algebra between datacontainers
paskino Jan 21, 2021
2a634b2
Merge remote-tracking branch 'origin' into add_python_algebra_test
paskino Jan 22, 2021
e91c9ed
address codacy complaints
paskino Jan 22, 2021
bf613af
added fill number and MR algebra tests
paskino Jan 27, 2021
2549841
split the algebra tests
paskino Jan 28, 2021
c42f5a3
removed tests in common
paskino Jan 28, 2021
13b60f1
Merge remote-tracking branch 'origin' into add_python_algebra_test
paskino Jan 28, 2021
ab0136d
[ci skip] Update src/common/tests/CMakeLists.txt
paskino Jan 28, 2021
6c41dbf
[ci skip] fixed headers and removed Gadgetron tests from STIR dir
paskino Jan 28, 2021
d0a2c46
Merge branch 'add_python_algebra_test' of https://github.com/SyneRBI/…
paskino Jan 28, 2021
8a44c60
Move TestDataContainerAlgebra to Utilities.py
paskino Jan 29, 2021
860b7fa
add multiplication and division to NiftiImageData
paskino Jan 29, 2021
6841618
removed empty tests in common directory
paskino Jan 29, 2021
b9288b2
added multiplication and division in cSIRF for NiftiImageData
paskino Jan 29, 2021
d771609
test catch division by zero
paskino Jan 29, 2021
daf4000
test for zero division exception
paskino Jan 29, 2021
c698c00
move catch of ZeroDivisionError up
paskino Jan 29, 2021
66bc040
[ci skip] updates dates in headers
paskino Jan 29, 2021
75b0752
rename members to make them private
paskino Jan 29, 2021
0500127
Merge remote-tracking branch 'origin' into add_python_algebra_test
paskino Feb 1, 2021
170c068
algebra tests are equal in Gadgetron STIR and Reg
paskino Feb 1, 2021
9ab2819
in travis unittest fail because cwd is missing
paskino Feb 1, 2021
980c74e
use AcquisitionData for test on AcquisitionData
paskino Feb 1, 2021
87caf35
removed chdir in tests. Added tests for storage scheme
paskino Feb 3, 2021
0794f8a
update the tests
paskino Feb 3, 2021
c2bfb76
removed single quote
paskino Feb 3, 2021
4d66087
gadgetron python tests fixed
paskino Feb 3, 2021
a4bf83c
use variables in the scope
paskino Feb 3, 2021
7620751
fixed PET algebra tests
paskino Feb 4, 2021
6ceb6d1
skip test if SPM not available
paskino Feb 4, 2021
634893e
probably all test pass
paskino Feb 4, 2021
0950033
temporary enable tests from builds/SIRF/build
paskino Feb 5, 2021
0a98e67
codacy fixes
paskino Feb 5, 2021
613a001
[ci skip] reinstate original .travis.yml
paskino Feb 5, 2021
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
37 changes: 30 additions & 7 deletions src/Registration/cReg/NiftiImageData.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -293,11 +293,24 @@ NiftiImageData<dataType>& NiftiImageData<dataType>::operator*=(const float val)
maths(val, mul);
return *this;
}
template<class dataType>
NiftiImageData<dataType>& NiftiImageData<dataType>::operator*=(const NiftiImageData<dataType>& rhs)
{
maths(rhs, mul);
return *this;
}

template<class dataType>
NiftiImageData<dataType>& NiftiImageData<dataType>::operator/=(const float val)
{
maths(1.f/val, mul);
maths(val, div);
return *this;
}

template<class dataType>
NiftiImageData<dataType>& NiftiImageData<dataType>::operator/=(const NiftiImageData<dataType>& rhs)
{
maths(rhs, div);
return *this;
}

Expand Down Expand Up @@ -593,12 +606,18 @@ void NiftiImageData<dataType>::maths(const NiftiImageData<dataType>& c, const Ma
throw std::runtime_error("NiftiImageData<dataType>::maths_image: at least one image is not initialised.");
if (!NiftiImageData<dataType>::do_nifti_image_metadata_match(*this, c, true))
throw std::runtime_error("NiftiImageData<dataType>::maths_image: metadata do not match.");
if (type != add && type != sub)
throw std::runtime_error("NiftiImageData<dataType>::maths_image: only implemented for add and subtract.");
if (type != add && type != sub && type != mul && type != div)
throw std::runtime_error("NiftiImageData<dataType>::maths_image: only implemented for add, subtract, multiply and divide.");

for (int i=0; i<int(this->_nifti_image->nvox); ++i) {
if (type == add) (*this)(i) += c(i);
else (*this)(i) -= c(i);
else if (type == sub) (*this)(i) -= c(i);
else if (type == mul) (*this)(i) *= c(i);
else if (type == div) {
if (c(i) != 0) (*this)(i) /= c(i);
else throw std::runtime_error("NiftiImageData<dataType>::maths_image: division by zero.");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if this is what's expected. It's possibly that division should silently fail, generating NaN or inf. Might be good to check behaviour of some other libraries (or indeed SIRF)

}

}
}

Expand All @@ -607,13 +626,17 @@ void NiftiImageData<dataType>::maths(const float val, const MathsType type)
{
if (!this->is_initialised())
throw std::runtime_error("NiftiImageData<dataType>::maths_image_val: image is not initialised.");
if (type != add && type != sub && type != mul)
throw std::runtime_error("NiftiImageData<dataType>::maths_image_val: only implemented for add, subtract and multiply.");
if (type != add && type != sub && type != mul && type != div)
throw std::runtime_error("NiftiImageData<dataType>::maths_image_val: only implemented for add, subtract, multiply and divide.");

for (int i=0; i<int(this->_nifti_image->nvox); ++i) {
if (type == add) (*this)(i) += val;
else if (type == sub) (*this)(i) -= val;
else (*this)(i) *= val;
else if (type == mul) (*this)(i) *= val;
else if (type == div) {
if (val != 0) (*this)(i) /= val;
else throw std::runtime_error("NiftiImageData<dataType>::maths_image_val: division by zero.");
}
}
}

Expand Down
7 changes: 5 additions & 2 deletions src/Registration/cReg/cReg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,10 @@ void* cReg_NiftiImageData_maths_im(const void *res_ptr, const void* im1_ptr, con

if (maths_type == 0) res = im1 + im2;
else if (maths_type == 1) res = im1 - im2;
else if (maths_type == 2) res = im1 * im2;
else if (maths_type == 3) res = im1 / im2;
else
throw std::runtime_error("cReg_NiftiImageData_maths_im: Bad maths type (0=add, 1=subtract).");
throw std::runtime_error("cReg_NiftiImageData_maths_im: Bad maths type (0=add, 1=subtract, 2=multiply, 3=divide).");
return new DataHandle;
}
CATCH;
Expand All @@ -344,8 +346,9 @@ void* cReg_NiftiImageData_maths_num(const void *res_ptr, const void* im1_ptr, co
if (maths_type == 0) res = im1 + val;
else if (maths_type == 1) res = im1 - val;
else if (maths_type == 2) res = im1 * val;
else if (maths_type == 3) res = im1 / val;
else
throw std::runtime_error("cReg_NiftiImageData_maths_val: Bad maths type (0=add, 1=subtract, 2=multiply.");
throw std::runtime_error("cReg_NiftiImageData_maths_num: Bad maths type (0=add, 1=subtract, 2=multiply, 3=divide");
return new DataHandle;
}
CATCH;
Expand Down
24 changes: 21 additions & 3 deletions src/Registration/cReg/include/sirf/Reg/NiftiImageData.h
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,8 @@ class NiftiImageData : public ImageData

/// Multiplication operator
NiftiImageData& operator*=(const float);
/// Multiplication operator
NiftiImageData& operator*=(const NiftiImageData &rhs);

/// Multiplication operator
friend NiftiImageData operator*(NiftiImageData lhs, const float val)
Expand All @@ -275,16 +277,32 @@ class NiftiImageData : public ImageData
return lhs;
}

/// Division operator
NiftiImageData& operator/=(const float);
/// Multiplication operator
friend NiftiImageData operator*(NiftiImageData lhs, const NiftiImageData& rhs)
{
lhs *= rhs;
return lhs;
}

/// Division operator
NiftiImageData& operator/=(const float);
// /// Division operator
NiftiImageData& operator/=(const NiftiImageData &rhs);

// /// Division operator
friend NiftiImageData operator/(NiftiImageData lhs, const float val)
{
lhs /= val;
return lhs;
}

/// Division operator
friend NiftiImageData operator/(NiftiImageData lhs, const NiftiImageData& rhs)
{
lhs /= rhs;
return lhs;
}

/// Access data element via 1D index (const)
float operator()(const int index) const;

Expand Down Expand Up @@ -431,7 +449,7 @@ class NiftiImageData : public ImageData

enum NiftiImageDataType { _general, _3D, _3DTensor, _3DDisp, _3DDef};

enum MathsType { add, sub, mul };
enum MathsType { add, sub, mul, div};

/// Image data as a nifti object
std::shared_ptr<nifti_image> _nifti_image;
Expand Down
36 changes: 27 additions & 9 deletions src/Registration/pReg/Reg.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Object-Oriented wrap for the cReg-to-Python interface pyreg.py."""

# SyneRBI Synergistic Image Reconstruction Framework (SIRF)
# Copyright 2018 - 2020 University College London
# Copyright 2018 - 2021 University College London
# Copyright 2018 - 2021 Science Technology Facilities Council
#
# This is software developed for the Collaborative Computational
# Project in Synergistic Reconstruction for Biomedical Imaging
Expand Down Expand Up @@ -146,7 +147,10 @@ def get_as_deformation_field(self, ref):

class NiftiImageData(SIRF.ImageData):
"""General class for nifti image data."""

_ADD = 0
_SUBTRACT = 1
_MULTIPLY = 2
_DIVIDE = 3
def __init__(self, src=None):
"""init."""
self.handle = None
Expand Down Expand Up @@ -174,11 +178,11 @@ def __add__(self, other):
if isinstance(other, NiftiImageData):
try_calling(
pyreg.cReg_NiftiImageData_maths_im(
z.handle, self.handle, other.handle, 0))
z.handle, self.handle, other.handle, NiftiImageData._ADD))
else:
try_calling(
pyreg.cReg_NiftiImageData_maths_num(
z.handle, self.handle, float(other), 0))
z.handle, self.handle, float(other), NiftiImageData._ADD))
check_status(z.handle)
return z

Expand All @@ -187,21 +191,35 @@ def __sub__(self, other):
z = self.clone()
if isinstance(other, NiftiImageData):
try_calling(pyreg.cReg_NiftiImageData_maths_im(z.handle,
self.handle, other.handle, 1))
self.handle, other.handle, NiftiImageData._SUBTRACT))
else:
try_calling(pyreg.cReg_NiftiImageData_maths_num(z.handle,
self.handle, float(other), 1))
self.handle, float(other), NiftiImageData._SUBTRACT))
check_status(z.handle)
return z

def __mul__(self, other):
"""Overloads * operator."""
z = self.clone()
try_calling(pyreg.cReg_NiftiImageData_maths_num(z.handle, self.handle,
float(other), 2))
if isinstance(other, NiftiImageData):
try_calling(pyreg.cReg_NiftiImageData_maths_im(z.handle,
self.handle, other.handle, NiftiImageData._MULTIPLY))
else:
try_calling(pyreg.cReg_NiftiImageData_maths_num(z.handle,
self.handle, float(other), NiftiImageData._MULTIPLY))
check_status(z.handle)
return z
def __div__(self, other):
"""Overloads / operator."""
z = self.clone()
if isinstance(other, NiftiImageData):
try_calling(pyreg.cReg_NiftiImageData_maths_im(z.handle,
self.handle, other.handle, NiftiImageData._DIVIDE))
else:
try_calling(pyreg.cReg_NiftiImageData_maths_num(z.handle,
self.handle, float(other), NiftiImageData._DIVIDE))
check_status(z.handle)
return z

def equal(self, other):
"""Overload comparison operator."""
if not isinstance(other, NiftiImageData):
Expand Down
17 changes: 10 additions & 7 deletions src/Registration/pReg/tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,15 @@
# limitations under the License.
#
#=========================================================================

if (NOT SPM_FOUND)
set(exclude_test "--exclude=test_pReg_spm.py")
if (SPM_BOOL_STR EQUAL "0")
set (exclude_tests "--ignore-files=\"test_algebra\"" "--exclude=TestDataContainerAlgebra")
else()
set (exclude_tests "--ignore-files=\"test_algebra\"" "--exclude=TestDataContainerAlgebra")
endif()

# Make into test
ADD_TEST(NAME REG_TEST_PYTHON
COMMAND ${PYTHON_EXECUTABLE} -m nose --with-coverage --cover-package=sirf.Reg --cover-erase -d -v ${CMAKE_SOURCE_DIR}/src/Registration/pReg ${exclude_test}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
ADD_TEST(NAME REG_TESTS_PYTHON
COMMAND ${PYTHON_EXECUTABLE} -m nose --with-coverage --cover-package=sirf.Reg --cover-erase -d -v ${CMAKE_SOURCE_DIR}/src/Registration/pReg ${exclude_tests})

add_test(NAME REG_PYTHON_ALGEBRA
COMMAND ${PYTHON_EXECUTABLE} -m unittest test_algebra
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
41 changes: 41 additions & 0 deletions src/Registration/pReg/tests/test_algebra.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#========================================================================
# Copyright 2021 Science Technology Facilities Council
#
# This file is part of the SyneRBI Synergistic Image Reconstruction Framework (SIRF).
#
# 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.txt
#
# 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 os
import unittest
import sirf.Reg as reg
from sirf.Utilities import examples_data_path, TestDataContainerAlgebra


class TestNiftiImageDataAlgebra(unittest.TestCase, TestDataContainerAlgebra):

def setUp(self):
image1 = reg.ImageData(os.path.join(
examples_data_path('Registration'),'test2.nii.gz')
)
image2 = reg.ImageData(os.path.join(
examples_data_path('Registration'),'test2.nii.gz')
)

self.image1 = image1
self.image2 = image2

def tearDown(self):
#shutil.rmtree(self.cwd)
pass
2 changes: 1 addition & 1 deletion src/Registration/pReg/tests/test_pReg.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
print('WARNING: nibabel is not installed, so not running corresponding tests')

import sirf.Reg
from pUtilities import *
from sirf.Utilities import is_operator_adjoint

# Paths
SIRF_PATH = os.environ.get('SIRF_PATH')
Expand Down
8 changes: 6 additions & 2 deletions src/Registration/pReg/tests/test_pReg_spm.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@
import time
import numpy as np
import sirf.Reg
from pUtilities import *
import unittest

has_spm = hasattr(sirf.Reg, 'SPMRegistration')



# Paths
SIRF_PATH = os.environ.get('SIRF_PATH')
Expand Down Expand Up @@ -136,7 +140,7 @@ def try_spm():
sys.stderr.write('# --------------------------------------------------------------------------------- #\n')
time.sleep(0.5)


@unittest.skipUnless(has_spm, "SPM not available")
def test():
try_spm()

Expand Down
1 change: 0 additions & 1 deletion src/common/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ if (BUILD_PYTHON)
INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/pysirf.py" DESTINATION "${PYTHON_DEST}/sirf")
file(GLOB PythonFiles "${CMAKE_CURRENT_LIST_DIR}/*.py")
INSTALL(FILES ${PythonFiles} DESTINATION "${PYTHON_DEST}/sirf")

endif (BUILD_PYTHON)

if (BUILD_MATLAB)
Expand Down
Loading