File: clients.py

package info (click to toggle)
python-bioframe 0.4.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,000 kB
  • sloc: python: 5,860; makefile: 38; sh: 13
file content (179 lines) | stat: -rw-r--r-- 5,911 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
from urllib.parse import urljoin, urlencode
import os
import posixpath as pp
import os.path as op
import pandas as pd
import requests
import socket
import base64
import glob

from ..io.fileops import read_table


class EncodeClient:

    BASE_URL = "http://www.encodeproject.org/"

    # 2020-05-15 compatible with ENCODE Metadata at:
    METADATA_URL = "https://www.encodeproject.org/metadata/type=Experiment&status=released/metadata.tsv"

    KNOWN_ASSEMBLIES = [
        "GRCh38",
        "GRCh38-minimal",
        "ce10",
        "ce11",
        "dm3",
        "dm6",
        "hg19",
        "mm10",
        "mm10-minimal",
        "mm9",
    ]

    def __init__(self, cachedir, assembly, metadata=None):
        if assembly not in self.KNOWN_ASSEMBLIES:
            raise ValueError("assembly must be in:", self.KNOWN_ASSEMBLIES)

        self.cachedir = op.join(cachedir, assembly)
        if not op.isdir(self.cachedir):
            os.makedirs(self.cachedir, exist_ok=True)

        if metadata is None:
            metadata_path = op.join(cachedir, "metadata.tsv")

            if not op.exists(metadata_path):

                print(
                    "getting metadata from ENCODE, please wait while (~240Mb) file downloads"
                )
                with requests.get(self.METADATA_URL, stream=True) as r:
                    r.raise_for_status()
                    with open(metadata_path, "wb") as f:
                        for chunk in r.iter_content(chunk_size=8192):
                            f.write(chunk)

            self._meta = pd.read_table(metadata_path, low_memory=False)
            table_assemblies = sorted(
                self._meta["File assembly"].dropna().unique().tolist()
            )

            if not set(table_assemblies).issubset(set(self.KNOWN_ASSEMBLIES)):
                raise ValueError(
                    "Table assemblies do not match known assemblies, "
                    "check ENCODE metadata version"
                )
            self._meta = self._meta[self._meta["File assembly"] == assembly].copy()
            self._meta = self._meta.set_index("File accession")

        else:
            self._meta = metadata

    def _batch_download(self, args):
        params = urlencode(args)
        url = pp.join("batch_download", params)
        url = urljoin(self.BASE_URL, url)
        r = requests.get(url)
        r.raise_for_status()
        return r

    def _metadata(self, args):
        params = urlencode(args)
        url = pp.join("metadata", params, "metadata.tsv")
        url = urljoin(self.BASE_URL, url)
        r = requests.get(url)
        r.raise_for_status()
        return r

    @property
    def meta(self):
        return self._meta.copy()

    def info(self, accession, width=850, height=450):
        from IPython.display import HTML

        url = urljoin(self.BASE_URL, pp.join("experiments", accession))
        return HTML(
            '<iframe width="{}px" height="{}px" src={}></iframe>'.format(
                width, height, url
            )
        )

    def fetch(self, accession):
        url = self.meta.loc[accession, "File download URL"]
        # sig = self.meta.loc[accession, 'md5sum']
        filename = op.split(url)[1]
        path = op.join(self.cachedir, filename)
        if op.exists(path):
            pass
            # print('File "{}" available'.format(filename))
        else:
            print('Downloading "{}"'.format(filename))
            r = requests.get(url)
            r.raise_for_status()
            with open(path, "wb") as f:
                f.write(r.content)
        return path

    def fetch_all(self, accessions):
        return list(map(self.fetch, accessions))


class FDNClient:
    BASE_URL = "https://data.4dnucleome.org/"

    def __init__(self, cachedir, assembly, metadata=None, key_id=None, key_secret=None):
        self.cachedir = op.join(cachedir, assembly)
        if not op.isdir(self.cachedir):
            raise OSError("Directory doesn't exist: '{}'".format(cachedir))
        if metadata is None:
            metadata_paths = sorted(glob.glob(op.join(cachedir, "metadata*.tsv")))
            metadata_path = metadata_paths[-1]
            self._meta = pd.read_table(metadata_path, low_memory=False, comment="#")
            if assembly == "GRCh38":
                self._meta = self._meta[self._meta["Organism"] == "human"].copy()
            self._meta = self._meta.set_index("File Accession")
        else:
            self._meta = metadata
        if key_id is not None:
            credential = (key_id + ":" + key_secret).encode("utf-8")
            self._token = base64.b64encode(credential)
        else:
            self._token = None

    @property
    def meta(self):
        return self._meta.copy()

    def info(self, accession, width=850, height=450):
        from IPython.display import HTML

        url = urljoin(self.BASE_URL, pp.join("experiments", accession))
        return HTML(
            '<iframe width="{}px" height="{}px" src={}></iframe>'.format(
                width, height, url
            )
        )

    def fetch(self, accession):
        url = self.meta.loc[accession, "File Download URL"]
        # sig = self.meta.loc[accession, 'md5sum']
        filename = op.split(url)[1]
        path = op.join(self.cachedir, filename)
        if op.exists(path):
            pass
            # print('File "{}" available'.format(filename))
        else:
            print('Downloading "{}"'.format(filename))
            if self._token:
                headers = {"Authorization": b"Basic " + self._token}
            else:
                headers = None
            r = requests.get(url, headers=headers)
            r.raise_for_status()
            with open(path, "wb") as f:
                f.write(r.content)
        return path

    def fetch_all(self, accessions):
        return list(map(self.fetch, accessions))