Skip to content

Queries fix - #467

Merged
ivirshup merged 8 commits into
scverse:masterfrom
ivirshup:queries_fix
Aug 20, 2019
Merged

ivirshup merged 8 commits into
scverse:masterfrom
ivirshup:queries_fix

Conversation

@ivirshup

@ivirshup ivirshup commented Feb 8, 2019

Copy link
Copy Markdown
Member

Following up on #242.

Here's my solution to the current queries being pretty unreliable for me (due to issue with bioservices module). It's all a pretty thin wrapper around pybiomart, which has a nice API and is well tested but has maintenance issues.

Currently I've replaced the gene_coordinates query with a more generic biomart_annotations – the example covers the functionality of gene_coordinates. I'm debating how to add tests given that they're network based (could fail when nothing is wrong with the code) and can take a while.

@flying-sheep

Copy link
Copy Markdown
Member

Looks nice! The singledispatch makes it pretty neat!

Could you please add return type annotations? I think gprofiler usually returns a pd.DataFrame, but if the query comes back empty it for some reason returns an empty list? I guess that’s a leftover from the R port.

I think we could return gprofiler(...) or None to catch that case and add the return annotation Optional[pd.DataFrame].

@LuckyMD

LuckyMD commented Feb 15, 2019

Copy link
Copy Markdown
Contributor

gprofiler functionality is being added to scanpy? I have a small wrapper for that as well... the main components being a try-catch wrapper around it as it can give an error when there are no results.

@flying-sheep

Copy link
Copy Markdown
Member

Ah? The code seems like it just returns an empty list when there’s no results. Where is the error thrown?

@LuckyMD

LuckyMD commented Feb 15, 2019

Copy link
Copy Markdown
Contributor

This is the traceback I get when I receive no results:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-91-65d9edda0106> in <module>()
      1 test = gprofiler(list(module_membership['MEpink']), 
      2                                custom_bg=list(np.unique([v.split(".")[0] for v in var.index.tolist()])),
----> 3                                organism='mmusculus', correction_method='fdr', src_filter=['GO:BP'])

~/anaconda3/lib/python3.6/site-packages/gprofiler/__init__.py in gprofiler(query, organism, ordered_query, significant, exclude_iea, region_query, max_p_value, max_set_size, correction_method, hier_filtering, domain_size, custom_bg, numeric_ns, no_isects, png_fn, include_graph, src_filter)
    147                           "query.size", "overlap.size", "recall", "precision",
    148                           "term.id", "domain", "subgraph.number", "term.name",
--> 149                           "relative.depth", "intersection"]
    150     enrichment.index = enrichment['term.id']
    151     numeric_columns = ["query.number", "p.value", "term.size",

~/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py in __setattr__(self, name, value)
   4387         try:
   4388             object.__getattribute__(self, name)
-> 4389             return object.__setattr__(self, name, value)
   4390         except AttributeError:
   4391             pass

pandas/_libs/properties.pyx in pandas._libs.properties.AxisProperty.__set__()

~/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py in _set_axis(self, axis, labels)
    644 
    645     def _set_axis(self, axis, labels):
--> 646         self._data.set_axis(axis, labels)
    647         self._clear_item_cache()
    648 

~/anaconda3/lib/python3.6/site-packages/pandas/core/internals.py in set_axis(self, axis, new_labels)
   3321             raise ValueError(
   3322                 'Length mismatch: Expected axis has {old} elements, new '
-> 3323                 'values have {new} elements'.format(old=old_len, new=new_len))
   3324 
   3325         self.axes[axis] = new_labels

ValueError: Length mismatch: Expected axis has 0 elements, new values have 14 elements

I guess it has to do with the output expecting 14 values for the pd.Dataframe, but receiving 0.

@ivirshup

ivirshup commented Feb 16, 2019 •

Copy link
Copy Markdown
Member Author

How about an empty DataFrame instead of None? I think I prefer len(results) == 0 to results is None.

Also, I need to look into the arguments to gprofiler a bit more before this is ready to merge. I'd also like to add tests, but probably ones that are optional. Does scanpy have a preferred way of adding tests that don't run by default?

@ivirshup

Copy link
Copy Markdown
Member Author

Ha, just saw your PR to gprofiler @flying-sheep! I guess enrich should return None then?

@flying-sheep

flying-sheep commented Feb 18, 2019 •

Copy link
Copy Markdown
Member

Eh, good question what would be better. I think both work, but if we return an empty one, we have to make sure that the column names and types are still correct.

In [4]: bool(pd.DataFrame(dict(a=[])))                                                                                                                                    
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-5108fad10cc0> in <module>
----> 1 bool(pd.DataFrame(dict(a=[])))

/usr/lib/python3.7/site-packages/pandas/core/generic.py in __nonzero__(self)
   1477         raise ValueError("The truth value of a {0} is ambiguous. "
   1478                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1479                          .format(self.__class__.__name__))
   1480 
   1481     __bool__ = __nonzero__

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

In [5]: pd.DataFrame(dict(a=[])).empty                                                                                                                                    
Out[5]: True

@ivirshup

Copy link
Copy Markdown
Member Author

I liked returning a data frame for type stability (i.e. this method always returns a data frame). However, you bring up a good point about the columns and dtypes of the data frame being part of it's type. Because it'd add more complexity that it's worth and type stability isn't that much of a thing in python, I've gone ahead with None.

org: str = "hsapiens",
correction_method: str = "analytical",
gprofiler_kwargs: dict = {},
) -> pd.DataFrame:

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.

You said you’ve gone with None, so this is Optional[pd.DataFrame]

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.

Oops, only updated the docs.

Any chance you know of some tooling where I could just specify the types once and have them propagate between annotations and docs? Or maybe a linter that would warn me about mismatches?

@flying-sheep flying-sheep Feb 21, 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.

That’s what I’ve worked on a lot in the scanpydoc package.

Just delete them from the docs, they’ll be added automatically from the type annotations!

@liiskolb

Copy link
Copy Markdown

Hey!
I'm a member of g:Profiler (biit.cs.ut.ee/gprofiler) development team and was scanning through web to find services that might depend on us.

We recently went live with an extensive update which might break some of the previous pipelines and wrappers.

All the existing Python and R packages should work, however they are linking to an archived data version and they don't access the most up-to-date data from g:Profiler due to the new API etc.

We have already created a new R package that corresponds to the new API, Python package is still in the progress.

I just wanted to let you know and please feel free to contact me if I can be of any help.

All the best,
Liis

@ivirshup

Copy link
Copy Markdown
Member Author

@liiskolb Thanks for letting us know. Where can I track the python package at? Could you also point me towards the old and new docs for the API? I'd like to check what's different. Thanks!

@flying-sheep I'm thinking I'll drop the enrich function from this PR until this is resolved. Thoughts?

@liiskolb

Copy link
Copy Markdown

@ivirshup
Our official Python package is not public yet.
The old API description is here: https://biit.cs.ut.ee/gprofiler_archive2/r1760_e93_eg40/web/help.cgi?help_id=55
and the new one with Python examples is here: https://biit.cs.ut.ee/gprofiler/page/apis.
So, not only the parameters changed but also the request type, paths and output format (it's JSON now).
Let me know if you have any other questions about the tool, results, enrichment analysis, etc

@LuckyMD

LuckyMD commented Feb 27, 2019

Copy link
Copy Markdown
Contributor

Hi,
This is very relevant information for me as well. I currently use valentine svensson's g:profiler python API (https://github.com/vals/python-gprofiler) in my single-cell tutorial (https://github.com/theislab/single-cell-tutorial). I'm guessing that will be similarly outdated soon... I would thus be quite keen for this to be included in scanpy @ivirshup ;).

@falexwolf

Copy link
Copy Markdown
Member

Let me know when this can be merged. The discussion here got a bit long; it's interesting but I can't figure if we're there, yet. 😄

@flying-sheep, happy if you merge this, too, of course.

@flying-sheep

Copy link
Copy Markdown
Member

I made some changes regarding how we want APIs defined from now on.

@ivirshup I hope I didn’t make any mistakes, I’m still a bit sick. Could you please check my changes in 4550142?

@fidelram

Copy link
Copy Markdown
Collaborator

This PR looks very useful. Do you mind adding an example in the function descriptions?

@ivirshup

Copy link
Copy Markdown
Member Author

@liiskolb, any chance you have an estimate of when the python package will be released? I'd like to have this PR merge with up-to-date results, and am trying to figure out if I should write a little client.

@fidelram Sure!

Just a heads up to everyone, I'm pretty swamped this week and probably won't get around to updating this PR until at least this weekend.

@liiskolb

Copy link
Copy Markdown

@ivirshup We estimate that the package will be released around 15th of April. So, in a month or so.
If this is ok, then I'll let you know when it is out:)

@ivirshup

Copy link
Copy Markdown
Member Author

Writing the example for sc.queries.enrich(adata, ...) made me realize I probably don't want to encourage that. Potentially could be fixed by a default p-value cutoff.

As for the gprofiler version, there are two paths forward I think would work:

  1. Put a hold on the enrich function for a bit for the new API to be released
  2. If it'd be useful enough to include now, the docs could note current implementation is provisional and results will change pretty soon. Maybe @fidelram and @LuckyMD have thoughts on that?

@liiskolb

liiskolb commented Apr 9, 2019

Copy link
Copy Markdown

@ivirshup We have updated gprofiler-official to version 1.0.0 that corresponds to the new API.
See the descriptions here: https://pypi.org/project/gprofiler-official/#description

@LuckyMD

LuckyMD commented Apr 15, 2019

Copy link
Copy Markdown
Contributor

@ivirshup Sorry, I didn't see this until just now. I guess @liiskolb's comment addresses your options though... as it's out now, it would be really helpful to have in scanpy.

@ivirshup

ivirshup commented Apr 15, 2019 •

Copy link
Copy Markdown
Member Author

Just pushing the updates now @LuckyMD 😄.

One issue with the enrichment as is, is that gprofiler-official import name conflicts with the previous unofficial wrapper. I'm worried that this will break peoples environments if they're not aware of this. @liiskolb, do you have any thoughts on this?

Otherwise, I think this should be alright. I'd like to know if there'd be any interest in moving the utility function rank_genes_groups_df (added here) into a more central place. I personally use it anytime I use scanpys differential expression.

@ivirshup

Copy link
Copy Markdown
Member Author

@flying-sheep, current thoughts on this?

Comment thread scanpy/queries/_queries.py Outdated
-------
A `pd.DataFrame` containing annotations.
:class:`pandas.DataFrame`
Dataframe containing annotations.

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.

Due to recent doc changes: If you just have one return value, write prose and use a return value annotation.

(same for every other time you changed this in this commit)

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.

Just changed.

Also, I think it would be reasonable to include this with v1.5, if v1.4.1 is otherwise just bug fixes.

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.

sure!

@liiskolb

Copy link
Copy Markdown

@ivirshup "One issue with the enrichment as is, is that gprofiler-official import name conflicts with the previous unofficial wrapper. I'm worried that this will break peoples environments if they're not aware of this. @liiskolb, do you have any thoughts on this?"

I'm not really sure I got it right, but if new version of scanpy includes new version of gprofiler-official, then it should work well. If people have old version of scanpy that uses old version of gprofiler, then it should also work but with data from archived release of gprofiler.

With this kind of updates it is inevitable that some environments break (we have the experience as you can see;)), these just need to be solved case by case if people with problems start to contact. They could be advised to update their packages to solve these issues.

@ivirshup ivirshup changed the title [WIP] Queries fix Queries fix Apr 22, 2019
@LuckyMD

LuckyMD commented Jun 24, 2019

Copy link
Copy Markdown
Contributor

@liiskolb The problem is that the python-gprofiler and gprofiler-official packages are both imported as import gprofiler. That means that someone who has installed one of them and then gets the other with scanpy won't know what they are importing if they just run import gprofiler. This is not ideal. I just experienced the same thing and decided to remove python-gprofiler. But we can't really mandate that everyone does this.

@ivirshup maybe the solution is to detect which version people have and then parse according to their version? The format is quite similar. I've used both now and could probably convert inputs and outputs easily. And then I'd throw a warning if python-gprofiler is installed.

@liiskolb

Copy link
Copy Markdown

@LuckyMD Ok. For me it seems that the packages can be differentiated by using from gprofiler import GProfiler for official package (for python-gprofiler this is from gprofiler import gprofiler). Possibly this allows to control if gprofiler-official is installed and used.

I've given a shot at documenting a single dispatch function, largely following how it's done in `R`. I assume that will be most familiar to people who use scanpy. Also made the api to `gprofiler` more flexible by letting the user pass arbitrary arguments.

Additionally, ran formatting with black and fixed some doc errors
Now uses `gprofiler-official` and can take cut-offs for differential expression.
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.

6 participants