Repository navigation
Conversation
…ped accesses in check_consistency
…upParams return a dict to fix assignment
…ing InstanceOf and ValidateAs
…g dict of allowed constructor args
…take a computed default value (like gSiz)
…extensions by . (assuming no other dots in path)
…tax in demo_pipeline
pgunn
left a comment
There was a problem hiding this comment.
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).
|
|
||
| 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]) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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>()
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.bardoes cause a runtime error!
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Apart from the paths being short, I like that there's some degree of pathing added.
|
|
||
| ######## | ||
| main() | ||
| if __name__ == '__main__': |
There was a problem hiding this comment.
What's the reason for the main stuff here? We're not expecting anyone to import the demos as a library, are we?
There was a problem hiding this comment.
See #1565 - it is important for multiprocessing when not using the fork method.
| ######## | ||
| main() No newline at end of file | ||
| if __name__ == '__main__': | ||
| main() No newline at end of file |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
This is also part of #1565 - I was hoping we could review/merge that first, so I didn't bother separating them
| if save_hdf5: | ||
| Yr.save(fname[:-idx_dot] + 'hdf5') | ||
| np.savez(fname[:-idx_dot] + 'npz', shifts=shifts, | ||
| Yr.save(fname_no_ext + '.hdf5') |
| import caiman.utils.utils | ||
| from caiman.paths import caiman_datadir | ||
| from caiman.source_extraction.cnmf import params, cnmf |
There was a problem hiding this comment.
alphabetise imports in this section
…nging params within `fit` as much as possible
|
OK so in this latest commit, I made some more changes. I realized that instead of just rejecting changes to Also, I set up Finally, I went through 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 |
| # 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) |
There was a problem hiding this comment.
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.)
There was a problem hiding this comment.
I wish I knew whether that was intended offhand, but I don't.
Always up for more tests (provided they don't add dependencies)
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
OK I think this is out of scope for the PR, so I documented it in #1575 and will restore the original behavior.
|
Now passes mesmerize tests (with appropriate updates) 🎉 |
…(specifically fix loading cnmf.{estimates.}dims)
|
Currently seems to be failing CI due to a certificate error for caiman.flatironinstitute.org. |
…xes - instead validate 'IntSlice' specifically which was my root problem
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:
change_paramsmethod).CNMFParamsconstructor. This is a new alternative construction method that allows full type checking. I modified thedemo_pipeline.ipynbnotebook to demonstrate this method.check_consistencycould be decentralized, reducing redundant checks when not relevant:Nonevalue and set based on other parameters were converted to properties on the respectiveGroupParamssubclass. 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 isdependent, the fieldSomeParams._dependentalways containsNoneif the value has not been set and should take a default (or has been set explicitly toNone). Meanwhile, ifsome_params._dependent is None, reading the param usingsome_params.dependentcomputes 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 ofdependentis just a default and it will take an updated value, as opposed to the case where_dependent is not Noneindicating a user-set value.spatial.nbandtemporal.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 frominit.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 fornb).Nonefrom string or bytes types, or ensuring the values ofgSizare odd integers.CNMFParamsobject.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
Has your PR been tested?
Yes,
caimanmanager testandcaimanmanager demotestpass. I added a new test file for the new params features.