Skip to content

Add obs_array and var_array functions - #144

Merged
ivirshup merged 11 commits into
scverse:masterfrom
ivirshup:obs_array
Jun 3, 2019
Merged

ivirshup merged 11 commits into
scverse:masterfrom
ivirshup:obs_array

Conversation

@ivirshup

@ivirshup ivirshup commented Apr 30, 2019 •

Copy link
Copy Markdown
Member

Convenience functions for retrieving an array of values along either the obs or var dimension.

A proposed update to _get_{obs,var}_array as discussed with @falexwolf in scverse/scanpy#619.

As I was writing it, it got more complicated that I expected (of course). I think use_raw may be poorly posed here, unless it's meant to only refer to .raw.X. For var_array(..., use_raw=True), how many values should be returned? adata.shape[1] or adata.raw.shape[1]? Should we only check adata.raw.var for keys? This would change _get_var_array's current behavior: https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L1488-L1510

@codecov

codecov Bot commented Apr 30, 2019 •

Copy link
Copy Markdown

Codecov Report

❗ No coverage uploaded for pull request base (master@410b805). Click here to learn what that means.
The diff coverage is 91.93%.

Impacted file tree graph

@@            Coverage Diff            @@
##             master     #144   +/-   ##
=========================================
  Coverage          ?   75.13%           
=========================================
  Files             ?       11           
  Lines             ?     2031           
  Branches          ?        0           
=========================================
  Hits              ?     1526           
  Misses            ?      505           
  Partials          ?        0
Impacted Files Coverage Δ
anndata/layers.py 79.66% <100%> (ø)
anndata/base.py 78.61% <91.66%> (ø)

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 410b805...664fde3. Read the comment docs.

@scverse scverse deleted a comment from codecov Bot Apr 30, 2019
Comment thread anndata/base.py
pass
else:
# TODO: Raise deprecation warning
layer = None

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I just checked the previous implementations of this, which got really complicated by several people iterating on it... This here is much better.

I would do:

if use_raw:
     obj = self.raw
else:
     obj = self

So that if use_raw==True this looks into self.raw.var.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Hmm. I don't think I like that the var accessor could return something with a different shape that adata.shape[1]. What if you have to ask adata.raw for those values? Like adata.raw.var_array?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Your alternative solution is 100% fine, too!

Comment thread anndata/base.py Outdated
return a


def var_array(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think the naming is optimal and I'm also not sure whether we really want this as a public method. If public, I'd think that something like

adata.get_var_1dslice()

would make it more clear that this is not another data storage attribute but a convenience function that gives access to existing data.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'd find it useful enough to have as a public function, since it'd be good to advertise that there's a solution to having:

if issparse(a):
    a.toarray().reshape(-1)

which is all over the place in my analysis code.

I agree there's a better name. get_1d_obs or obs_array_1d. I'll think about it a bit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Good! 😄

How come you have this all over your analysis code and I don't? A sparse matrix slice is cast to a 1d array automatically: https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L965

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I get this:

from scipy.sparse import random, issparse
issparse(random(10, 10, format="csr")[0, :])
# True
issparse(random(10, 10, format="csr")[:, 0])
# True

But I might be working more directly with the sparse matrices.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This does remind me of something. Are there any benchmarks for the overhead of subsetting AnnData? It'd be nice if subsetting was lazy enough to have low overhead, but I'm not sure if this is the case.

@falexwolf falexwolf May 6, 2019 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

But I might be working more directly with the sparse matrices.

Scipy sparse matrices obviously maintain their type, .X does the cast for you. That's why I linked to .toarray() above. :)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This does remind me of something. Are there any benchmarks for the overhead of subsetting AnnData? It'd be nice if subsetting was lazy enough to have low overhead, but I'm not sure if this is the case.

No, there are no benchmarks and you are absolutely right. It should be lazier. I think the subsets on all the arrays, dataframes etc. are fine because they are themselves lazy (that's at least what I expect). But the deepcopy(adata.uns) is awful...

Comment thread anndata/base.py Outdated
X = self._X
return pd.DataFrame(X, index=self.obs_names, columns=self.var_names)

def _get_expression(self, use_raw=False, layer=None):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

AnnData is not meant for expression data only. Hence this should be _get_matrix or _get_X, I'd say. :)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Totally agree. Though I might just get rid of this function if I go with obj = self.raw

@ivirshup

ivirshup commented May 1, 2019

Copy link
Copy Markdown
Member Author

Implemented methods for Raw and changed naming scheme to the more precise but verbose: get_{obs,var}_slice_1d. I'd be happy to make these private.

@falexwolf

Copy link
Copy Markdown
Member

I'd leave them as public!

get_{obs,var}_slice_1d is very long. In particular, if we foresee it to become the default access for 1d slices along the obs and var axes, then this will seriously start cluttering code. I agree we should be verbose in general, but for highly accessed stuff, a short name greatly helps readability. That's why .obs is not called .annotations_of_observations or something. :)

You don't like this other suggestion we had: get_1d_obs (when reading, one mentally completes this with "slice", I think)? I don't think there is any chance of confusion. Every user knows that .obs is not 1d but a DataFrame, so that it's implicitly clear that it must refer to a slice-retrieval method.

But you're doing all the work, so, you should decide!

@ivirshup

ivirshup commented May 7, 2019

Copy link
Copy Markdown
Member Author

When I put get_{obs,var}_slice_1d I was thinking these would be private, in which case niceness of name is less important.

I think if this is going to be part of the API, I'd like a shorter name (ideally two words), especially since it's a pretty simple operation. get_1d_obs is pretty good, but I'm not totally happy with it. I think it's partially because of the numeric value and partially because it kinda looks like it will return all one dimensional observations.

Just some brainstorming:

  • vector or possibly vec to replace need to specify 1d
adata.get_obs_vector("leiden")
adata.get_obs_vec("leiden")
adata.get_var_vector("pct_dropouts")
  • Merge it into one function, where the dimension being sliced across is specified by a keyword argument replacement for k:
adata.get_vec(obs="Oct4", layer="counts")
adata.get_vec(var="pct_dropout")
adata.get_vector(obs="leiden")
  • Following functions like obs_keys we could drop the get verb?
adata.obs_vector("Oct4", layer="counts")
for k in adata.obs_keys():
    adata.obs_vector(k)

@ivirshup

ivirshup commented May 15, 2019 •

Copy link
Copy Markdown
Member Author

I think I like {obs,var}_vector the best, but I'd be happy with get_1d_{obs,var} if you think there is ambiguity here. To me vector captures that it's an array of 1 dimension, but my thinking on this was definitely shaped by julia using Vector as an alias for 1d arrays. Mostly I think the functionality here is ready to go, and will help me merge a bunch of stuff over on scanpy.

@ivirshup

Copy link
Copy Markdown
Member Author

@falexwolf, thoughts on this?

@falexwolf

Copy link
Copy Markdown
Member

As mentioned before, I'd vote for prepending a get_ to distinguish from an attribute that can be set: get_obs_1d_... or get_obs_vector_..., whatever you like better.

Don't you think there might be confusion otherwise? The get_... can be a natural place for people to look up convenience accessors.

@ivirshup

Copy link
Copy Markdown
Member Author

I'm resistant to a three word name for such a short method, but could be swayed. I also like leading with the dimension name, since I think it fits better with the existing (though small) anndata api.

adata.obs_names
adata.obs_keys()
adata.obs_names_make_unique()

To me, .obs_vector() 'rhymes' well with .obs_keys(). I could settle for adata.obs_get_vector, though I think .obs_vector reads equivalently in use.

If we were to start a .get_ naming convention, what other convenience accessors could fit there? Could you suggest other APIs I could look at that use this convention? I only found a couple xarray methods (get_index, get_axis_num). If this method was meant to reflect other python array libraries, I'd probably make it work something like:

adata.get_vector(key, dim="obs")
# Or the equivalent
adata.get_vector(key, axis=0)

Of course, this doesn't have to live here or be a public method (it could always become a public method in the future). I do want this functionality somewhere, so I can use it in and merge scverse/scanpy#619 followed by scverse/scanpy#467.

@falexwolf

falexwolf commented May 20, 2019 •

Copy link
Copy Markdown
Member

OK. I'm convinced. 😄 Please make it .obs_vector(). I think it should be public... It could become the lightweight way of what is adata[:, 'var'].X right now. I'd say...

PS: I had always thought that, e.g., adata.obs_keys() should be deprecated over .obs.keys() at some point, but probably it's not going to happen...

@ivirshup

Copy link
Copy Markdown
Member Author

I think those should be the names right now.

Any idea what codecov is trying to tell me? I'm not sure how I've increased coverage but also decreased coverage.

@falexwolf

Copy link
Copy Markdown
Member

Hm, I think that 69.35% of diff hit (target 73.61%) means that in the changes you made, only 69% are covered with tests and that in the previous corresponding code pieces, this fraction was 73%. But as you reduced the total lines of untested code, the total coverage even slightly increased. [If one replaces 100 lines with coverage 80% with 3 lines with coverage 30%, one still reduced the total number of uncovered lines from 20 to 2.]

Don't worry... Should we merge, now?

@flying-sheep

flying-sheep commented May 22, 2019 •

Copy link
Copy Markdown
Member

The issue codacy reports might also be valid:

Using type() instead of isinstance() for a typecheck.

assert type(r1) == type(r2)

This should be

assert type(r1) is type(r2)

but no biggie

@ivirshup

Copy link
Copy Markdown
Member Author

@flying-sheep, I thought it wasn't going to like either since it recommended isinstance. I've changed it anyways.

@falexwolf so what's the other passing codecov check telling me?

And yeah, I think this is good to go.

@falexwolf

Copy link
Copy Markdown
Member

Awesome! 😄

@falexwolf

Copy link
Copy Markdown
Member

Despite telling me that merging in master (rebasing on the command line would also have been an option), it tells me that I can only squash and merge. So, I'd go ahead and do that. But, after all your work here and in the other PR, @ivirshup, you should be an admin (also on the author list) of anndata. I'll quickly make you one and then you can merge this in yourself.

@falexwolf

Copy link
Copy Markdown
Member

You now have write access and can merge yourself, Isaac.

@ivirshup

ivirshup commented Jun 1, 2019

Copy link
Copy Markdown
Member Author

Thanks for the access!

It wouldn't let me do any sort of merging without getting that codecov check to pass.

It now tells me that I can only squash and merge, and that both "Rebase and Merge" and "Create a merge commit" are not enabled for this repo. Is that what we want to do? If not I think the repository owner can modify this at Settings > Options > Merge button.

@falexwolf

Copy link
Copy Markdown
Member

OK, now all options are available. "Rebase and Merge" is definitely fine. I don't know why this wasn't enabled by default.

@ivirshup

ivirshup commented Jun 3, 2019

Copy link
Copy Markdown
Member Author

Since tests weren't passing on master (an f-string was added in a recent commit) I've gone ahead and bumped the minimum python version to 3.6. This was previously discussed in #140 (comment).

@ivirshup

ivirshup commented Jun 3, 2019 •

Copy link
Copy Markdown
Member Author

Thanks for changing those settings!

Let me know when you think this is ready for a point release so I can merge those PRs over on scanpy.

@ivirshup
ivirshup merged commit 61eb5bb into scverse:master Jun 3, 2019
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.

3 participants