Skip to content

Make some fields of the Info object read-only and auto-generated #2300

Closed

Description

@wmvanvliet

it would be nice if info['nchans'] would be read only and internally map to len(info['chs']). The same with info['ch_names'], which should map internally to [ch['name'] for ch in info['chs']]. This would reduce the chances of having inconsistent data and help with the DRY.

This would involve overwriting the __get_item__ and __set_item__ methods.

Activity

  1. jasmainak commented on Dec 18, 2015

    @jasmainak
    Member

    I like this idea. Although I'm not sure how it would interplay with IO routines.

  2. agramfort commented on Dec 18, 2015

    @agramfort
    SponsorMember
  3. jasmainak commented on Dec 18, 2015

    @jasmainak
    Member

    I will take a look after the eeglab reader ...

  4. larsoner commented on Dec 18, 2015

    @larsoner
    Member

    it would be nice if info['nchans'] would be read only and internally map
    to len(info['chs']). The same with info['ch_names'], which should map
    internally to [ch['name'] for ch in info['chs']]. This would reduce the
    chances of having inconsistent data and help with the DRY.

    Okay but we have to be very careful about performance regressions. Having
    to e.g. construct a list on every access can have unintended consequences.

    At one point we did something like this for raw.times: since you can
    construct the array on the fly from sfreq and the number of samples, it's a
    bit more DRY to make it a property and compute it on access instead of
    storing it. This is in the same spirit as some of what you're proposing.
    However, it had the unintended consequence of slowing down epochs creation
    for some users by a factor of 100 or more, since creating many short epochs
    meant creating a ton of arrays instead of accessing a single one.

    This would involve overwriting the get_item and set_item methods.

    Again we need to make sure this does not hurt performance. Native
    dictionary access uses hashes so it is very fast. I fear whatever we
    implement will hurt parts of our code. We'd need to extensively validate
    it.

    And keep in mind this will not be sufficient to make it truly read only.
    Everything inside the dictionary would need to be made immutable, including
    numpy arrays and other dictionaries. So it will still be dangerous for
    people to think of dictionaries as being read only, so we don't want to
    give that impression.

    To me the added complexity and risk to performance might not be worth the
    gain for some of these changes. W don't actually want users or devs to have
    the impression that info and its contents are immutable, since I don't
    think it's practically achievable. I'd rather try to educate them through
    documentation if possible. I can think of a few easy changes that could
    prevent some pain though:

    1. Setting array writable status to False
    2. Casting singleton numpy arrays to float or int (so they're immutable)
    3. Using tuples instead of lists (especially of strings since those are
      immutable)

    But we'd still need to see how much code e.g. changing to tuple would
    break.

  5. wmvanvliet commented on Dec 18, 2015

    @wmvanvliet
    ContributorAuthor

    We can see if we can come up with an implementation that works. If we do, we can extend the pattern to other "dictionary" classes. If we cannot, than just leave it. Call this dictionary-that-should-have-been-a-class antipattern one of the warts that makes MNE so lovable :)

  6. larsoner commented on Dec 18, 2015

    @larsoner
    Member

    Heh, perhaps. On the other hand, having it not be a class also makes certain operations much easier (e.g., writing out with h5io, accessing members very quickly, etc.). Tradeoffs both ways unfortunately.

  7. agramfort commented on Dec 18, 2015

    @agramfort
    SponsorMember
  8. larsoner commented on Dec 18, 2015

    @larsoner
    Member
  9. agramfort commented on Dec 18, 2015

    @agramfort
    SponsorMember
  10. wmvanvliet commented on Dec 19, 2015

    @wmvanvliet
    ContributorAuthor

    now I feel compelled to write something clever :)

  11. wmvanvliet commented on Dec 23, 2015

    @wmvanvliet
    ContributorAuthor

    Some thoughts so far:

    Lets keep the info object a dictionary. It's too big a change to make the interface an object instead (e.g. info.nchan instead of info['nchan'])

    Since it's a subclass of dict already, lets make it a subclass of collections.MutableMapping instead so we can overload __getitem__ and _setitem__ while keeping perfect compatibility with dict (http://stackoverflow.com/questions/3387691/python-how-to-perfectly-override-a-dict)

    Let's make the nchan and ch_names fields read-only and behave like properties.

    Removing redundancies in the Info object is a good idea. For example, here is a subtle bug I found while refactoring the code: #2741
    If we can't even get it right, how can we expect the user to? :)

    nchan can just map to len(info['chs']), no big deal.
    But since @Eric89GXL is completely right about performance concerns, I suggest that ch_names maps to a generator: (ch['ch_name'] for ch in info['chs'])

    Let's talk about ch_names being a generator a little bit more, because it results in lots of little changes all over the code base. Simultaneously, let's talk about performance.

    There are a few idioms that don't work anymore when ch_names is a generator:

    • number_of_channels = len(info['ch_names'])

      this is very common... Why number_of_channels = info['nchan'] is not used is beyond me.
    • channel_indices = [info['ch_names'].index(name) for name in list_of_channel_names]

      this is also very common. It is quite inefficient, because it is an O(m*n) operation. This can be replaced with our better O(m) implementation known as pick_channels, which has the extra bonus of DRY and better readability.
    • channel_names = [info['ch_names'][index] for index in [1, 42, 4, 3, 5]]

      this can be rewritten as channel_names = ['info['chs'][index]['ch_name'] for index in [1, 42, 4, 3, 5]]

    I'm working on refactoring the code base to see how it would look and so far I'm very happy with the changes I'm forced to make since ch_names is now a generator.

  12. self-assigned this
    on Dec 23, 2015
  13. wmvanvliet commented on Dec 23, 2015

    @wmvanvliet
    ContributorAuthor

    Oh and while this common idiom works fine with info['ch_names'] as a generator:

    for name in list_of_channel_names:
        if name not in info['ch_names']:
            raise ScaryErrorMessage()
    

    This is more efficient:

    valid_ch_names = set(info['ch_names'])
    for name in list_of_channel_names:
        if name not in valid_ch_names:
            raise ScaryErrorMessage()
    
  14. larsoner commented on Dec 23, 2015

    @larsoner
    Member

    I suggest that ch_names maps to a generator: (ch['ch_name'] for ch in info['chs'])

    FYI this also won't work for np.array(info['ch_names']) but maybe that's okay, too.

  15. 1 remaining item

  16. wmvanvliet commented on Dec 24, 2015

    @wmvanvliet
    ContributorAuthor

    Cool -- just make sure the return values are actually the same for the two operations. For example make sure that the order of channels is preserved like it would be with the .index iteration method), i.e. pick_channels(['EEG 001', 'EEG 002']) != pick_channels(['EEG 002', 'EEG 001']). Not sure if pick_channels behaves this way, or if it always returns an ordered list.

    In the existing implementation, pick_channels preserves the order of the supplied ch_names parameter, not the include parameter, hence pick_channels(ch_names, ['EEG 001', 'EEG 002']) == pick_channels(ch_names, ['EEG 002', 'EEG 001']). I don't know (yet) if any code depends on this behaviour. It seems more useful for me to preserve the order specified in the include parameter.

    If we really want to squeeze performance, we could actually have a dict ch_name->index lookup

    I've added an info.ch_name_to_index() method that constructs a dictionary mapping channel names to their integer indices. I use it in the refactoring sometimes, when the number of ch_names.index() calls gets crazy.

    So performance testing might actually probably be more useful than thinking about operations, unless we know all code is in C or Python.

    Yeah, lets do some tests:

    ch_names_list = ['channel %3d' % i for i in range(1000)]
    ch_names_set = set(ch_names_list)
    ch_names_dict = {name: index for index, name in enumerate(ch_names)}
    ch_names_gen = lambda: ('channel %3d' % i for i in range(1000))
    

    Now for some common idioms:

    > %timeit [name in ch_names_list for name in ch_names_list]
    100 loops, best of 3: 14.3 ms per loop
    > %timeit [name in ch_names_set for name in ch_names_list]
    10000 loops, best of 3: 85.9 µs per loop
    > %timeit [name in ch_names_dict for name in ch_names_list]
    10000 loops, best of 3: 98.1 µs per loop
    >  %timeit [name in ch_names_gen() for name in ch_names_list]    
    1 loops, best of 3: 390 ms per loop (ouch)
    
    > %timeit [ch_names_list.index(name) for name in ch_names_list]
    100 loops, best of 3: 14.2 ms per loop 
    > %timeit [ch_names_dict[name] for name in ch_names_list]
    10000 loops, best of 3: 95.1 µs per loop
    > %timeit mne.pick_channels(ch_names_list, ch_names_list) (existing implementation)
    100 loops, best of 3: 14.7 ms per loop
    
  17. larsoner commented on Dec 24, 2015

    @larsoner
    Member

    In the existing implementation, pick_channels preserves the order of the
    supplied ch_names parameter, not the include parameter, hence
    pick_channels(ch_names, ['EEG 001', 'EEG 002']) == pick_channels(ch_names,
    ['EEG 002', 'EEG 001']). I don't know (yet) if any code depends on this
    behaviour. It seems more useful for me to preserve the order specified in
    the include parameter.

    You will have to be very careful with this, because getting it wrong can
    have difficult to test but potentially catastrophic bugs. We shouldn't in
    general always get the picks in ascending order. Consider a weird case
    where someone's covariance matrix has MEG channels before EEG and their
    forward has the EEG before MEG (but otherwise the same channels) and you'll
    see why getting channels in the list order, and not ascending order, can
    matter. That particular example is an unlikely (but not impossible)
    scenario, but I seem to remember actually hitting this sort of problem
    before, where assuming a monotonic increasing ordering instead of getting
    the "match" list order broke something.

    %timeit [name in ch_names_list for name in ch_names_list]
    100 loops, best of 3: 14.3 ms per loop
    %timeit [name in ch_names_set for name in ch_names_list]
    10000 loops, best of 3: 85.9 µs per loop
    %timeit [name in ch_names_dict for name in ch_names_list]
    10000 loops, best of 3: 98.1 µs per loop
    %timeit [name in ch_names_gen() for name in ch_names_list]
    1 loops, best of 3: 390 ms per loop (ouch)

    Sounds about right. Dict is basically immediate (hashing) and so is set
    (likely does some sorting on init under the hood making "in" a much faster
    check), list isn't bad since it might be able to use C or built in types
    quickly, and the generator is slow because it requires more work from the
    Python interpreter. At least that's my guess.

    %timeit [ch_names_list.index(name) for name in ch_names_list]
    100 loops, best of 3: 14.2 ms per loop
    %timeit [ch_names_dict[name] for name in ch_names_list]
    10000 loops, best of 3: 95.1 µs per loop
    %timeit mne.pick_channels(ch_names_list, ch_names_list) (existing
    implementation)
    100 loops, best of 3: 14.7 ms per loop

    Again keep in mind the first .index and the last pick_channels are not
    equivalent operations here. Good to know speed is comparable though. Looks
    like the dict is indeed a couple orders of magnitude faster, and still
    preserves the input list channel ordering. In some cases the "setup" time
    for the dict might matter, though, e.g. if you're only picking a couple of
    channels, and the direct .index method might be faster.

    But we might be going a little overboard on the optimization here. The
    existing .index might already be good enough, and not really be a
    bottleneck for our processes. Are you thinking we'll gain enough
    performance to justify making all the necessary changes? It seems like we
    don't gain any more DRY code from using the dict at least.

  18. wmvanvliet commented on Dec 25, 2015

    @wmvanvliet
    ContributorAuthor

    this change is not about performance gains. The point is to remove the redundancy in this important data structure. It leads to bugs.

  19. larsoner commented on Dec 25, 2015

    @larsoner
    Member

    this change is not about performance gains. The point is to remove the
    redundancy in this important data structure. It leads to bugs.

    Fair enough. At the same time, a bit of increased DRYness to prevent
    (primarily) developers from error might not be worth introducing
    performance regressions. It seems to me that the only sufficiently
    performing alternative to the channel list we have right now is the dict
    (the generator seems too slow), but the dict has the same lack of DRYness
    as the current solution, so I'm assuming you don't want that, then. I guess
    we could use tuple instead of list...? What do you propose as the solution
    now?

  20. wmvanvliet commented on Dec 26, 2015

    @wmvanvliet
    ContributorAuthor

    my solution is to make the ch_names field a generator and to add a ch_name_to_index method that returns a dictionary.
    the generator covers the overwhelming majority of the use cases. the dictionary offers a better performing solution in the other cases. When l finish the refactor of the code I will open a pull request and you can take a look.

  21. larsoner commented on Dec 26, 2015

    @larsoner
    Member
  22. agramfort commented on Dec 26, 2015

    @agramfort
    SponsorMember
  23. jasmainak commented on Dec 27, 2015

    @jasmainak
    Member

    Good that we are having this discussion. I just wanted to pitch in with my two cents about pick_channels. I think the current implementation of pick_channels is confusing. At least, the docstring doesn't specify that pick_channels(ch_names, ['EEG 001', 'EEG 002']) == pick_channels(ch_names, ['EEG 002', 'EEG 001']). I was thinking it returns the unsorted indices, but I learnt it the hard way that it doesn't. Maybe a param sorted=True may make it explicit.

  24. wmvanvliet commented on Dec 27, 2015

    @wmvanvliet
    ContributorAuthor

    Heh, TIL even the developers of MNE Python don't know what pick_channels does :)
    Let me enlighten you: this is the signature:

    def pick_channels(ch_names, include, exclude)
    

    It iterates over ch_names. For any channel that is a member of include and not a member of exclude, the channel's integer index is added to the picks list. The aggregated picks is returned.

    So it doesn't return a random, nor ascending, nor descending order, but it returns the channels in the order they are listed in the ch_names parameter!

    I agree that this is a bit counter intuitive, but I don't know if any piece of code relies on this behaviour. I do know that the [ch_names.index(name) for name in include] idiom is used a lot, which is a bit weird because we have tons of pick_* functions.

  25. jona-sassenhagen commented on Dec 27, 2015

    @jona-sassenhagen
    Contributor

    What I keep forgetting about the pick functions, and why I rarely use them (or the params), is which take or return indices and which take or return names.

  26. jona-sassenhagen commented on Dec 27, 2015

    @jona-sassenhagen
    Contributor

    Maybe that's just me being lazy/stupid though.

  27. jasmainak commented on Dec 27, 2015

    @jasmainak
    Member

    I agree that this is a bit counter intuitive, but I don't know if any piece of code relies on this behaviour. I do know that the [ch_names.index(name) for name in include] idiom is used a lot, which is a bit weird because we have tons of pick_* functions.

    yeah, I agree. And now I know why this idiom is used so often instead of a pick_* function ...

  28. agramfort commented on Dec 28, 2015

    @agramfort
    SponsorMember

    So it doesn't return a random, nor ascending, nor descending order, but it
    returns the channels in the order they are listed in the ch_names parameter!

    I agree that this is a bit counter intuitive, but I don't know if any piece
    of code relies on this behaviour. I do know that the [ch_names.index(name)
    for name in include] idiom is used a lot, which is a bit weird because we
    have tons of pick_* functions.

    the logic is the following. If you pass as ch_names the inst.ch_names and
    pass include / exclude you get the indices of the channels in the data
    attribute that you want to keep.

    makes sense?

  29. wmvanvliet commented on Jan 4, 2016

    @wmvanvliet
    ContributorAuthor

    I like my lunches free: #2765

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

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions