We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
sc.queries.enrich throws AssertionError with floats
<!-- Please give a clear and concise description of what the bug is: -->
I'm trying to run an enrichment analysis after filtering out certain genes via `sc.tl.filter_rank_genes_groups`, so I use `key='rank_genes_groups_filtered'` as an argument for `sc.queries.enrich`. Since the filtered values are replaced with `nan` I hoped they'd by ignored in the enrichment analysis, but it actually leads to an uninformative `AssertionError`.

My suggestion here is simply to filter `nan` values from the gene list around here and 2 lines later: https://github.com/theislab/scanpy/blob/249fc572471683357b86b8bbf41d3284118bc8f8/scanpy/queries/_queries.py#L296

I can make a little PR if we agree with this simple fix

Note you can reproduce this very simply without an adata object (but of course the likely use case is with an adata object as outlined above):

<!-- Put a minimal reproducible example that reproduces the bug in the code block below: -->
```
sc.queries.enrich([float('nan')])
```
Output:
<!-- Put your Error output in this code block (if applicable, else delete the block): -->
```pytb
AssertionError: query failed with error 500
```

#### Versions:
```
scanpy==1.4.5.post2 anndata==0.6.22.post1 umap==0.3.10 numpy==1.18.1 scipy==1.2.1 pandas==1.0.1 scikit-learn==0.22.1 statsmodels==0.11.0 python-igraph==0.8.0
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `scanpy/queries/_queries.py`
Content:
```
1 import collections.abc as cabc
2 from functools import singledispatch
3 from types import MappingProxyType
4 from typing import Any, Union, Optional, Iterable, Dict, Mapping
5 
6 import pandas as pd
7 from anndata import AnnData
8 
9 from ..get import rank_genes_groups_df
10 from .._utils import _doc_params
11 
12 
13 _doc_org = """\
14 org
15     Organism to query. Must be an organism in ensembl biomart. "hsapiens",
16     "mmusculus", "drerio", etc.\
17 """
18 
19 _doc_host = """\
20 host
21     A valid BioMart host URL. Alternative values include archive urls (like
22     "grch37.ensembl.org") or regional mirrors (like "useast.ensembl.org").\
23 """
24 
25 _doc_use_cache = """\
26 use_cache
27     Whether pybiomart should use a cache for requests. Will create a
28     `.pybiomart.sqlite` file in current directory if used.\
29 """
30 
31 
32 @_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)
33 def simple_query(
34     org: str,
35     attrs: Union[Iterable[str], str],
36     *,
37     filters: Optional[Dict[str, Any]] = None,
38     host: str = "www.ensembl.org",
39     use_cache: bool = False,
40 ) -> pd.DataFrame:
41     """\
42     A simple interface to biomart.
43 
44     Params
45     ------
46     {doc_org}
47     attrs
48         What you want returned.
49     filters
50         What you want to pick out.
51     {doc_host}
52     {doc_use_cache}
53     """
54     if isinstance(attrs, str):
55         attrs = [attrs]
56     elif isinstance(attrs, cabc.Iterable):
57         attrs = list(attrs)
58     else:
59         raise TypeError(f"attrs must be of type list or str, was {type(attrs)}.")
60     try:
61         from pybiomart import Server
62     except ImportError:
63         raise ImportError(
64             "This method requires the `pybiomart` module to be installed."
65         )
66     server = Server(host, use_cache=use_cache)
67     dataset = server.marts["ENSEMBL_MART_ENSEMBL"].datasets[
68         "{}_gene_ensembl".format(org)
69     ]
70     res = dataset.query(attributes=attrs, filters=filters, use_attr_names=True)
71     return res
72 
73 
74 @_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)
75 def biomart_annotations(
76     org: str,
77     attrs: Iterable[str],
78     *,
79     host: str = "www.ensembl.org",
80     use_cache: bool = False,
81 ) -> pd.DataFrame:
82     """\
83     Retrieve gene annotations from ensembl biomart.
84 
85     Parameters
86     ----------
87     {doc_org}
88     attrs
89         Attributes to query biomart for.
90     {doc_host}
91     {doc_use_cache}
92 
93     Returns
94     -------
95     Dataframe containing annotations.
96 
97     Examples
98     --------
99     Retrieve genes coordinates and chromosomes
100 
101     >>> import scanpy as sc
102     >>> annot = sc.queries.biomart_annotations(
103             "hsapiens",
104             ["ensembl_gene_id", "start_position", "end_position", "chromosome_name"],
105         ).set_index("ensembl_gene_id")
106     >>> adata.var[annot.columns] = annot
107     """
108     return simple_query(org=org, attrs=attrs, host=host, use_cache=use_cache)
109 
110 
111 @_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)
112 def gene_coordinates(
113     org: str,
114     gene_name: str,
115     *,
116     gene_attr: str = "external_gene_name",
117     chr_exclude: Iterable[str] = (),
118     host: str = "www.ensembl.org",
119     use_cache: bool = False,
120 ) -> pd.DataFrame:
121     """\
122     Retrieve gene coordinates for specific organism through BioMart.
123 
124     Parameters
125     ----------
126     {doc_org}
127     gene_name
128         The gene symbol (e.g. "hgnc_symbol" for human) for which to retrieve
129         coordinates.
130     gene_attr
131         The biomart attribute the gene symbol should show up for.
132     chr_exclude
133         A list of chromosomes to exclude from query.
134     {doc_host}
135     {doc_use_cache}
136 
137     Returns
138     -------
139     Dataframe containing gene coordinates for the specified gene symbol.
140 
141     Examples
142     --------
143     >>> import scanpy as sc
144     >>> sc.queries.gene_coordinates("hsapiens", "MT-TF")
145     """
146     res = simple_query(
147         org=org,
148         attrs=["chromosome_name", "start_position", "end_position"],
149         filters={gene_attr: gene_name},
150         host=host,
151         use_cache=use_cache,
152     )
153     return res[~res["chromosome_name"].isin(chr_exclude)]
154 
155 
156 @_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)
157 def mitochondrial_genes(
158     org: str,
159     *,
160     attrname: str = "external_gene_name",
161     host: str = "www.ensembl.org",
162     use_cache: bool = False,
163     chromosome: str = "MT",
164 ) -> pd.DataFrame:
165     """\
166     Mitochondrial gene symbols for specific organism through BioMart.
167 
168     Parameters
169     ----------
170     {doc_org}
171     attrname
172         Biomart attribute field to return. Possible values include
173         "external_gene_name", "ensembl_gene_id", "hgnc_symbol", "mgi_symbol",
174         and "zfin_id_symbol".
175     {doc_host}
176     {doc_use_cache}
177     chromosome
178         Mitochrondrial chromosome name used in BioMart for organism.
179 
180     Returns
181     -------
182     Dataframe containing identifiers for mitochondrial genes.
183 
184     Examples
185     --------
186     >>> import scanpy as sc
187     >>> mito_gene_names = sc.queries.mitochondrial_genes("hsapiens")
188     >>> mito_ensembl_ids = sc.queries.mitochondrial_genes("hsapiens", attrname="ensembl_gene_id")
189     >>> mito_gene_names_fly = sc.queries.mitochondrial_genes("dmelanogaster", chromosome="mitochondrion_genome")
190     """
191     return simple_query(
192         org,
193         attrs=[attrname],
194         filters={"chromosome_name": [chromosome]},
195         host=host,
196         use_cache=use_cache,
197     )
198 
199 
200 @singledispatch
201 @_doc_params(doc_org=_doc_org)
202 def enrich(
203     container: Iterable[str],
204     *,
205     org: str = "hsapiens",
206     gprofiler_kwargs: Mapping[str, Any] = MappingProxyType({}),
207 ) -> pd.DataFrame:
208     """\
209     Get enrichment for DE results.
210 
211     This is a thin convenience wrapper around the very useful gprofiler_.
212 
213     This method dispatches on the first argument, leading to the following two
214     signatures::
215 
216         enrich(container, ...)
217         enrich(adata: AnnData, group, key: str, ...)
218 
219     Where::
220 
221         enrich(adata, group, key, ...) = enrich(adata.uns[key]["names"][group], ...)
222 
223     .. _gprofiler: https://pypi.org/project/gprofiler-official/#description
224 
225     Parameters
226     ----------
227     container
228         Contains genes you'd like to search.
229     adata
230         AnnData object whose group will be looked for.
231     group
232         The group whose genes should be used for enrichment.
233     key
234         Key in `uns` to find group under.
235     {doc_org}
236     gprofiler_kwargs
237         Keyword arguments to pass to `GProfiler.profile`, see gprofiler_.
238 
239     Returns
240     -------
241     Dataframe of enrichment results.
242 
243     Examples
244     --------
245     Using `sc.queries.enrich` on a list of genes:
246 
247     >>> import scanpy as sc
248     >>> sc.queries.enrich(['Klf4', 'Pax5', 'Sox2', 'Nanog'], org="hsapiens")
249 
250     Using `sc.queries.enrich` on an :class:`anndata.AnnData` object:
251 
252     >>> pbmcs = sc.datasets.pbmc68k_reduced()
253     >>> sc.tl.rank_genes_groups(pbmcs, "bulk_labels")
254     >>> sc.queries.enrich(pbmcs, "CD34+")
255     """
256     try:
257         from gprofiler import GProfiler
258     except ImportError:
259         raise ImportError(
260             "This method requires the `gprofiler-official` module to be installed."
261         )
262     gprofiler = GProfiler(user_agent="scanpy", return_dataframe=True)
263     gprofiler_kwargs = dict(gprofiler_kwargs)
264     for k in ["organism"]:
265         if gprofiler_kwargs.get(k) is not None:
266             raise ValueError(
267                 f"Argument `{k}` should be passed directly through `enrich`, "
268                 "not through `gprofiler_kwargs`"
269             )
270     return gprofiler.profile(list(container), organism=org, **gprofiler_kwargs)
271 
272 
273 @enrich.register(AnnData)
274 def _enrich_anndata(
275     adata: AnnData,
276     group: str,
277     *,
278     org: Optional[str] = "hsapiens",
279     key: str = "rank_genes_groups",
280     pval_cutoff: float = 0.05,
281     log2fc_min: Optional[float] = None,
282     log2fc_max: Optional[float] = None,
283     gene_symbols: Optional[str] = None,
284     gprofiler_kwargs: Mapping[str, Any] = MappingProxyType({}),
285 ) -> pd.DataFrame:
286     de = rank_genes_groups_df(
287         adata,
288         group=group,
289         key=key,
290         pval_cutoff=pval_cutoff,
291         log2fc_min=log2fc_min,
292         log2fc_max=log2fc_max,
293         gene_symbols=gene_symbols,
294     )
295     if gene_symbols is not None:
296         gene_list = list(de[gene_symbols])
297     else:
298         gene_list = list(de["names"])
299     return enrich(gene_list, org=org, gprofiler_kwargs=gprofiler_kwargs)
300
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/scanpy/queries/_queries.py b/scanpy/queries/_queries.py
--- a/scanpy/queries/_queries.py
+++ b/scanpy/queries/_queries.py
@@ -235,6 +235,9 @@
     {doc_org}
     gprofiler_kwargs
         Keyword arguments to pass to `GProfiler.profile`, see gprofiler_.
+    **kwargs
+        All other keyword arguments are passed to `sc.get.rank_genes_groups_df`. E.g.
+        pval_cutoff, log2fc_min.
 
     Returns
     -------
@@ -293,7 +296,7 @@
         gene_symbols=gene_symbols,
     )
     if gene_symbols is not None:
-        gene_list = list(de[gene_symbols])
+        gene_list = list(de[gene_symbols].dropna())
     else:
-        gene_list = list(de["names"])
+        gene_list = list(de["names"].dropna())
     return enrich(gene_list, org=org, gprofiler_kwargs=gprofiler_kwargs)

{"golden_diff": "diff --git a/scanpy/queries/_queries.py b/scanpy/queries/_queries.py\n--- a/scanpy/queries/_queries.py\n+++ b/scanpy/queries/_queries.py\n@@ -235,6 +235,9 @@\n     {doc_org}\n     gprofiler_kwargs\n         Keyword arguments to pass to `GProfiler.profile`, see gprofiler_.\n+    **kwargs\n+        All other keyword arguments are passed to `sc.get.rank_genes_groups_df`. E.g.\n+        pval_cutoff, log2fc_min.\n \n     Returns\n     -------\n@@ -293,7 +296,7 @@\n         gene_symbols=gene_symbols,\n     )\n     if gene_symbols is not None:\n-        gene_list = list(de[gene_symbols])\n+        gene_list = list(de[gene_symbols].dropna())\n     else:\n-        gene_list = list(de[\"names\"])\n+        gene_list = list(de[\"names\"].dropna())\n     return enrich(gene_list, org=org, gprofiler_kwargs=gprofiler_kwargs)\n", "issue": "sc.queries.enrich throws AssertionError with floats\n<!-- Please give a clear and concise description of what the bug is: -->\r\nI'm trying to run an enrichment analysis after filtering out certain genes via `sc.tl.filter_rank_genes_groups`, so I use `key='rank_genes_groups_filtered'` as an argument for `sc.queries.enrich`. Since the filtered values are replaced with `nan` I hoped they'd by ignored in the enrichment analysis, but it actually leads to an uninformative `AssertionError`.\r\n\r\nMy suggestion here is simply to filter `nan` values from the gene list around here and 2 lines later: https://github.com/theislab/scanpy/blob/249fc572471683357b86b8bbf41d3284118bc8f8/scanpy/queries/_queries.py#L296\r\n\r\nI can make a little PR if we agree with this simple fix\r\n\r\nNote you can reproduce this very simply without an adata object (but of course the likely use case is with an adata object as outlined above):\r\n\r\n<!-- Put a minimal reproducible example that reproduces the bug in the code block below: -->\r\n```\r\nsc.queries.enrich([float('nan')])\r\n```\r\nOutput:\r\n<!-- Put your Error output in this code block (if applicable, else delete the block): -->\r\n```pytb\r\nAssertionError: query failed with error 500\r\n```\r\n\r\n#### Versions:\r\n```\r\nscanpy==1.4.5.post2 anndata==0.6.22.post1 umap==0.3.10 numpy==1.18.1 scipy==1.2.1 pandas==1.0.1 scikit-learn==0.22.1 statsmodels==0.11.0 python-igraph==0.8.0\r\n```\n", "before_files": [{"content": "import collections.abc as cabc\nfrom functools import singledispatch\nfrom types import MappingProxyType\nfrom typing import Any, Union, Optional, Iterable, Dict, Mapping\n\nimport pandas as pd\nfrom anndata import AnnData\n\nfrom ..get import rank_genes_groups_df\nfrom .._utils import _doc_params\n\n\n_doc_org = \"\"\"\\\norg\n    Organism to query. Must be an organism in ensembl biomart. \"hsapiens\",\n    \"mmusculus\", \"drerio\", etc.\\\n\"\"\"\n\n_doc_host = \"\"\"\\\nhost\n    A valid BioMart host URL. Alternative values include archive urls (like\n    \"grch37.ensembl.org\") or regional mirrors (like \"useast.ensembl.org\").\\\n\"\"\"\n\n_doc_use_cache = \"\"\"\\\nuse_cache\n    Whether pybiomart should use a cache for requests. Will create a\n    `.pybiomart.sqlite` file in current directory if used.\\\n\"\"\"\n\n\n@_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)\ndef simple_query(\n    org: str,\n    attrs: Union[Iterable[str], str],\n    *,\n    filters: Optional[Dict[str, Any]] = None,\n    host: str = \"www.ensembl.org\",\n    use_cache: bool = False,\n) -> pd.DataFrame:\n    \"\"\"\\\n    A simple interface to biomart.\n\n    Params\n    ------\n    {doc_org}\n    attrs\n        What you want returned.\n    filters\n        What you want to pick out.\n    {doc_host}\n    {doc_use_cache}\n    \"\"\"\n    if isinstance(attrs, str):\n        attrs = [attrs]\n    elif isinstance(attrs, cabc.Iterable):\n        attrs = list(attrs)\n    else:\n        raise TypeError(f\"attrs must be of type list or str, was {type(attrs)}.\")\n    try:\n        from pybiomart import Server\n    except ImportError:\n        raise ImportError(\n            \"This method requires the `pybiomart` module to be installed.\"\n        )\n    server = Server(host, use_cache=use_cache)\n    dataset = server.marts[\"ENSEMBL_MART_ENSEMBL\"].datasets[\n        \"{}_gene_ensembl\".format(org)\n    ]\n    res = dataset.query(attributes=attrs, filters=filters, use_attr_names=True)\n    return res\n\n\n@_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)\ndef biomart_annotations(\n    org: str,\n    attrs: Iterable[str],\n    *,\n    host: str = \"www.ensembl.org\",\n    use_cache: bool = False,\n) -> pd.DataFrame:\n    \"\"\"\\\n    Retrieve gene annotations from ensembl biomart.\n\n    Parameters\n    ----------\n    {doc_org}\n    attrs\n        Attributes to query biomart for.\n    {doc_host}\n    {doc_use_cache}\n\n    Returns\n    -------\n    Dataframe containing annotations.\n\n    Examples\n    --------\n    Retrieve genes coordinates and chromosomes\n\n    >>> import scanpy as sc\n    >>> annot = sc.queries.biomart_annotations(\n            \"hsapiens\",\n            [\"ensembl_gene_id\", \"start_position\", \"end_position\", \"chromosome_name\"],\n        ).set_index(\"ensembl_gene_id\")\n    >>> adata.var[annot.columns] = annot\n    \"\"\"\n    return simple_query(org=org, attrs=attrs, host=host, use_cache=use_cache)\n\n\n@_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)\ndef gene_coordinates(\n    org: str,\n    gene_name: str,\n    *,\n    gene_attr: str = \"external_gene_name\",\n    chr_exclude: Iterable[str] = (),\n    host: str = \"www.ensembl.org\",\n    use_cache: bool = False,\n) -> pd.DataFrame:\n    \"\"\"\\\n    Retrieve gene coordinates for specific organism through BioMart.\n\n    Parameters\n    ----------\n    {doc_org}\n    gene_name\n        The gene symbol (e.g. \"hgnc_symbol\" for human) for which to retrieve\n        coordinates.\n    gene_attr\n        The biomart attribute the gene symbol should show up for.\n    chr_exclude\n        A list of chromosomes to exclude from query.\n    {doc_host}\n    {doc_use_cache}\n\n    Returns\n    -------\n    Dataframe containing gene coordinates for the specified gene symbol.\n\n    Examples\n    --------\n    >>> import scanpy as sc\n    >>> sc.queries.gene_coordinates(\"hsapiens\", \"MT-TF\")\n    \"\"\"\n    res = simple_query(\n        org=org,\n        attrs=[\"chromosome_name\", \"start_position\", \"end_position\"],\n        filters={gene_attr: gene_name},\n        host=host,\n        use_cache=use_cache,\n    )\n    return res[~res[\"chromosome_name\"].isin(chr_exclude)]\n\n\n@_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)\ndef mitochondrial_genes(\n    org: str,\n    *,\n    attrname: str = \"external_gene_name\",\n    host: str = \"www.ensembl.org\",\n    use_cache: bool = False,\n    chromosome: str = \"MT\",\n) -> pd.DataFrame:\n    \"\"\"\\\n    Mitochondrial gene symbols for specific organism through BioMart.\n\n    Parameters\n    ----------\n    {doc_org}\n    attrname\n        Biomart attribute field to return. Possible values include\n        \"external_gene_name\", \"ensembl_gene_id\", \"hgnc_symbol\", \"mgi_symbol\",\n        and \"zfin_id_symbol\".\n    {doc_host}\n    {doc_use_cache}\n    chromosome\n        Mitochrondrial chromosome name used in BioMart for organism.\n\n    Returns\n    -------\n    Dataframe containing identifiers for mitochondrial genes.\n\n    Examples\n    --------\n    >>> import scanpy as sc\n    >>> mito_gene_names = sc.queries.mitochondrial_genes(\"hsapiens\")\n    >>> mito_ensembl_ids = sc.queries.mitochondrial_genes(\"hsapiens\", attrname=\"ensembl_gene_id\")\n    >>> mito_gene_names_fly = sc.queries.mitochondrial_genes(\"dmelanogaster\", chromosome=\"mitochondrion_genome\")\n    \"\"\"\n    return simple_query(\n        org,\n        attrs=[attrname],\n        filters={\"chromosome_name\": [chromosome]},\n        host=host,\n        use_cache=use_cache,\n    )\n\n\n@singledispatch\n@_doc_params(doc_org=_doc_org)\ndef enrich(\n    container: Iterable[str],\n    *,\n    org: str = \"hsapiens\",\n    gprofiler_kwargs: Mapping[str, Any] = MappingProxyType({}),\n) -> pd.DataFrame:\n    \"\"\"\\\n    Get enrichment for DE results.\n\n    This is a thin convenience wrapper around the very useful gprofiler_.\n\n    This method dispatches on the first argument, leading to the following two\n    signatures::\n\n        enrich(container, ...)\n        enrich(adata: AnnData, group, key: str, ...)\n\n    Where::\n\n        enrich(adata, group, key, ...) = enrich(adata.uns[key][\"names\"][group], ...)\n\n    .. _gprofiler: https://pypi.org/project/gprofiler-official/#description\n\n    Parameters\n    ----------\n    container\n        Contains genes you'd like to search.\n    adata\n        AnnData object whose group will be looked for.\n    group\n        The group whose genes should be used for enrichment.\n    key\n        Key in `uns` to find group under.\n    {doc_org}\n    gprofiler_kwargs\n        Keyword arguments to pass to `GProfiler.profile`, see gprofiler_.\n\n    Returns\n    -------\n    Dataframe of enrichment results.\n\n    Examples\n    --------\n    Using `sc.queries.enrich` on a list of genes:\n\n    >>> import scanpy as sc\n    >>> sc.queries.enrich(['Klf4', 'Pax5', 'Sox2', 'Nanog'], org=\"hsapiens\")\n\n    Using `sc.queries.enrich` on an :class:`anndata.AnnData` object:\n\n    >>> pbmcs = sc.datasets.pbmc68k_reduced()\n    >>> sc.tl.rank_genes_groups(pbmcs, \"bulk_labels\")\n    >>> sc.queries.enrich(pbmcs, \"CD34+\")\n    \"\"\"\n    try:\n        from gprofiler import GProfiler\n    except ImportError:\n        raise ImportError(\n            \"This method requires the `gprofiler-official` module to be installed.\"\n        )\n    gprofiler = GProfiler(user_agent=\"scanpy\", return_dataframe=True)\n    gprofiler_kwargs = dict(gprofiler_kwargs)\n    for k in [\"organism\"]:\n        if gprofiler_kwargs.get(k) is not None:\n            raise ValueError(\n                f\"Argument `{k}` should be passed directly through `enrich`, \"\n                \"not through `gprofiler_kwargs`\"\n            )\n    return gprofiler.profile(list(container), organism=org, **gprofiler_kwargs)\n\n\n@enrich.register(AnnData)\ndef _enrich_anndata(\n    adata: AnnData,\n    group: str,\n    *,\n    org: Optional[str] = \"hsapiens\",\n    key: str = \"rank_genes_groups\",\n    pval_cutoff: float = 0.05,\n    log2fc_min: Optional[float] = None,\n    log2fc_max: Optional[float] = None,\n    gene_symbols: Optional[str] = None,\n    gprofiler_kwargs: Mapping[str, Any] = MappingProxyType({}),\n) -> pd.DataFrame:\n    de = rank_genes_groups_df(\n        adata,\n        group=group,\n        key=key,\n        pval_cutoff=pval_cutoff,\n        log2fc_min=log2fc_min,\n        log2fc_max=log2fc_max,\n        gene_symbols=gene_symbols,\n    )\n    if gene_symbols is not None:\n        gene_list = list(de[gene_symbols])\n    else:\n        gene_list = list(de[\"names\"])\n    return enrich(gene_list, org=org, gprofiler_kwargs=gprofiler_kwargs)\n", "path": "scanpy/queries/_queries.py"}], "after_files": [{"content": "import collections.abc as cabc\nfrom functools import singledispatch\nfrom types import MappingProxyType\nfrom typing import Any, Union, Optional, Iterable, Dict, Mapping\n\nimport pandas as pd\nfrom anndata import AnnData\n\nfrom ..get import rank_genes_groups_df\nfrom .._utils import _doc_params\n\n\n_doc_org = \"\"\"\\\norg\n    Organism to query. Must be an organism in ensembl biomart. \"hsapiens\",\n    \"mmusculus\", \"drerio\", etc.\\\n\"\"\"\n\n_doc_host = \"\"\"\\\nhost\n    A valid BioMart host URL. Alternative values include archive urls (like\n    \"grch37.ensembl.org\") or regional mirrors (like \"useast.ensembl.org\").\\\n\"\"\"\n\n_doc_use_cache = \"\"\"\\\nuse_cache\n    Whether pybiomart should use a cache for requests. Will create a\n    `.pybiomart.sqlite` file in current directory if used.\\\n\"\"\"\n\n\n@_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)\ndef simple_query(\n    org: str,\n    attrs: Union[Iterable[str], str],\n    *,\n    filters: Optional[Dict[str, Any]] = None,\n    host: str = \"www.ensembl.org\",\n    use_cache: bool = False,\n) -> pd.DataFrame:\n    \"\"\"\\\n    A simple interface to biomart.\n\n    Params\n    ------\n    {doc_org}\n    attrs\n        What you want returned.\n    filters\n        What you want to pick out.\n    {doc_host}\n    {doc_use_cache}\n    \"\"\"\n    if isinstance(attrs, str):\n        attrs = [attrs]\n    elif isinstance(attrs, cabc.Iterable):\n        attrs = list(attrs)\n    else:\n        raise TypeError(f\"attrs must be of type list or str, was {type(attrs)}.\")\n    try:\n        from pybiomart import Server\n    except ImportError:\n        raise ImportError(\n            \"This method requires the `pybiomart` module to be installed.\"\n        )\n    server = Server(host, use_cache=use_cache)\n    dataset = server.marts[\"ENSEMBL_MART_ENSEMBL\"].datasets[\n        \"{}_gene_ensembl\".format(org)\n    ]\n    res = dataset.query(attributes=attrs, filters=filters, use_attr_names=True)\n    return res\n\n\n@_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)\ndef biomart_annotations(\n    org: str,\n    attrs: Iterable[str],\n    *,\n    host: str = \"www.ensembl.org\",\n    use_cache: bool = False,\n) -> pd.DataFrame:\n    \"\"\"\\\n    Retrieve gene annotations from ensembl biomart.\n\n    Parameters\n    ----------\n    {doc_org}\n    attrs\n        Attributes to query biomart for.\n    {doc_host}\n    {doc_use_cache}\n\n    Returns\n    -------\n    Dataframe containing annotations.\n\n    Examples\n    --------\n    Retrieve genes coordinates and chromosomes\n\n    >>> import scanpy as sc\n    >>> annot = sc.queries.biomart_annotations(\n            \"hsapiens\",\n            [\"ensembl_gene_id\", \"start_position\", \"end_position\", \"chromosome_name\"],\n        ).set_index(\"ensembl_gene_id\")\n    >>> adata.var[annot.columns] = annot\n    \"\"\"\n    return simple_query(org=org, attrs=attrs, host=host, use_cache=use_cache)\n\n\n@_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)\ndef gene_coordinates(\n    org: str,\n    gene_name: str,\n    *,\n    gene_attr: str = \"external_gene_name\",\n    chr_exclude: Iterable[str] = (),\n    host: str = \"www.ensembl.org\",\n    use_cache: bool = False,\n) -> pd.DataFrame:\n    \"\"\"\\\n    Retrieve gene coordinates for specific organism through BioMart.\n\n    Parameters\n    ----------\n    {doc_org}\n    gene_name\n        The gene symbol (e.g. \"hgnc_symbol\" for human) for which to retrieve\n        coordinates.\n    gene_attr\n        The biomart attribute the gene symbol should show up for.\n    chr_exclude\n        A list of chromosomes to exclude from query.\n    {doc_host}\n    {doc_use_cache}\n\n    Returns\n    -------\n    Dataframe containing gene coordinates for the specified gene symbol.\n\n    Examples\n    --------\n    >>> import scanpy as sc\n    >>> sc.queries.gene_coordinates(\"hsapiens\", \"MT-TF\")\n    \"\"\"\n    res = simple_query(\n        org=org,\n        attrs=[\"chromosome_name\", \"start_position\", \"end_position\"],\n        filters={gene_attr: gene_name},\n        host=host,\n        use_cache=use_cache,\n    )\n    return res[~res[\"chromosome_name\"].isin(chr_exclude)]\n\n\n@_doc_params(doc_org=_doc_org, doc_host=_doc_host, doc_use_cache=_doc_use_cache)\ndef mitochondrial_genes(\n    org: str,\n    *,\n    attrname: str = \"external_gene_name\",\n    host: str = \"www.ensembl.org\",\n    use_cache: bool = False,\n    chromosome: str = \"MT\",\n) -> pd.DataFrame:\n    \"\"\"\\\n    Mitochondrial gene symbols for specific organism through BioMart.\n\n    Parameters\n    ----------\n    {doc_org}\n    attrname\n        Biomart attribute field to return. Possible values include\n        \"external_gene_name\", \"ensembl_gene_id\", \"hgnc_symbol\", \"mgi_symbol\",\n        and \"zfin_id_symbol\".\n    {doc_host}\n    {doc_use_cache}\n    chromosome\n        Mitochrondrial chromosome name used in BioMart for organism.\n\n    Returns\n    -------\n    Dataframe containing identifiers for mitochondrial genes.\n\n    Examples\n    --------\n    >>> import scanpy as sc\n    >>> mito_gene_names = sc.queries.mitochondrial_genes(\"hsapiens\")\n    >>> mito_ensembl_ids = sc.queries.mitochondrial_genes(\"hsapiens\", attrname=\"ensembl_gene_id\")\n    >>> mito_gene_names_fly = sc.queries.mitochondrial_genes(\"dmelanogaster\", chromosome=\"mitochondrion_genome\")\n    \"\"\"\n    return simple_query(\n        org,\n        attrs=[attrname],\n        filters={\"chromosome_name\": [chromosome]},\n        host=host,\n        use_cache=use_cache,\n    )\n\n\n@singledispatch\n@_doc_params(doc_org=_doc_org)\ndef enrich(\n    container: Iterable[str],\n    *,\n    org: str = \"hsapiens\",\n    gprofiler_kwargs: Mapping[str, Any] = MappingProxyType({}),\n) -> pd.DataFrame:\n    \"\"\"\\\n    Get enrichment for DE results.\n\n    This is a thin convenience wrapper around the very useful gprofiler_.\n\n    This method dispatches on the first argument, leading to the following two\n    signatures::\n\n        enrich(container, ...)\n        enrich(adata: AnnData, group, key: str, ...)\n\n    Where::\n\n        enrich(adata, group, key, ...) = enrich(adata.uns[key][\"names\"][group], ...)\n\n    .. _gprofiler: https://pypi.org/project/gprofiler-official/#description\n\n    Parameters\n    ----------\n    container\n        Contains genes you'd like to search.\n    adata\n        AnnData object whose group will be looked for.\n    group\n        The group whose genes should be used for enrichment.\n    key\n        Key in `uns` to find group under.\n    {doc_org}\n    gprofiler_kwargs\n        Keyword arguments to pass to `GProfiler.profile`, see gprofiler_.\n    **kwargs\n        All other keyword arguments are passed to `sc.get.rank_genes_groups_df`. E.g.\n        pval_cutoff, log2fc_min.\n\n    Returns\n    -------\n    Dataframe of enrichment results.\n\n    Examples\n    --------\n    Using `sc.queries.enrich` on a list of genes:\n\n    >>> import scanpy as sc\n    >>> sc.queries.enrich(['Klf4', 'Pax5', 'Sox2', 'Nanog'], org=\"hsapiens\")\n\n    Using `sc.queries.enrich` on an :class:`anndata.AnnData` object:\n\n    >>> pbmcs = sc.datasets.pbmc68k_reduced()\n    >>> sc.tl.rank_genes_groups(pbmcs, \"bulk_labels\")\n    >>> sc.queries.enrich(pbmcs, \"CD34+\")\n    \"\"\"\n    try:\n        from gprofiler import GProfiler\n    except ImportError:\n        raise ImportError(\n            \"This method requires the `gprofiler-official` module to be installed.\"\n        )\n    gprofiler = GProfiler(user_agent=\"scanpy\", return_dataframe=True)\n    gprofiler_kwargs = dict(gprofiler_kwargs)\n    for k in [\"organism\"]:\n        if gprofiler_kwargs.get(k) is not None:\n            raise ValueError(\n                f\"Argument `{k}` should be passed directly through `enrich`, \"\n                \"not through `gprofiler_kwargs`\"\n            )\n    return gprofiler.profile(list(container), organism=org, **gprofiler_kwargs)\n\n\n@enrich.register(AnnData)\ndef _enrich_anndata(\n    adata: AnnData,\n    group: str,\n    *,\n    org: Optional[str] = \"hsapiens\",\n    key: str = \"rank_genes_groups\",\n    pval_cutoff: float = 0.05,\n    log2fc_min: Optional[float] = None,\n    log2fc_max: Optional[float] = None,\n    gene_symbols: Optional[str] = None,\n    gprofiler_kwargs: Mapping[str, Any] = MappingProxyType({}),\n) -> pd.DataFrame:\n    de = rank_genes_groups_df(\n        adata,\n        group=group,\n        key=key,\n        pval_cutoff=pval_cutoff,\n        log2fc_min=log2fc_min,\n        log2fc_max=log2fc_max,\n        gene_symbols=gene_symbols,\n    )\n    if gene_symbols is not None:\n        gene_list = list(de[gene_symbols].dropna())\n    else:\n        gene_list = list(de[\"names\"].dropna())\n    return enrich(gene_list, org=org, gprofiler_kwargs=gprofiler_kwargs)\n", "path": "scanpy/queries/_queries.py"}]}