-
Notifications
You must be signed in to change notification settings - Fork 51
AbsFunctions added #1976
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
Merged
hrobarts
merged 40 commits into
TomographicImaging:master
from
fmwatson:function_of_abs
Jul 25, 2025
Merged
AbsFunctions added #1976
Changes from 27 commits
Commits
Show all changes
40 commits
Select commit
Hold shift + click to select a range
e6f2e47
AbsFunctions added
fmwatson 12f8010
First pass at tests and documentation
MargaretDuff 252cec3
Merge branch 'master' into function_of_abs
MargaretDuff ea99da8
Actually add the file
MargaretDuff 2beefc2
Merge branch 'function_of_abs' of github.com:fmwatson/CIL into pr/fmw…
MargaretDuff 78daaab
Check documentation again
MargaretDuff 55b8cdd
Fix test
MargaretDuff 5c82c66
Improve documentation
MargaretDuff d9150ea
Merge branch 'master' into function_of_abs
MargaretDuff 620a602
Testing for out in place
MargaretDuff 5c0c893
Merge branch 'function_of_abs' of github.com:fmwatson/CIL into pr/fmw…
MargaretDuff 1eb7d8b
Documentation tweaks
MargaretDuff d82777d
Update from Edo's review
MargaretDuff 7b4f08a
Proximal map --> proximal operator
MargaretDuff bd16470
Merge branch 'master' into function_of_abs
MargaretDuff 0572db1
Merge branch 'master' into function_of_abs
MargaretDuff 735a5b6
Updates from Laura's review
MargaretDuff ac5d4a1
Reference formatting
MargaretDuff 7869881
Merge branch 'master' into function_of_abs
MargaretDuff c421fb5
Parameters section formatting
MargaretDuff 848ef9e
Added single/double precision options
MargaretDuff 8c5df65
Fix failing unit test
MargaretDuff 1d10cfc
set default precision to double, as necessary for SAR which is curren…
fmwatson bb44155
added output type hints
fmwatson 4fa481a
convex_conjugate returns 0. when mathematically undefined to ensure c…
fmwatson d64316f
made decorators separate from class
fmwatson 7b5e577
removed unnecessary comments/old code
fmwatson 8446924
Updates from discussion in dev meeting - still failing out tests
MargaretDuff 1c6a034
Get precision from inputted x
MargaretDuff c5f5320
Merge branch 'master' into function_of_abs
MargaretDuff f687556
Merge branch 'master' into function_of_abs
MargaretDuff 9b91a7f
Apply suggestion from @hrobarts
MargaretDuff b7e17bb
Merge branch 'master' into function_of_abs
lauramurgatroyd 95c2dc1
Update NOTICE.txt
hrobarts 7a622e1
Update Wrappers/Python/cil/optimisation/functions/AbsFunction.py
hrobarts 00afe5b
Update Wrappers/Python/cil/optimisation/functions/AbsFunction.py
hrobarts 77cc514
Update Wrappers/Python/cil/optimisation/functions/AbsFunction.py
hrobarts e1eeee1
Apply suggestions from code review
hrobarts 25187a4
Update Wrappers/Python/cil/optimisation/functions/AbsFunction.py
hrobarts 43a9664
Changelog
hrobarts File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
227 changes: 227 additions & 0 deletions
227
Wrappers/Python/cil/optimisation/functions/AbsFunction.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,227 @@ | ||
# Copyright 2024 United Kingdom Research and Innovation | ||
# Copyright 2024 The University of Manchester | ||
# | ||
# 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. | ||
# | ||
# Authors: | ||
# CIL Developers, listed at: https://github.com/TomographicImaging/CIL/blob/master/NOTICE.txt | ||
# | ||
# This work has been supported by the Royal Academy of Engineering and the | ||
# Office of the Chief Science Adviser for National Security under the UK | ||
# Intelligence Community Postdoctoral Research Fellowship programme. | ||
# | ||
# Francis M Watson, University of Manchester 2024 | ||
# | ||
|
||
|
||
import numpy as np | ||
from cil.optimisation.functions import Function | ||
from cil.framework import DataContainer | ||
from typing import Optional | ||
import warnings | ||
import logging | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
class FunctionOfAbs(Function): | ||
r'''A function which acts on the absolute value of the complex-valued input, | ||
|
||
.. math:: G(z) = H(abs(z)) | ||
|
||
This function is initialised with another CIL function, :math:`H` in the above formula. When this function is called, first the absolute value of the input is taken, and then the input is passed to the provided function. | ||
|
||
Included in this class is the proximal map for FunctionOfAbs. From this, the proximal conjugate is also available from the parent CIL Function class, which is valid for this function. | ||
In the case that :math:`H` is lower semi-continuous, convex, non-decreasing and finite at the origin, (and thus `assume_lower_semi` is set to `True` in the `init`) the convex conjugate is also defined. | ||
The gradient is not defined for this function. | ||
|
||
|
||
|
||
Parameters | ||
---------- | ||
function : Function | ||
Function acting on a real input, :math:`H` in the above formula. | ||
assume_lower_semi : bool, default False | ||
If True, assume that the function is lower semi-continuous, convex, non-decreasing and finite at the origin. | ||
This allows the convex conjugate to be calculated as the monotone conjugate, which is less than or equal to the convex conjugate. | ||
If False, the convex conjugate returned as 0. This is to ensure compatibility with Algorithms such as PDHG. | ||
precision : str, default 'double' | ||
Precision of the calculation, 'single' or 'double' | ||
Some complex-valued imaging problems involve high dynamic range and/or require fine phase accuracy, necessitating the use of double precision (default). | ||
For example, in synthetic aperture radar imagery 100dB+ dynamic range may be encountered, which is more than single precision allows. | ||
In other cases use of single precision will reduce memory reservation and may improve performance, depending on the compute architecture. | ||
|
||
|
||
|
||
|
||
Reference | ||
--------- | ||
For further details see https://doi.org/10.48550/arXiv.2410.22161 | ||
|
||
hrobarts marked this conversation as resolved.
Show resolved
Hide resolved
|
||
''' | ||
|
||
def __init__(self, function: Function, assume_lower_semi: bool=False, precision: str='double'): | ||
self._function = function | ||
self._lower_semi = assume_lower_semi | ||
|
||
if precision=='single' or precision=='double': | ||
self.precision = precision | ||
else: | ||
raise ValueError('Precision must be `single` or `double`') | ||
|
||
super().__init__(L=function.L) | ||
|
||
def __call__(self, x: DataContainer) -> float: | ||
call_abs = (_take_abs_input(self.precision))(self._function.__call__) | ||
return call_abs(self._function, x) | ||
|
||
def proximal(self, x: DataContainer, tau: float, out: Optional[DataContainer]=None) -> DataContainer: | ||
r'''Returns the proximal map of function :math:`\tau G` evaluated at x | ||
|
||
.. math:: \text{prox}_{\tau G}(x) = \underset{z}{\text{argmin}} \frac{1}{2}\|z - x\|^{2} + \tau G(z) | ||
|
||
This is accomplished by calculating a bounded proximal map and making a change of phase, | ||
:math:`prox_G(z) = prox^+_H(r) \circ \Phi` where :math:`z = r \circ \Phi`, :math:`r = abs(z)`, :math:`\Phi = \exp(i angl(z))`, | ||
hrobarts marked this conversation as resolved.
Show resolved
Hide resolved
|
||
and :math:`\circ` is element-wise product. Also define :math:`prox^+` to be the proximal map of :math:`H` in which the minimisation carried out over the positive orthant. | ||
|
||
|
||
Parameters | ||
---------- | ||
x : DataContainer | ||
The input to the function | ||
tau: scalar | ||
The scalar multiplying the function in the proximal map | ||
out: return DataContainer, if None a new DataContainer is returned, default None. | ||
DataContainer to store the result of the proximal map | ||
|
||
|
||
Returns | ||
------- | ||
DataContainer, the proximal map of the function at x with scalar :math:`\tau`. | ||
|
||
''' | ||
prox_abs = _abs_and_project(self.precision)(self._function.proximal) | ||
return prox_abs(self._function, x, tau=tau, out=out) | ||
|
||
def convex_conjugate(self, x: DataContainer) -> float: | ||
r''' | ||
Evaluation of the function G* at x, where G* is the convex conjugate of function G, | ||
|
||
.. math:: G^{*}(x^{*}) = \underset{x}{\sup} \langle x^{*}, x \rangle - G(x) | ||
|
||
If :math:`H` is lower semi-continuous, convex, non-decreasing | ||
finite at the origin, then :math:`G^*(z*) = H^+(|z*|)`, where the monotone conjugate :math:`g^+` is | ||
|
||
.. math:: H^+(z^*) =sup {(z, z^*) - H(z) : z >= O} | ||
|
||
The monotone conjugate will therefore be less than or equal to the convex conjugate, | ||
since it is taken over a smaller set. It is not available directly, but may coincide with | ||
the convex conjugate, which is therefore the best estimate we have. This is only valid for | ||
real x. In other cases, a general convex conjugate is not available or defined. | ||
|
||
|
||
For reference see: Convex Analysis, R. Tyrrell Rocakfellar, pp110-111. | ||
|
||
|
||
Parameters | ||
---------- | ||
x : DataContainer | ||
The input to the function | ||
|
||
Returns | ||
------- | ||
float: | ||
|
||
hrobarts marked this conversation as resolved.
Show resolved
Hide resolved
|
||
''' | ||
|
||
if self._lower_semi: | ||
conv_abs = (_take_abs_input(self.precision))(self._function.convex_conjugate) | ||
return conv_abs(self._function, x) | ||
else: | ||
warnings.warn('Convex conjugate is not properly for this function, returning 0 for compatibility with optimisation algorithms') | ||
lauramurgatroyd marked this conversation as resolved.
Show resolved
Hide resolved
hrobarts marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return 0.0 | ||
|
||
def gradient(self, x): | ||
'''Gradient of the function at x is not defined for this function. | ||
''' | ||
raise NotImplementedError('Gradient not available for this function') | ||
|
||
def _take_abs_input(precision='double'): | ||
def _take_abs_input_inner(func): | ||
'''Decorator for function to act on abs of input of a method''' | ||
|
||
def _take_abs_decorator(self, x: DataContainer, *args, **kwargs): | ||
if precision == 'single': | ||
real_dtype = np.float32 | ||
elif precision == 'double': | ||
real_dtype = np.float64 | ||
else: | ||
raise ValueError('Precision must be `single` or `double`') | ||
rgeo = x.geometry.copy() | ||
rgeo.dtype = real_dtype | ||
r = rgeo.allocate(0) | ||
r.fill(np.abs(x.array).astype(real_dtype)) | ||
hrobarts marked this conversation as resolved.
Show resolved
Hide resolved
|
||
fval = func(r, *args, **kwargs) | ||
return fval | ||
return _take_abs_decorator | ||
return _take_abs_input_inner | ||
|
||
def _abs_and_project(precision='double'): | ||
def _abs_and_project_inner(func): | ||
'''Decorator for function to act on abs of input, | ||
with return being projected to the angle of the input. | ||
Requires function return to have the same shape as input, | ||
such as prox.''' | ||
|
||
|
||
def _abs_project_decorator(self, x: DataContainer, *args, **kwargs): | ||
if precision == 'single': | ||
real_dtype = np.float32 | ||
complex_dtype = np.complex64 | ||
elif precision == 'double': | ||
real_dtype = np.float64 | ||
complex_dtype = np.complex128 | ||
else: | ||
raise ValueError('Precision must be `single` or `double`') | ||
rgeo = x.geometry.copy() | ||
rgeo.dtype = real_dtype | ||
r = rgeo.allocate(None) | ||
r.fill( np.abs(x.array).astype(real_dtype)) | ||
Phi = np.exp((1j*np.angle(x.array))) | ||
out = kwargs.pop('out', None) | ||
|
||
fvals = func(r, *args, **kwargs) | ||
|
||
# Douglas-Rachford splitting to find solution in positive orthant | ||
if np.any(fvals.array < 0): | ||
log.info('AbsFunctions: projection to +ve orthant triggered') | ||
cts = 0 | ||
y = r.copy() | ||
while np.any(fvals.array < 0): | ||
tmp = fvals.array - 0.5*y.array + 0.5*r.array | ||
tmp[tmp < 0] = 0. | ||
y.array += tmp - fvals.array | ||
fvals = func(y, *args, **kwargs) | ||
cts += 1 | ||
if cts > 10: | ||
fvals.array[fvals.array < 0] = 0. | ||
break | ||
|
||
if out is not None: | ||
out.array = fvals.array.astype(complex_dtype)*Phi | ||
lauramurgatroyd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
else: | ||
out = x.geometry.allocate(None) | ||
out.array = fvals.array.astype(complex_dtype)*Phi | ||
return out | ||
return _abs_project_decorator | ||
return _abs_and_project_inner |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.