Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: Edge case where a resampled column was too-long-by-one #365

Merged
merged 3 commits into from
Feb 1, 2019

Conversation

adswa
Copy link
Contributor

@adswa adswa commented Jan 29, 2019

Fixes the dimension mismatch after resampling described in #358 and #361.

@yarikoptic and I suspect that the problem lies within the recomputation of num with num = int(np.ceil(n * sampling_rate / old_sr)) -- if done per each run with up/downsampling adapted to the runs data it might explain why it results in failures for some runs of mine, but not for others.
Its not an ideal solution, but for now we reassign num to the length of self.Index instead of recomputing and ignore it when there is a slight difference in length (of 1), and if there are larger deviations in length (>1) we blow up.

I put the commit on top of @effigies test in 8cfba06 (which passes with the change).

@adswa
Copy link
Contributor Author

adswa commented Jan 29, 2019

@yarikoptic also says (but he adds that him and I need to actually check whether this happens) that this in principle is not complete, and that there must be no resampling across runs when there are multiple.

Copy link
Collaborator

@effigies effigies left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some thoughts. @tyarkoni Sorry to interrupt your deep dive, but under what conditions are multiple runs involved in a single variable?

bids/variables/variables.py Outdated Show resolved Hide resolved
num = len(self.index)
# _build_entity_index computation above does it per run,
# which possibly provides a more stable solution and yadadada
num_computed = int(np.ceil(n * sampling_rate / old_sr))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to change this to np.round() a la #361 (comment)? And do we want to include f936aed as well?

Copy link
Collaborator

@yarikoptic yarikoptic Jan 29, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would say that with any resampling it should be ceil (to not loose any point) and then analysis of the actual target duration based on the actual target temporal duration which might require trimming. But here in particular, given the comment below I think this all computation should be gone altogether (and thus warnings, and assertions)

assert num_diff == 1 # the only way to get here
import warnings
warnings.warn(
"Probably due to multiple runs we ran into a slight "
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This appears with a single run when TR=2.000001. I don't think this is a great error message. It's not clear that it's a warning that will do anything but cause confusion.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we added it because there were no other way to inform user (e.g. logging) and we see how silence could be problematic to read down the road ;) again, with aforementioned suggested fix by just relying on index length this would be gone altogether

"Probably due to multiple runs we ran into a slight "
"divergence between obtained number of samples in the index (computed "
"per each run) and overall estimate down/up-sampled samples. "
"But that is ok")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we looked at the code more, and our verdict is that we just need to get rid of num_computed here altogether and use the length of the index, estimated (by going through runs and using their actual duration which is not a subject of up/down sampling effects of "ints").

The reason is -- the n is not "reliable". It is already a result of applying ceil operation in to_dense function (called by the test first to upsample by 10). so there is really no reliable way to get back the original number of points.

But also what is important probably is that interp1d below should also be applied per run, similarly to how to_dense is doing it I guess, to not leak values across the run boundaries.... but that is a separate issue

@tyarkoni
Copy link
Collaborator

@effigies a BIDSVariable isn't intrinsically tied to any particular level (though the level does impose some constraints on which subclasses make sense), so in principle, each variable can store multiple runs from multiple subjects. I believe this is actually the modal situation if you use merge=True when calling get_collections.

The main reason for doing this is that we eventually want to be able to fit arbitrary mixed-effects structures without having to spend a lot of time restructuring the variables in complicated ways. For example, this approach makes it trivial to both do a 2-level-style analysis where you concatenate each subject's runs and add nuisance regressors for all runs to the same model (instead of fitting each run separately, and then aggregating the estimate within-subject), and to fit the full dataset in one shot. There are also some potential efficiency and interface benefits (e.g., nearly all transformers take an undocumented groupby argument that can be used to do the transformation separately for each level of the variables in the groupby).

@codecov
Copy link

codecov bot commented Feb 1, 2019

Codecov Report

Merging #365 into master will increase coverage by 0.09%.
The diff coverage is 80%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #365      +/-   ##
==========================================
+ Coverage   73.27%   73.36%   +0.09%     
==========================================
  Files          24       24              
  Lines        2604     2613       +9     
  Branches      640      642       +2     
==========================================
+ Hits         1908     1917       +9     
+ Misses        513      512       -1     
- Partials      183      184       +1
Flag Coverage Δ
#unittests 73.36% <80%> (+0.09%) ⬆️
Impacted Files Coverage Δ
bids/variables/variables.py 87.98% <80%> (-0.42%) ⬇️
bids/layout/layout.py 76.05% <0%> (+0.56%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update e9fc2df...319f81c. Read the comment docs.

@codecov
Copy link

codecov bot commented Feb 1, 2019

Codecov Report

Merging #365 into master will increase coverage by 0.5%.
The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff            @@
##           master     #365     +/-   ##
=========================================
+ Coverage   73.27%   73.77%   +0.5%     
=========================================
  Files          24       23      -1     
  Lines        2604     2494    -110     
  Branches      640      623     -17     
=========================================
- Hits         1908     1840     -68     
+ Misses        513      471     -42     
  Partials      183      183
Flag Coverage Δ
#unittests 73.77% <100%> (+0.5%) ⬆️
Impacted Files Coverage Δ
bids/variables/variables.py 88.44% <100%> (+0.05%) ⬆️
bids/layout/__init__.py 100% <0%> (ø) ⬆️
bids/variables/io.py 75.12% <0%> (ø) ⬆️
bids/layout/validation.py
bids/layout/layout.py 76.05% <0%> (+0.56%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update e9fc2df...319f81c. Read the comment docs.

Copy link
Collaborator

@effigies effigies left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks!

@effigies effigies changed the title FIX: Bug/resampling error FIX: Edge case where a resampled column was too-long-by-one Feb 1, 2019
@effigies effigies merged commit 99178b7 into bids-standard:master Feb 1, 2019
@@ -448,12 +448,13 @@ def resample(self, sampling_rate, inplace=False, kind='linear'):
self.index = self._build_entity_index(self.run_info, sampling_rate)

x = np.arange(n)
num = int(np.ceil(n * sampling_rate / old_sr))
num = len(self.index)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I worry that this will hide other potential edge cases where there's a bigger mismatch... I suggest checking for a discrepancy and issuing a warning either if any is found, or if a large one is found (like you did in one of the other PRs).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that was an earlier version of this PR. I'm curious what kind of edge case you're talking about?

As I understand it, we have a run duration, which is the original TR * nvols.

For a given sampling rate, we find the nearest n such that n / sampling_rate == duration. So this line was a way of taking from duration ~= n_old / sr_old ~= n_new / sr_new, and calculating n_new from n_old, sr_old, and sr_new. Index instead calculates directly from duration and sr_new. So the discrepancy we were finding is when you get an off-by-one between the two ways of calculating n_new.

So it's not really clear where another discrepancy can arise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants