You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Error checking in Info - setting unsupported keys in mne.Info or mne.Info attributes partially works and doesn't show any warnings #9752
In my preprocessing pipeline, I'm setting some information about the subjects. One of the interesting features is the age, or the birth year. But MNE only supports the birthday as a tuple (year, month, day), as per the documentation ofmne.Info.
Sadly, I do not have the exact birthday, and instead of setting it as (year, month, 1), I figured I could set a different birthyear or age argument directly.
And it worked really nicely. Until I saved and reloaded the file.
raw = mne.io.read_raw_fif(...)
raw.info['subject_info']
{'id': 65, 'his_id': '065', 'sex': 1}
The issue is that this emits no warning, no error, and yet the added data is not saved to disk.
If the dictionary stored in 'subject_info' is not used by anything, and is just here for user-defined variables (is this the case?) then how about dropping the limitation on what the keys can be?
We have some history of trying to make things read-only, see for example #7816 (comment). I don't remember the full discussion but that comment has a bunch of links
@larsoner Thanks for the bedside reading.
In my opinion, MNE and Python have both come a long way since the Info structure has been designed, and maybe it could (and need) to be reworked and improved.
As an end-user, I am always surprised by the structure of Info.
Why is it a class where you access the attributes as you would with a dictionary?
Why not a class with the attributes accessible as Info.attribute?
Why only ch_names is accessible as Info.ch_names?
Obviously, you do get used to this structure; but it doesn't make it convenient. Most (if not all) IDE completion providers will not always work with the dictionary syntax Info[' while they will with a plain attribute one Info..
e.g. in IPython console:
e.g in Spyder IDE: (Kite is not that smart, but still..)
Even as someone who is used to it, I still have to go look what are the valid keys in Info from time to time.
And finally, the underwater part of the iceberg: error checking. What is preventing users from modifying attributes they are not supposed to modify directly? A note in the documentation:
The only entries that should be manually changed by the user are info['bads'] and info['description'].
All other entries should be considered read-only, though they can be modified by various MNE-Python functions or methods (which have safeguards to ensure all fields remain in sync).
And even for those 2, some error checking would be necessary. Example with bads:
"""
mne.set_log_level('INFO')
raw = mne.io.read_raw_fif(...)
raw.info['bads'].append('test')
raw.info['bads']
Out: ['M1', 'CP1', 'test']
"""
I didn't expect this to work, but apparently, it is valid? Of course, a channel name 'test' is an extreme case; but typos in the channel name syntax are not, e.g. "FP1" instead of "Fp1". For instance, the LSL plugin I am using for eego amplifiers has a build-in typo on 10 channel names.
Proposed changes:
Turn the attribute of Info into properties. @cbrnr pinging the properties aficionado. Info['bads'] would become Info.bads pointing to e.g. Info._bads.
Properties setter can be used to perform error checking on properties that can be edited manually and to display a logger warning pointing toward the functions/methods used to change properties that can not be edited manually.
Properties pointing to a mutable type must be either changed to an immutable type OR to a custom class inheriting the mutable type and performing error checking when necessary OR to a different smart solution enabling error checking.
I know @agramfort is not a fan of properties and implicit properties setters. However, this is different from the case where the implicit setter changes the property value and other properties/attributes/settings under the hood. The setter is only used to either perform error checking on its own property (and thus display an instructive logging message if needed) OR to point the user with a logging message towards the function/method to use to change this property (equivalent to an explicit setter).
Refactoring Info looks like a major overhaul, impacting not only itself but many functions and methods across MNE, but it looks to me like a major improvement of the existing MNE structures.
And it doesn't need to be done all in one go. It can be done attribute per attribute while preserving the current structure. With one PR per attribute, discussions on the correct, smarter implementation adding error checking while not impacting performance should be efficient.
Example for bads: (Disclaimer: it's just some quick and simple ideas!)
It should remain a list-like object supporting both assignment with bads = [...] and expansion with bads += [...] and bads.append().
Define a MutableSequence instance that is a sequence of strings.
Define the init and append methods of this instance in a way that performs error checking.
In Info, define the property bads and its setter to use the created MutableSequence instance.
Change in MNE the call Info['bads'] to Info.bads.
Add a deprecation warning to calls Info['bads']
Rinse and repeat for every attribute (more or less). Some will be harder than others and will require more time.
Apology for the long post, it might spark some unwanted discussions; but I wanted to give you my opinion on the Info structure design.
if si.get('weight') is not None:
write_float(fid, FIFF.FIFF_SUBJ_WEIGHT, si['weight'])
if si.get('height') is not None:
write_float(fid, FIFF.FIFF_SUBJ_HEIGHT, si['height'])
Those are not documented. I'm guessing those are not the only example of attributes poorly documented/checked in Info.
As discussed, this is a very very very low priority issue. But it would be nice if little by little, error checking gets implemented in mne.Info to avoid having users shoot themselves in the foot on a regular basis.
Use Bunch -> Turn Info into a Bunch; as this is already inheriting from dict, it should not break anything. Error checking would be implemented in the attribute getter/setter.
Use dataclasses (py 3.7+) and let the interpreter do the error checking.
Bunch idea PRs:
See if anything breaks when turning info into a Bunch
Limit the set of valid attributes to supported keys
However, some people use Info dict to pass variables around. It's not officially supported, but blocking this would break user code. Idea: issue a warning when the user uses an unsupported variable would be already a good improvement, explicitly informing the user that this variable will not be guarantee to remain in the info and will not get saved.
Give a shot to an error checking on an attribute, e.g. bads.
changed the title [-]Settings unexpected keys in `raw.info['subject_info']` works but does not get saved.[/-][+]Error checking in Info - setting unsupported keys in `mne.Info` or `mne.Info` attributes partially works and doesn't show any warnings[/+]on Sep 17, 2021
See if anything breaks when turning info into a Bunch
+1 for a quick PR that does this, it will help us see if it's already going to be a maintenance pain...
Idea: issue a warning when the user uses an unsupported variable would be already a good improvement, explicitly informing the user that this variable will not be guarantee to remain in the info and will not get saved.
Another option would be to officially support a info['temp'] / info.temp variable that we explicitly document will not survive I/O round-trip. That makes an easy transition for people that have been mis-using (knowingly or unknowingly) Info. And in the meantime we can simultaneously make our key/property checking strictly limited to writable keys + temp.
It looks like most of this is taken care of now. What remains to be protected at some point are values of Info that are dicts themselves like info['subject_info'], but we can tackle those as people are motivated to do it (and see a need to do so), so I'll close this. Thanks for all your work on this @mscheltienne !
Activity
larsoner commentedon Sep 16, 2021
We have some history of trying to make things read-only, see for example #7816 (comment). I don't remember the full discussion but that comment has a bunch of links
mscheltienne commentedon Sep 17, 2021
@larsoner Thanks for the bedside reading.
In my opinion, MNE and Python have both come a long way since the
Infostructure has been designed, and maybe it could (and need) to be reworked and improved.As an end-user, I am always surprised by the structure of
Info.Info.attribute?ch_namesis accessible asInfo.ch_names?Obviously, you do get used to this structure; but it doesn't make it convenient. Most (if not all) IDE completion providers will not always work with the dictionary syntax
Info['while they will with a plain attribute oneInfo..e.g. in IPython console:
e.g in Spyder IDE: (Kite is not that smart, but still..)
Even as someone who is used to it, I still have to go look what are the valid keys in
Infofrom time to time.And finally, the underwater part of the iceberg: error checking. What is preventing users from modifying attributes they are not supposed to modify directly? A note in the documentation:
And even for those 2, some error checking would be necessary. Example with
bads:"""
mne.set_log_level('INFO')
raw = mne.io.read_raw_fif(...)
raw.info['bads'].append('test')
raw.info['bads']
Out: ['M1', 'CP1', 'test']
"""
I didn't expect this to work, but apparently, it is valid? Of course, a channel name
'test'is an extreme case; but typos in the channel name syntax are not, e.g."FP1"instead of"Fp1". For instance, the LSL plugin I am using for eego amplifiers has a build-in typo on 10 channel names.Proposed changes:
Turn the attribute of
Infointo properties. @cbrnr pinging the properties aficionado.Info['bads']would becomeInfo.badspointing to e.g.Info._bads.Properties setter can be used to perform error checking on properties that can be edited manually and to display a logger warning pointing toward the functions/methods used to change properties that can not be edited manually.
Properties pointing to a mutable type must be either changed to an immutable type OR to a custom class inheriting the mutable type and performing error checking when necessary OR to a different smart solution enabling error checking.
I know @agramfort is not a fan of properties and implicit properties setters. However, this is different from the case where the implicit setter changes the property value and other properties/attributes/settings under the hood. The setter is only used to either perform error checking on its own property (and thus display an instructive logging message if needed) OR to point the user with a logging message towards the function/method to use to change this property (equivalent to an explicit setter).
Refactoring
Infolooks like a major overhaul, impacting not only itself but many functions and methods across MNE, but it looks to me like a major improvement of the existing MNE structures.And it doesn't need to be done all in one go. It can be done attribute per attribute while preserving the current structure. With one PR per attribute, discussions on the correct, smarter implementation adding error checking while not impacting performance should be efficient.
Example for
bads: (Disclaimer: it's just some quick and simple ideas!)It should remain a list-like object supporting both assignment with
bads = [...]and expansion withbads += [...]andbads.append().MutableSequenceinstance that is a sequence of strings.badsand its setter to use the createdMutableSequenceinstance.Info['bads']toInfo.bads.Info['bads']Rinse and repeat for every attribute (more or less). Some will be harder than others and will require more time.
Apology for the long post, it might spark some unwanted discussions; but I wanted to give you my opinion on the Info structure design.
cbrnr commentedon Sep 17, 2021
Refactoring
Infowould break a lot of code, I'm not sure if it's worth it unless we provide some backwards compatibility. Actually, MNE already has aBunchclass that exposes dict keys as attributes. Maybe we'd have to update this minimal implementation to what scikit-learn uses (https://github.com/scikit-learn/scikit-learn/blob/2beed5584/sklearn/utils/__init__.py#L61), but this might be a quick solution at least.mscheltienne commentedon Sep 17, 2021
Also noticed in the code for
subject_info:Those are not documented. I'm guessing those are not the only example of attributes poorly documented/checked in Info.
agramfort commentedon Sep 17, 2021
mscheltienne commentedon Sep 17, 2021
@agramfort Yes, sounds good to me.
mscheltienne commentedon Sep 17, 2021
As discussed, this is a very very very low priority issue. But it would be nice if little by little, error checking gets implemented in
mne.Infoto avoid having users shoot themselves in the foot on a regular basis.+1 from @larsoner @drammock
-1 for lack of bandwidth from @agramfort
2 ideas have come up:
Bunch idea PRs:
However, some people use Info dict to pass variables around. It's not officially supported, but blocking this would break user code. Idea: issue a warning when the user uses an unsupported variable would be already a good improvement, explicitly informing the user that this variable will not be guarantee to remain in the info and will not get saved.
Dataclasses idea PRs, to be looked into.
[-]Settings unexpected keys in `raw.info['subject_info']` works but does not get saved.[/-][+]Error checking in Info - setting unsupported keys in `mne.Info` or `mne.Info` attributes partially works and doesn't show any warnings[/+]larsoner commentedon Sep 17, 2021
+1 for a quick PR that does this, it will help us see if it's already going to be a maintenance pain...
Another option would be to officially support a
info['temp']/info.tempvariable that we explicitly document will not survive I/O round-trip. That makes an easy transition for people that have been mis-using (knowingly or unknowingly) Info. And in the meantime we can simultaneously make our key/property checking strictly limited to writable keys + temp.mscheltienne commentedon Oct 18, 2021
Getting this moving again with proposition by @larsoner #9767 (comment)
mscheltienne commentedon Oct 25, 2021
Quick summary to keep track. Feel free to add any point I forgot.
Related PRs:
dict.update(). (Use locking/unlocking for Info.update() #9914)subject_info,device_info? ()larsoner commentedon Feb 21, 2022
It looks like most of this is taken care of now. What remains to be protected at some point are values of
Infothat are dicts themselves likeinfo['subject_info'], but we can tackle those as people are motivated to do it (and see a need to do so), so I'll close this. Thanks for all your work on this @mscheltienne !