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
Make some fields of the Info object read-only and auto-generated #2300
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.
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:
Setting array writable status to False
Casting singleton numpy arrays to float or int (so they're immutable)
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.
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 :)
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.
I am the same feeling as Eric but I wanted to see if @wmvanvliet could
do something really smart or be convinced himself that there is no
free lunch :)
one option could be to remove ch_names from info and add a method that
makes it explicit that there is some computation involved.
but I can live without any change :)
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.
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
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.
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?
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.
I don't think you included in the profiling how long it takes to actually
construct the dict, that's probably worth doing first if you're going to
make it be created on demand each time we need to use it in a given
function. So create the dict, then use it repeatedly (e.g. loop over all
channels) would be the proper equivalent benchmark step to what you're
proposing, not just using it repeatedly as I think was tested.
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.
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 includeand 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.
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.
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 ...
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.
Activity
jasmainak commentedon Dec 18, 2015
I like this idea. Although I'm not sure how it would interplay with IO routines.
agramfort commentedon Dec 18, 2015
jasmainak commentedon Dec 18, 2015
I will take a look after the eeglab reader ...
larsoner commentedon Dec 18, 2015
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.
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:
immutable)
But we'd still need to see how much code e.g. changing to tuple would
break.
wmvanvliet commentedon Dec 18, 2015
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 :)
larsoner commentedon Dec 18, 2015
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.agramfort commentedon Dec 18, 2015
larsoner commentedon Dec 18, 2015
agramfort commentedon Dec 18, 2015
wmvanvliet commentedon Dec 19, 2015
now I feel compelled to write something clever :)
wmvanvliet commentedon Dec 23, 2015
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.nchaninstead ofinfo['nchan'])Since it's a subclass of
dictalready, lets make it a subclass ofcollections.MutableMappinginstead so we can overload__getitem__and_setitem__while keeping perfect compatibility withdict(http://stackoverflow.com/questions/3387691/python-how-to-perfectly-override-a-dict)Let's make the
nchanandch_namesfields read-only and behave like properties.Removing redundancies in the
Infoobject is a good idea. For example, here is a subtle bug I found while refactoring the code: #2741If we can't even get it right, how can we expect the user to? :)
nchancan just map tolen(info['chs']), no big deal.But since @Eric89GXL is completely right about performance concerns, I suggest that
ch_namesmaps to a generator:(ch['ch_name'] for ch in info['chs'])Let's talk about
ch_namesbeing 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_namesis 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_namesis now a generator.wmvanvliet commentedon Dec 23, 2015
Oh and while this common idiom works fine with
info['ch_names']as a generator:This is more efficient:
larsoner commentedon Dec 23, 2015
FYI this also won't work for
np.array(info['ch_names'])but maybe that's okay, too.1 remaining item
wmvanvliet commentedon Dec 24, 2015
In the existing implementation,
pick_channelspreserves the order of the suppliedch_namesparameter, not theincludeparameter, hencepick_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 theincludeparameter.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 ofch_names.index()calls gets crazy.Yeah, lets do some tests:
Now for some common idioms:
larsoner commentedon Dec 24, 2015
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.
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.
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.
wmvanvliet commentedon Dec 25, 2015
this change is not about performance gains. The point is to remove the redundancy in this important data structure. It leads to bugs.
larsoner commentedon Dec 25, 2015
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?
wmvanvliet commentedon Dec 26, 2015
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.
larsoner commentedon Dec 26, 2015
agramfort commentedon Dec 26, 2015
jasmainak commentedon Dec 27, 2015
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 ofpick_channelsis 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 paramsorted=Truemay make it explicit.wmvanvliet commentedon Dec 27, 2015
Heh, TIL even the developers of MNE Python don't know what
pick_channelsdoes :)Let me enlighten you: this is the signature:
It iterates over
ch_names. For any channel that is a member ofincludeand not a member ofexclude, the channel's integer index is added to thepickslist. The aggregatedpicksis 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_namesparameter!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 ofpick_*functions.jona-sassenhagen commentedon Dec 27, 2015
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.
jona-sassenhagen commentedon Dec 27, 2015
Maybe that's just me being lazy/stupid though.
jasmainak commentedon Dec 27, 2015
yeah, I agree. And now I know why this idiom is used so often instead of a pick_* function ...
agramfort commentedon Dec 28, 2015
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?
wmvanvliet commentedon Jan 4, 2016
I like my lunches free: #2765