Лекция 15 (OWL)

advertisement
Кафедра «ОСУ»
Весенний семестр 2010/2011 уч. года
Языки описания информации
Лекция ХХХ.
Онтологии и язык OWL
Что такое Semantic Web?
• В соответствии с Tim Berners-Lee (1998):
“... логически согласованная паутина данных ...” в
которой “... информации задается строго
определенный смысл …”
Что такое Semantic Web?
• В соответствии с Tim Berners-Lee (1998):
“... логически согласованная паутина данных ...” в которой “...
информации задается строго определенный смысл …”
• Теперь это определение развилось в:
“платформа для распределенных приложений и
совместного использования (связывания) данных”
Что такое Semantic Web?
• В соответствии с Tim Berners-Lee (1998):
“... логически согласованная паутина данных ...” в которой
“... информации задается строго определенный смысл …”
• Теперь это определение развилось в:
“платформа для распределенных приложений и
совместного использования (связывания) данных”
– RDF предоставляет универсальную
синтаксическую структуру для данных.
– Онтологии предоставляют схемы, с которыми
могут работать программы.
Что такое Semantic Web?
• В соответствии с Tim Berners-Lee (1998):
“... логически согласованная паутина данных ...” в которой “... информации
задается строго определенный смысл …”
• Теперь это определение развилось в:
“платформа для распределенных приложений и совместного
использования (связывания) данных”
– RDF предоставляет универсальную синтаксическую структуру
для данных.
– Онтологии предоставляют схемы, с которыми могут работать
программы.
• Большое разнообразие исследовательских проектов:
– нацеленных на извлечение “полезной информации” из
содержания web сети;
– с помощью средств Представления Знаний (KR) (в особенности
с помощью онтологий), играющих ключевую роль.
Переход к Semantic Web

Задачи часто требуют объединения данных,
расположенных в Web-сети:




информация о гостиницах и путешествиях может
поступать с разных сайтов;
поиск в разных цифровых библиотеках;
и т.п.
Люди объединяют такую информацию легко,
даже если


используется разная терминология;
информация является не полной, размытые
изображения, видео, …
Пример: автоматический заказ билетов
на самолет

Ваша система автоматического заказа билета на
самолет



знает о ваших предпочтениях;
строит базу знаний, используя ваш прошлый опыт;
может объединять локальные знания с удаленными
сервисами:





airline preferences
dietary requirements
calendaring
etc
It communicates with remote information (i.e., on
the Web!)

(M. Dertouzos: The Unfinished Revolution)
Пример: интеграция баз данных


Databases are very different in structure, in
content
Lots of applications require managing several
databases






after company mergers
combination of administrative data for e-Government
biochemical, genetic, pharmaceutical research
combination of online library data
etc.
Most of these data are accessible from the Web
(though not necessarily public yet)
Эту проблему вы знаете очень хорошо…
Пример: социальные сети



Social sites are everywhere these days (LinkedIn,
Facebook, Dopplr, Digg, Plexo, Zyb, …)
Data is not interchangeable: how many times did
you have to add your contacts?
Applications should be able to get to those data
via standard means

there are, of course, privacy issues…
Пример: цифровые библиотеки

Типа каталогов для Web-сети




librarians have known how to do that for centuries
goal is to have this on the Web, World-wide
extend it to multimedia data, too
But it is more: software agents should also be
librarians!

e.g., help you in finding the right publications
Example: Semantics of Web Services
• Web services technology is great
• But if services are ubiquitous, searching issue
comes up, for example:
– “find me the best differential equation solver”
– “check if it can be combined with the XYZ plotter
service”
• It is necessary to characterize the service
– not only in terms of input and output parameters…
– …but also in terms of its semantics
Пример: поиск подходящего эксперта в
NASA

Expertise locater for nearly 70,000 NASA civil
servants, integrating 6 or 7 geographically distributed
databases, data sources, and web services…
Michael Grove, Clark & Parsia, LLC, and Andrew Schain, NASA, (SWEO Case Study)
Что требуется?




(Некоторые) данные должны быть доступны
для программ, что они могли выполнять их
обработку.
Data should be possibly combined, merged on a
Web scale
Machines may also need to reason about that
data
Create a Web of Data (beyond the Web of
Documents)
Что требуется (технически)?
• Чтобы данные можно было обрабатывать программно,
требуется:
– недвусмысленные (unambiguous) имена для ресурсов
(которые также могут связывать данные с объектами
реального мира): URI идентификаторы;
– общая модель данных для получения доступа, соединения,
описания ресурсов: RDF;
– доступ к этим данным: SPARQL;
– описание общих словарей: RDFS, OWL, SKOS;
– возможность логического вывода: OWL, Rules.
• “Semantic Web” это расширение существующей Webсети, предоставляющей инфраструктуру для
интеграции данных в Web-сети
Таким образом, что такое
Semantic Web?
По существу Semantic Web это
Паутина данных (Web of Data).
“Технологии Semantic Web” это набор
стандартных технологий для
реализации Паутины Данных (Web of
Data).
• Базовая архитектура метаданных: RDF
RDF Триплеты
• Мы сказали “связывание” данных…
• Но простого связывания не достаточно… оно
должно быть как-то именовано (названо)
– a connection from “me” to my calendar is not the same as
the connection from “me” to my CV (even if all of these are
on the Web)
– the first connection should somehow say “myCalendar”',
the second “myCV”
• Следовательно RDF Триплеты: именованные связи
между двумя ресурсамми.
RDF Триплеты (продолжение)
• RDF Триплет (s,p,o) это:
– “s”, “p” are URI-s, ie, resources on the Web; “o” is a URI or a literal
– conceptually: “p” connects, or relates the “s” and ”o”
– note that we use URI-s for naming: i.e., we can
use http://www.example.org/myCalendar
– here is the complete triple:
(http://www.ivan-herman.net, http://…/myCalendar, http://…/calendar)
• RDF это общая модель для таких триплетов
– … с программно читаемыми форматами (RDF/XML, Turtle, n3,
RXR, …)
RDF Триплеты (продолжение)
• RDF Триплеты также называются “триплетами”
или “утверждениями”.
• The s, p, o resources are also referred to
as “subject”, “predicate”, ”object”,
or “subject”, ”property”,”object”
• Resources can use any URI; i.e., it can denote an
element within an XML file on the Web, not only a
“full” resource, e.g.:
– http://www.example.org/file.xml#xpointer(id('calendar'))
– http://www.example.org/file.html#calendar
RDF это Граф
• Триплет (s,p,o) может рассматриваться в виде
именованной дуги (labeled edge) в графе
– т.е., набор RDF утверждений является направленным,
размеченным графом
• both “objects” and “subjects” are the graph nodes
• “properties” are the edges
• One should “think” in terms of graphs; XML or Turtle syntax
are only the tools for practical usage!
• RDF authoring tools may work with graphs, too (XML or
Turtle is done “behind the scenes”)
Простой пример RDF
(в формате RDF/XML)
<rdf:Description rdf:about="http://.../membership.svg#FullSlide">
<axsvg:graphicsType>Chart</axsvg:graphicsType>
<axsvg:labelledBy rdf:resource="http://...#BottomLegend"/>
<axsvg:chartType>Line</axsvg:chartType>
</rdf:Description>
Простой пример RDF
(в формате Turtle)
<http://.../membership.svg#FullSlide>
axsvg:graphicsType "Chart";
axsvg:labelledBy
<http://...#BottomLegend>;
axsvg:chartType
"Line".
URI идентификаторы играют
фундаментальную роль
• Любой может создать (мета)данные об любом ресурсе в
Web-сети
– например, the same SVG file could be annotated through other
terms
– semantics is added to existing Web resources via URI-s
– URI-s make it possible to link (via properties) data with one
another
• URI идентификаторы погружают RDF в Web-сеть
– информация может быть получена с помощью
существующих инструментов;
– это создает «Семантическую Паутину» (“Semantic Web”),
действительно… “Semantic Web”
•
URI идентификаторы: Соединение
• Становится просто соединять (merge) данные
– например, applications may merge the SVG annotations
• Merge can be done because statements refer to
the same URI-s
– nodes with identical URI-s are considered identical
• Merging is a very powerful feature of RDF
– metadata may be defined by several (independent) parties…
– …and combined by an application
– one of the areas where RDF is much handier than pure XML in
many applications
•
Что может сделать слияние…
• RDF Vocabulary Description Language
(RDFS)(a.k.a. RDFS)
Потребность в RDF Schemas
• Определение данных и их использование в программах
будет работать… при условии, программа знает какие
термины следует использовать!
• Мы использует такие термины, как:
– Chart, labelledBy, isAnchor, …
– myCV, myCalendar, …
– etc
• Являются ли все они известными? Являются ли все они
правильными (correct)? Имеются ли (логические)
взаимосвязи между данными терминами?
• Именно для этого и используется RDF Schemas
– официально: “RDF Vocabulary Description Language”; термин
“Schema” сохранен по историческим причинам…
Classes, Resources, …
• Think of well known in traditional ontologies:
–
–
–
–
use the term “mammal”
“every dolphin is a mammal”
“Flipper is a dolphin”
etc.
• RDFS defines resources and classes:
– everything in RDF is a “resource”
– “classes” are also resources, but…
– they are also a collection of possible resources (i.e.,
“individuals”)
• “mammal”, “dolphin”, …
•
Classes, Resources, … (cont.)
• Между классами/ресурсами определены
отношения (relationships) :
– “typing”: an individual belongs to a specific class
(“Flipper is a dolphin”)
– “subclassing”: instance of one is also the instance
of the other (“every dolphin is a mammal”)
• RDFS формализует такие обозначения в
формате RDF.
Classes, Resources in RDF(S)
• RDFS defines rdfs:Resource, rdfs:Class as nodes; rdf:type,
rdfs:subClassOf as properties
– (these are all special URI-s, we just use the namespace abbreviation)
Пример схемы в RDF/XML
• The schema part (“application’s data types”):
<rdf:Description rdf:ID="Dolphin">
<rdf:type rdf:resource= "http://www.w3.org/2000/01/rdf-schema#Class"/>
</rdf:Description>
• The RDF data on a specific animal (“using the type”):
<rdf:Description rdf:about="#Flipper">
<rdf:type rdf:resource="animal-schema.rdf#Dolphin"/>
</rdf:Description>
• In traditional knowledge representation this separation is often
referred to as: “Terminological axioms” and “Assertions”
Выведенные свойства
(#Flipper rdf:type #Mammal)
• этого нет в исходных RDF данных…
• …но может быть логически выведено с помощью RDFS правил;
• Better RDF environments return that triplet, too.
Логический вывод: позволяет нам
быть формальными…
• В документе RDF Semantics перечислены (44) правил логического
вывода (entailment rules):
– “if such and such triplets are in the graph, add this and this triplet”
– do that recursively until the graph does not change
– this can be done in polynomial time for a specific graph
• The relevant rule for our example:
If:
uuu rdfs:subClassOf xxx .
vvv rdf:type uuu .
Then add:
vvv rdf:type xxx .
• Добавляются ли эти дополнительные триплеты к графу физически
(physically added) или выводятся (deduced) при необходимости
является вопросом реализации (implementation issue).
Свойства (Properties)
• Свойства (Property) это специальный класс
(rdf:Property).
– properties are also resources identified by URI-s
• Свойства ограничены их областью определения
(range) и областью значений (domain).
– т.е., какие индивидуумы могут использоваться в
качестве субъектов (subject) и объектов (object).
• Также могут быть «подсвойства» (“sub-property”)
– all resources bound by the “sub” are also bound by the
other.
Пример спецификации свойств
• Отметим, что в среде RDF(S) нельзя
определить какие литералы могут использоваться.
Литералы (Literals)
• Литералы могут иметь тип данных (data
type)
– floats, integers, booleans, etc, defined in XML
Schemas
• one can also define complex structures and restrictions
via regular expressions, …
– full XML fragments
• Также может быть задан (естественный)
язык (с помощью xml:lang).
Сериализация литералов
• In RDF/XML
<rdf:Description rdf:about="#Flipper">
<animal:is_TV_Star
rdf:datatype="http://www.w3.org/2001/XMLSchema#boolean">
True
</animal:is_TV_Star>
</rdf:Description/>
• In Turtle
:Flipper
animal:is_TV_Star
"True"^^<http://www.w3.org/2001/XMLSchema#boolean>.
Querying RDF Data: SPARQL
How to retrieve triples?
• In simple cases: a programming environment
gives direct access. E.g.:
triples = graph.triples((Resource, Property, None))
to retrieve all objects for (Resource, Property)
• This is programming language dependent
• It becomes too complex for complex data
• Does not work if the data are remote
• We need query facilities
Выполнение запросов к RDF Графам
• Базовая идея: использовать шаблоны графов (raph
patterns) для описания подграфов:
– шаблон содержит не связанные (unbound) символы;
– by binding the symbols, subgraphs of the RDF graph may be
matched
– if there is such a match, the query returns the bound resources
or a subgraph
• SPARQL (Query Language for RDF) определяется как:
– язык программирования – независимый язык запросов;
– является стандартом W3C (SPARQL Query Language for
RDF W3C Recommendation 15 January 2008).
Пример простого SPARQL запроса
• Запрос
SELECT ?cat ?val # note: not ?x!
WHERE { ?x rdf:value ?val. ?x category ?cat }
• Результат
[["Total Members",100],["Total Members",200],…,["Full Members",10],…]
Другие возможности SPARQL
• Определять необязательные шаблоны.
• Limit the number of returned results; remove duplicates, sort
them,…
• Add functional constraints to pattern matching
• Return a full subgraph (instead of a list of bound variables)
• Use datatypes and/or language tags when matching a pattern
• SPARQL is a Candidate Recommendation, i.e. the technical
aspects are now finalized (modulo implementation problems)
– but there are a number of implementations already!
Практическое использование
SPARQL
• Locally, i.e., bound to a programming
environments like Jena
• Remotely, e.g., over the network or into a
database
– separate documents define the protocol and the result
format
• SPARQL Protocol for RDF with HTTP and SOAP bindings
• SPARQL Results XML Format
• there is also a JSON binding (soon a W3C note…)
• There are already a number of applications,
demos, etc.,
Получение RDF(S) данных
Самый простой способ: записать
свои собственные RDF данные…
• The simplest aproach: write your own RDF data in your preferred
syntax
• Using URI-s in RDF binds you automatically to the real resources
• You may add RDF to XML directly (in its own namespace)
– e.g., in SVG:
<svg ...>
...
<metadata>
<rdf:RDF xmlns:rdf="http://../rdf-syntax-ns#">
...
</rdf:RDF>
</metadata>
...
</svg>
• Works in some cases, but not satisfactory for a real deployement!
RDF Can Also Be Extracted/Generated
• Использование интеллектуальных “scrapers” или
“wrappers” для извлечения структуры (следовательно
и RDF) из Web страницы …
– using conventions in, e.g., class names or header conventions
like meta elements
• … а затем автоматическое генерирование RDF
(например, с помощью XSLT скрипта)
• Although they may not say it: this is what the
“microformat” world is doing
– they may not extract RDF but use the data directly instead,
but that depends on the application
– other applications may extract it to yield RDF (e.g., RSS1.0)
•
RDF Can Also Be Extracted/Generated
(cont.)
• There are projects at W3C in this direction:
– RDFa: a scalable and more rigorous microformat
approach (annotations are intermixed with XHTML
content)
– GRDDL: “formalizing” the scraping process
(instructing the client where to find a
transformator engine to extract the RDF data)
• The two projects are complementary
Bridge to Relational Databases
• Большинство данных хранится в реляционных БД.
• Преобразование их в “RDF” является невозможной
задачей.
• Для этого описываются «мосты»:
– a layer between RDF and the database
– RDB tables are “mapped” to RDF graphs on the fly
– in some cases the mapping is generic (columns represent
properties, cells are, e.g., literals or references to other tables
via blank nodes)…
– … in other cases separate mapping files define the details
• Это является очень важным источником RDF данных.
• Is instrumental to the fundamental goal of RDF: qualified
relationship among data on the Web
SPARQL как средство объединения
Ontologies (OWL)
Онтологии
• RDFS is useful, but does not solve all the issues
• Complex applications may want more possibilities:
– can a program reason about some terms? E.g.:
• “if «A» is left of «B» and «B» is left of «C», is «A» left of «C»?”
• programs should be able to deduce such statements
– if somebody else defines a set of terms: are they the
same?
– construct classes, not just name them
– restrict a property range when used for a specific class
– disjointness or equivalence of classes
– etc.
Классы в OWL
• In RDFS, you can subclass existing classes… that’s all
• In OWL, you can construct classes from existing ones:
– enumerate its content
– through intersection, union, complement
– through property restrictions
• To do so, OWL introduces its own Class and Thing to
differentiate the classes from individuals
Union of Classes
• Essentially, like a set-theoretical union:
Same Serialized
•
XML
<owl:Class rdf:ID="MarineMammal">
<owl:unionOf rdf:parseType="Collection">
<owl:Class rdf:about="#Dolphin"/>
<owl:Class rdf:about="#Orca"/>
<owl:Class rdf:about="#Whale"/>
…
</owl:unionOf>
</owl:Class>
•
Tertle
:Dolphin rdf:type owl:Class.
:Orca rdf:type owl:Class.
:Whale rdf:type owl:Class.
:MarineMammal rdf:type owlClass;
owl:unionOf (:Dolphin, :Orca, :Whale).
•
Other possibilities: complementOf, intersectionOf
Property Restrictions
• (Sub)classes created by restricting the
property value on that class
• For example, “a dolphin is a mammal living in
sea or in the Amazonas” means:
– restrict the value of “living in” when applied to
“mammal” to a specific set…
– …thereby define the class of “dolphins”
Ограничения свойств в OWL
• Restriction may be by:
– value constraints (i.e., further restrictions on the range)
• all values must be from a class (like the dolphin example)
• some value must be from a class
– cardinality constraints
– (i.e., how many times the property can be used on an
instance?)
• minimum cardinality
• maximum cardinality
• exact cardinality
•
Пример ограничения свойств
• “A dolphin is a mammal living in the sea or in the
Amazonas”:
Property Characterization
• In OWL, one can characterize the behavior of
properties (symmetric, transitive, …)
• OWL also separates data properties
– “datatype property” means that its range
are typed literals
Characterization Example
• “There should be only one order for each
animal class” (in scientific classification)
OWL: Additional Features
• Ontologies may be extremely a large:
– their management requires special care
– they may consist of several modules
– come from different places and must be integrated
• Ontologies are on the Web. That means
– applications may use several, different ontologies, or…
– … same ontologies but in different languages
– equivalence of, and relations among terms become an
issue
• OWL includes possibilites for class/property
equivalence, version and deprecation control, etc.
Example: Connecting to Hungarian
However: Ontologies are Hard!
• Hard to implement a full ontology management system
– may be superfluous for some applications
• Hence the “onion” model of increasingly complex specs:
–
–
–
–
no property expressions or datatypes in RDF Schemas
not all set operators, restricted cardinality in OWL Lite
some restrictions, but a computational guarantee in OWL DL
full expressive power in OWL Full (but no computational
guarantee)
Ontologies are Hard! (cont)
• “Lite” < “DL” < “Full”, but not completely true for RDFS
– RDFS is “almost” a subcategory
– not all RDFS statements are valid in DL…
– …but they are for Full
• Applications may take what they really need!
RDF/OWL in Practice
RDF in Programming Practice
• Programming environments usually provide:
– creation of a “Graph”, “Triple Store”, or “Model” (the
terms used are different in various implementations)
– the RDF file(s) are parsed and results stored in the
Graph
– the Graph offers methods to retrieve and/or remove
triples, resources, etc
– “merge” is automatic if several files are parsed
– the rest is conventional programming…
Example: Jena
• RDF toolkit in Java from HP’s Bristol lab
// create a model (a.k.a. Triple Store)
Model model = new ModelMem();
Resource subject = model.createResource("URI_of_Subject") ;
// 'in' refers to the input file
model.read(new InputStreamReader(in));
StmtIterator iter = model.listStatements(subject,null,null);
while(iter.hasNext()) {
st = iter.next();
p = st.getProperty();
o = st.getObject();
do_something(p,o);
}
Jena (cont)
• But Jena is much more than just the basics; it has
– a huge number of classes/methods
• listing, removing associated properties, objects, comparing full
RDF graphs, manage typed literals, etc.
– an “RDFS Reasoner”
• all the “inferred” properties, types are accessible and errors are
checked
– a SPARQL implementation
– an OWL reasoner
– a layer (Joseki) for remote access of triples (essentially,
and triple database)
• Probably the most widely used RDF environment in
Java today
Множество других инструментов
• There are lots of other tools:
– RDF frameworks for specific languages: RDFStore (Perl), RAP (PHP,
includes a SPARQL engine), SWI-Prolog (Prolog),RDFLib for
Python,…
– Redland: general RDF Framework, with bindings to C, C++, C#,
Python, …, and with a SPARQL engine (Rasqal)
– RDF storage
systems: (Sesame, Kowari, Tucana, Gateway, @Semantics
RDFStore, Virtuoso, 3Store, Jena’s Joseki,InferEd, Oracle Database
10g , Allegro…)
• some of these are based on an internal sql engine (3Store, Oracle),
others are made bottom up as triple stores
• most of them have, or plan for, SPARQL facilities
– RDB→RDF layers, tools: D2R Server, SquirrelRDF
• See the tool list at W3C or the Free University of Berlin list
Current/future Developments
Simple Knowledge Organization
System
• Цель: перенести в Web-сеть (“Webifying”)
тезаурусы (thesauri): описывающие и
представляющих общий доступ к
классификациям, глоссариям, тезаурусам и т.п.,
которые разработаны в “Print World”.
• Например:
– Dewey Decimal Classification, Art and Architecture
Thesaurus, ACM classification of keywords and terms…
– DMOZ categories (a.k.a. Open Directory Project)
• The system must be simple to allow for a quick port
of traditional data (done by “traditional” people…)
• Как раз в этом случае используется SKOS
Example: Entries in a Glossary (1)
• “Assertion”
– (i) Any expression which is claimed to be true.
– (ii) The act of claiming something to be true.
• “Class”
– A general concept, category or classification. Something
used primarily to classify or categorize other things.
• “Resource”
– (i) An entity; anything in the universe.
– (ii) As a class name: the class of everything; the most
inclusive category possible.
(from the RDF Semantics Glossary)
Example: Entries in a Glossary (2)
Example: Entries in a Glossary (3)
Example: Thesaurus (1)
• Term
– Economic cooperation
• Used For
– Economic co-operation
• Broader terms
– Economic policy
• Narrower terms
– Economic integration, European economic cooperation, …
• Related terms
– Interdependence
• Scope Note
– Includes cooperative measures in banking, trade, …
Example: Thesaurus (2)
Why Having SKOS OWL?
• OWL’s precision not always necessary or even appropriate
– “OWL a sledge hammer / SKOS a nutcracker”, or “OWL a
Harley / SKOS a bike”
– complement each other, can be used in combination to
optimize cost/benefit
• Role of SKOS is
– to bring the worlds of library classification and Web
technology together
– to be simple and undemanding enough in terms of cost and
required expertise
• A typical example: the Glossary of project of W3C stores
all terms in SKOS (and extracted from W3C documents)
“Core” Vocabularies
• A number of public “core” vocabularies evolve to be
used by applications, e.g.:
– SKOS Core: about knowledge systems
– Dublin Core: about information resources, digital
libraries, with extensions for rights, permissions, digital
right management
– FOAF: about people and their organizations
– DOAP: on the descriptions of software projects
– MusicBrainz: on the description of CDs, music tracks, …
–…
• They share the underlying RDF model (provides
mechanisms for extensibility, sharing, …)
Rules
• OWL can be used for simple inferences
• Applications may want to express domain-specific
knowledge, like “Horn clauses”:
– (P1 ∧ P2 ∧ …) → C
– e.g.: for any «X», «Y» and «Z»: “if «Y» is a parent of «X», and
«Z» is a brother of «Y» then «Z» is the uncle of «X»”
• There is also a large corpus of rule–based systems and
languages, though not necessarily bound to the Web (yet)
• Several attempts already to combine Semantic Web with
Rules (Metalog, RuleML, SWRL, WRL, cwm, …)
– note: cwm, for example, defines Horn predicates in terms of
graph patterns, a connection to SPARQL…
Rules Interchange Format Working
Group
• The W3C Working Group started at the
beginning of November 2005
• Work is planned in two “phases”:
– construct an extensible format for rule interchange
– define more complex extensions
• Great interest from financial services, business
rules, life science community…
RIF Phase 1 Goals
• An interchange format to exchange rules among
rule engines and systems
– probably based on “full Horn Logic” with some simple
datatypes (int, boolean, strings,…)
– make it relatively simple, leave the more complex
issues to Phase 2
– make a new type of data accessible for the Web…
• An extensible format to allow more complex
alternatives to be defined
– e.g., fuzzy and/or temporal logic
• Recommendation 2010
Переход от RDFS к OWL
• Язык OIL был разработан в проекте On-To-Knowledge.
• Язык DAML-ONT был разработан позже в программе
DAML (DARPA Agent Markup Language).
• Вскоре оба этих языка объединились и получился язык
DAML+OIL
– Дальнейшая разработка выполнялась “Joint EU/US Committee”
• Язык DAML+OIL явился основой для разработки стандарта
организации W3C.
• Была создана рабочая группа WebOnt , которая создала
– язык OWL, основанный на DAML+OIL;
– OWL стал стандартом W3C (recommendation)
– данный язык имеет “дружественный к Web”
синтаксис для дескриптивной логики
Почему используется
Дескриптивная Логика?
• OWL использует результаты 20+ годов
исследований в области Дескриптивной Логики (DL)
– Строго определенная (модельно теоретическая)
семантика
Почему используется
Дескриптивная Логика?
• OWL использует результаты 20+ годов исследований в
области Дескриптивной Логики (DL)
– Строго определенная (модельно теоретическая) семантика
– Хорошо понятные формальные свойства (сложность,
разрешимость)
Я не могу найти эффективный алгоритм, но это не могут сделать и все эти
знаменитые люди.
[Garey & Johnson. Computers and Intractability: A Guide to the
Theory of NP-Completeness. Freeman, 1979.]
Почему используется
Дескриптивная Логика?
• OWL использует результаты 20+ годов
исследований в области Дескриптивной Логики
(DL)
– Строго определенная (модельно теоретическая) семантика
– Хорошо понятные формальные свойства (сложность,
разрешимость)
– Разработаны алгоритмы логического вывода
Почему используется
Дескриптивная Логика?
• OWL использует результаты 20+ годов
исследований в области Дескриптивной Логики
(DL)
– Строго определенная (модельно теоретическая) семантика
– Хорошо понятные формальные свойства (сложность,
разрешимость)
– Разработаны алгоритмы логического вывода
– Масштабируемость, демонстрируемая
реализованными системами.
Программные инструменты
Большим преимуществом OWL явилось
большой рост разнообразия и сложности
программных инструментов и инфраструктур:
• Среды редактирования/разработки:
Программные инструменты
Большим преимуществом OWL явилось большой
рост разнообразия и сложности программных
инструментов и инфраструктур:
• Среды редактирования/разработки;
• Системы логического вывода (reasoners):
Hermi
t
KAON2
Pellet
CEL
Программные инструменты
Большим преимуществом OWL явилось большой
рост разнообразия и сложности программных
инструментов и инфраструктур:
• среды редактирования/разработки;
• системы логического вывода (reasoners):
• объяснения,
обоснования и
точного нахождения
местонахождения
утверждений.
Программные инструменты
Большим преимуществом OWL явилось большой
рост разнообразия и сложности программных
инструментов и инфраструктур:
• среды редактирования/разработки;
• системы логического вывода (reasoners):
• объяснения, обоснования
и точного нахождения
местонахождения
утверждений;
• интеграции и
модуляризации
Программные инструменты
Большим преимуществом OWL явилось большой
рост разнообразия и сложности программных
инструментов и инфраструктур:
• среды редактирования/разработки;
• системы логического вывода (reasoners):
• объяснения, обоснования
и точного нахождения
местонахождения
утверждений;
• интеграции и
модуляризации
• Прикладные интерфейсы
(API), в частности OWL API
В чем состоит проблема?
Рассмотрим типичную web страницу:
Markup consists of:
– rendering
information (e.g.,
font size and
colour)
– Hyper-links to
related content
Semantic content is
accessible to
humans but not
(easily) to
computers…
Какую информацию здесь можем
увидеть мы …
WWW2002
The eleventh international world wide web conference
Sheraton waikiki hotel
Honolulu, hawaii, USA
7-11 may 2002
1 location 5 days learn interact
Registered participants coming from
australia, canada, chile denmark, france, germany, ghana, hong kong, india,
ireland, italy, japan, malta, new zealand, the netherlands, norway,
singapore, switzerland, the united kingdom, the united states, vietnam,
zaire
Register now
On the 7th May Honolulu will provide the backdrop of the eleventh
international world wide web conference. This prestigious event …
Speakers confirmed
Tim berners-lee
Tim is the well known inventor of the Web, …
Ian Foster
Ian is the pioneer of the Grid, the next generation internet …
Какую информацию здесь можем
увидеть программа …
WWW2002
The eleventh international world wide web
conference
Sheraton waikiki hotel
Honolulu, hawaii, USA
7-11 may 2002
1 location 5 days learn interact
Registered participants coming from
australia, canada, chile denmark, france,
germany, ghana, hong kong, india,
ireland, italy, japan, malta, new zealand,
the netherlands, norway, singapore,
switzerland, the united kingdom, the united
states, vietnam, zaire
Register now
On the 7th May Honolulu will provide the
backdrop of the eleventh international world
wide web conference This prestigious event 
Speakers confirmed
Tim berners-lee
Tim is the well known inventor of the Web, 
Ian Foster
Ian is the pioneer of the Grid, the next
generation internet 
Использовании XML разметка с
“осмысленными” тэгами?
<name>WWW2002
The eleventh international world wide webcon</name>
<location>Sheraton waikiki hotel
Honolulu, hawaii, USA</location>
<date>7-11 may 2002</date>
<slogan>1 location 5 days learn interact</slogan>
<participants>Registered participants coming from
australia, canada, chile denmark, france,
germany, ghana, hong kong, india, ireland,
italy, japan, malta, new zealand, the
netherlands, norway, singapore, switzerland, the
united kingdom, the united states, vietnam,
zaire</participants>
<introduction>Register now
On the 7th May Honolulu will provide the backdrop
of the eleventh international world wide web
conference This prestigious event 
Speakers confirmed</introduction>
<speaker>Tim berners-lee</speaker>
<bio>Tim is the well known inventor of the Web,</bio>…
А как насчет такой разметки…
<conf>WWW2002
The eleventh
international world
wide webcon</conf>
<place>Sheraton
Honolulu,
waikiki hotel
hawaii, USA</place>
<date>7-11 may 2002</date>
<slogan>1 location 5 days
learn interact</slogan>
<participants>Registered participants coming from
australia, canada, chile denmark, france,
germany, ghana, hong kong, india, ireland,
italy, japan, malta, new zealand, the
netherlands, norway, singapore, switzerland, the
united kingdom, the united states, vietnam,
zaire</participants>
<introduction>Register now
On the 7th May Honolulu will provide the backdrop
of the eleventh international world wide web
conference This prestigious event 
Speakers confirmed</introduction>
<speaker>Tim berners-lee</speaker>
<bio>Tim is the well known inventor of the Web,…
Что видит программа …
<name>WWW2002
The eleventh international world wide webc</name>
<location>Sheraton waikiki hotel
Honolulu, hawaii, USA</location>
<date>7-11 may 2002</date>
<slogan>1 location 5 days learn interact</slogan>
<participants>Registered participants coming from
australia, canada, chile denmark, france,
germany, ghana, hong kong, india, ireland,
italy, japan, malta, new zealand, the
netherlands, norway, singapore, switzerland, the
united kingdom, the united states, vietnam,
zaire</participants>
<introduction>Register now
On the 7th May Honolulu will provide the backdrop
of the eleventh international world wide web
conference This prestigious event 
Speakers confirmed</introduction >
<speaker>Tim berners-lee</speaker>
<bio>Tim is the well known inventor of the W</bio>
<speaker>Ian Foster</speaker>
<bio>Ian is the pioneer of the Grid, the ne</bio>
Требуется добавить “Cемантику”
• Внешнее соглашение о смысле аннотаций
– Например, Dublin Core
• Agree on the meaning of a set of annotation tags
– Проблема такого подходом
• Inflexible
• Limited number of things can be expressed
• Использование Онтологии для описания смысла
аннотаций
–
–
–
–
Ontologies provide a vocabulary of terms
New terms can be formed by combining existing ones
Meaning (semantics) of such terms is formally specified
Can also specify relationships between terms in multiple
ontologies
Онтология: истоки и история
Онтология в Философии
a philosophical discipline—a branch of philosophy
that
deals with the nature and the organisation of reality
• Science of Being (Aristotle, Metaphysics, IV, 1)
• Tries to answer the questions:
What characterizes being?
Eventually, what is being?
Онтология в Лингвистике
Понятие
связывается с
активизирует
Метка
Стоит вместо
“Tank“
[Ogden, Richards, 1923]
Реальный
объект
?
Онтология в информатике
• Онтология является результатом работы инженера (engineering
artifact):
– она состоит из специфического словаря, используемого для описания
некоторой части внешнего мира (certain reality), а также:
– набора явно заданный утверждений, которые предназначены для
задания смысла данного словаря.
• Таким образом, онтология описывает формальную
спецификацию некоторой предметной области:
– совместного понимания рассматриваемой предметной области;
– формальная и программно обрабатываемая модель
рассматриваемой предметной области.
“Явное детальное описание (specification) концептуальной
модели предметной области (conceptualisation)” [Gruber93]
Структура онтологии
Онтология обычно имеет два различных компонента:
• Имена для важных понятий (concepts) в предметной области
(domain). Например:
– Слон (Elephant) это понятие, экземпляры которого являются видами
животных (kind of animal).
– Травоядные (Herbivore) это понятие, экземплярами которого являются
только те животные, которые едят только растения или их части.
– Взрослый_Слон (Adult_Elephant) это понятие, экземплярами которого
являются только те Слоны, чей возраст больше чем 20 лет.
• Базовые знания/ограничения на предметную область:
– Взрослый_Слоны весят не менее 2,000 кг.
– Все Слоны являются либо Африканские_Слоны (African_Elephants) или
Индийский_Слон (Indian_Elephants).
– Ни один индивидуум (слон) не может быть как Травоядный
(Herbivore), так и Плотоядный (Carnivore).
Semantic Web — первые шаги
Сделать web ресурсы более доступными для
автоматической обработки.
• Добавить к существующей разметке отображения (rendering
markup) семантическую разметку (semantic markup)
– Metadata annotations that describe content/funtion of web accessible
resources
• Использовать Онтологии для предоставления словаря
(vocabulary) для создания аннотаций:
– “Формальная спецификация” доступная для программ.
• Предпосылкой этого является стандартный язык описания
онтологий в web-сети (web ontology language):
– Необходимо согласовать общий синтаксис прежде чем начать
совместно использовать семантику.
– Синтаксическая web-сеть основывается на таких стандартах, как
HTTP и HTML.
Разработка и использование
онтологий
• Учитывая роль онтологий в Semantic Web, важным является
предоставление инструментов и сервисов, которые будут
помогать пользователям:
– проектировать и поддерживать высококачественные онтологии,
например:
•
•
•
•
Выразительные (meaningful) - all named classes can have instances
Правильные (correct) — captured intuitions of domain experts
Минимально избыточные (minimally redundant) — no unintended synonyms
Богато аксиматизированные (richly axiomatised) — (sufficiently) detailed
descriptions.
– хранить (большое количество) экземпляров (instances) классов
онтологий, например:
• Annotations from web pages
– отвечать на запросы (queries) к классам онтологий и их экземплярам,
например:
• Найти более общие/конкретные (general/specific) классы.
• Получить аннотации/страницы (annotations/pages), соответствующие
заданному описанию.
– Интегрировать (integrate) и согласовывать множество онтологий.
Языки описания онтологий для
Semantic Web
Языки описания онтологий
•
Большой набор языков для «Явного Описания спецификации» (“Explicit
Specification”)
– Графические обозначения (Graphical notations)
• Семантические сети (Semantic networks)
• Тематические Карты (Topic Maps, http://www.topicmaps.org/)
• UML
• RDF
– Основанные на логике (Logic based)
• Дескриптивные Логики (Description Logics) (например, OIL, DAML+OIL, OWL).
• Правила (Rules) (например, RuleML, LP/Prolog)
• Логика Первого Порядка (First Order Logic (e.g., KIF)
• Conceptual graphs
• (Syntactically) higher order logics (e.g., LBase)
• Non-classical logics (e.g., Flogic, Non-Mon, modalities)
– Вероятностные/Размытая логика (Probabilistic/fuzzy)
•
Степень формализации меняется в широких пределах
– Increased formality makes languages more amenable to machine processing (e.g.,
automated reasoning)
Многие языки используют “объектноориентированную” модель, основанную на:
• Объекты/Экземпляры/Индивидуумы
(Objects/Instances/Individuals)
– Elements of the domain of discourse
– Equivalent to constants in FOL
• Типы/Классы/Понятия (Types/Classes/Concepts)
– Sets of objects sharing certain characteristics
– Equivalent to unary predicates in FOL
• Отношения/Свойства/Роли (Relations/Properties/Roles)
– Sets of pairs (tuples) of objects
– Equivalent to binary predicates in FOL
• Такие языки являются/могут быть:
–
–
–
–
Хорошо понятными.
Формально описываемыми (Formally specified).
(Относительно) простыми в использовании.
Поддающимися программной обработке.
Языки «Схем» (“Schema”) для Web
сети
• Существующие языки Web-сети расширены для
облегчения описания контента:
– XML  XML Schema (XMLS)
– RDF  RDF Schema (RDFS)
• XMLS не является языком описания онтологий:
– Changes format of DTDs (document schemas) to be XML
– Adds an extensible type hierarchy
• Integers, Strings, etc.
• Can define sub-types, e.g., positive integers
• RDFS считается языком описания онтологий:
– Classes and properties
– Sub/super-classes (and properties)
– Range and domain (of properties)
RDF и RDFS
• RDF это аббревиатура для Resource Description
Framework (Среда Описания Ресурсов)
• Это стандарт W3C (http://www.w3.org/RDF)
• RDF является графическим формализмом ( + XML
синтаксис + семантика)
– для представления метаданных
– для описания семантики (смысла) информации таким
способом, который может использоваться программой.
• RDFS расширяет RDF “словарем схемы”, например:
– Class, Property
– type, subClassOf, subPropertyOf
– range, domain
RDF модель данных
• Утверждениями являются триплеты вида <subject, predicate,
object>:
<Ian,hasColleague,Uli>
• Триплеты могут быть представлены в виде графа:
Ian
hasColleague
Uli
Утверждения описывают свойства (properties) ресурсов.
Ресурсом является любой объект, на который можно
сослаться с помощью URI:
– документ, картинка, параграф текста в Web сети;
– http://www.cs.man.ac.uk/index.html
– книга в библиотеке, реальный человек (?)
– isbn://5031-4444-3333
– …
Сами свойства также являются ресурсом (имеют URI
идентификаторы)
URI идентификаторы
• URI = Uniform Resource Identifier
• «Обобщенное множество всех имен/адресов,
являющиеся короткими строками, которые являются
ссылками на ресурсы.»
• URLs (Uniform Resource Locators) are a particular type of
URI, used for resources that can be accessed on the WWW
(e.g., web pages)
• In RDF, URIs typically look like “normal” URLs, often with
fragment identifiers to point at specific parts of a
document:
– http://www.somedomain.com/some/path/to/file#fragmentID
Связывание утверждений
• Субъект одного утверждения может быть объектом для другого
утверждения.
• Такие коллекции утверждений формируют направленный,
размеченный граф.
Ian
hasColleague
Uli
hasColleague
Carole
hasHomePage
http://www.cs.mam.ac.uk/~sa
ttler
• Отметим, что объектом триплета может также быть “литерал”
(строка).
RDF Syntax
•
•
•
•
RDF имеет XML синтаксис, который имеет специальный смысл:
Каждый элемент Description описывает ресурс.
Каждый атрибут или вложенный подэлемент в элементе Description
является свойством (property) данного Ресурса (Resource).
На ресурсы можно ссылаться с помощью URI:
<Description about="some.uri/person/ian_horrocks">
<hasColleague resource="some.uri/person/uli_sattler"/>
</Description>
<Description about="some.uri/person/uli_sattler">
<hasHomePage>http://www.cs.mam.ac.uk/~sattler</hasHomePage>
</Description>
<Description about="some.uri/person/carole_goble">
<hasColleague resource="some.uri/person/uli_sattler"/>
</Description>
Язык RDF Schema (RDFS)
• RDF предоставляет формализм для аннотирования метаданных
(meta data annotation), и задает способ их записи на языке XML,
но он не предоставляет каких-либо специальных средств
(смысла) для описания словарей, таких, как subClassOf или type
– Interpretation is an arbitrary binary relation
• RDF Schema позволяет описать словарь терминов и отношений
между ними:
– it gives “extra meaning” to particular RDF predicates and resources
– this “extra meaning”, or semantics, specifies how a term should be
interpreted
Язык RDFS
• Основные термины языка RDF Schema:
–
–
–
–
–
–
Class
Property
type
subClassOf
range
domain
• Эти термины являются строительными элементами
(конструкторами, constructors) языка RDF Schema,
используемыми для создания словарей:
<Person,type,Class>
<hasColleague,type,Property>
<Professor,subClassOf,Person>
<Carole,type,Professor>
<hasColleague,range,Person>
<hasColleague,domain,Person>
«Степени свободы» RDF/RDFS
• Нет различия между классами (classes) и экземплярами
(instances) (индивидуумами, individuals)
<Species,type,Class>
<Lion,type,Species>
<Leo,type,Lion>
• Свойства (Properties) сами могут иметь свойства
<hasDaughter,subPropertyOf,hasChild>
<hasDaughter,type,familyProperty>
• Нет различия между конструкторами языка (language
constructors) и словарем онтологии (ontology vocabulary),
поэтому конструкторы могут применяться к самим
себе/друг к другу
<type,range,Class>
<Property,type,Class>
<type,subPropertyOf,subClassOf>
Семантика RDF/RDFS
• RDF имеет “не-стандартную” семантику,
чтобы обеспечить такую степень свободы.
• Данная семантика задается Модельной
Теорией RDF (RDF Model Theory, MT).
Семантика и Модельные Теории
Онтологии/Языки Представления Знаний предназначены для
моделирования (части) мира.
Термины в языке соответствуют сущностям данного мира.
Смысл терминов задается, например:
– отображением (mapping) на другой формализм, например, такой, как ЛППП
(FOL), который имеет свою хорошо определенную семантику;
– или с помощью специальной Модельной Теории (Model Theory, MT)
Модельная Теория (MT) определяет взаимосвязь между синтаксисом
и интерпретациями (interpretations)
– Can be many interpretations (models) of one piece of syntax
– Models supposed to be analogue of (part of) world
E.g., elements of model correspond to objects in world
– Formal relationship between syntax and models
Structure of models reflect relationships specified in syntax
– Inference (e.g., subsumption) defined in terms of MT
E.g., T ² A \sqsubseteq B iff in every model of T, ext(A) \subseteq ext(B)
Проблемы с RDFS
• RDFS является слишком слабым для достаточно детального
описания ресурсов
– No localised range and domain constraints
• Can’t say that the range of hasChild is person when applied to persons and
elephant when applied to elephants
– No existence/cardinality constraints
• Can’t say that all instances of person have a mother that is also a person, or
that persons have exactly 2 parents
– No transitive, inverse or symmetrical properties
• Can’t say that isPartOf is a transitive property, that hasPart is the inverse of
isPartOf or that touches is symmetrical
– …
• Трудно обеспечить поддержку логического вывода (reasoning
support)
– No “native” reasoners for non-standard semantics
– May be possible to reason via FO axiomatisation
Требования к языку описания
онтологий в сети Web
Desirable features identified for Web Ontology Language:
• Extends existing Web standards
– Such as XML, RDF, RDFS
• Easy to understand and use
– Should be based on familiar KR idioms
• Formally specified
• Of “adequate” expressive power
• Possible to provide automated reasoning support
Язык OWL
• Три вида языка OWL:
– OWL full is union of OWL syntax and RDF
– OWL DL restricted to FOL fragment (¼ DAML+OIL)
– OWL Lite is “easier to implement” subset of OWL DL
• Semantic layering
– OWL DL ¼ OWL full within DL fragment
– DL semantics officially definitive
• OWL DL based on SHIQ Description Logic
– In fact it is equivalent to SHOIN(Dn) DL
• OWL DL Benefits from many years of DL research
–
–
–
–
Well defined semantics
Formal properties well understood (complexity, decidability)
Known reasoning algorithms
Implemented systems (highly optimised)
(In)famous “Layer Cake”
???
???
???
 Semantics+reasoning
 Relational Data
 Data Exchange
?
?
Relationship between layers is not clear
OWL DL extends “DL subset” of RDF
OWL Class Constructors
•
XMLS datatypes as well as classes in 8P.C and 9P.C
– E.g., 9hasAge.nonNegativeInteger
•
Arbitrarily complex nesting of constructors
– E.g., Person u 8hasChild.Doctor t 9hasChild.Doctor
Синтаксис OWL
E.g., Person u 8hasChild.Doctor t 9hasChild.Doctor:
<owl:Class>
<owl:intersectionOf rdf:parseType=" collection">
<owl:Class rdf:about="#Person"/>
<owl:Restriction>
<owl:onProperty rdf:resource="#hasChild"/>
<owl:toClass>
<owl:unionOf rdf:parseType=" collection">
<owl:Class rdf:about="#Doctor"/>
<owl:Restriction>
<owl:onProperty rdf:resource="#hasChild"/>
<owl:hasClass rdf:resource="#Doctor"/>
</owl:Restriction>
</owl:unionOf>
</owl:toClass>
</owl:Restriction>
</owl:intersectionOf>
</owl:Class>
Аксиомы OWL
• Axioms (mostly) reducible to inclusion (v)
– C ´ D iff both C v D and D v C
Семантика языка OWL DL
• Mapping OWL to equivalent DL (SHOIN(Dn)):
– Facilitates provision of reasoning services (using DL
systems)
– Provides well defined semantics
• DL semantics defined by interpretations: I = (DI, ¢I),
where
– DI is the domain (a non-empty set)
– ¢I is an interpretation function that maps:
• Concept (class) name A ! subset AI of DI
• Role (property) name R ! binary relation RI over DI
• Individual name i ! iI element of DI
DL Semantics
• Interpretation function ¢I extends to concept
expressions in an obvious(ish) way, i.e.:
Базы знаний дескриптивной
логики (Онтологии)
• An OWL ontology maps to a DL Knowledge Base K = hT , Ai
– T (Tbox) is a set of axioms of the form:
•
•
•
•
•
C v D (concept inclusion)
C ´ D (concept equivalence)
R v S (role inclusion)
R ´ S (role equivalence)
R+ v R (role transitivity)
– A (Abox) is a set of axioms of the form
• x 2 D (concept instantiation)
• hx,yi 2 R (role instantiation)
• Two sorts of Tbox axioms often distinguished
– “Definitions”
• C v D or C ´ D where C is a concept name
– General Concept Inclusion axioms (GCIs)
• C v D where C in an arbitrary concept
Семантика баз знаний
• An interpretation I satisfies (models) an axiom A (I ² A):
–
–
–
–
–
–
–
I ² C v D iff CI µ DI
I ² C ´ D iff CI = DI
I ² R v S iff RI µ SI
I ² R ´ S iff RI = SI
I ² R+ v R iff (RI)+ µ RI
I ² x 2 D iff xI 2 DI
I ² hx,yi 2 R iff (xI,yI) 2 RI
• I satisfies a Tbox T (I ² T ) iff I satisfies every axiom A in T
• I satisfies an Abox A (I ² A) iff I satisfies every axiom A in
A
• I satisfies an KB K (I ² K) iff I satisfies both T and A
Задачи логического вывода
• Knowledge is correct (captures intuitions)
– C subsumes D w.r.t. K iff for every model I of K, CI µ DI
• Knowledge is minimally redundant (no unintended synonyms)
– C is equivallent to D w.r.t. K iff for every model I of K, CI = DI
• Knowledge is meaningful (classes can have instances)
– C is satisfiable w.r.t. K iff there exists some model I of K s.t. CI  ;
• Querying knowledge
– x is an instance of C w.r.t. K iff for every model I of K, xI 2 CI
– hx,yi is an instance of R w.r.t. K iff for, every model I of K, (xI,yI) 2 RI
• Knowledge base consistency
– A KB K is consistent iff there exists some model I of K
Введение в язык OWL
•
•
OWL is a language for processing web information.
What is OWL?
–
–
–
–
–
–
–
–
•
OWL stands for Web Ontology Language
OWL is built on top of RDF
OWL is for processing information on the web
OWL was designed to be interpreted by computers
OWL was not designed for being read by people
OWL is written in XML
OWL has three sublanguages
OWL is a W3C standard
What is Ontology?
– Ontology is about the exact description of things and their relationships.
– For the web, ontology is about the exact description of web information and relationships between
web information.
•
Why OWL?
–
–
–
–
•
OWL is a part of the "Semantic Web Vision" - a future where:
Web information has exact meaning
Web information can be processed by computers
Computers can integrate information from the web
OWL was Designed for Processing Information
– OWL was designed to provide a common way to process the content of web information (instead of
displaying it).
– OWL was designed to be read by computer applications (instead of humans).
• OWL is Different from RDF
– OWL and RDF are much of the same thing, but OWL is a stronger language
with greater machine interpretability than RDF.
– OWL comes with a larger vocabulary and stronger syntax than RDF.
• OWL has three sublanguages:
– OWL Lite
– OWL DL (includes OWL Lite)
– OWL Full (includes OWL DL)
• OWL is Written in XML
– By using XML, OWL information can easily be exchanged between different
types of computers using different types of operating system and application
languages.
• OWL is a Web Standard
– OWL became a W3C (World Wide Web Consortium) Recommendation in
February 2004.
– A W3C Recommendation is understood by the industry and the web
community as a web standard. A W3C Recommendation is a stable
specification developed by a W3C Working Group and reviewed by the W3C
Membership.
RDF Reference
• The RDF Namespaces
– The RDF namespace (xmlns:rdf)
is: http://www.w3.org/1999/02/22-rdf-syntax-ns#
– The RDFS namespace (xmlns:rdfs )
is: http://www.w3.org/2000/01/rdf-schema#
• The RDF Extension and MIME Type
– The recommended file extension for RDF files is .rdf.
However, the extension .xml is often used to
provide compatibility with old xml parsers.
– The MIME type should be "application/rdf+xml".
RDFS / RDF Classes
Element
rdfs:Class
Class of
All classes
Subclass of
rdfs:Datatype
rdfs:Resource
Data types
All resources
Class
Class
rdfs:Container
rdfs:Literal
Containers
Literal values (text and numbers)
Resource
Resource
rdf:List
rdf:Property
rdf:Statement
Lists
Properties
Statements
Resource
Resource
Resource
rdf:Alt
rdf:Bag
rdf:Seq
Containers of alternatives
Unordered containers
Ordered containers
Container
Container
Container
rdfs:ContainerMembershipProp Container membership properties
erty
rdf:XMLLiteral
XML literal values
Property
Literal
RDFS / RDF Properties
Element
rdfs:domain
rdfs:range
rdfs:subPropertyOf
Domain
Property
Property
Property
Range
Class
Class
Property
Description
The domain of the resource
The range of the resource
The property is a sub property of a property
rdfs:subClassOf
rdfs:comment
rdfs:label
Class
Resource
Resource
Class
Literal
Literal
rdfs:isDefinedBy
rdfs:seeAlso
rdfs:member
Resource
Resource
Resource
Resource
Resource
Resource
The resource is a subclass of a class
The human readable description of the resource
The human readable label (name) of the
resource
The definition of the resource
The additional information about the resource
The member of the resource
rdf:first
rdf:rest
rdf:subject
rdf:predicate
List
List
Statement
Statement
Resource
List
Resource
Resource
rdf:object
rdf:value
rdf:type
Statement
Resource
Resource
Resource
Resource
Class
The subject of the resource in an RDF Statement
The predicate of the resource in an RDF
Statement
The object of the resource in an RDF Statement
The property used for values
The resource is an instance of a class
RDF Attributes
Element
Domain
Range
Description
rdf:about
Defines the resource being described
rdf:Description
rdf:resource
Container for the description of a resource
Defines a resource to identify a property
rdf:datatype
Defines the data type of an element
rdf:ID
Defines the ID of an element
rdf:li
rdf:_n
rdf:nodeID
Defines a list
Defines a node
Defines the ID of an element node
rdf:parseType
Defines how an element should be parsed
rdf:RDF
The root of an RDF document
xml:base
xml:lang
Defines the XML base
Defines the language of the element content
rdf:aboutEach
rdf:aboutEachPrefix
rdf:bagID
(removed)
(removed)
(removed)
OWL 2
• OWL recommendation now updated to OWL 2
(I didn’t learn my lesson!)
• OWL 2 based on
– includes complex role inclusions, so properly
includes GRAIL
• OWL 2 also defines several profiles – fragments
with desirable computational properties
– OWL 2 EL targeted at very large ontologies
– OWL 2 QL targeted at very large data sets
OWL 2 EL
• A (near maximal) fragment of OWL 2 such that
– Satisfiability checking is in PTime (PTime-Complete)
– Data complexity of query answering also PTimeComplete
• Based on EL family of description logics
• Can exploit saturation based reasoning
techniques
– Computes complete classification in “one pass”
– Computationally optimal (PTime for EL)
– Can be extended to Horn fragment of OWL DL
OWL 2 QL
• A (near maximal) fragment of OWL 2 such that
– Data complexity of conjunctive query answering in AC0
• Based on DL-Lite family of description logics
• Can exploit query rewriting based reasoning technique
– Computationally optimal
– Data storage and query evaluation can be delegated to
standard RDBMS
– Can be extended to more expressive languages (beyond
AC0)
by using “hybrid” techniques or by delegating query
answering to a Datalog engine
Начнем с книги...
Упрощенные данные книжного магазина
(dataset “A”)
ID
Author
Title
Publisher
ISBN 0-00-6511409-X
id_xyz
The Glass Palace
id_qpr
ID
Name
id_xyz
Ghosh, Amitav
ID
id_qpr
Homepage
http://www.amitavghosh.com
Publisher’s name
Harper Collins
City
London
Year
2000
1: Преобразование данных в набор
отношений
The Glass Palace
http://…isbn/000651409X
2000
London
a:author
Harper Collins
a:name
Ghosh, Amitav
a:homepage
http://www.amitavghosh.com
Некоторые замечания по экспорту
данных
• Отношения формируют граф
– Вершины (узлы, nodes) ссылаются на
“реальные” данные или содержат некоторые
литералы (literal);
– как данный граф будет представлен в
компьютере пока не существенно.
Некоторые замечания по экспорту
данных
• Экспорт данных не обязательно означает
физическое преобразование данных
– отношения могут формироваться «на лету» во
время обработки запросов
•
•
•
•
via SQL “bridges”
scraping HTML pages
extracting data from Excel sheets
etc.
• Можно экспортировать часть данных.
Та же самая книга на французском
языке (French) …
Другие данные книжного магазина
(dataset “F”)
A
1
2
B
ID
ISBN 2020286682
C
Titre
Le Palais des Miroirs
3
4
5
6
7
ID
ISBN 0-00-6511409-X
8
9
10
Nom
11
Ghosh, Amitav
12
Besse, Christianne
Auteur
$A11$
D
Traducteur
$A12$
Original
ISBN 0-00-6511409-X
2: Преобразование второго набора
данных
http://…isbn/000651409X
Le palais des miroirs
f:auteur
http://…isbn/2020386682
f:traducteur
f:nom
f:nom
Ghosh, Amitav
Besse, Christianne
3: Объединение (слияние, merging)
данных
The Glass Palace
http://…isbn/000651409X
2000
London
a:author
Harper Collins
a:name
http://…isbn/000651409X
a:homepage
Le palais des miroirs
Ghosh, Amitav
http://www.amitavghosh.com
f:auteur
http://…isbn/2020386682
f:traducteur
f:nom
Ghosh, Amitav
f:nom
Besse, Christianne
3rd: начинаем сливать (merging)
наши данные (продолжение)
The Glass Palace
http://…isbn/000651409X
2000
Same URI!
London
a:author
Harper Collins
a:name
http://…isbn/000651409X
a:homepage
Le palais des miroirs
Ghosh, Amitav
http://www.amitavghosh.com
f:auteur
http://…isbn/2020386682
f:traducteur
f:nom
Ghosh, Amitav
f:nom
Besse, Christianne
3rd: начинаем сливать (merging)
наши данные
The Glass Palace
http://…isbn/000651409X
2000
London
a:author
Harper Collins
f:original
a:name
f:auteur
a:homepage
Le palais des miroirs
Ghosh, Amitav
http://www.amitavghosh.com
http://…isbn/2020386682
f:traducteur
f:nom
Ghosh, Amitav
f:nom
Besse, Christianne
Выполнение запросов…
• User of data “F” can now ask queries like:
– “give me the title of the original”
• well, … « donnes-moi le titre de l’original »
• This information is not in the dataset “F”…
• …but can be retrieved by merging with dataset
“A”!
However, more can be achieved…
• We “feel” that a:author and f:auteur should be
the same
• But an automatic merge doest not know that!
• Let us add some extra information to the merged
data:
– a:author same as f:auteur
– both identify a “Person”
– a term that a community may have already defined:
• a “Person” is uniquely identified by his/her name and, say,
homepage
• it can be used as a “category” for certain type of resources
3 (скорректированный):
использование экстра знаний
The Glass Palace
http://…isbn/000651409X
2000
Le palais des miroirs
f:original
London
a:author
Harper Collins
http://…isbn/2020386682
f:auteur
r:type
a:name
f:nom
f:traducteur
r:type
a:homepage
http://…foaf/Person
f:nom
Besse, Christianne
Ghosh, Amitav
http://www.amitavghosh.com
Начинаем выполнять более
сложные запросы!
• User of dataset “F” can now query:
– “donnes-moi la page d’accueil de l’auteur de
l’original”
• well… “give me the home page of the original’s ‘auteur’”
• The information is not in datasets “F” or “A”…
• …but was made available by:
– merging datasets “A” and datasets “F”
– adding three simple extra statements as an extra
“glue”
Объединение с разными наборами
данных
• Using, e.g., the “Person”, the dataset can be
combined with other sources
• For example, data in Wikipedia can be
extracted using dedicated tools
– e.g., the “dbpedia” project can extract the
“infobox” information from Wikipedia already…
Слияние с данными из Wikipedia
The Glass Palace
http://…isbn/000651409X
2000
Le palais des miroirs
f:original
London
a:author
Harper Collins
http://…isbn/2020386682
f:auteur
r:type
a:name
f:nom
a:homepage
f:traducteur
http://…foaf/Person
r:type
r:type
f:nom
Besse, Christianne
Ghosh, Amitav
foaf:name
http://www.amitavghosh.com
w:reference
http://dbpedia.org/../Amitav_Ghosh
Слияние с данными из Wikipedia
The Glass Palace
http://…isbn/000651409X
2000
Le palais des miroirs
f:original
London
a:author
Harper Collins
http://…isbn/2020386682
f:auteur
r:type
a:name
a:homepage
f:nom
f:traducteur
http://…foaf/Person
r:type
f:nom
r:type
w:isbn
Ghosh, Amitav
foaf:name
Besse, Christianne
http://www.amitavghosh.com
http://dbpedia.org/../The_Glass_Palace
w:reference
w:author_of
http://dbpedia.org/../Amitav_Ghosh
w:author_of
http://dbpedia.org/../The_Hungry_Tide
w:author_of
http://dbpedia.org/../The_Calcutta_Chromosome
Слияние с данными из Wikipedia
The Glass Palace
http://…isbn/000651409X
2000
Le palais des miroirs
f:original
London
a:author
Harper Collins
http://…isbn/2020386682
f:auteur
r:type
a:name
a:homepage
f:nom
f:traducteur
http://…foaf/Person
r:type
f:nom
r:type
w:isbn
Ghosh, Amitav
foaf:name
Besse, Christianne
http://www.amitavghosh.com
http://dbpedia.org/../The_Glass_Palace
w:reference
w:author_of
http://dbpedia.org/../Amitav_Ghosh
w:born_in
w:author_of
http://dbpedia.org/../Kolkata
http://dbpedia.org/../The_Hungry_Tide
w:long
w:author_of
http://dbpedia.org/../The_Calcutta_Chromosome
w:lat
Удивительно ли это?
• It may look like it but, in fact, it should not
be…
• What happened via automatic means is done
every day by Web users!
• The difference: a bit of extra rigour so that
machines could do this, too
It could become even more powerful
• We could add extra knowledge to the merged
datasets
– e.g., a full classification of various types of library data
– geographical information
– etc.
• This is where ontologies, extra rules, etc, come in
– ontologies/rule sets can be relatively simple and
small, or huge, or anything in between…
• Even more powerful queries can be asked as a
result
Что мы сделали?
Applications
Manipulate
Query
…
Data represented in abstract format
Map,
Expose,
…
Data in various formats
Тогда, где же место Semantic Web?
• Semantic Web предоставляет технологии
для того, чтобы сделать такую интеграцию
возможной!
Основы: RDF
RDF триплеты
• Let us begin to formalize what we did!
– we “connected” the data…
– but a simple connection is not enough… data
should be named somehow
– hence the RDF Triples: a labelled connection
between two resources
RDF триплеты (продолжение)
• An RDF Triple (s,p,o) is such that:
– “s”, “p” are URI-s, ie, resources on the Web; “o” is a
URI or a literal
• “s”, “p”, and “o” stand for “subject”, “property”, and “object”
– here is the complete triple:
(<http://…isbn…6682>, <http://…/original>, <http://…isbn…409X>)

RDF is a general model for such triples
 with machine readable formats like RDF/XML, Turtle,
N3, RDFa, …
RDF triples (cont.)
• Resources can use any URI
– http://www.example.org/file.html#home
– http://www.example.org/file2.xml#xpath(//q[@a
=b])
– http://www.example.org/form?a=b&c=d
• RDF triples form a directed, labeled graph (the
best way to think about them!)
A simple RDF example (in RDF/XML)
http://…isbn/2020386682
Le palais des miroirs
http://…isbn/000651409X
<rdf:Description rdf:about="http://…/isbn/2020386682">
<f:titre xml:lang="fr">Le palais des mirroirs</f:titre>
<f:original rdf:resource="http://…/isbn/000651409X"/>
</rdf:Description>
(Note: namespaces are used to simplify the URI-s)
Простой RDF пример
(с использованием Turtle)
http://…isbn/2020386682
Le palais des miroirs
http://…isbn/000651409X
<http://…/isbn/2020386682>
f:titre "Le palais des mirroirs"@fr ;
f:original <http://…/isbn/000651409X> .
A simple RDF example (in RDFa)
http://…isbn/2020386682
Le palais des miroirs
http://…isbn/000651409X
<p about="http://…/isbn/2020386682">The book entitled
“<span property="f:title" lang="fr">Le palais des mirroirs</span>”
is the French translation of the
“<span rel="f:original" resource="http://…/isbn/000651409X">Glass
Palace</span>”</p> .
“Внутренние” вершины
• Consider the following statement:
– “the publisher is a «thing» that has a name and an
address”
• Until now, nodes were identified with a URI.
But…
• …what is the URI of «thing»?
London
Harper Collins
a:publisher
http://…isbn/000651409X
One solution: create an extra URI
• The resource will be “visible” on the Web
– care should be taken to define unique URI-s
<rdf:Description rdf:about="http://…/isbn/000651409X">
<a:publisher rdf:resource="urn:uuid:f60ffb40-307d-…"/>
</rdf:Description>
<rdf:Description rdf:about="urn:uuid:f60ffb40-307d-…">
<a:p_name>HarpersCollins</a:p_name>
<a:city>HarpersCollins</a:city>
</rdf:Description>
Internal identifier (“blank nodes”)
<rdf:Description rdf:about="http://…/isbn/000651409X">
<a:publisher rdf:nodeID="A234"/>
</rdf:Description>
<rdf:Description rdf:nodeID="A234">
<a:p_name>HarpersCollins</a:p_name>
<a:city>HarpersCollins</a:city>
</rdf:Description>
<http://…/isbn/2020386682> a:publisher _:A234.
_:A234 a:p_name "HarpersCollins".
Internal = these resources are not visible outside
London
Harper Collins
a:publisher
http://…isbn/000651409X
Blank nodes: the system can do it
• Let the system create a “nodeID” internally
(you do not really care about the name…)
<http://…/isbn/000651409X> a:publisher [
a:p_name "HarpersCollins";
…
].
London
Harper Collins
a:publisher
http://…isbn/000651409X
Blank nodes when merging
• Blank nodes require attention when merging
– blanks nodes with identical nodeID-s in different
graphs are different
– implementations must be careful…
RDF in programming practice
• For example, using Java+Jena (HP’s Bristol Lab):
– a “Model” object is created
– the RDF file is parsed and results stored in the Model
– the Model offers methods to retrieve:
•
•
•
•
triples
(property,object) pairs for a specific subject
(subject,property) pairs for specific object
etc.
– the rest is conventional programming…
• Similar tools exist in Python, PHP, etc.
Jena example
// create a model
Model model = new ModelMem();
Resource subject=model.createResource("URI_of_Subject")
// 'in' refers to the input file
model.read(new InputStreamReader(in));
StmtIterator iter=model.listStatements(subject,null,null);
while(iter.hasNext()) {
st = iter.next();
p = st.getProperty();
o = st.getObject();
do_something(p,o);
}
Merge in practice
• Environments merge graphs automatically
– e.g., in Jena, the Model can load several files
– the load merges the new statements
automatically
– merge takes care of blank node issues, too
Еще одно относительно простое
приложение
n
n
n
Goal: reuse of older
experimental data
Keep data in
databases or XML,
just export key
“fact” as RDF
Use a faceted
browser to visualize
and interact with the
result
Courtesy of Nigel Wilkinson, Lee Harland, Pfizer Ltd, Melliyal Annamalai, Oracle (SWEO Case Study)
Поднимемся на один уровень выше
(RDFS, Datatypes)
Потребность в RDF схемах
• Первый шаг к “экстра знаниям”:
– define the terms we can use
– what restrictions apply
– what extra relationships are there?
• Officially: “RDF Vocabulary Description
Language”
– the term “Schema” is retained for historical
reasons…
Классы, ресурсы, …
• Рассмотрим широко известные обычные
словари:
–
–
–
–
используем термин “novel”
“every novel is a fiction”
“«The Glass Palace» is a novel”
etc.
• RDFS определяет ресурсы и классы:
– все RDF является “ресурсом” (“resource”)
– “классы” (“classes”) также являются ресурсами, но
…
– … они также являются коллекциями (наборами)
возможных ресурсов (т.е. i.e., индивидуумов
(“individuals”))
• “fiction”, “novel”, …
Классы, ресурсы, … (продолжение)
• Relationships are defined among resources:
– “typing”: an individual belongs to a specific class
• “«The Glass Palace» is a novel”
• to be more precise: “«http://.../000651409X» is a
novel”
– “subclassing”: all instances of one are also the
instances of the other (“every novel is a fiction”)
• RDFS formalizes these notions in RDF
Классы и ресурсы в RDF(S)
rdfs:Class
http://…isbn/000651409X
rdf:type
#Novel
• RDFS defines the meaning of these terms
– (these are all special URI-s, we just use the
namespace abbreviation)
Inferred properties
#Fiction
http://…isbn/000651409X
rdf:type
#Novel
(<http://…/isbn/000651409X> rdf:type #Fiction)
• is not in the original RDF data…
• …but can be inferred from the RDFS rules
• RDFS environments return that triple, too
Логический вывод: позволяет нам
быть формальными…
• The RDF Semantics document has a list of (33)
entailment rules:
– “if such and such triples are in the graph, add this
and this”
– do that recursively until the graph does not change
• The relevant rule for our example:
If:
uuu rdfs:subClassOf xxx .
vvv rdf:type uuu .
Then add:
vvv rdf:type xxx .
Properties
• Property is a special class (rdf:Property)
– properties are also resources identified by URI-s
• There is also a possibility for a “sub-property”
– all resources bound by the “sub” are also bound
by the other
• Range and domain of properties can be
specified
– i.e., what type of resources serve as object and
subject
Example for property characterization
:title
rdf:type
rdf:Property;
rdfs:domain :Fiction;
rdfs:range rdfs:Literal.
What does this mean?
• Again, new relations can be deduced. Indeed, if
:title
rdf:type
rdf:Property;
rdfs:domain :Fiction;
rdfs:range rdfs:Literal.
<http://…/isbn/000651409X> :title "The Glass Palace" .

then the system can infer that:
<http://…/isbn/000651409X> rdf:type :Fiction .
Literals
• Literals may have a data type
– floats, integers, booleans, etc, defined in XML
Schemas
– full XML fragments
• (Natural) language can also be specified
Examples for datatypes
<http://…/isbn/000651409X>
:page_number "543"^^xsd:integer ;
:publ_date
"2000"^^xsd:gYear ;
:price
"6.99"^^xsd:float .
A bit of RDFS can take you far…
• Remember the power of merge?
• We could have used, in our example:
– f:auteur is a subproperty of a:author and vice
versa
(although we will see other ways to do that…)
• Of course, in some cases, more complex
knowledge is necessary (see later…)
Find the right experts at NASA
n
Expertise locater for nearly 70,000 NASA civil
servants,
n
integrate 6 or 7 geographically distributed
databases, …
Michael Grove, Clark & Parsia, LLC, and Andrew Schain, NASA, (SWEO Case Study)
Как получить и создать RDF данные?
Простой подход
• Написать RDF/XML, RDFa или Turtle
“вручную”.
• В некоторых случаях это необходимо
сделать, но в действительности это не
является основным (большим) источником
RDF данных …
RDF с XHTML
• Очевидно, что это огромный источник
информации.
• Путем добавления некоторой “мета”
информации, тот же самый источник может
использоваться повторно, например, для
интеграции данных, лучшего mashups и т.п.
– типичный пример: ваша персональная
информация, такая, как адрес, должна быть
читаемой людьми и обрабатываемой
компьютерными программами.
RDF с XML/(X)HTML (продолжение)
• Появилось два решения:
– использовать микроформаты и
преобразовывать такое содержание в RDF;
• лучше всего такое преобразование выполнять с
помощью XSLT.
– добавить сходные с RDF утверждения
непосредственно в XHTML с помощью RDFa.
Связь с реляционными базами
данных
• Data on the Web are mostly stored in databases
• “Bridges” are being defined:
– a layer between RDF and the relational data
• RDB tables are “mapped” to RDF graphs, possibly on the fly
• different mapping approaches are being used
– a number RDB systems offer this facility already (eg,
Oracle, OpenLink, …)
• W3C is working on a standard in this area
Связанные Открытые Данные
(Linked Open Data)
Проект «Linked Open Data»
• Цель: “выставить на общее обозрение
(expose)” открытые (общедоступные)
наборы данных в RDF формате;
• Задать RDF ссылки (links) между
элементами данных из различных наборов
данных.
• Установить, если это возможно, конечные
точки обработки запросов (query
endpoints).
Пример источника данных: DBpedia
• DBpedia is a community effort to
– extract structured (“infobox”) information from
Wikipedia
– provide a query endpoint to the dataset
– interlink the DBpedia dataset with other datasets
on the Web
Извлечение структурированных
данных из Wikipedia
@prefix dbpedia <http://dbpedia.org/resource/>.
@prefix dbterm <http://dbpedia.org/property/>.
dbpedia:Amsterdam
dbterm:officialName "Amsterdam" ;
dbterm:longd "4” ;
dbterm:longm "53" ;
dbterm:longs "32” ;
dbterm:leaderName dbpedia:Lodewijk_Asscher ;
...
dbterm:areaTotalKm "219" ;
...
dbpedia:ABN_AMRO
dbterm:location dbpedia:Amsterdam ;
...
Автоматическое связывание между
открытыми наборами данных
<http://dbpedia.org/resource/Amsterdam>
owl:sameAs <http://rdf.freebase.com/ns/...> ;
owl:sameAs <http://sws.geonames.org/2759793> ;
...
<http://sws.geonames.org/2759793>
owl:sameAs <http://dbpedia.org/resource/Amsterdam>
wgs84_pos:lat "52.3666667" ;
wgs84_pos:long "4.8833333";
geo:inCountry <http://www.geonames.org/countries/#NL> ;
...
Processors can switch automatically from one to the other…
«Облако» LOD, June 2009
Remember the BBC example?
NYT articles on university alumni
Query RDF Data
(SPARQL)
Выполнение запросов к RDF графам
• Remember the Jena idiom:
StmtIterator iter = model.listStatements(subject,null,null);
while(iter.hasNext()) {
st = iter.next();
p = st.getProperty(); o = st.getObject();
do_something(p,o);


In practice, more complex queries into the RDF data are
necessary
 something like “give me (a,b) pairs for which there is
an x such that (x parent a) and (b brother x) holds”
(ie, return the uncles)
The goal of SPARQL (Query Language for RDF)
Анализ примера на Jena
StmtIterator iter = model.listStatements(subject, null, null);
while(iter.hasNext()) {
st = iter.next();
p = st.getProperty(); o = st.getObject();
do_something(p,o);
?p
?p
subject
?o
?o
?p
?o
?p
?o
General: graph patterns
• The fundamental idea: use graph patterns
– the pattern contains unbound symbols
– by binding the symbols, subgraphs of the RDF
graph are selected
– if there is such a selection, the query returns
bound resources
Перевод примера на в SPARQL запрос
SELECT ?p ?o
WHERE {subject ?p ?o}
• Триплеты в WHERE описывают (define) графовый
шаблон (graph pattern), в котором ?p и ?o
являются “не связанными” символами.
• Данный запрос возвращает все пары (p, o).
?p
?p
subject
?o
?o
?p
?o
?p
?o
Пример простого SPARQL запроса
SELECT ?isbn ?price ?currency # note: not ?x!
WHERE {?isbn a:price ?x. ?x rdf:value ?price. ?x p:currency ?currency.}
Ghosh, Amitav
a:name
a:author
a:author
http://…isbn/000651409X
a:price
rdf:value
33
p:currency
:£
http://…isbn/2020386682
a:price
rdf:value
50
a:price
p:currency
:€
rdf:value
60
p:currency
:€
a:price
rdf:value
78
p:currency
:$
Пример простого SPARQL запроса
SELECT ?isbn ?price ?currency # note: not ?x!
WHERE {?isbn a:price ?x. ?x rdf:value ?price. ?x p:currency ?currency.}
Returns: [<…409X>,33,:£]
Ghosh, Amitav
a:name
a:author
a:author
http://…isbn/000651409X
a:price
rdf:value
33
p:currency
:£
http://…isbn/2020386682
a:price
rdf:value
50
a:price
p:currency
:€
rdf:value
60
p:currency
:€
a:price
rdf:value
78
p:currency
:$
Пример простого SPARQL запроса
SELECT ?isbn ?price ?currency # note: not ?x!
WHERE {?isbn a:price ?x. ?x rdf:value ?price. ?x p:currency ?currency.}
Returns: [<…409X>,33,:£], [<…409X>,50,:€]
Ghosh, Amitav
a:name
a:author
a:author
http://…isbn/000651409X
a:price
rdf:value
33
p:currency
:£
http://…isbn/2020386682
a:price
rdf:value
50
a:price
p:currency
:€
rdf:value
60
p:currency
:€
a:price
rdf:value
78
p:currency
:$
Пример простого SPARQL запроса
SELECT ?isbn ?price ?currency # note: not ?x!
WHERE {?isbn a:price ?x. ?x rdf:value ?price. ?x p:currency ?currency.}
Returns: [<…409X>,33,:£], [<…409X>,50,:€],
[<…6682>,60,:€]
Ghosh, Amitav
a:name
a:author
a:author
http://…isbn/000651409X
a:price
rdf:value
33
p:currency
:£
http://…isbn/2020386682
a:price
rdf:value
50
a:price
p:currency
:€
rdf:value
60
p:currency
:€
a:price
rdf:value
78
p:currency
:$
Пример простого SPARQL запроса
SELECT ?isbn ?price ?currency # note: not ?x!
WHERE {?isbn a:price ?x. ?x rdf:value ?price. ?x p:currency ?currency.}
Returns: [<…409X>,33,:£], [<…409X>,50,:€],
[<…6682>,60,:€], [<…6682>,78,:$]
Ghosh, Amitav
a:name
a:author
a:author
http://…isbn/000651409X
a:price
rdf:value
33
p:currency
:£
http://…isbn/2020386682
a:price
rdf:value
50
a:price
p:currency
:€
rdf:value
60
p:currency
:€
a:price
rdf:value
78
p:currency
:$
Ограничения на шаблоны
SELECT ?isbn ?price ?currency # note: not ?x!
WHERE { ?isbn a:price ?x. ?x rdf:value ?price. ?x p:currency ?currency.
FILTER(?currency == :€) }
Returns: [<…409X>,50,:€], [<…6682>,60,:€]
Ghosh, Amitav
a:name
a:author
a:author
http://…isbn/000651409X
a:price
rdf:value
33
p:currency
:£
http://…isbn/2020386682
a:price
rdf:value
50
a:price
p:currency
:€
rdf:value
60
p:currency
:€
a:price
rdf:value
78
p:currency
:$
Другие дополнительные
возможности SPARQL
• Limit the number of returned results; remove
duplicates, sort them, …
• Optional branches: if some part of the pattern
does not match, ignore it
• Specify several data sources (via URI-s) within
the query (essentially, a merge on-the-fly!)
• Construct a graph using a separate pattern on
the query results
• In SPARQL 1.1: updating data, not only query
Практическое использование
SPARQL
• SPARQL is usually used over the network
– separate documents define the protocol and the
result format
• SPARQL Protocol for RDF with HTTP and SOAP bindings
• SPARQL results in XML or JSON formats
• Big datasets often offer “SPARQL endpoints”
using this protocol
– typical example: SPARQL endpoint to DBpedia
SPARQL как объединяющая точка
SPARQL Endpoint
SPARQL Endpoint
SPARQL Processor
Database
SQLRDF
NLP Techniques
Triple store
Application
Relational
Database
RDF Graph
HTML
Unstructured Text
XML/XHTML
Integrate knowledge for Chinese
Medicine

Integration of a large number of TCM databases
 around 80 databases, around 200,000 records each
Courtesy of Huajun Chen, Zhejiang University, (SWEO Case Study)
Словари
(Vocabularies)
Словари
• Для интеграции данных нужно достигнуть
согласия (agreements) о
– терминах (terms)
• “translator”, “author”
– используемых категориях (categories)
• “Person”, “literature”
– отношениях между ними
• “an author is also a Person…”, “historical fiction is a
narrower term than fiction”
• ie, new relationships can be deduced
Словари
• Требуется “язык” для определения (define)
таких словарей:
– to define those vocabularies
– to assign clear “semantics” on how new
relationships can be deduced
Может использовать RDFS?
• Indeed RDFS is such framework:
– there is typing, subtyping
– properties can be put in a hierarchy
– datatypes can be defined
• RDFS is enough for many vocabularies
• But not for all!
Три новые технологии
1. SKOS – для повторного использования
тезаурусов (thesauri), глоссариев
(glossaries) и т.п.
2. OWL – для определения более сложных
словарей со строгой логической основой.
3. RIF – Обобщенная (Generic) среда для
определения правил для терминов и
данных.
Использование тезаурусов и
глоссариев (SKOS)
Простая система организации
знаний - SKOS
• Represent and share classifications, glossaries,
thesauri, etc
– for example:
• Dewey Decimal Classification, Art and Architecture
Thesaurus, ACM classification of keywords and terms…
• classification/formalization of Web 2.0 type tags
• Define classes and properties to add those
structures to an RDF universe
– allow for a quick port of this traditional data, combine
it with other data
Example: the term “Fiction”, as defined by the Library of
Congress (LOC)
Example: the term “Fiction”, as defined by the Library of
Congress
Тезаурусы имеют идентичные
структуры…
• The structure of the LOC page is fairly typical
– label, alternate label, narrower, broader, …
– there is even an ISO standard for such structures
• SKOS provides a basic structure to create an
RDF representation of these
LOC’s “Fiction” in SKOS/RDF
Literature
skos:Concept
skos:prefLabel
Fiction
rdf:type
http://id.loc.gov/…#concept
Metafiction
Allegories
skos:prefLabel
Adventure stories
skos:prefLabel
Novels
Usage of the LOC graph
Fiction
skos:prefLabel
dc:subject
rdf:type
skos:Concept
The Glass Palace
dc:title
http:.//…/isbn/…
Historical Fiction
Важность SKOS
• SKOS предоставляет простой мост (bridge)
между “print world” и (Semantic) Web.
• Можно сделать тезаурусы, глоссарии и т.п. из
библиотечного сообщества доступными:
– LOC is a good example
• SKOS также может использоваться для
организации тэгов (tags), аннотирования
других словарей …
Важность SKOS
• Любой житель Мира может сослаться на
общие понятия:
– они означают одно и тоже для всех.
• Приложения могут использовать взаимосвязи
между понятиями (concepts):
– например, SPARQL запросы могут использоваться к
объединению библиотечных данных и терминам
LOC.
Semantic portal for art collections
Courtesy of Jacco van Ossenbruggen, CWI, and Guus Schreiber, VU Amsterdam
Онтологии (ontologies)
(OWL)
Системы SKOS не достаточно …
• SKOS может использоваться для
предоставления простых словарей.
• Но это не полное решение
– оно сосредотачивается только на понятиях;
– не характеризует (описывает) свойства в общем
виде;
– простая с точки зрения логики
• т.е., возможно только небольшое количество
экземпляров.
Приложениям может потребоваться
большее …
• Сложным приложениям может потребоваться
больше возможностей:
–
–
–
–
–
–
описание свойств;
identification of objects with different URI-s
disjointness or equivalence of classes
construct classes, not only name them
more complex classification schemes
can a program reason about some terms? E.g.:
• “if «Person» resources «A» and «B» have the same
«foaf:email» property, then «A» and «B» are identical”
– etc.
Web Ontology Language = OWL
• OWL is an extra layer, a bit like RDFS or SKOS
– own namespace, own terms
– it relies on RDF Schemas
• It is a separate recommendation
– actually… there is a 2004 version of OWL (“OWL 1”)
– and there is an update (“OWL 2”) published in 2009
OWL является сложным …
• OWL это большой набор дополнительных
терминов.
• Мы не будем рассматривать все их здесь…
Термины эквивалентности
• Для классов:
– owl:equivalentClass: два класса имеют
одинаковый набор индивидуумов;
– owl:disjointWith: два класса не имеют общих
индивидуумов.
• Для свойств:
– owl:equivalentProperty
• remember the a:author vs. f:auteur?
– owl:propertyDisjointWith
Термины эквивалентности
• Для индивидуумов:
– owl:sameAs: two URIs refer to the same concept
(“individual”)
– owl:differentFrom: negation of owl:sameAs
Other example: connecting to French
a:author
a:Novel
owl:equivalentProperty
owl:equivalentClass
f:auteur
f:Roman
Типичное использование owl:sameAs
• Linking our example of Amsterdam from one
data set (DBpedia) to the other (Geonames):
<http://dbpedia.org/resource/Amsterdam>
owl:sameAs <http://sws.geonames.org/2759793>;

This is the main mechanism of “Linking” in the Linked
Open Data project
Описание свойств
• In OWL, one can characterize the behavior of
properties (symmetric, transitive, functional,
reflexive, inverse functional…)
• One property can be defined as the “inverse”
of another
Это означает, что…
• Если среди триплетов имеется:
:email rdf:type owl:InverseFunctionalProperty.
• :
Это означает, что…
• Если среди триплетов имеется:
:email rdf:type owl:InverseFunctionalProperty.
<A> :email "mailto:a@b.c".
<B> :email "mailto:a@b.c".
Это означает, что…
• Если среди триплетов имеется:
:email rdf:type owl:InverseFunctionalProperty.
<A> :email "mailto:a@b.c".
<B> :email "mailto:a@b.c".
то тогда, в результате обработке OWL, также
верным является:
<A> owl:sameAs <B>.
Ключи (Keys)
• Inverse functional properties are important for
identification of individuals
– think of the email examples
• But… identification based on one property
may not be enough
Keys
“if two persons have the same emails and the same
homepages then they are identical”
• Identification is based on the identical values of
two properties
• The rule applies to persons only
Previous rule in OWL
:Person rdf:type owl:Class;
owl:hasKey (:email :homepage) .
What it means is…
If:
<A> rdf:type :Person ;
:email
"mailto:a@b.c";
:homepage "http://www.ex.org".
<B> rdf:type :Person ;
:email
"mailto:a@b.c";
:homepage "http://www.ex.org".
then, processed through OWL, the following holds,
too:
<A> owl:sameAs <B>.
Классы в OWL
• In RDFS, you can subclass existing classes…
that’s all
• In OWL, you can construct classes from
existing ones:
– enumerate its content
– through intersection, union, complement
– etc
Enumerate class content
:Currency
rdf:type owl:Class;
owl:oneOf (:€ :£ :$).
• I.e., the class consists of exactly of those
individuals and nothing else
Union of classes
:Novel
rdf:type owl:Class.
:Short_Story
rdf:type owl:Class.
:Poetry
rdf:type owl:Class.
:Literature rdf:type owl:Class;
owl:unionOf (:Novel :Short_Story :Poetry).
• Other possibilities: owl:complementOf,
owl:intersectionOf, …
For example…
If:
:Novel
rdf:type owl:Class.
:Short_Story
rdf:type owl:Class.
:Poetry
rdf:type owl:Class.
:Literature rdf:type owl:Class;
owl:unionOf (:Novel :Short_Story :Poetry).
<myWork> rdf:type :Novel .
then the following holds, too:
<myWork> rdf:type :Literature .
It can be a bit more complicated…
If:
:Novel
rdf:type owl:Class.
:Short_Story
rdf:type owl:Class.
:Poetry
rdf:type owl:Class.
:Literature rdf:type owlClass;
owl:unionOf (:Novel :Short_Story :Poetry).
fr:Roman owl:equivalentClass :Novel .
<myWork> rdf:type fr:Roman .
then, through the combination of different terms, the following still holds:
<myWork> rdf:type :Literature .
What we have so far…
• The OWL features listed so far are already
fairly powerful
• E.g., various databases can be linked via
owl:sameAs, functional or inverse functional
properties, etc.
• Many inferred relationship can be found using
a traditional rule engine
However… that may not be enough
• Very large vocabularies might require even
more complex features
– some major issues
• the way classes (i.e., “concepts”) are defined
• handling of datatypes like intervals
• OWL includes those extra features but… the
inference engines become (much) more
complex
Example: property value restrictions
• New classes are created by restricting the
property values on a class
• For example: how would I characterize a
“listed price”?
– it is a price that is given in one of the “allowed”
currencies (€, £, or $)
– this defines a new class
But: OWL is hard!
• The combination of class constructions with
various restrictions is extremely powerful
• What we have so far follows the same logic as
before
– extend the basic RDF and RDFS possibilities with new
features
– define their semantics, ie, what they “mean” in terms
of relationships
– expect to infer new relationships based on those
• However… a full inference procedure is hard
– not implementable with simple rule engines, for
example
OWL “species” or profiles
• OWL species comes to the fore:
– restricting which terms can be used and under
what circumstances (restrictions)
– if one abides to those restrictions, then simpler
inference engines can be used
• They reflect compromises: expressiveness vs.
implementability
OWL Species
OWL Full
OWL DL
OWL RL
OWL EL
OWL QL
OWL RL
• Goal: to be implementable with rule engines
• Usage follows a similar approach to RDFS:
– merge the ontology and the instance data into an
RDF graph
– use the rule engine to add new triples (as long as
it is possible)
What can be done in OWL RL?
• Many features are available:
– identity of classes, instances, properties
– subproperties, subclasses, domains, ranges
– union and intersection of classes (but with some
restrictions)
– property characterizations (functional, symmetric, etc)
– property chains
– keys
– some property restrictions
• All examples so far could be inferred with OWL RL!
Improved Search via Ontology
(GoPubMed)
• Search results are re-ranked using ontologies
– related terms are highlighted
Improved Search via Ontology (Go3R)

Same dataset, different ontology

(ontology is on non-animal experimentation)
Download