-
Notifications
You must be signed in to change notification settings - Fork 12
Constrained scan update #44
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
Open
michaelxu01
wants to merge
19
commits into
hexane360:develop
Choose a base branch
from
michaelxu01:scanobject
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
6eaed78
untested refactor, conventional still needs fix, basic hook and for s…
michaelxu01 0bcdd5b
bug fixes, functional h5 output
michaelxu01 7d348c2
functioning reconstruction with affine constraint... not yet verified
michaelxu01 13880c0
before split
michaelxu01 9ce4dd3
working new scanconstraintprops and bug fixes
michaelxu01 d9558b1
add reference
michaelxu01 29cfe0f
write and read h5 functional
michaelxu01 f5039fd
bug fix in read h5
michaelxu01 3bca912
initial changes to conventional
michaelxu01 c80d382
Update test_initialization.py
michaelxu01 56d5a74
match statement, matmul, private, and cleanup of comments
michaelxu01 a2566cb
additional cleanup
michaelxu01 6d94fd2
lsqml working
michaelxu01 3e596d0
fixed constraint weights, no renormalization
michaelxu01 a4de8a8
added docs for scan constraint reg, additional cleanup
michaelxu01 b50f062
cleanup
michaelxu01 1bc614e
bug fix
michaelxu01 04c45f3
change metadata read/write to json
michaelxu01 48ad8f7
fixed import of same function name
michaelxu01 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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,12 +11,157 @@ | |
| ) | ||
| from phaser.utils.image import convolve1d | ||
| from phaser.state import ReconsState | ||
| from phaser.hooks.regularization import ( | ||
| from phaser.hooks.regularization import (ScanConstraintProps, | ||
| ClampObjectAmplitudeProps, LimitProbeSupportProps, NonNegObjectPhaseProps, | ||
| RegularizeLayersProps, ObjLowPassProps, GaussianProps, | ||
| CostRegularizerProps, TVRegularizerProps, UnstructuredGaussianProps | ||
| ) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| class ScanUpdate(t.NamedTuple): | ||
| """ | ||
| Scan update object for holding the scan constraint row index and previous position arrays | ||
| """ | ||
| previous: numpy.typing.NDArray[numpy.floating] | ||
| row_bins: t.Optional[numpy.typing.NDArray[numpy.integer]] = None | ||
| class ScanConstraint: | ||
| """ | ||
| Constraints for the scan position updates. | ||
| This per iteration regularizer takes the unconstrained position updates and applies a | ||
| weighted average of its affine, line (row) averaged, high pass filtered, or low pass filtered components. | ||
| Currently, only the affine and line averaged constraints are implemented. | ||
|
|
||
| See ref for details: | ||
| S. Ning, W. Xu, L. Loh, Z. Lu, M. Bosman, F. Zhang, Q. He, An integrated constrained gradient descent (iCGD) protocol to correct scan-positional errors for electron ptychography with high accuracy and precision. Ultramicroscopy 248, 113716 (2023). | ||
| """ | ||
| def __init__(self, args: None, props: ScanConstraintProps): | ||
| self.valid_kinds: t.Set[str] = {'affine', 'line', 'hpf', 'lpf'} | ||
| self.constraints: t.Dict[str, float] = {} #= {'default': 1.0} | ||
|
|
||
| total_constraint_weight = 0 | ||
| for kind in self.valid_kinds: | ||
| if getattr(props, kind) > 0: | ||
| val = getattr(props, kind) | ||
| self.constraints[kind] = val | ||
|
|
||
| total_constraint_weight += val | ||
|
|
||
| if total_constraint_weight > 1.0: | ||
| raise ValueError("Sum of scan constraint weights cannot exceed 1.0") | ||
|
|
||
| self.constraints['default'] = 1-total_constraint_weight | ||
|
|
||
| logger.info(f"Initialized scan constraint with kinds {list(self.constraints.keys())} and weights {list(self.constraints.values())}") | ||
|
|
||
| def init_state(self, sim: ReconsState) -> ScanUpdate: | ||
| if 'line' in self.constraints: | ||
| if (sim.scan.metadata.get('type') != 'raster') | (sim.scan.metadata.get('rows') is None): | ||
| raise ValueError("Line scan constraint cannot be applied to scans without row metadata") | ||
| row_vals = sim.scan.metadata.get('rows') | ||
| if isinstance(row_vals, list): | ||
| row_vals = numpy.array(row_vals, dtype=numpy.integer) | ||
| state = ScanUpdate(previous=sim.scan.data.copy(), row_bins=row_vals.ravel()) | ||
| else: | ||
| state = ScanUpdate(previous=sim.scan.data.copy(), row_bins=None) | ||
| return state | ||
|
|
||
| def apply_group(self, group: NDArray[numpy.integer], sim: ReconsState, state: ScanUpdate) -> t.Tuple[ReconsState, ScanUpdate]: | ||
| return self.apply_iter(sim, state) | ||
|
|
||
| def apply_iter(self, sim: ReconsState, state: ScanUpdate) -> t.Tuple[ReconsState, ScanUpdate]: | ||
| xp = get_array_module(sim.scan.data) | ||
| update = xp.zeros_like(sim.scan.data, dtype=sim.scan.data.dtype) | ||
| for kind, weight in self.constraints.items(): | ||
| match kind: | ||
| case 'affine': | ||
| update += _scan_affine(sim.scan.data, state.previous) * weight | ||
| case 'line': | ||
| if state.row_bins is not None: | ||
| update += _scan_line(sim.scan.data, state.previous, state.row_bins) * weight | ||
| case 'hpf': | ||
| pass | ||
| case 'lpf': | ||
| pass | ||
| case 'default': | ||
| update += _scan_default(sim.scan.data, state.previous) * weight | ||
|
|
||
| sim.scan.data = state.previous + update | ||
| state = ScanUpdate(previous=sim.scan.data.copy(), row_bins=state.row_bins) | ||
| return (sim, state) | ||
|
|
||
| # @partial(jit, donate_argnames=('pos',), cupy_fuse=True) | ||
| def _scan_default( | ||
| pos: NDArray[numpy.floating], | ||
| prev: NDArray[numpy.floating], | ||
| ) -> NDArray[numpy.floating]: | ||
| """ | ||
| Pass through function for calculating the scan update from final and initial scan positions. | ||
|
|
||
| :param pos: N x 2 array of unconstrained updated scan positions | ||
| :type pos: NDArray[numpy.floating] | ||
| :param prev: N x 2 array of scan positions, before update (previous iteration) | ||
| :type prev: NDArray[numpy.floating] | ||
| :return: N x 2 array of updates to the scan positions | ||
| :rtype: NDArray[floating[Any]] | ||
| """ | ||
| return pos - prev | ||
|
|
||
| def _scan_affine( | ||
| pos: NDArray[numpy.floating], | ||
| prev: NDArray[numpy.floating], | ||
| ) -> NDArray[numpy.floating]: | ||
| """ | ||
| Calculates and returns the affine component of the update between final and initial scan positions. | ||
|
|
||
| :param pos: N x 2 array of unconstrained updated scan positions | ||
| :type pos: NDArray[numpy.floating] | ||
| :param prev: N x 2 array of scan positions, before update (previous iteration) | ||
| :type prev: NDArray[numpy.floating] | ||
| :return: N x 2 array of updates to the scan positions (affine only) | ||
| :rtype: NDArray[floating[Any]] | ||
| """ | ||
| xp = get_array_module(pos) | ||
|
|
||
| disp_update = pos - prev | ||
| ones = xp.ones((pos.shape[0], 1), pos.dtype) | ||
| pos_prev = xp.concatenate([pos, ones], axis=1) | ||
| left = xp.matmul(pos_prev.T, disp_update) | ||
| right = xp.matmul(pos_prev.T, pos_prev) | ||
| A = xp.matmul(xp.linalg.inv(right), left) | ||
| constraint = xp.matmul(pos_prev, A) | ||
| center_ones = xp.ones((1, 1), pos.dtype) | ||
| center = xp.concatenate([xp.average(pos, axis = 0, keepdims=True), center_ones], axis=1, dtype=pos.dtype) | ||
| center_shift = center @ A | ||
| constraint -= center_shift | ||
| return constraint | ||
|
|
||
| # @partial(jit, donate_argnames=('pos',), cupy_fuse=True) | ||
| def _scan_line( | ||
| pos: NDArray[numpy.floating], | ||
| prev: NDArray[numpy.floating], | ||
| rows: NDArray[numpy.integer], | ||
| ) -> NDArray[numpy.floating]: | ||
| """ | ||
| Calculates and returns a line (row) averaged update from the unconstrained final and initial scan positions. | ||
|
|
||
| :param pos: N x 2 array of unconstrained updated scan positions | ||
| :type pos: NDArray[numpy.floating] | ||
| :param prev: N x 2 array of scan positions, before update (previous iteration) | ||
| :type prev: NDArray[numpy.floating] | ||
| :param rows: an array of row indices corresponding to the N positions given by pos and prev | ||
| :type rows: NDArray[numpy.integer] | ||
| :return: N x 2 array of updates to the scan positions (row averaged) | ||
| :rtype: NDArray[floating[Any]] | ||
| """ | ||
| xp = get_array_module(pos) | ||
|
|
||
| disp_val = pos - prev | ||
|
|
||
| y_shifts = xp.bincount(rows, disp_val[:,0]) / xp.bincount(rows) | ||
| x_shifts = xp.bincount(rows, disp_val[:,1]) / xp.bincount(rows) | ||
| constraint = xp.stack([y_shifts[rows], x_shifts[rows]], axis=1, dtype=pos.dtype) | ||
| return constraint | ||
|
|
||
| class ClampObjectAmplitude: | ||
| def __init__(self, args: None, props: ClampObjectAmplitudeProps): | ||
|
|
@@ -250,7 +395,7 @@ def calc_loss_group( | |
| xp = get_array_module(sim.object.data) | ||
|
|
||
| cost = xp.sum(xp.abs(sim.object.data - 1.0)) | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.shape[:-1]), dtype=cost.dtype) | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.data.shape[:-1]), dtype=cost.dtype) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe unnecessary for this PR, but we could probably make |
||
| return (cost * cost_scale * self.cost, state) | ||
|
|
||
|
|
||
|
|
@@ -272,7 +417,7 @@ def calc_loss_group( | |
|
|
||
| cost = xp.sum(abs2(sim.object.data - 1.0)) | ||
|
|
||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.shape[:-1]), dtype=cost.dtype) | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.data.shape[:-1]), dtype=cost.dtype) | ||
| return (cost * cost_scale * self.cost, state) # type: ignore | ||
|
|
||
|
|
||
|
|
@@ -293,7 +438,7 @@ def calc_loss_group( | |
| xp = get_array_module(sim.object.data) | ||
|
|
||
| cost = xp.sum(xp.abs(xp.angle(sim.object.data))) | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.shape[:-1]), dtype=cost.dtype) | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.data.shape[:-1]), dtype=cost.dtype) | ||
| return (cost * cost_scale * self.cost, state) | ||
|
|
||
|
|
||
|
|
@@ -319,7 +464,7 @@ def calc_loss_group( | |
| xp.abs(fft2(xp.prod(sim.object.data, axis=0))) | ||
| ) | ||
| # scale cost by fraction of the total reconstruction in the group | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.shape[:-1]), dtype=cost.dtype) | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.data.shape[:-1]), dtype=cost.dtype) | ||
|
|
||
| return (cost * cost_scale * self.cost, state) | ||
|
|
||
|
|
@@ -351,7 +496,7 @@ def calc_loss_group( | |
| #) | ||
| # scale cost by fraction of the total reconstruction in the group | ||
| # TODO also scale by # of pixels or similar? | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.shape[:-1]), dtype=cost.dtype) | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.data.shape[:-1]), dtype=cost.dtype) | ||
|
|
||
| return (cost * cost_scale * self.cost, state) | ||
|
|
||
|
|
@@ -377,7 +522,7 @@ def calc_loss_group( | |
| xp.sum(abs2(xp.diff(sim.object.data, axis=-2))) | ||
| ) | ||
| # scale cost by fraction of the total reconstruction in the group | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.shape[:-1]), dtype=cost.dtype) | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.data.shape[:-1]), dtype=cost.dtype) | ||
|
|
||
| return (cost * cost_scale * self.cost, state) # type: ignore | ||
|
|
||
|
|
@@ -403,7 +548,7 @@ def calc_loss_group( | |
|
|
||
| cost = xp.sum(xp.abs(xp.diff(sim.object.data, axis=0))) | ||
| # scale cost by fraction of the total reconstruction in the group | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.shape[:-1]), dtype=cost.dtype) | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.data.shape[:-1]), dtype=cost.dtype) | ||
|
|
||
| return (cost * cost_scale * self.cost, state) | ||
|
|
||
|
|
@@ -429,7 +574,7 @@ def calc_loss_group( | |
|
|
||
| cost = xp.sum(abs2(xp.diff(sim.object.data, axis=0))) | ||
| # scale cost by fraction of the total reconstruction in the group | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.shape[:-1]), dtype=cost.dtype) | ||
| cost_scale = xp.array(group.shape[-1] / prod(sim.scan.data.shape[:-1]), dtype=cost.dtype) | ||
|
|
||
| return (cost * cost_scale * self.cost, state) # type: ignore | ||
|
|
||
|
|
@@ -519,7 +664,7 @@ def __init__(self, args: None, props: UnstructuredGaussianProps): | |
| self.attr_path = props.attr_path | ||
|
|
||
| def init_state(self, sim: ReconsState) -> NDArray[numpy.floating]: | ||
| xp = get_array_module(sim.scan) | ||
| xp = get_array_module(sim.scan.data) | ||
| try: | ||
| self.getattr_nested(sim, self.attr_path) | ||
| except AttributeError as e: | ||
|
|
@@ -547,8 +692,8 @@ def setattr_nested(self, obj: t.Any, attr_path: str, value: t.Any): | |
| def apply_iter(self, sim: ReconsState, state: NDArray[numpy.floating]) -> t.Tuple[ReconsState, NDArray[numpy.floating]]: | ||
| from scipy.spatial import KDTree | ||
| obj_samp = sim.object.sampling | ||
| scan_flat = sim.scan.reshape(-1, 2) | ||
| scan_ndim = sim.scan.ndim - 1 | ||
| scan_flat = sim.scan.data.reshape(-1, 2) | ||
| scan_ndim = sim.scan.data.ndim - 1 | ||
|
|
||
| attr = self.getattr_nested(sim, self.attr_path) | ||
| vals = t.cast(NDArray[numpy.inexact], getattr(attr, 'data', attr)) # Extract raw array | ||
|
|
||
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this deterministic? It seems like it could apply the updates in arbitrary order, we may want to add sorted() if it matters
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should be deterministic, since the updates are summed and applied after each kind * weight is calculated from the common unconstrained update and previous scan state. Example:
update += scan_affine(sim.scan.data, state.previous) * weight