Skip to content

Pydantic for CNMFParams - #1566

Open
ethanbb wants to merge 56 commits into
flatironinstitute:devfrom
proektlab:improve-params-serialization
Open

ethanbb wants to merge 56 commits into
flatironinstitute:devfrom
proektlab:improve-params-serialization

Conversation

@ethanbb

@ethanbb ethanbb commented Feb 4, 2026 •

Copy link
Copy Markdown
Collaborator

Description

(Note: this includes changes from #1565 as well.)

This adds automatic validation/conversion of the types of incoming parameters (whether from the constructor, JSON, or when loading a CNMF HDF5 file) and reversible serialization. With the power of pydantic, which I am myself only newly aware of, we can also do all kinds of semantic validation on the values as well (like ranges of ints/floats, making sure paths are valid, etc.); I didn't put much of that in here.

Benefits:

  • Having the type declared for each parameter means that we can reliably convert data read from other formats (mainly JSON) to the right types, with the help of some custom validators and serializers. For example, the b'NoneType' and incorrect slice roundtripping can be totally handled by adding validation/serialization logic in one place (the params.py file).
  • The type of each parameter is available for static type checking when accessing using dot syntax (now works because they are housed in dataclasses). I extended the base class for the sub-parameters to also work as a non-mutable mapping, so dict syntax will continue to work as well for backward compatibility (but not for setting, which was already not recommended in favor of the change_params method).
    • Each group params object can also be instantiated by itself with type-checked keyword arguments, and then passed as an argument to the CNMFParams constructor. This is a new alternative construction method that allows full type checking. I modified the demo_pipeline.ipynb notebook to demonstrate this method.
  • I made it so that validation errors never actually raise an error, rather just print a warning that the type may be incorrect. I figured that this is more in keeping with the training-wheels-off nature of this package and the reality that tracking how each of them is used is difficult, thus setting the values to types I didn't anticipate may sometimes be necessary.
  • Many of the checks previously done in check_consistency could be decentralized, reducing redundant checks when not relevant:
    • Most notably, defaults triggered by a None value and set based on other parameters were converted to properties on the respective GroupParams subclass. I set this up in a "clever" way so that any non-default value is stored in an actual field with an underscore, but with an "alias" of the public name, which allows it to be set by that name in the constructor. So if our field is dependent, the field SomeParams._dependent always contains None if the value has not been set and should take a default (or has been set explicitly to None). Meanwhile, if some_params._dependent is None, reading the param using some_params.dependent computes the correct default/fallback value in the property implementation. The benefit here is that if the params it depends on change, we know that the value of dependent is just a default and it will take an updated value, as opposed to the case where _dependent is not None indicating a user-set value.
    • For some params, such as spatial.nb and temporal.nb, there is no need for them to be set by the user; they are only ever computed/dependent (in this case, these should be read from init.nb). I converted these params to properties with no corresponding field, and attempting to set them again logs a warning (matching the existing "attempts to change them elsewhere are ignored" warning for nb).
    • Some checks can be handled by custom validators, such as converting to None from string or bytes types, or ensuring the values of gSiz are odd integers.
    • Some checks that only pertain to one parameter group could be moved to a model validator on that group rather than on the full CNMFParams object.

Overall I hope this leads to more robustness with the parameters system and make fixes to any residual bugs cleaner and less ad-hoc. I realize it is a new, somewhat complicated library to learn though - I'm happy to explain more and I'll leave some comments inline in the diff as well.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Changes in documentation or new examples for demos and/or use cases.

Has your PR been tested?

Yes, caimanmanager test and caimanmanager demotest pass. I added a new test file for the new params features.

…extensions by . (assuming no other dots in path)

@pgunn pgunn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In general I really like these changes (apart from the incomplete-path import names); this also strengthens the structure in the params object, something I've wanted to do for a long time.

For this I think it would need to be a mid-dot release because some user code might break with these changes, but we'll be glad it was done after the dust settles. Eventually someday it might make sense to start turning validation on, selectively.

It may be necessary to look over the volpy cloning of CNMFParams, as this will leave that codebase as the odd one out (and there's a chance this will break that); in the long run it probably makes sense to just pull the volpy parameters into the main params object and have volpy use that. Might not be necessary to do that in this PR (unless this breaks the volpy params handling).

Comment thread caiman/base/movies.py Resolved

if d == 3 and Y.shape[-1] > 1 and ds[0] == ds[1]:
ds_mat = caiman.source_extraction.cnmf.utilities.decimation_matrix(Y.shape[:2], ds[0])
ds_mat = utilities.decimation_matrix(Y.shape[:2], ds[0])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm not a fan of the shortened paths; this requires users to go read the import to see if this is a method call, a library called utilities, or a partial path and a call.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

OK, but pyright gives me a linting error the way that it was before with just import caiman (aside from the imports of specific functions): "source_extraction" is not a known attribute of module "caiman". I think this kind of reference without explicitly importing the sub-package only works because the __init__.py of caiman, or any of the modules it imports, imports something within caiman.source_extraction.cnmf.utilities. So that's a fragile pattern even though it works most of the time.

I can change it to import caiman.source_extraction.cnmf and use absolute paths for the function calls again, though.

@ethanbb ethanbb Feb 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Or what about from caiman.source_extraction import cnmf and then use cnmf.<whatever>? I think this is the standard in Rust for the reason you stated.

Edit: I don't know what I was talking about, that wouldn't make sense. The Rust convention is to do what I did here, so it's <module>.<function>()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm curious - do you get the linting error if you run the linter from outside the caiman source directory? e.g. if you have ~/src/caiman_dev

does

~$ mylinter src/caiman_dev/caiman/source_extraction/cnmf/CNMFParams.py

work? This might be one of those build quirks.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yeah, I think it is actually correct. I was surprised too. But I think the key to why it normally works is here. Basically, any modules that have to be traversed in the initial package import (through __init__.py) are available through their fully-qualified names: "The invariant holding is that if you have sys.modules['spam'] and sys.modules['spam.foo'] (as you would after the above import), the latter must appear as the foo attribute of the former."

I tested and found that if I create a dummy package foo with an empty top-level __init__.py and a sub-package bar, doing:

import foo
foo.bar

does cause a runtime error!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hm. It would be nice to find a set of templates and practices so we never have to think about this again; if that means init.py imports everything, that seems fine. What do you think?


@profile
def greedyROI_corr(Y, Y_ds, max_number=None, gSiz=None, gSig=None, center_psf=True,
def greedyROI_corr(Y, Y_ds, options: params.CNMFParams, max_number=None, gSiz=None, gSig=None, center_psf=True,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ordinarily I'd be worried about reordering params in case people pass in a large number of positionals, but this may be fine? We just have to hope no user code does that. It might be worth using the asterisk to stop use of positionals so it will throw a better error if any user code does that. We haven't been using asterisks in prototypes in the codebase but maybe it's time to start doing that?

@ethanbb ethanbb Feb 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yeah, params isn't really an optional argument which is why I did this. Unfortunately that requires reordering the arguments. Alternatively an error could just be raised immediately if params is None.

Edit: I will do this

data_filtered -= data_filtered.mean(axis=0)
data_max = np.max(data_filtered, axis=0)
noise_pixel = get_noise_fft(data_filtered.T, noise_method='mean')[0].T
noise_pixel = pre_processing.get_noise_fft(data_filtered.T, noise_method='mean')[0].T

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Apart from the paths being short, I like that there's some degree of pathing added.


########
main()
if __name__ == '__main__':

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What's the reason for the main stuff here? We're not expecting anyone to import the demos as a library, are we?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

See #1565 - it is important for multiprocessing when not using the fork method.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ah, fair enough.

Comment thread demos/general/demo_OnACID_mesoscope.py Outdated
########
main() No newline at end of file
if __name__ == '__main__':
main() No newline at end of file

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

If we're touching this let's get that final newline in

plt.xlabel('Frame #')
plt.ylabel('Processing time [ms]')

if not cfg.no_play:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ah, good catch with this

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This is also part of #1565 - I was hoping we could review/merge that first, so I didn't bother separating them

Comment thread caiman/motion_correction.py Outdated
if save_hdf5:
Yr.save(fname[:-idx_dot] + 'hdf5')
np.savez(fname[:-idx_dot] + 'npz', shifts=shifts,
Yr.save(fname_no_ext + '.hdf5')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe an f-string?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Sure, why not.

Comment thread caiman/tests/test_params.py Outdated
Comment on lines +18 to +20
import caiman.utils.utils
from caiman.paths import caiman_datadir
from caiman.source_extraction.cnmf import params, cnmf

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

alphabetise imports in this section

…nging params within `fit` as much as possible
@ethanbb

ethanbb commented Feb 11, 2026

Copy link
Copy Markdown
Collaborator Author

OK so in this latest commit, I made some more changes. I realized that instead of just rejecting changes to nb that were on the wrong group, it would be more likely to align with the user's intention to warn but still make the change on the correct group. On the other hand, if there are multiple different values for nb in one update, that should be an error rather than just taking the one on the init group. So I added some new logic to check for that.

Also, I set up p and n_pixels_per_process to work the same way, since they're both always set to be the same value anyway within CNMF.fit. I decided the canonical group for p should be temporal and for n_pixels_per_process should be spatial - even though they may be accessed more often through preprocess, the spatial and temporal groups seem to make more logical sense. Like nb, they can both still be read from the preprocess group.

Finally, I went through CNMF.fit and some of the functions it calls and tried to eliminate calls to CNMFParams.set that converted default placeholders to concrete values, in the same spirit as the parameters that are now computed dynamically instead of set to a default when not explicitly set. For example, n_pixels_per_process and patch.stride now remain None on the params object if not set to a non-None value. (stride could be one of those computed params, except that the run_CNMF_patches function uses a different way of computing the default, so I didn't want to commit to one way or the other in case it is ever run on its own.)

This is a bit debatable - I've been thinking of the params object as something that might be reused in the future for other runs (e.g., for a grid search), so we should avoid changing parameters unexpectedly in ways that will change the behavior depending on the order of runs. But maybe this particular params object (which is saved with the CNMF results) should hold all the parameter values that were actually used, as a persistent record in case the code changes in the future? Now that I'm thinking about this some more, I think the right thing to do might be to just make a copy of any passed-in CNMFParams immediately and then treat that as something that can be freely modified to reflect the current run.

@ethanbb
ethanbb marked this pull request as draft March 2, 2026 04:55
Comment thread caiman/source_extraction/cnmf/params.py Outdated
Comment on lines +1471 to +1477
# Set structuring element to the no-op value (previously done in initialization.greedyROI_corr)
ndim = len(self.data.dims) if self.data.dims is not None else 2
null_se = np.ones((1,) * ndim, dtype=np.uint8)
if not utilities.all_same(self.spatial.se, null_se):
logger.warning("using CNMF-E's ringmodel for background hence setting key "
"se in group spatial automatically to null element.")
self.set('spatial', {'se': null_se}, warn=False, verbose=False)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I'm marking this as a draft for now because I found this behavior isn't quite consistent with the current behavior. Specifically, when initializing using greedyROI_corr (i.e., corr_pnr), there are 2 lines where update_spatial_components is called with the original value of se (lines 1245 and 1285) before it is set to this identity element for the call on line 1335 and for the rest of the CNMF run, since the params object gets modified. And I think this is causing a difference in outputs for one of the mesmerize tests.

I'd like to see if I can guess from the git history whether this is intentional or a mistake...since the current actual behavior is a bit weird, I don't really want to try to figure out a way to replicate it with an immutable params object if it might just be a bug.

(As an aside, I was thinking it might be good to incorporate the mesmerize tests or maybe something similar but not depending on mesmerize, as part of the caiman CI. Since they seems to be better at catching when the behavior of the algorithms changes, at least for the ones mesmerize uses.)

@pgunn pgunn Mar 2, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I wish I knew whether that was intended offhand, but I don't.

Always up for more tests (provided they don't add dependencies)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I did some more reading and looking through the code... It looks like the first 2 times update_spatial_components is run during initialization, using the se provided, it is operating on data downsampled by ssub (by a factor of 2 by default). Then, in the 3rd update_spatial run during initialization and once more on the full image if a lower-rank background is requested (nb > 0, which is not recommended for 1p anyway), when operating on non-downsampled data, the closing step is skipped. I do think this is intentional, because only_init is always used for 1p, and the only other place where update_spatial would be called and implicitly use the 1x1 se set during corr_pnr initialization is when only_init is false.

Since the effect of the closing operation depends on the scale of the image relative to the structuring element, it makes sense that the same se shouldn't be used for both downsampled and non-downampled data. To me, it would make more sense to use a downsampled se for downsampled data (e.g., 2x2 rather than 3x3) and the original se for original data. It's probably also fine to skip it on later spatial refinement runs, but it would be surprising if someone used a more aggressive downsampling and ended up filling in a large hole because a 3x3 closing step was still performed and then upsampled...so I think this is potentially worth changing to be consistent with the way the se is used for other init methods.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

OK I think this is out of scope for the PR, so I documented it in #1575 and will restore the original behavior.

@ethanbb

ethanbb commented Mar 4, 2026

Copy link
Copy Markdown
Collaborator Author

Now passes mesmerize tests (with appropriate updates) 🎉

@ethanbb

ethanbb commented Mar 31, 2026

Copy link
Copy Markdown
Collaborator Author

Currently seems to be failing CI due to a certificate error for caiman.flatironinstitute.org.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants