Skip to content

VladimirAlexiev/soml

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

60 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Semantic Objects Modeling Language

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

Table of Contents

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.

PrefixOntologyClassesProps
cgOntotext Company Graph1270
admsAsset Description Metadata Schema11
dcatData Catalog Vocabulary3
dctDublin Core Terms8
ebgeuBusinessGraph112
gnGeoNames19
locnW3C Location Ontology18
orgW3C Core Organization Ontology15
qbW3C Cube Ontology11
rovW3C Registered Organization14
schemaSchema.org312
skosSimple Knowledge Organization System16
timeW3C Time Ontology2
voidVocabulary of Interlinked Datasets17
wgs84World Geodetic Survey2
24150

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

./eg/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

./eg/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:

./eg/CG-sheet.png

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

./eg/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/proplabelInherits/rangechardescr
Organization
sameAssame asirimin: 1, max: infURL 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
  • -O: add owl:Restriction to bind props to classes (else it uses only s:domainIncludes to props)
  • -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 #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 listed under several classes.
    • Use option -O to also add owl:Restriction to each class. This binds the prop to the class, and shows the class-dependent cardinality of the prop
    • Use the update tsv2owl-domain-range.ru to convert domainIncludes to rdfs:domain for props listed only once.
  • Emits s:rangeIncludes for each prop
    • Use the update tsv2owl-domain-range.ru to convert rangeIncludes to rdfs:range for props that always point to the same class or datatype
    • We strongly recommend that for all props, and indeed that is currently a restriction in SOML.
  • 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/proprange/inheritsRDF
Event
-EventSeriesEvent
-EventParticipationEventotkg: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/proprange/inheritscharRDF
EventCommonkind: abstract
-EventEventCommon
-EventSeriesEventCommon
-EventParticipationEventCommonotkg: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/proprange/inheritscharRDFRDF replacement
EventCommonkind: abstractEvent
-EventEventCommon
-EventSeriesEventCommon
-EventParticipationEventCommonotkg: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/proprange/inheritscharRDFRDF replacement
Conceptname: prefLabel, kind: abstractskos:Concept
–prefLabelstringmin: 1skos:prefLabel
–inSchemeConceptSchemeskos:inScheme
-AudienceConcepttypeProp: inSchemeOTKG:audienceskos:Concept
-ContentTypeConcepttypeProp: inSchemeOTKG:contentTypeskos:Concept
–appliesToClassiriotkg:appliesToClass
PersonCommonThingkind: abstractPerson
–jobTitlestring
–worksForOrganizationmin: 1
–sameAsirimax: inf
-PersonPersonCommon
-OntotextPersonPersonCommontypeProp: worksForOTKG-agent:Ontotextnone
–sameAsirimin: 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

About

Semantic Objects Modeling Language

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published