Skip to content

Error checking in Info - setting unsupported keys in mne.Info or mne.Info attributes partially works and doesn't show any warnings #9752

Closed

Description

@mscheltienne

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 of mne.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.

raw = mne.io.read_raw_fif(...)
raw.info['subject_info']['birthyear'] = 1995
{'id': 65, 'his_id': '065', 'birthyear': 1995, 'sex': 1}
raw.save(...)

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?

Activity

  1. larsoner commented on Sep 16, 2021

    @larsoner
    Member

    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

  2. mscheltienne commented on Sep 17, 2021

    @mscheltienne
    MemberAuthor

    @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:

    Screenshot 2021-09-17 at 11 11 35

    e.g in Spyder IDE: (Kite is not that smart, but still..)

    Screenshot 2021-09-17 at 11 12 36

    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.

  3. cbrnr commented on Sep 17, 2021

    @cbrnr
    Contributor

    Refactoring Info would break a lot of code, I'm not sure if it's worth it unless we provide some backwards compatibility. Actually, MNE already has a Bunch class 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.

  4. mscheltienne commented on Sep 17, 2021

    @mscheltienne
    MemberAuthor

    Also noticed in the code for subject_info:

            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.

  5. agramfort commented on Sep 17, 2021

    @agramfort
    SponsorMember
  6. mscheltienne commented on Sep 17, 2021

    @mscheltienne
    MemberAuthor

    @agramfort Yes, sounds good to me.

  7. mscheltienne commented on Sep 17, 2021

    @mscheltienne
    MemberAuthor

    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.

    +1 from @larsoner @drammock
    -1 for lack of bandwidth from @agramfort

    2 ideas have come up:

    • 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.
    • Attribute after attribute, keep going.

    Dataclasses idea PRs, to be looked into.

  8. 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
  9. larsoner commented on Sep 17, 2021

    @larsoner
    Member

    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.

  10. mscheltienne commented on Oct 18, 2021

    @mscheltienne
    MemberAuthor

    Getting this moving again with proposition by @larsoner #9767 (comment)

    class Info(dict):
        def __init__(self, *args, **kwargs):
             with self._unlocked():
                 super().__init__(*args, **kwargs)
    
        def __setitem__(self, key, val)
             if self._locked:
                  ... # check
             super().__setitem__(key, val)
    
        @contextmanager
        def _unlocked(self, check_after=True):
            self._locked = False
            try:
                yield
            else:
                if check_after:
                    self._check_consistency()
            finally:
                self._locked = True
    
  11. mscheltienne commented on Oct 25, 2021

    @mscheltienne
    MemberAuthor

    Quick summary to keep track. Feel free to add any point I forgot.

    Related PRs:

  12. larsoner commented on Feb 21, 2022

    @larsoner
    Member

    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 !

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions