LinkML based SPARQL template library and execution engine

Overview

sparqlfun

LinkML based SPARQL template library and execution engine

  • modularized core library of SPARQL templates
    • generic templates using common vocabs (rdf, owl, skos, ...)
    • OBO and biology specific, e.g. Ubergraph
    • coming soon: uniprot, wikidata, etc
  • Fully FAIR description of templates
    • Each template has a URI
    • Each template parameters has a URI
    • Full metadata including descriptions of each
    • Templates described in YAML, RDF, SHACL, ShEx, ...
  • optional python bindings using LinkML
  • supports both SELECT and CONSTRUCT
  • optional export to TSV, JSON, YAML

Browse the default templates

Note: currently not all metadata from the yaml is shown in the generated docs

Command Line

sparqlfun -e ubergraph -T PairwiseCommonSubClassAncestor node1=GO:0046220 node2=GO:0008295

results:

results:
- node1: GO:0046220
  node2: GO:0008295
  predicate1: rdfs:subClassOf
  predicate2: rdfs:subClassOf
  ancestor: GO:0009987
- node1: GO:0046220
  node2: GO:0008295
  predicate1: rdfs:subClassOf
  predicate2: rdfs:subClassOf
  ancestor: GO:0044237
- node1: GO:0046220
  node2: GO:0008295
  predicate1: rdfs:subClassOf
  predicate2: rdfs:subClassOf
  ancestor: GO:0044271
...

Python

se = SparqlEngine(endpoint='ubergraph')
se.bind_prefixes(GO='http://purl.obolibrary.org/obo/GO_')
for row in se.query(PairwiseCommonSubClassAncestor, node1='GO:0046220', node2='GO:0008295'):
        print(f'ROW={row}')

For more examples, see tests/

Service (via Fast API)

coming soon!

Browsing the templates

  • source is in sparqlfun/schema
    • add new templates here
  • Browse the generated markdown on the site

How it works

Basics

Templates are defined as YAML files following the LinkML schema.

A yaml file with a single template might look like this:

classes:
  my template:
    slots:
      - my_var1
      - my_var2
    annotations:
      sparql.select: |-
        SELECT  * WHERE { ... ?my_var1 ... ?my_var2}
      
slots:
  my_var1:
    description: about my var 1
  my_var2:
    description: about my var 2

This defines a template MyTemplate with two slots/parameters, and an arbitrarily complex SPARQL select query.

Note that the definitions of the slots go in a different section from the classes/templates. You are encouraged to "reuse" slots across templates.

The above can be used in queries:

sparqlfun -e ubergraph -T MyTemplate my_var2=MY_VAL

You can ground any or all of your vars on the command line (if you ground all then your SELECT is effectively an ASK query).

However, the features go beyond other templating systems, and leverage the fact that LinkML is a fully-fledged rich modeling language with bindings to JSON-Schema, SHACL, ShEx, etc.

For example, you will get markdown documentation describing your templates. This markdown documentation will be even richer if you annotate your schemas with metadata such as

  • descriptions
  • ranges for slots
  • mappings and URIs for your templates and slots

Template Inheritance

Templates can be inherited, facilitating reuse and composition patterns

To illustrate consider a simple "base" template to query a triple:

triple:
    aliases:
      - statement
    description: >-
      Represents an RDF triple
    slots:
      - subject
      - predicate
      - object
    class_uri: rdf:Statement
    in_subset:
      - base table
    annotations:
      sparql.select: SELECT  * WHERE { ?subject ?predicate ?object}

This is not a particularly useful template in isolation - you may as well query directly with sparql (nevertheless it can be useful to have templates for even this simple pattern, to faciliate generation of APIs etc)

This template can be inherited, which means that slots will be inherited, eliminating some boilerplate and the need to redefine them

Inerhitance allows even more powerful features using the LinkML classification_rules construct. Let's say we want to represent type triples as children of generic triples:

rdf type triple:
    is_a: triple
    description: >-
      A triple that indicates the asserted type of the subject entity
    slot_usage:
      object:
        description: >-
          The entity type
        range: class node
    classification_rules:
      - is_a: triple
        slot_conditions:
          predicate:
            equals_string: rdf:type

Note we don't need to specify a SPARQL template here - the template is autogenerated from the classification rule.

SPARQL CONSTRUCT and nested/inlined objects

Example CONSTRUCT query:

obo class:
    is_a: class node
    class_uri: owl:Class
    slots:
      - definition
      - exact_synonyms
    annotations:
      sparql.construct: |-
        CONSTRUCT {
          ?id a owl:Class ;
              IAO:0000115 ?definition ;
              oboInOwl:hasExactSynonym ?exact_snonyms
        }
        WHERE {
          ?id a owl:Class .
          OPTIONAL { ?id IAO:0000115 ?definition } .
          OPTIONAL { ?id oboInOwl:hasExactSynonym ?exact_snonyms } .
        }

...

slots:
  definition:
    slot_uri: IAO:0000115
  exact_synonyms:
    slot_uri: oboInOwl:hasExactSynonym
    multivalued: true

We can then query this as follows:

sparqlfun -e ubergraph -T OboClass id=GO:0000023

The results will be nested following the LinkML specification for the model

{
  "results": [
    {
      "id": "GO:0000023",
      "definition": "The chemical reactions and pathways involving the disaccharide maltose (4-O-alpha-D-glucopyranosyl-D-glucopyranose), an intermediate in the catabolism of glycogen and starch.",
      "exact_synonyms": [
        "malt sugar metabolic process",
        "malt sugar metabolism",
        "maltose metabolism"
      ]
    }
  ],
  "@type": "ResultSet"
}

You can also get the turtle as returned by the triplestore:

@prefix ns1: 
    .
@prefix ns2: 
    .
@prefix ns3: 
    .

ns2:GO_0000023 a 
    ;
    ns2:IAO_0000115 "The chemical reactions and pathways involving the disaccharide maltose (4-O-alpha-D-glucopyranosyl-D-glucopyranose), an intermediate in the catabolism of glycogen and starch." ;
    ns1:hasExactSynonym "malt sugar metabolic process",
        "malt sugar metabolism",
        "maltose metabolism" .

[] a ns3:ResultSet ;
    ns3:results ns2:GO_0000023 .

With -t tsv the linkml csv dumper will attempt to flatten the nested structure to TSV as closely as possible, e.g. using pipe internal seperators for multivalued

Modularity

LinkML allows importing so templates can be modularized

In future this repo may be split up, with the bio/obo specific features migrating to a new repo.

Use of Jinja commands

You can incorporate additional logic via Jinja2 templating instructions:

obo class filtered:
    is_a: class node
    class_uri: owl:Class
    slots:
      - definition
      - exact_synonyms
    annotations:
      sparql.construct: |-
        CONSTRUCT {
          ?id a owl:Class ;
              IAO:0000115 ?definition ;
              oboInOwl:hasExactSynonym ?exact_snonyms
        }
        WHERE {
          ?id a owl:Class .
          OPTIONAL { ?id IAO:0000115 ?definition } .
          OPTIONAL { ?id oboInOwl:hasExactSynonym ?exact_snonyms } .
          {% if query_has_subclass_ancestor %}
          ?id rdfs:subClassOf ?query_has_subclass_ancestor
          {% endif %}
        }

Supported Endpoints

This framework can be used with any SPARQL endpoint. However, the current pre-defined templates are geared towards the combination of OBO-style ontologies together with storage patterns employed in triplestores such as ubergraph and ontobee.

In particular, ubergraph uses the relation-graph inference tool to pre-compute inferred direct triples from TBox existential axioms, allowing for simple and powerful queries over inferred ontologies

See also

This was inspired in part by the powerful but arcane sparqlprog system

TODOs

  • Better Document
    • framework
    • templates
    • How-tos for use with Python, SHACL, ...
    • exemplar notebooks
  • Unify with SQL/rdftab functionality in semantic-sql
  • Split into bio-specific
  • Expose more ubergraph awesomeness
  • FastAPI/serverless endpoint
  • Expose more validatin
  • Integrate visualization / obographviz
  • Chaining
    • inject output from one into another and merge results, e.g. to get labels
    • similar to wikidata services
  • Templates for
    • uniprot
    • gocams
    • wikidata
You might also like...
Hydralit package is a wrapping and template project to combine multiple independant Streamlit applications into a multi-page application.
Hydralit package is a wrapping and template project to combine multiple independant Streamlit applications into a multi-page application.

Hydralit The Hydralit package is a wrapping and template project to combine multiple independant (or somewhat dependant) Streamlit applications into a

A parallel branch-and-bound engine for Python.

pybnb A parallel branch-and-bound engine for Python. This software is copyright (c) by Gabriel A. Hackebeil (gabe.hacke

XlvnsScriptTool -  Tool for decompilation and compilation of scripts .SDT from the visual novel's engine xlvns
XlvnsScriptTool - Tool for decompilation and compilation of scripts .SDT from the visual novel's engine xlvns

XlvnsScriptTool English Dual languaged (rus+eng) tool for decompiling and compiling (actually, this tool is more than just (dis)assenbler, but less th

Python Project Template

A low dependency and really simple to start project template for Python Projects.

Simple logger for Urbit pier size, with systemd timer template

urbit-piermon Simple logger for Urbit pier size, with systemd timer template. Syntax piermon.py -i [PATH TO PIER] -o [PATH TO OUTPUT CSV] systemd serv

Python template for Advent of Code event

Advent of Code Python Starter A tamplate for Advent of Code write in Python. Usage The project use poetry for project manager. Clone this repository a

This is the Code Institute student template for Gitpod.
This is the Code Institute student template for Gitpod.

Welcome AnaG0307, This is the Code Institute student template for Gitpod. We have preinstalled all of the tools you need to get started. It's perfectl

Template (v0) do Sistema Chatbot - atividade síncrona - INE5404
Template (v0) do Sistema Chatbot - atividade síncrona - INE5404

ine-5404-sistema-chatbot-template Template (v0) do Sistema Chatbot - atividade síncrona - INE5404 Veja abaixo um exemplo de funcionamento do sistema:

NotesToCommands - a fully customizable notes / command template program, allowing users to instantly execute terminal commands

NotesToCommands is a fully customizable notes / command template program, allowing users to instantly execute terminal commands with dynamic arguments grouped into sections in their notes/files. It was originally created for pentesting uses, to avoid the needed remembrance and retyping of sets of commands for various attacks.

Comments
  • Github Action that runs the test suite

    Github Action that runs the test suite

    Similar to the exemplar linkml-runtime repo, added a main.yaml github action that runs the test suite and generates coverage reports. Once this PR has been merged in, we can create the initial release to PyPI.

    opened by sujaypatil96 0
  • Refresh docs

    Refresh docs

    The old Ubergraph endpoint is referenced in the published docs, but I think it's correct in the source. See https://github.com/INCATools/ubergraph/issues/73

    opened by balhoff 0
Releases(v0.2.1)
  • v0.2.1(Apr 30, 2022)

    What's Changed

    • support for local rdf graphs by @cmungall in https://github.com/linkml/sparqlfun/pull/6

    Full Changelog: https://github.com/linkml/sparqlfun/compare/v0.2.0...v0.2.1

    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Apr 28, 2022)

    What's Changed

    • missing line that is not updating pypi version by @sujaypatil96 in https://github.com/linkml/sparqlfun/pull/3
    • refactor-docs by @cmungall in https://github.com/linkml/sparqlfun/pull/4
    • endpoint docs by @cmungall in https://github.com/linkml/sparqlfun/pull/5

    New Contributors

    • @cmungall made their first contribution in https://github.com/linkml/sparqlfun/pull/4

    Full Changelog: https://github.com/linkml/sparqlfun/compare/v0.1.3...v0.2.0

    Source code(tar.gz)
    Source code(zip)
  • v0.1.3(Jan 15, 2022)

    What's Changed

    • Github Action responsible for automatically publishing PyPI releases by @sujaypatil96 in https://github.com/linkml/sparqlfun/pull/2

    Full Changelog: https://github.com/linkml/sparqlfun/compare/v0.1.2...v0.1.3

    Source code(tar.gz)
    Source code(zip)
  • v0.1.2(Jan 15, 2022)

    What's Changed

    • First official release of the package on PyPI
    • Github Action that runs the test suite by @sujaypatil96 in https://github.com/linkml/sparqlfun/pull/1

    New Contributors

    • @sujaypatil96 made their first contribution in https://github.com/linkml/sparqlfun/pull/1

    Full Changelog: https://github.com/linkml/sparqlfun/compare/v0.1.1...v0.1.2

    Source code(tar.gz)
    Source code(zip)
  • v0.1.1(Jan 11, 2022)

  • v0.1.0(Jan 11, 2022)

Owner
Linked data Modeling Language
LinkML is a general purpose modeling language that can be used with linked data, JSON, and other formalisms
Linked data Modeling Language
A funny alarm clock I made in python

Wacky-Alarm-Clock Basically, I kept forgetting to take my medications, so I thought it would be a fun project to code my own alarm clock and make it r

1 Nov 18, 2021
An Advanced Wordlist Library Written In Python For Acm114

RBAPG -RBAPG is the abbreviation of "Rule Based Attack Password Generator". -This module is a wordlist generator module. -You can generate randomly

Aziz Kaplan 11 Aug 28, 2022
Binjago - Set of tools aiding in analysis of stripped Golang binaries with Binary Ninja

Binjago 🥷 Set of tools aiding in analysis of stripped Golang binaries with Bina

W3ndige 2 Jul 23, 2022
Load, explore and analyse data from Scotland and rest of the world related to Covid19.

Streamlit Examples This is my first attempt with Streamlit. It is an open-source framework, free, Python-based and easy to use tool to build and deplo

Eyad Elyan 12 Mar 01, 2021
A minimal configuration for a dockerized kafka project.

Docker Kafka Quickstart A minimal configuration for a dockerized kafka project. Usage: Run this command to build kafka and zookeeper containers, and c

Nouamane Tazi 5 Jan 12, 2022
Module 2's katas from Launch X's python introduction course.

Module2Katas Module 2's katas from Launch X's python introduction course. Virtual environment creation process (on Windows): Create a folder in any de

Javier Méndez 1 Feb 10, 2022
Solutions to the language assignment for Internship in JALA Technologies.

Python Assignment Solutions (JALA Technologies) Solutions to the language assignment for Internship in JALA Technologies. Features Properly formatted

Samyak Jain 2 Jan 17, 2022
aaencode for python,把python代码转换为颜文字

py-aaencode aaencode for python,把python代码转换为颜文字 compile.py: 将python编译成颜文字,编译结果有随机性,可以选择BPE词表压缩代码 compile_min.py: 最小化的编译器 compiled_min.txt: 编译得到的最小的com

11 Dec 30, 2021
适用于HoshinoBot下的人生重来模拟器插件

LifeRestart for HoshinoBot 原作地址 python版原地址 本项目地址 安装方法 这是一个HoshinoBot的人生重来模拟器插件 这个项目使用的HoshinoBot的消息触发器,如果你了解其他机器人框架的api(比如nonebot)可以只修改消息触发器就将本项目移植到其他

黛笙笙 16 Sep 03, 2022
Pampy: The Pattern Matching for Python you always dreamed of.

Pampy: Pattern Matching for Python Pampy is pretty small (150 lines), reasonably fast, and often makes your code more readable and hence easier to rea

Claudio Santini 3.5k Dec 30, 2022
Shopify Backend Developer Intern Challenge - Summer 2022

Shopify Backend Developer Intern The task is build an inventory tracking web application for a logistics company. The detailed task details can be fou

Meet Gandhi 11 Oct 08, 2022
Given tool find related trending keywords of input keyword

blog_generator Given tool find related trending keywords of input keyword (blog_related_to_keyword). Then cretes a mini blog. Currently its customised

Shivanshu Srivastava 2 Nov 30, 2021
Python script for the radio in the Junior float.

hoco radio 2021 Python script for the radio in the Junior float. Populate the ./music directory with 2 or more .wav files and run radio2.py. On the Ra

Kevin Yu 2 Jan 18, 2022
A data engineering project with Kafka, Spark Streaming, dbt, Docker, Airflow, Terraform, GCP and much more!

Streamify A data pipeline with Kafka, Spark Streaming, dbt, Docker, Airflow, Terraform, GCP and much more! Description Objective The project will stre

Ankur Chavda 206 Dec 30, 2022
A Python tool to check ASS subtitles for common mistakes and errors.

A Python tool to check ASS subtitles for common mistakes and errors.

1 Dec 18, 2021
A webapp for taking fast notes, designed for business, school, and collaboration with groups.

JOTS Journal of the Session A webapp for taking fast notes, designed for business, school, and collaboration with groups.

Zebadiah S. Taylor 2 Jun 10, 2022
A simple python project which control paint brush in microsoft paint app

Paint Buddy In Python A simple python project which control paint brush in micro

Ordinary Pythoneer 1 Dec 27, 2021
This is a fork of the BakeTool with some improvements that I did to have better workflow.

blender-bake-tool This is a fork of the BakeTool with some improvements that I did to have better workflow. 99.99% of work was done by BakeTool team.

Acvarium 3 Oct 04, 2022
A simple but fully functional calculator that will take multiple operations.

Functional-Calculator A simple but fully functional calculator that will take multiple operations. Usage Run the following command through terminal: p

Uzziel Ariel 1 Dec 22, 2022
Todos os exercícios do Curso de Python, do canal Curso em Vídeo, resolvidos em Python, Javascript, Java, C++, C# e mais...

Exercícios - CeV Oferecido por Linguagens utilizadas atualmente O que vai encontrar aqui? 👀 Esse repositório é dedicado a armazenar todos os enunciad

Coding in Community 43 Nov 10, 2022