Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/vladimiralexiev/soml

Semantic Objects Modeling Language
https://github.com/vladimiralexiev/soml

Last synced: 2 months ago
JSON representation

Semantic Objects Modeling Language

Awesome Lists containing this project

README

        

Semantic Objects Modeling Language

#content { max-width: 60em; margin: auto; }
.title { text-align: center;
margin-bottom: .2em; }
.subtitle { text-align: center;
font-size: medium;
font-weight: bold;
margin-top:0; }
.todo { font-family: monospace; color: red; }
.done { font-family: monospace; color: green; }
.priority { font-family: monospace; color: orange; }
.tag { background-color: #eee; font-family: monospace;
padding: 2px; font-size: 80%; font-weight: normal; }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.org-right { margin-left: auto; margin-right: 0px; text-align: right; }
.org-left { margin-left: 0px; margin-right: auto; text-align: left; }
.org-center { margin-left: auto; margin-right: auto; text-align: center; }
.underline { text-decoration: underline; }
#postamble p, #preamble p { font-size: 90%; margin: .2em; }
p.verse { margin-left: 3%; }
pre {
border: 1px solid #e6e6e6;
border-radius: 3px;
background-color: #f2f2f2;
padding: 8pt;
font-family: monospace;
overflow: auto;
margin: 1.2em;
}
pre.src {
position: relative;
overflow: auto;
}
pre.src:before {
display: none;
position: absolute;
top: -8px;
right: 12px;
padding: 3px;
color: #555;
background-color: #f2f2f299;
}
pre.src:hover:before { display: inline; margin-top: 14px;}
/* Languages per Org manual */
pre.src-asymptote:before { content: 'Asymptote'; }
pre.src-awk:before { content: 'Awk'; }
pre.src-authinfo::before { content: 'Authinfo'; }
pre.src-C:before { content: 'C'; }
/* pre.src-C++ doesn't work in CSS */
pre.src-clojure:before { content: 'Clojure'; }
pre.src-css:before { content: 'CSS'; }
pre.src-D:before { content: 'D'; }
pre.src-ditaa:before { content: 'ditaa'; }
pre.src-dot:before { content: 'Graphviz'; }
pre.src-calc:before { content: 'Emacs Calc'; }
pre.src-emacs-lisp:before { content: 'Emacs Lisp'; }
pre.src-fortran:before { content: 'Fortran'; }
pre.src-gnuplot:before { content: 'gnuplot'; }
pre.src-haskell:before { content: 'Haskell'; }
pre.src-hledger:before { content: 'hledger'; }
pre.src-java:before { content: 'Java'; }
pre.src-js:before { content: 'Javascript'; }
pre.src-latex:before { content: 'LaTeX'; }
pre.src-ledger:before { content: 'Ledger'; }
pre.src-lisp:before { content: 'Lisp'; }
pre.src-lilypond:before { content: 'Lilypond'; }
pre.src-lua:before { content: 'Lua'; }
pre.src-matlab:before { content: 'MATLAB'; }
pre.src-mscgen:before { content: 'Mscgen'; }
pre.src-ocaml:before { content: 'Objective Caml'; }
pre.src-octave:before { content: 'Octave'; }
pre.src-org:before { content: 'Org mode'; }
pre.src-oz:before { content: 'OZ'; }
pre.src-plantuml:before { content: 'Plantuml'; }
pre.src-processing:before { content: 'Processing.js'; }
pre.src-python:before { content: 'Python'; }
pre.src-R:before { content: 'R'; }
pre.src-ruby:before { content: 'Ruby'; }
pre.src-sass:before { content: 'Sass'; }
pre.src-scheme:before { content: 'Scheme'; }
pre.src-screen:before { content: 'Gnu Screen'; }
pre.src-sed:before { content: 'Sed'; }
pre.src-sh:before { content: 'shell'; }
pre.src-sql:before { content: 'SQL'; }
pre.src-sqlite:before { content: 'SQLite'; }
/* additional languages in org.el's org-babel-load-languages alist */
pre.src-forth:before { content: 'Forth'; }
pre.src-io:before { content: 'IO'; }
pre.src-J:before { content: 'J'; }
pre.src-makefile:before { content: 'Makefile'; }
pre.src-maxima:before { content: 'Maxima'; }
pre.src-perl:before { content: 'Perl'; }
pre.src-picolisp:before { content: 'Pico Lisp'; }
pre.src-scala:before { content: 'Scala'; }
pre.src-shell:before { content: 'Shell Script'; }
pre.src-ebnf2ps:before { content: 'ebfn2ps'; }
/* additional language identifiers per "defun org-babel-execute"
in ob-*.el */
pre.src-cpp:before { content: 'C++'; }
pre.src-abc:before { content: 'ABC'; }
pre.src-coq:before { content: 'Coq'; }
pre.src-groovy:before { content: 'Groovy'; }
/* additional language identifiers from org-babel-shell-names in
ob-shell.el: ob-shell is the only babel language using a lambda to put
the execution function name together. */
pre.src-bash:before { content: 'bash'; }
pre.src-csh:before { content: 'csh'; }
pre.src-ash:before { content: 'ash'; }
pre.src-dash:before { content: 'dash'; }
pre.src-ksh:before { content: 'ksh'; }
pre.src-mksh:before { content: 'mksh'; }
pre.src-posh:before { content: 'posh'; }
/* Additional Emacs modes also supported by the LaTeX listings package */
pre.src-ada:before { content: 'Ada'; }
pre.src-asm:before { content: 'Assembler'; }
pre.src-caml:before { content: 'Caml'; }
pre.src-delphi:before { content: 'Delphi'; }
pre.src-html:before { content: 'HTML'; }
pre.src-idl:before { content: 'IDL'; }
pre.src-mercury:before { content: 'Mercury'; }
pre.src-metapost:before { content: 'MetaPost'; }
pre.src-modula-2:before { content: 'Modula-2'; }
pre.src-pascal:before { content: 'Pascal'; }
pre.src-ps:before { content: 'PostScript'; }
pre.src-prolog:before { content: 'Prolog'; }
pre.src-simula:before { content: 'Simula'; }
pre.src-tcl:before { content: 'tcl'; }
pre.src-tex:before { content: 'TeX'; }
pre.src-plain-tex:before { content: 'Plain TeX'; }
pre.src-verilog:before { content: 'Verilog'; }
pre.src-vhdl:before { content: 'VHDL'; }
pre.src-xml:before { content: 'XML'; }
pre.src-nxml:before { content: 'XML'; }
/* add a generic configuration mode; LaTeX export needs an additional
(add-to-list 'org-latex-listings-langs '(conf " ")) in .emacs */
pre.src-conf:before { content: 'Configuration File'; }

table { border-collapse:collapse; }
caption.t-above { caption-side: top; }
caption.t-bottom { caption-side: bottom; }
td, th { vertical-align:top; }
th.org-right { text-align: center; }
th.org-left { text-align: center; }
th.org-center { text-align: center; }
td.org-right { text-align: right; }
td.org-left { text-align: left; }
td.org-center { text-align: center; }
dt { font-weight: bold; }
.footpara { display: inline; }
.footdef { margin-bottom: 1em; }
.figure { padding: 1em; }
.figure p { text-align: center; }
.equation-container {
display: table;
text-align: center;
width: 100%;
}
.equation {
vertical-align: middle;
}
.equation-label {
display: table-cell;
text-align: right;
vertical-align: middle;
}
.inlinetask {
padding: 10px;
border: 2px solid gray;
margin: 10px;
background: #ffffcc;
}
#org-div-home-and-up
{ text-align: right; font-size: 70%; white-space: nowrap; }
textarea { overflow-x: auto; }
.linenr { font-size: smaller }
.code-highlighted { background-color: #ffff00; }
.org-info-js_info-navigation { border-style: none; }
#org-info-js_console-label
{ font-size: 10px; font-weight: bold; white-space: nowrap; }
.org-info-js_search-highlight
{ background-color: #ffff00; color: #000000; font-weight: bold; }
.org-svg { }

#content {max-width: 120em; margin: auto} h1,h2,h3,h4,h5,h6,h7 {font-family: Arial} .author, .date, .creator {-webkit-margin-before: 0em; -webkit-margin-after: 0em} .abstract {margin: 1em; padding: 1em; border: 1px solid black} .abstract:before {content: 'Abstract: '; font-weight: bold} #preamble p {font-size: 110%%; margin-left: auto; margin-right: auto; text-align: center} th.org-left {text-align:left} th.org-right {text-align:right} th.org-center {text-align:center} th, td {line-height: 1em; border-width: 1px; border-style: solid solid; border-spacing: 2px 2px; padding: 2px 1px} .CANCELED {color: blue} .MAYBE {color: blue} .POSTPONED {color: blue} .SAME {color: blue} .APPLIED {color: orange} .FOLLOW {color: orange} .INPROGRESS {color: orange} .NEXT {color: orange} .IER {color: orange}.underline {text-decoration:underline}


Author: Vladimir Alexiev ([email protected])


Date: 2024-10-14




Semantic Objects Modeling Language



Table of Contents





(You can read this rendered by github or rendered as HTML)


Intro




The Semantic Objects Modeling Language (SOML)
is a simple YAML-based language for describing business objects (business entities, domain objects)
that are handled using semantic technologies and GraphQL.
SOML is the language of the Ontotext Platform.


The Ontotext Platform helps create knowledge graphs in an easier way,
both using and enabling text analytics to interlink and enrich knowledge graphs,
and enabling better search, exploration, classification, and recommendation across diverse information spaces.


Version 3.0 of the Platform was released at the end of 2019 and is under active develoment and evolution.



This blog goes in-depth on SOML:
motivates the use of SOML,
describes some tricky points of SOML usage and GraphQL deficiencies,
and introduces some SOML tooling for
generating SOML (tsv2soml) and mapping RDF data (soml-map)



Why SOML?




We often are asked why we had to introduce yet another object modeling language?
Why didn't we use existing semantic web mechanisms such as
ontologies (RDFS or OWL) or shapes (SHACL or SHEX),
or schema mechanisms such as GraphQL schema, JSON schema and the like?
The answer is multi-fold:



Semantic models are more than ontologies

Every sizable semantic project (and many LOD datasets) use a number of ontologies together.
While ontologies describe the vocabulary of classes and properties to use,
extra mechanisms are required to describe how these elements are put together,
and what are the data expectations about different kinds of nodes in the graph.
One could do some of that with ontologies,
e.g. use OWL property cardinalities,
complex OWL classes to define polymorphic domains and ranges,
and XSD datatype constructions to describe literal patterns.
However, the inferential rather than validation semantics of RDFS and OWL
and their inherent complexity
have led people to use application profiles and RDF shapes instead.

Lack of standardization

While there are several implementations of GraphQL querying over RDF,
each of them does it in a different way and there is no standardization.
The TopQuadrant GraphQL to SHACL mapping comes close to using
SHACL for generating GraphQL schemas, but still uses custom extensions.
Definitive mappings between SHACL and SHEX are not available.
The Bridging GraphQL and RDF W3C Community Group has been launched (Jan 2020)
with the mission to close this gap,
and hopefully define standard mappings/crosswalks between SHACL, SHEX and
GraphQL schemas and validation mechanisms.
We plan to participate actively in this group.

Freedom to innovate

Our ambition is for the Ontotext platform to cover a wide variety of enterprise features.
To be able to develop them at our own pace, we need a language where we can add such innovations.
Examples include
data validation based on RDF shapes (generated from SOML);
Role-Based Access Control (RBAC);
faceting, autocompletion and full-text search;
aggregation;
distribution of data to various stores through GraphDB Connectors and/or GraphQL Federation.

Technology independence

Flowing from the previous reason, we'd like SOML to be technology-independent to some degree.
While we don't aim for a theoretical develpment that lives in a technological vacuum,
we need to be able to generate a number of technical artefacts from the same business-level model.




Similar Schema Languages




A number of schema languages have appeared recently that are based on YAML,
express business-level object models that are somewhat independent of technological choices,
and can render the models to a variety of schema technologies:




What is SOML




At present SOML is very simple, but will evolve to include more features.
The overall structure of a SOML file (schema) is shown below.


# comment

id: /soml/<identifier>
label: some name
created: yyyy-mm-dd
updated: yyyy-mm-dd
creator: name and/or URL
versionInfo: version

# comment
specialPrefixes:
base_iri: <base>
vocab_iri: <vocab>
vocab_prefix: <voc>
ontology_iri: <ontology>
shape_iri: <shape>
prefixes:
<pfx>: <namespace>

# datatypes
types:
<type>: {rdf: <xsd-type>, graphql: <GQL-type>, descr: "...", graphqlExtension: <boolean>}
<union-type>: {union: [<type>...], graphql: <GQL-type>, descr: "..."}

# common property definitions
properties:
<prop>: {label: "...", descr: "...", range: <datatype|Obj>, rangeCheck: <boolean>, typeCast: <boolean>,
kind: (object|literal|mixed), min: <default 0>, max: <default 1>,
inverseAlias: <prop>, inverse: <prop>, rdfProp: pfx:prop, symmetric: <boolean>, regex: '<regex>', prefix: "<string>"}

# object class definitions
objects:
<Obj>: {label: "...", descr: "...", regex: '<regex>', prefix: "<string>",
typeProp: <prop>, type: [<iri>...], name: <prop>, inherits: <Obj>, kind: (abstract|supertype)}
props:
<prop>: ...



From this schema the Platform generates a complex GraphQL schema
including a fairly complete querying language that allows you to
find any kind of object, filter, order, navigate through the KG,
and do pagination (limit, offset).


You can find details in the SOML documentation, while below we describe
some tricky points of SOML usage and GraphQL deficiencies, and some tooling.





Complex Schema (Company Graph)




To introduce the proper context for this blog (working with complex SOML schemas),
we'll describe the Ontotext Company Graph (ONTO CG) ontology and model.
It's a medium-high complexity data model that reuses 14 ontologies and adds classes and props of its own.
Of its 24 classes and 150 props, about half are reused and half are created especially for CG.
It's fairly typical data model for the kind of projects that Ontotext deals with.


Creating the ONTO CG knowledge graph is part of
the Intelligent Matching and Linking of Company Data (CIMA) research project.
We are integrating data from open and a few proprietary datasets. The emphasis of the project is on financial transactions, industrial classification, company size/importance observations (e.g. annual sales, number of employees), etc.


The following table shows the count of classes and properties defined by the ONTO-CG ontology, as well as those reused from other ontologies.

Table 1: Ontology reuse and extension in Ontotext Company Graph.

Prefix
Ontology
Classes
Props

cg
Ontotext Company Graph
12
70

adms
Asset Description Metadata Schema
1
1

dcat
Data Catalog Vocabulary
 
3

dct
Dublin Core Terms
 
8

ebg
euBusinessGraph
1
12

gn
GeoNames
1
9

locn
W3C Location Ontology
1
8

org
W3C Core Organization Ontology
1
5

qb
W3C Cube Ontology
1
1

rov
W3C Registered Organization
1
4

schema
Schema.org
3
12

skos
Simple Knowledge Organization System
1
6

time
W3C Time Ontology
 
2

void
Vocabulary of Interlinked Datasets
1
7

wgs84
World Geodetic Survey
 
2

 
 
24
150


ONTO CG builds upon the results of the euBusinessGraph project.
The euBusinessGraph semantic model and dataset covers the following
(we have submitted a description of it to a prominent journal on semantic technologies):



  • Basic firmography (legal names, preferred name)

  • Basic person info

  • Geography, address, hieararchical administrative divisions

  • Company legal type and status

  • Industry classification (based on NACE)

  • Identifiers from Official registers and others

  • Company officers and directors (positions, using org:Membership)

  • Datasets, providers, dataset descriptions


ONTO-CG steps on the euBusinessGraph model and adds the following:



  • IdentifierSystems: We extend the euBusinessGraph idea of generalized identifiers to record any kind of potentially useful identification info in a generic way: phone, email, website, blog, logo/image; profile links and identifiers in various external systems such as: Wikidata, DBpedia, Facebook, LinkedIn, Twitter, Youtube, Reddit, Github, CrunchBase, OpenCorporates, Thomson Reuters permid (TR), ISO 10383 Market Identifier Code (MIC); research-oriented identifiers such as CrossRef funder, Microsoft Academic Graph, Global Research Identifier Database (GRID), Research Organization Registry (ROR), Virtual International Authority File (VIAF).


  • cg:StockExchange: a Stock exchange where companies can offer shares or other securities. We record MIC and TR exchange codes as identifiers.


  • cg:Event and cg:EventAppearance: Conference, workshop, meetup, etc where the work of a certain person or company may be highlighted.


  • gn:Feature: While the euBusinessGraph geographic hierarchy is based on EuroStat NUTS and LAU, ONTO-CG uses Geonames locations to implement geographic matching, auto-completion and faceting. We are particularly interested in the 3 levels Country, Region, City that we have defined as particular lists of gn:featureCodes (e.g. Country corresponds to gn:A.PCLI, gn:A.PCLD, gn:A.PCLIX, gn:A.PCLS, gn:A.PCL, gn:A.TERR, gn:A.PCLF).


  • cg:AcademicQualification: Academic degree (completed or not) of a person at a scholl in an academic major.


  • qb:Observation: Statistical or other observation about an object (typically company), such as annual sales, number of employees, etc. May be for a particular year, point in time, or without date (current).


  • cg:Transaction: Financial transaction that gives money to a company in return for shares or other consideration.


  • cg:OrganizationRelation: Relation between two agents. For asymmetric relations we use two fields "agentMinor" (e.g. subsidiary, owned, supplier) and "agentMajor" (e.g. parent, owner, customer); for symmetric relations we use the field "agent" twice. Usually these are Organizations, but "owner" could involve Persons.

  • Sourcing (provenance) for each node:


    • void:Dataset: Dataset as source of entities


    • void:Linkset: Linkset as source of identifiers (links)


    • cg:SourceMatch: Cluster of matched lower-level entities as the source of a higher-level entity.




In addition to the above new classes, ONTO-CG adds:



  • A 2-level data model where data from individual datasets sits at a lower (KG-building) level, and after matching and data fusion is promoted at a higher (data consumption) level.

  • Various extra fields, e.g. cg:geoPrecision "Precision of geo coordinates in meters (e.g. street address or building -> 30.8)" to complement ebg:geoResolution "Resolution of geo coordinates as a categorial value (e.g. building -> <resolution/L9>)"

  • Various flags, e.g. for Organization (cg:isResearch), Position (cg:isCurrent, cg:isPrimary), AcademicQualification (cg:isCompleted), ExchangeListing, OrganizationRelation (cg:isCurrent)

  • Business nomenclatures (skos:ConceptScheme): Organization Type, Legal Form, Organization Status, Industry, Investor Type, Geo Coordinate Resolution, Address Type, Observation Type, Gender, Event Type, Event Appearance Type, Position Type, Transaction Type, Relation Type


The full CG schema is included: CG.yaml. Below we show a couple of typical examples.



Example Class




ExchangeListing:

label: "Exchange Listing"
inherits: Transaction
type: [cg:ExchangeListing]
descr: "Public offering (IPO, SPO etc) wheres the company receives money from the wide public, and as a result is listed for trading on an exchange"
props:
exchange:
label: "exchange"
range: StockExchange
min: 1
rdfProp: cg:exchange
descr: "Stock exchange"
stockSymbol:
label: "stock symbol"
range: string
rdfProp: cg:stockSymbol
descr: "Stock symbol (ticker). TODO: this should also be represented as an Identifier?"
valuation:
label: "valuation (MUSD)"
range: decimal
rdfProp: cg:valuation
descr: "Company valuation at IPO in MUSD"
valuationLocal:
label: "valuation (M local currency)"
range: decimal
rdfProp: cg:valuationLocal
descr: "Company valuation at IPO in millions of local currency"
valuationCurrency:
label: "valuation currency"
range: string
rdfProp: cg:valuationCurrency
descr: "Currency code of the valuation"
dateEnd:
descr: "Date delisted or left this exchange"
isCurrent:
rdfProp: cg:isCurrent
descr: "Whether the listing is still effective"


If you look closely, you may wonder where the range and RDF mapping of dateEnd is defined.
It's in the list of reusable properties:


properties: # reused props

dateEnd: {label: "dateCompleted", range: dateOrYearOrMonth, rdfProp: cg:dateEnd}


A more appropriate descr is given at the object level, overriding the generic description.




Example Inverse Alias




A Position is an associative node between Person and Organization that adds more data (not shown):



Position:

label: "Position"
inherits: BusinessObject
type: [org:Membership]
descr: "Position of a person in an organization, former or current"
props:
person: {label: "person", range: PersonCommon, min: 1, rdfProp: org:member}
organization: {label: "organization", range: OrganizationCommon, min: 1, rdfProp: org:organization}


To allow navigation in any direction (not just from Position out, but also in), we add inverse aliases:


PersonCommon:

props:
position: {label: "position", range: Position, inverseAlias: person}
OrganizationCommon:
props:
position: {label: "position", range: Position, inverseAlias: organization}




Example Diagram: Exchange Listing SOML




For example, the figure below shows the stock exchange listing (IPO) of Apple on the Tokyo exchange and NASDAQ, and the listing of Nasdaq Inc (the company) on NASDAQ (the stock exchange).



  • The data is integrated from Wikidata.

  • This figure is generated from RDF Turtle using rdfpuml (see V.Alexiev, RDF by Example: rdfpuml for True RDF Diagrams, rdf2rml for R2RML Generation, Semantic Web in Libraries (SWIB), Nov 2016.

  • This version of the diagram uses original SOML (GraphQL) property and class names, i.e. all of them share the same namespace (expressed using the empty) prefix.

  • It can be considered as a "logical" data model of how data should be queried with GraphQL


./eg/model-exchange-listing.ttl


model-exchange-listing.png





Example Diagram: Exchange Listing RDF




This version of the diagram uses soml-map to map SOML names to RDF names in specific namespaces.



  • So this can be considered the "physical" data model of data as it's stored in the semantic database


./eg/model-exchange-listing-mapped.ttl


model-exchange-listing-mapped.png






SOML Tooling




owl2soml




This tool (written in Perl) generates SOML schemas from ontologies (that use RDFS, OWL and/or schema.org constructs).
It handles numerous features and has been integrated in the Ontotext Platform (reimplemented in Java).
See its own README.




tsv2soml




Editing large schemas is often easier to do in a table, even when the schema language is simple.
(Also, this enables domain experts to participate in schema authoring, even if only editing the descriptions.)


The CG model was not written by hand, it was generated from a TSV (google sheet).


The sheet has 300 rows, and the generated SOML is 1176 lines.
Here's the beginning of the sheet:


CG-sheet.png



Here is the end of the sheet, which exposes various thesauri (ConceptSchemes)
as distinct business classes


CG-sheet2.png



To generate a SOML schema from the google sheet CG-data-model, call it like this:



curl -s "https://docs.google.com/spreadsheets/d/1_-bn9Y-9rtysnvKiVus6BkFKXqHhiV4vCjYeiRmb6XU/export?format=tsv" | perl tsv2soml.pl | cat CG-preamble.yaml - > CG.yaml


Here CG-preamble.yaml is some fixed SOML metadata (a header).


Options:




  • -p: don't emit pattern (this feature restricts URLs to a certain pattern)


  • -l: downgrade Literals: stringOrLangString, langString -> string, dateOrYearOrMonth -> date.
    This can be used to simplify the schema not to use langString and union datatypes


Comment lines start with hash (#) in the first column




  • # HEADER: if there is a space after the hash, the first cell is printed surrounded by newlines


  • #commented out: if there is no space, the whole line is skipped



Reusing Property Characteristics




  • The script counts how many times each prop is used in objects

  • For props used more than once, the script emits the first occurrence of each prop
    in the common properties section:



properties: # reused props




  • This allows you to omit common details (eg label, descr, range) on subsequent occurrences

  • But it also means that characteristics given in the first occurrence override the defaults
    for subsequent occurrences, which may lead to unintended consequences.


Consider a SOML based on schema.org where we allow multiple sameAs values
(e.g. the item's Wikipedia page, Wikidata entry, Linkedin profile, YouTube profile, etc),
and want the field to be mandatory for Organization but optional for Person.


We write the details on the first occurrence and then just mention the prop on the second occurrence:

Class/prop
label
Inherits/range
char
descr

Organization
 
 
 
 

sameAs
same as
iri
min: 1, max: inf
URL that unambiguously indicates the thing's identity

Person
 
 
 
 

sameAs
 
 
 
 


This results in a SOML like this:



objects:

Organization:
props:
sameAs:
range: iri
min: 1
max: inf
descr: URL that unambiguously indicates the thing's identity
Person:
props:
sameAs:
properties: # reused props
sameAs:
range: iri
min: 1
max: inf
descr: URL that unambiguously indicates the thing's identity



The prop characteristics are copied from properties into Person.props,
which means that the default cardinality min: 0 is overridden by min: 1,
which doesn't match the requirement "optional for Person".


To fix this, you need to specify min: 0 explicitly in the Person.sameAs table row.





soml-map




tsv2soml writes out a file soml-map.tsv (see exmaple soml-map.tsv) with columns "class, prop (optional), rdf"



  • For props without RDF value, it uses the RDF name from the shared first occurrence of the same prop name


It can be used to map from SOML names to RDF names (class/prop URLs) in specific namespaces.
Eg compare Example Diagram: Exchange Listing SOML vs Example Diagram: Exchange Listing RDF.


It can be used to map examples (models) or conversion scripts (TARQL, or SPARQL Update for OpenRefine)
from a "logical" representation using uniform GraphQL names
to a "physical" representaiton using specific RDF names.


Usage:



perl soml-map.pl < file.(tarql|ru|ttl) > file-mapped.(tarql|ru|ttl)



soml-simplify




The purpose of this script is to simplify a SOML entity schema significantly,
so it can be communicated more easily to LLM for querying (NLQ to GraphQL).


Note: we need to preserve abstract classes (interfaces) because:



  • This saves on the description of common props.
    We don't expand props inherited from superclasses, but hope that LLM can track this

  • Sometimes the range of a prop is an abstract class


A draft script was made by GPT-4 following the specfication below, then improved by me.



  • Make a perl script soml-simplify.pl to simplify a YAML object schema, as shown in the Examples below

  • Give me only code, not any explanations

  • Use an appropriate CPAN module like YAML or YAML::PP

  • Use properties to collect global prop characteristics, then combine with per-object props definitions

  • Render only objects, skip all other major sections

  • Render inherits, props, range directly, not as YAML sub-objects

  • The default range is string

  • The default is max: 1. If a prop has a greater max cardinality, show it as array: [...]

  • Omit descriptions and other characteristics



Example Source (SOML schema)




objects:

AccumulatorReset:
descr: This command reset the counter value to zero
inherits: ControlInterface
label: AccumulatorReset
props:
accumulatorReset.AccumulatorValue: {}
type: cim:AccumulatorReset
ControlInterface:
descr: Abstract superclass of Control
inherits: IdentifiedObjectInterface
kind: abstract
search: {nested: true}
props:
control.PowerSystemResource: {}
properties:
accumulatorReset.AccumulatorValue:
descr: The accumulator value that is reset by the command
inverseOf: accumulatorValue.AccumulatorReset
kind: object
label: AccumulatorValue
max: 1
min: 1
range: AccumulatorValue
rdfProp: cim:AccumulatorReset.AccumulatorValue
control.PowerSystemResource:
descr: 'The controller outputs used to...'
inverseOf: powerSystemResource.Controls
kind: object
label: PowerSystemResource
max: inf
min: 0
range: PowerSystemResourceInterface
rdfProp: cim:Control.PowerSystemResource





Example Target (Simplified)




AccumulatorReset:

ISA: ControlInterface
accumulatorReset.AccumulatorValue: AccumulatorValue
ControlInterface:
ISA: IdentifiedObjectInterface
control.PowerSystemResource: [PowerSystemResourceInterface]





tsv2owl




This tool uses the same sheets that drive tsv2soml to generate an OWL ontology.
It works like this:



  • Generates term definitions from the sheet

  • Prepends a preamble

  • Formats the result with Jena riot or update

  • Sorts the file by term (Turtle block: such "paragraphs" are separated by a double newline)



Ontology Preamble




Use an ontology preamble, eg like this otkg-preamble.ttl.
Include all "system" prefixes that are shown after the newline (in particular, use s: instead of schema:)!



@prefix otkg:   <https://kg.ontotext.com/resource/ontology/>.

@prefix s: <http://schema.org/> .

@prefix dct: <http://purl.org/dc/terms/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix s: <http://schema.org/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

otkg: a owl:Ontology ;
rdfs:label "OTKG Ontology" ;
dct:created "2023-01-25"^^xsd:date ;
dct:creator <http://ontotext.com> ;
owl:versionInfo "1.0" .





tsv2owl Options




It has these options.





  • -v: default namespace for classes and props that don't have a specific URL in the RDF column.



    • By default is the empty prefix : (you must define this prefix in the preamble).



    For example, for the Ontotext KG (OTKG), we use -v s: -o otkg: i.e. schema.org (s:) as vocabulary namespace but otkg: as the ontology URL. Then eg:




    • keywords will be emitted as s:keywords because it doesn't have an RDF value


    • buyersJourney will be emitted as otkg:buyersJourney because that is its RDF value




  • -o:: ontology URL (optional).

    • Should match the owl:Ontology that you use in the preamble

    • Can be a prefixed URL (eg otkg:, in this case the URL has a slash at the end)
      or a full URL (eg https://kg.ontotext.com/resource/ontology without slash at the end)

    • For each term (class and prop), adds rdfs:isDefinedBy pointing to the ontology.
      This is a common practice and is used eg by MetaPhactory when collecting properties to generate forms.

    • Adds the current date as dct:modified of the ontology




  • -t: add rdfs:range owl:Thing to props with range iri
    (this is needed for Metaphactory to be able to edit "free URLs").

    • Without this option, they are still mapped to owl:ObjectProperty, but without any rdfs:range.




  • -l: downgrade literal datatypes.

    • Datatypes are mapped as follows:





langString rdf:langString
stringOrLangString rdf:langString
literal rdf:Literal
dateOrYearOrMonth xsd:date
dateOrTimeOrTimeStamp xsd:dateTimeStamp
<datatype> xsd:<datatype>


  • With this option, the following downgrading (simplification) is also done:



rdf:langString xsd:string
rdf:Literal xsd:string



tsv2owl Columns and Features




The tool uses the following sheet columns:




  • Class/prop: class (if capitalized) or property belonging to the class above (if lowercase)


  • label: emits rdfs:label, by default same as the first column


  • Inherits/range: superclass (if it's a class row) or property range


  • char: SOML characteristics:

    • Class: kind, typeProp, name, search: ignored

      • If it's kind: abstract, you'll want to use RDF Replacement (see below)



    • Prop:


      • inverseAlias: this is a virtual property, so it's omitted


      • min, max: mapped to owl:minCardinality, owl:maxCardinality restrictions on the containing class
        (but see https://github.com/VladimirAlexiev/soml/issues/1 for unimplemented features)


      • inverseOf (prop with or without namespace): mapped to owl:inverseOf


      • symmetric (only "true"): mapped to owl:SymmetricProperty


      • subPropertyOf: mapped to rdfs:subPropertyOf


      • transitiveOver: mapped to psys:transitiveOver


      • search: {...}: ignored

      • Not yet handled: owl:FunctionalProperty






  • RDF: RDF URL used for this class/prop. By default is uses the first column


  • (regex|pattern): ignored (these are used by SOML only)


  • descr: emits rdfs:comment


  • RDF replacement: optional. See next section


Features and limitations:



  • Prop definitions (characteristics, label, descr, range; but not cardinality)
    must conform in each use of a property.
    This is not checked !!!
    Use riot --formatted ttl to collect them in "paragraphs"
    so you can check whether you have consistent definitions.

  • Emits a rdfs:Class, owl:Class for each class

  • Emits s:domainIncludes for each prop to accommodate props used several times.
    You have an option to convert this to rdfs:domain for props that have a single domain.

  • Emits type owl:ObjectProperty vs owl:DatatypeProperty for each prop, depending on range:

    • If iri then ObjectProperty
      (and with option -t, add rdfs:range owl:Thing)

    • If lowercase then DatatypeProperty (and prepend xsd: to the range)

    • Else (the range is a class) then ObjectProperty



  • Map only the data ranges indicated above: currently doesn't support rdf:HTML, sysont:Markdown

  • Comment lines start with hash (#) in the first column


    • # HEADER: if there is a space after the hash, the first cell is printed surrounded by newlines


    • #commented out: if there is no space, the whole line is skipped






RDF Replacement




The column RDF is used when you need to specify something different from Class/name.
Eg if you have this in the SOML preamble:



prefixes:

vocab_iri: http://schema.org/
vocab_prefix: s



The following tabular schema excerpt (leading dashes indicate the class hierarchy):

Class/prop
range/inherits
RDF

Event
 
 

-EventSeries
Event
 

-EventParticipation
Event
otkg:EventPartcipation


generates s:Event, s:EventSeries and otkg:EventPartcipation respectively.


Semantic Objects currently supports only abstract superclasses,
so if we want to use all 3 classes with instance data,
we need to add an abstract parent like this:

Class/prop
range/inherits
char
RDF

EventCommon
 
kind: abstract
 

-Event
EventCommon
 
 

-EventSeries
EventCommon
 
 

-EventParticipation
EventCommon
 
otkg:EventPartcipation


It's quite common for one of the children (in this case Event) not to have any props of its own,
just to inherit the props of the parent.


This works fine for tsv2soml, but tsv2owl would generate a parasitic (non-existent) RDF class s:EventCommon.
I thought of using the value RDF: none to signal that such class should be omitted.
But then I'd need to carry over the properties and parent of that parasitic class to one of its children (in this case Event).


So instead, I add an extra column RDF replacement that indicates which RDF class is used instead of the parasitic class:

Class/prop
range/inherits
char
RDF
RDF replacement

EventCommon
 
kind: abstract
 
Event

-Event
EventCommon
 
 
 

-EventSeries
EventCommon
 
 
 

-EventParticipation
EventCommon
 
otkg:EventPartcipation
 


This replaces all references to EventCommon with Event: domain (prop attachment), range (prop target), superclass (parent), subclasses (children).


Notes:



  • It uses the fact that RDFS/OWL triples can be emitted in any order

  • It emits an extra reflexive triple s:Event rdfs:subClassOf s:Event, which is harmless and in fact is part of the RDFS semantics

  • It uses the RDF expression of the replacement class: in this case s:Event because the RDF column is not used, but you can specify something else in RDF


  • label and descr of the parasitic class are ignored to avoid emitting multiple labels/descriptions for the replacement class


You can also use replacement on leaf-level classes.
Consider the following example from OTKG (two leading dashes indicate the properties attached to the prev class):

Class/prop
range/inherits
char
RDF
RDF replacement

Concept
 
name: prefLabel, kind: abstract
skos:Concept
 

–prefLabel
string
min: 1
skos:prefLabel
 

–inScheme
ConceptScheme
 
skos:inScheme
 

-Audience
Concept
typeProp: inScheme
OTKG:audience
skos:Concept

-ContentType
Concept
typeProp: inScheme
OTKG:contentType
skos:Concept

–appliesToClass
iri
 
otkg:appliesToClass
 

PersonCommon
Thing
kind: abstract
 
Person

–jobTitle
string
 
 
 

–worksFor
Organization
min: 1
 
 

–sameAs
iri
max: inf
 
 

-Person
PersonCommon
 
 
 

-OntotextPerson
PersonCommon
typeProp: worksFor
OTKG-agent:Ontotext
none

–sameAs
iri
min: 1
 
 


Several sub-classes have an additional type discriminator designated by typeProp (in addition to the standard rdf:type):




  • ContentType is a skos:Concept that is further distinguished by skos:inScheme.
    It has extra prop otkg:appliesToClass, so we specify replacement=skos:Concept to carry over this prop to that parent class.
    Note: this prop indicates which concept goes with which Schema class, eg OTKG:contentType/blog_post goes with s:BlogPosting


  • Audience adds no props compared to Concept, but we still set replacement=skos:Concept
    to ensure that its incoming link s:audience will obtain range=skos:Concept


  • PersonCommon is a parasitic (abstract) parent class, so we replace it with Person (which is emitted in RDF as s:Person).
    We already such replacement case in the previous example.


  • OntotextPerson is a class that is the same as Person, but with fixed s:worksFor=OTKG-agent:Ontotext
    and with stronger information requirements (we demand that it has at least one s:sameAs, the default in Person is min: 0).
    There's neither RDF class s:OntotextPerson nor otkg:OntotextPerson, and it doesn't add any extra prop.
    So we use replacement=none to omit it from RDF altogether.




Running tsv2owl




You can run the tool with a Makefile like this (see tsv2owl), feeding from a Google Sheet:



ontology.ttl ::

curl -Ls "https://docs.google.com/spreadsheets/d/.../export?format=tsv" | \
perl -S tsv2owl.pl -vocab s: -ontology otkg: | \
cat ontology-preamble.ttl - > ontology-unformatted.ttl
riot --formatted=ttl ontology-unformatted.ttl | \
perl -00e '@a=<>; print sort @a' > ontology.ttl
# rm ontology-unformatted.ttl # keep for debugging


The tool attaches props to classes using two ways: s:domainIncludes and owl:Restriction:



s:legalName  rdf:type     owl:DatatypeProperty ;

s:domainIncludes s:Organization ;
s:rangeIncludes xsd:string .
s:Organization rdf:type owl:Class , rdfs:Class ;
rdfs:subClassOf [ rdf:type owl:Restriction ;
owl:maxCardinality 1 ;
# owl:allValuesFrom xsd:string
owl:onProperty s:legalName
] .



Metaphactory also needs the commented-out statement (allValuesFrom pointing to the property range).
To add that, use the SPARQL update tsv2owl-allValuesFrom.ru.
Replace riot with update (which is also part of Jena):



ontology.ttl ::

curl -Ls "https://docs.google.com/spreadsheets/d/.../export?format=tsv" | \
perl -S tsv2owl.pl -vocab s: -ontology otkg: | \
cat ontology-preamble.ttl - > ontology-unformatted.ttl
update --update=../bin/tsv2owl-allValuesFrom.ru --data=ontology-unformatted.ttl --dump | \
perl -00e '@a=<>; print sort @a' > ontology.ttl
# rm ontology-unformatted.ttl # keep for debugging


The tool emits s:domain/rangeIncludes (which are polymorphic, i.e. multi-valued).
If you need to emit rdfs:domain/range (which are monomorphic, i.e. single-valued),
use the SPARQL update tsv2owl-domain-range.ru that does this:



  • If a prop has a single s:domainIncludes, convert it to rdfs:domain

  • If a prop has a single s:rangeIncludes, convert it to rdfs:range



ontology.ttl ::

curl -Ls "https://docs.google.com/spreadsheets/d/.../export?format=tsv" | \
perl -S tsv2owl.pl -vocab s: -ontology otkg: | \
cat ontology-preamble.ttl - > ontology-unformatted.ttl
update --update=../bin/tsv2owl-domain-range.ru --data=ontology-unformatted.ttl --dump | \
perl -00e '@a=<>; print sort @a' > ontology.ttl
# rm ontology-unformatted.ttl # keep for debugging


You can diff otkg.ttl with otkg-allValuesFrom.ttl and otkg-domain-range.ttl to see the difference.





soml2puml




Generate nice PlantUML diagrams from SOML models.
See its own README.





Tricky Points and Deficiencies




GraphQL Type vs rdf:type





Single vs Multiple-Value Props





Inverse Aliases





Literals




(langString, union datatypes)




Extended Pattern (Prefix + Regex)





IRI Generation





Schema Inclusion/Modularity








Exported by Emacs 26.1 (Org mode 9.2.2)


Validate