1 """Interface with encoded software for ENCODE3 data submission & warehouse
3 This allows retrieving blocks
7 from __future__ import print_function
14 from urlparse import urljoin, urlparse, urlunparse
16 LOGGER = logging.getLogger(__name__)
19 # The None context will get added to the root of the tree and will
20 # provide common defaults.
22 # terms in multiple encoded objects
23 'award': {'@type': '@id'},
24 'dataset': {'@type': '@id'},
25 'description': 'rdf:description',
26 'documents': {'@type': '@id'},
27 'experiment': {'@type': '@id'},
28 'href': {'@type': '@id'},
29 'lab': {'@type': '@id'},
30 'library': {'@type': '@id'},
31 'pi': {'@type': '@id'},
32 'platform': {'@type': '@id'},
33 'replicates': {'@type': '@id'},
34 'submitted_by': {'@type': '@id'},
35 'url': {'@type': '@id'},
37 # Identify and markup contained classes.
38 # e.g. in the tree there was a sub-dictionary named 'biosample'
39 # That dictionary had a term 'biosample_term_id, which is the
40 # term that should be used as the @id.
42 'biosample_term_id': {'@type': '@id'},
45 "assay_term_id": {"@type": "@id"},
46 "files": {"@type": "@id"},
47 "original_files": {"@type": "@id"},
49 # I tried to use the JSON-LD mapping capabilities to convert the lab
50 # contact information into a vcard record, but the encoded model
51 # didn't lend itself well to the vcard schema
53 # "address1": "vcard:street-address",
54 # "address2": "vcard:street-address",
55 # "city": "vcard:locality",
56 # "state": "vcard:region",
57 # "country": "vcard:country"
60 'nucleic_acid_term_id': {'@type': '@id'}
64 #FIXME: this needs to be initialized from rdfns
65 ENCODED_NAMESPACES = {
66 # JSON-LD lets you define namespaces so you can used the shorted url syntax.
67 # (instead of http://www.w3.org/2000/01/rdf-schema#label you can do
69 "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
70 "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
71 "owl": "http://www.w3.org/2002/07/owl#",
72 "dc": "htp://purl.org/dc/elements/1.1/",
73 "xsd": "http://www.w3.org/2001/XMLSchema#",
74 "vcard": "http://www.w3.org/2006/vcard/ns#",
76 # for some namespaces I made a best guess for the ontology root.
77 "EFO": "http://www.ebi.ac.uk/efo/", # EFO ontology
78 "OBO": "http://purl.obolibrary.org/obo/", # OBO ontology
79 "OBI": "http://purl.obolibrary.org/obo/OBI_", # Ontology for Biomedical Investigations
80 # OBI: available from http://svn.code.sf.net/p/obi/code/releases/2012-07-01/merged/merged-obi-comments.owl
81 "SO": "http://purl.obolibrary.org/obo/SO_", # Sequence ontology
82 # SO: available from http://www.berkeleybop.org/ontologies/so.owl
83 # NTR: New Term Request space for DCC to implement new ontology terms
87 ENCODED_SCHEMA_ROOT = '/profiles/'
91 '''Programatic access encoded, the software powering ENCODE3's submit site.
93 def __init__(self, server, contexts=None, namespaces=None):
98 self.contexts = contexts if contexts else ENCODED_CONTEXT
99 self.namespaces = namespaces if namespaces else ENCODED_NAMESPACES
100 self.json_headers = {'content-type': 'application/json', 'accept': 'application/json'}
104 return (self.username, self.password)
105 auth = property(get_auth)
107 def load_netrc(self):
109 session = netrc.netrc()
110 authenticators = session.authenticators(self.server)
112 self.username = authenticators[0]
113 self.password = authenticators[2]
115 def add_jsonld_context(self, tree, default_base):
116 """Add contexts to various objects in the tree.
118 tree is a json tree returned from the DCC's encoded database.
119 contexts is a dictionary of dictionaries containing contexts
120 for the various possible encoded classes.
121 base, if supplied allows setting the base url that relative
122 urls will be resolved against.
124 self.add_jsonld_child_context(tree, default_base)
125 self.add_jsonld_namespaces(tree['@context'])
127 def add_jsonld_child_context(self, obj, default_base):
128 '''Add JSON-LD context to the encoded JSON.
130 This is recursive because some of the IDs were relative URLs
131 and I needed a way to properly compute a the correct base URL.
133 # pretend strings aren't iterable
134 if type(obj) in types.StringTypes:
137 # recurse on container types
138 if isinstance(obj, collections.Sequence):
139 # how should I update lists?
141 self.add_jsonld_child_context(v, default_base)
144 if isinstance(obj, collections.Mapping):
145 for v in obj.values():
146 self.add_jsonld_child_context(v, default_base)
148 # we have an object. attach a context to it.
149 if self._is_encoded_object(obj):
150 context = self.create_jsonld_context(obj, default_base)
152 obj.setdefault('@context', {}).update(context)
154 def add_jsonld_namespaces(self, context):
155 '''Add shortcut namespaces to a context
157 Only needs to be run on the top-most context
159 context.update(self.namespaces)
161 def create_jsonld_context(self, obj, default_base):
162 '''Synthesize the context for a encoded type
164 self.contexts[None] = default context attributes added to any type
165 self.contexts[type] = context attributes for this type.
167 context = {'@base': urljoin(default_base, obj['@id']),
168 '@vocab': self.get_schema_url(obj)}
170 context.update(self.contexts[None])
171 for t in obj['@type']:
172 if t in self.contexts:
173 context.update(self.contexts[t])
176 def get_json(self, obj_id, **kwargs):
177 '''GET an ENCODE object as JSON and return as dict
179 Uses prepare_url to allow url short-cuts
180 if no keyword arguments are specified it will default to adding limit=all
181 Alternative keyword arguments can be passed in and will be sent to the host.
184 limit - (integer or 'all') how many records to return, all for all of them
185 embed - (bool) if true expands linking ids into their associated object.
186 format - text/html or application/json
189 kwargs['limit'] = 'all'
191 url = self.prepare_url(obj_id)
192 LOGGER.info('requesting url: {}'.format(url))
196 LOGGER.debug('username: %s, password: %s', self.username, self.password)
197 response = requests.get(url, auth=self.auth, headers=self.json_headers, params=kwargs)
198 if not response.status_code == requests.codes.ok:
199 LOGGER.error("Error http status: {}".format(response.status_code))
200 response.raise_for_status()
201 return response.json()
203 def get_jsonld(self, obj_id, **kwargs):
204 '''Get ENCODE object as JSONLD annotated with classses contexts
206 see get_json for documentation about what keywords can be passed.
208 url = self.prepare_url(obj_id)
209 json = self.get_json(obj_id, **kwargs)
210 self.add_jsonld_context(json, url)
213 def get_object_type(self, obj):
214 """Return type for a encoded object
216 obj_type = obj.get('@type')
217 if obj_type and isinstance(obj_type, collections.Sequence):
220 def get_schema_url(self, obj):
221 obj_type = self.get_object_type(obj)
223 return self.prepare_url(ENCODED_SCHEMA_ROOT + obj_type + '.json') + '#'
225 def _is_encoded_object(self, obj):
226 '''Test to see if an object is a JSON-LD object
228 Some of the nested dictionaries lack the @id or @type
229 information necessary to convert them.
231 if not isinstance(obj, collections.Iterable):
234 if '@id' in obj and '@type' in obj:
238 def patch_json(self, obj_id, changes):
239 """Given a dictionary of changes push them as a HTTP patch request
241 url = self.prepare_url(obj_id)
242 payload = json.dumps(changes)
243 response = requests.patch(url, auth=self.auth, headers=self.json_headers, data=payload)
244 if response.status_code != requests.codes.ok:
245 LOGGER.error("Error http status: {}".format(response.status_code))
246 LOGGER.error("Response: %s", response.text)
247 response.raise_for_status()
248 return response.json()
250 def put_json(self, obj_id, new_object):
251 url = self.prepare_url(obj_id)
252 payload = json.dumps(new_object)
253 response = requests.put(url, auth=self.auth, headers=self.json_headers, data=payload)
254 if response.status_code != requests.codes.created:
255 LOGGER.error("Error http status: {}".format(response.status_code))
256 response.raise_for_status()
257 return response.json()
259 def post_json(self, collection_id, new_object):
260 url = self.prepare_url(collection_id)
261 payload = json.dumps(new_object)
263 response = requests.post(url, auth=self.auth, headers=self.json_headers, data=payload)
264 if response.status_code != requests.codes.created:
265 LOGGER.error("Error http status: {}".format(response.status_code))
266 response.raise_for_status()
267 return response.json()
269 def prepare_url(self, request_url):
270 '''This attempts to provide some convienence for accessing a URL
272 Given a url fragment it will default to :
274 * requests to self.server
276 This allows fairly flexible urls. e.g.
278 prepare_url('/experiments/ENCSR000AEG')
279 prepare_url('submit.encodedcc.org/experiments/ENCSR000AEG')
280 prepare_url('http://submit.encodedcc.org/experiments/ENCSR000AEG?limit=all')
282 should all return the same url
284 # clean up potentially messy urls
285 url = urlparse(request_url)._asdict()
286 if not url['scheme']:
287 url['scheme'] = self.scheme
288 if not url['netloc']:
289 url['netloc'] = self.server
290 url = urlunparse(url.values())
293 def search_jsonld(self, term, **kwargs):
294 '''Send search request to ENCODED
296 url = self.prepare_url('/search/')
297 result = self.get_json(url, searchTerm=term, **kwargs)
298 self.convert_search_to_jsonld(result)
301 def convert_search_to_jsonld(self, result):
302 '''Add the context to search result
304 Also remove hard to handle nested attributes
305 e.g. remove object.term when we have no id
307 graph = result['@graph']
308 for i, obj in enumerate(graph):
309 # suppress nested attributes
310 graph[i] = {k: v for k, v in obj.items() if '.' not in k}
312 self.add_jsonld_context(result, self.prepare_url(result['@id']))
315 def validate(self, obj):
316 obj_type = self.get_object_type(obj)
317 schema_url = self.get_schema_url(obj)
319 raise ValueError("Unable to construct schema url")
321 schema = self.schemas.setdefault(obj_type, self.get_json(schema_url))
325 jsonschema.validate(hidden, schema)
328 if __name__ == '__main__':
330 from htsworkflow.util.rdfhelp import get_model, dump_model
331 from htsworkflow.util.rdfjsonld import load_into_model
332 from pprint import pprint
334 logging.basicConfig(level=logging.DEBUG)
335 encoded = ENCODED('test.encodedcc.org')
337 body = encoded.get_jsonld('/experiments/ENCSR000AEC/')
339 load_into_model(model, body)