def route_examples(): links = hfn.render_table( [[name, hfn.atag(url_for("route_query", pred=pred, root=root) + (args[0] if args else ''), f'../query/{pred}/{root}{args[0] if args else ""}')] for name, pred, root, *args in examples], 'Root class', '../query/{predicate-curie}/{root-curie}?direction=INCOMING&depth=10&branch=master&local=false', halign='left') flinks = hfn.render_table( [[name, hfn.atag(url_for("route_filequery", pred=pred, root=root, file=file) + (args[0] if args else ''), f'../query/{pred}/{root}/{file}{args[0] if args else ""}')] for name, pred, root, file, *args in file_examples], 'Root class', '../query/{predicate-curie}/{root-curie}/{ontology-filepath}?direction=INCOMING&depth=10&branch=master&restriction=false', halign='left') dlinks = hfn.render_table( [[name, hfn.atag(url_for("route_dynamic", path=path) + (querystring if querystring else ''), f'../query/dynamic/{path}{querystring if querystring else ""}')] for name, path, querystring in dynamic_examples], 'Root class', '../query/dynamic/{path}?direction=OUTGOING&dynamic=query&args=here', halign='left') return hfn.htmldoc(links, flinks, dlinks, title='Example hierarchy queries')
def route_sparc_index(): hyp_rows = hyperlink_tree(sparc_view) return hfn.htmldoc( hfn.render_table(hyp_rows), title = 'SPARC Anatomical terms index', metas = ({'name':'date', 'content':time()},), )
def route_sparc_view(): hyp_rows = [] spaces = hfn.nbsp * 8 for tier1, tier2_on in sorted(sparc_view.items()): url = url_for('route_sparc_view_query', tier1=tier1) tier1_row = tier1.split(YML_DELIMITER) tier1_row += tier2_on['CURIES'] tagged_tier1_row = tag_row(tier1_row, url) hyp_rows.append(tagged_tier1_row) if not tier2_on: continue # BUG: Will break what we want if more is added to spinal cord if len(tier2_on.keys()) > 15: continue if tier1_row[0] == 'Nerve roots of spinal cord segments': continue for tier2, tier3_on in tier2_on.items(): if tier2 == 'CURIES': continue url = url_for('route_sparc_view_query', tier1=tier1, tier2=tier2) tier2_row = tier2.split(YML_DELIMITER) tier2_row += tier3_on['CURIES'] tagged_tier2_row = tag_row(row=tier2_row, url=url, tier_level=1) if len(list(sparc_view[tier1_row[0]][tier2_row[0]].keys())) == 1: tagged_tier2_row[0] = spaces+tier2_row[0] hyp_rows.append(tagged_tier2_row) return hfn.htmldoc( hfn.render_table(hyp_rows), title= 'Main Page Sparc', styles= ["p {margin: 0px; padding: 0px;}"], metas= ({'name':'date', 'content':time()},), )
def route_sparc_demos_isan2019_flatmap_queries(): # lift up to load from an external source at some point # from pyontutils.core import OntResPath # orp = OntResPath('annotations.ttl') # [i for i in sorted(set(OntId(e) for t in orp.graph for e in t)) if i.prefix in ('UBERON', 'FMA', 'ILX')] query = """ MATCH (blank)- [entrytype:ilxtr:hasSomaLocatedIn|ilxtr:hasAxonLocatedIn|ilxtr:hasDendriteLocatedIn|ilxtr:hasPresynapticTerminalsIn] ->(location:Class{{iri: "{iri}"}}) WITH entrytype, location, blank MATCH (phenotype)<-[predicate]-(blank)<-[:equivalentClass]-(neuron) WHERE NOT (phenotype.iri =~ ".*_:.*") RETURN location, entrytype.iri, neuron.iri, predicate.iri, phenotype """ def fetch(iri, limit=10): q = query.format(iri=iri) log.debug(q) blob = data_sgc.execute(q, limit, 'application/json') # oh boy # if there are less results than the limit scigraph segfaults # and returns nothing return blob hrm = [fetch(oid) for oid in test_terms] return hfn.htmldoc(hfn.render_table([[1, 2]],'oh', 'no'), title='Simulated flatmap query results', )
def route_dynamic(path): args = dict(request.args) if 'direction' in args: direction = args.pop('direction') else: direction = 'OUTGOING' # should always be outgoing here since we can't specify? if 'format' in args: format_ = args.pop('format') else: format_ = None try: j = sgd.dispatch(path, **args) except rHTTPError as e: log.exception(e) abort(e.response.status_code) # DO NOT PASS ALONG THE MESSAGE except ValueError as e: log.exception(e) abort(404) if j is None or 'edges' not in j or not j['edges']: log.error(pformat(j)) log.debug(sgd._last_url) return abort(400) prov = [ hfn.titletag(f'Dynamic query result for {path}'), f'<meta name="date" content="{UTCNOWISO()}">', f'<link rel="http://www.w3.org/ns/prov#wasGeneratedBy" href="{wgb}">', '<meta name="representation" content="SciGraph">', f'<link rel="http://www.w3.org/ns/prov#wasDerivedFrom" href="{sgd._last_url}">' ] kwargs = {'json': cleanBad(j), 'html_head': prov} tree, extras = creatTree(*Query(None, None, direction, None), **kwargs) #print(extras.hierarhcy) #print(tree) if format_ is not None: if format_ == 'table': #breakpoint() def nowrap(class_, tag=''): return (f'{tag}.{class_}' '{ white-space: nowrap; }') ots = [ OntTerm(n) for n in flatten_tree(extras.hierarchy) if 'CYCLE' not in n ] #rows = [[ot.label, ot.asId().atag(), ot.definition] for ot in ots] rows = [[ot.label, hfn.atag(ot.iri, ot.curie), ot.definition] for ot in ots] return hfn.htmldoc(hfn.render_table(rows, 'label', 'curie', 'definition'), styles=(hfn.table_style, nowrap('col-label', 'td'))) return hfn.htmldoc(extras.html, other=prov, styles=hfn.tree_styles)
def route_sparc_demos_isan2019_neuron_connectivity(): def connected(start): log.debug(start) blob = data_sgd.neurons_connectivity(start) #, limit=9999) edges = blob['edges'] neurons = {} types = {} rows = [] start_type = None sc = OntId(start).curie for e in edges: s, p, o = e['sub'], e['pred'], e['obj'] if p == 'operand': continue if s.startswith('_:'): if s not in neurons: neurons[s] = [] types[s] = {} otp = OntTerm(p) oto = OntTerm(o) neurons[s].append((otp, oto)) if o == sc: start_type = otp if oto not in types[s]: types[s][oto] = [] types[s][oto].append(otp) for v in neurons.values(): v.sort() return OntTerm(start), start_type, neurons, types hrm = [connected(t) for t in set(test_terms)] header = ['Start', 'Start Type', 'Neuron', 'Relation', 'Target'] rows = [] for start, start_type, neurons, types in sorted(hrm): start = start.atag() start_type = start_type.atag() if start_type is not None else '' for i, v in enumerate(neurons.values(), 1): neuron = i for p, o in v: relation = p.atag() target = o.atag() row = start, start_type, neuron, relation, target rows.append(row) rows.append(['|'] + [' '] * 4) h = hfn.htmldoc(hfn.render_table(rows, *header), title='neuron connectivity') return h
def route_sparc_view_query(tier1, tier2=None): journey = sparc_view if tier1 not in journey: return abort(404) journey = journey[tier1] if tier2 is not None: if tier2 not in journey: return abort(404) journey = journey[tier2] hyp_rows = hyperlink_tree(journey) return hfn.htmldoc( hfn.render_table(hyp_rows), title = 'Terms for ' + (tier2 if tier2 is not None else tier1), metas = ({'name':'date', 'content':time()},), )
def route_sparc_dynamic(path): args = dict(request.args) if 'direction' in args: direction = args.pop('direction') else: direction = 'OUTGOING' # should always be outgoing here since we can't specify? if 'format' in args: format_ = args.pop('format') else: format_ = None j = data_sgd.dispatch(path, **args) #breakpoint() if not j['edges']: log.error(pprint(j)) return abort(400) kwargs = {'json': j} tree, extras = creatTree(*Query(None, None, direction, None), **kwargs) #print(extras.hierarhcy) print(tree) if format_ is not None: if format_ == 'table': #breakpoint() def nowrap(class_, tag=''): return (f'{tag}.{class_}' '{ white-space: nowrap; }') ots = [ OntTerm(n) for n in flatten_tree(extras.hierarchy) if 'CYCLE' not in n ] #rows = [[ot.label, ot.asId().atag(), ot.definition] for ot in ots] rows = [[ot.label, hfn.atag(ot.iri, ot.curie), ot.definition] for ot in ots] return htmldoc(hfn.render_table(rows, 'label', 'curie', 'definition'), styles=(hfn.table_style, nowrap('col-label', 'td'))) return htmldoc(extras.html, styles=hfn.tree_styles)
def sparc_dynamic(data_sgd, data_sgc, path, wgb, process=lambda coll, blob: blob): args = dict(request.args) if 'direction' in args: direction = args.pop('direction') else: direction = 'OUTGOING' # should always be outgoing here since we can't specify? if 'format' in args: format_ = args.pop('format') else: format_ = None if 'apinat' in path: # FIXME bad hardcoded hack _old_get = data_sgd._get try: data_sgd._get = data_sgd._normal_get j = data_sgd.dispatch(path, **args) except ValueError as e: log.exception(e) abort(404) except rHTTPError as e: log.exception(e) abort(e.response.status_code) # DO NOT PASS ALONG THE MESSAGE finally: data_sgd._get = _old_get else: try: j = data_sgd.dispatch(path, **args) except rHTTPError as e: log.exception(e) abort(e.response.status_code) # DO NOT PASS ALONG THE MESSAGE except ValueError as e: log.exception(e) abort(404) j = process(collapse_apinat, j) if j is None or 'edges' not in j: log.error(pformat(j)) return abort(400) elif not j['edges']: return node_list(j['nodes']) # FIXME ... really should error? if path.endswith('housing-lyphs'): # FIXME hack root = 'NLX:154731' #direction = 'INCOMING' else: root = None prov = [ hfn.titletag(f'Dynamic query result for {path}'), f'<meta name="date" content="{UTCNOWISO()}">', f'<link rel="http://www.w3.org/ns/prov#wasGeneratedBy" href="{wgb}">', '<meta name="representation" content="SciGraph">', ('<link rel="http://www.w3.org/ns/prov#wasDerivedFrom" ' f'href="{data_sgd._last_url}">')] kwargs = {'json': cleanBad(j), 'html_head': prov, 'prefixes': data_sgc.getCuries(), # FIXME efficiency } tree, extras = creatTree(*Query(root, None, direction, None), **kwargs) #print(extras.hierarhcy) #print(tree) if format_ is not None: if format_ == 'table': #breakpoint() def nowrap(class_, tag=''): return (f'{tag}.{class_}' '{ white-space: nowrap; }') ots = [OntTerm(n) for n in flatten_tree(extras.hierarchy) if 'CYCLE' not in n] #rows = [[ot.label, ot.asId().atag(), ot.definition] for ot in ots] rows = [[ot.label, hfn.atag(ot.iri, ot.curie), ot.definition] for ot in ots] return hfn.htmldoc(hfn.render_table(rows, 'label', 'curie', 'definition'), styles=(hfn.table_style, nowrap('col-label', 'td'))) return hfn.htmldoc(extras.html, other=prov, styles=hfn.tree_styles)