Object-Oriented Knowledge Representation Jacques Robin CIn-UFPE

Download Report

Transcript Object-Oriented Knowledge Representation Jacques Robin CIn-UFPE

Object-Oriented
Knowledge Representation
Jacques Robin
CIn-UFPE
Ontologies
Reasoning
Components
Agents
Simulations
Outline
 Object-oriented languages
 Review: key concepts of objectorientation
 History of OO languages
 Motivation for OO software
engineering and knowledge
representation
 First generation OOKR languages
 Semantic networks
 Frames
 Comparison with Classical FirstOrder Logic (CFOL)
 UML
 The variety of UML diagrams
 Class diagrams
 Object diagrams
 Meta-knowledge representation
and MOF
 Ontologies
What is an ontology?
Elements of an ontology
Services provided by an ontology
The pluridisciplinary origin of
ontological engineering
 Typology of ontologies
 Sub-fields and general issues in
ontological engineering




 OCL
What is OCL?
Motivating examples
OCL expression contexts
The link between the OCL and UML
metamodels
 The OCL metamodel
 OCL Types
 Inheritance and encapsulation in OCL
 Local variale definitions
 The OCL operator library
 OCL vs. UML
 OCL vs. Java




Review of Key
Object-Orientation Concepts
 Class (or concept, or category): abstract represention of a set of individuals with
common structural and/or behavioral properties
 A class defines a complex type
 Object (or individual, or instance): individual instance of a given class
 An object conforms to the complex type defined by its class
 An object is created by instantiating its class (constructor method)
 Each object possess a unique identifier (oid) that distinguish it from other instance
of the same class sharing the same properties
 The structural properties of a class are a set of attributes (also called fields or
slots) names, each one constrained to be of a certain subset of types (primitive types
or classes)
 The structural properties of an object are specific values for these attributes within
the ranges defined by its class
 The behavioral properties of a class are a set of operations (also called methods,
procedures or functions) that its instance can execute
 The signature of a class is the set of constraints on its attributes and on the
parameters and return value of its operations
 The properties of a class have various visibilities such as public, protected and
private allowing their encapsulation
 Classes are organized in a generalization hierarchy
 Properties are inherited down the hierarchy from a class to its subclasses and its
objects
Inheritance
 Allows concise knowledge representation through reuse of especifications
and implementations among classes and objects down a generalization
hierarchy
 Types of inheritance:
 Structural inheritance
 Attribute signature inheritance (constraint inheritance)
 Value inheritance
 Behavioral inheritance
 Operation signature inheritance (constraint inheritance)
 Operation code inheritance
 Inheritance multiplicity
 Simple inheritance (each class restricted to having a single superclass, and each object
restricted to belong to a single class)
 Multiple inheritance of different properties from different sources
 Multiple inheritance of same property from different sources
 Inheritance monotonicity
 Monotonic inheritance: simple without overriding
 Non-monotonic inheritance: with overriding, logically equivalent to default reasoning,
semantics beyond Classicial First-Order Logic
A Brief History of OO Languages
Software
Engineering
Programming
Databases
Knowledge
Representation
Distributed
System
1965
Today
Simula
Semantic
Networks
Sketchpad
Smalltalk
Today
Frames
C++
UML1.0
OQL
Next
lecture
Description
Logics
SQL’99
OCL
Advanced
AI courses
Java
Today
Frame Logics
Advanced
AI coursed
MOF
C#
2005
UML2.0
Today
Advanced AI
courses
Semantic Web
Languages
Motivation for OO
in Software Engineering
 Improved productivity, quality, legibility and maintainability in
developing software artifacts
 Software reuse instead of rewriting or cut and paste
 More intuitive
 Divide software in abstract entities and relations that directly match
common cognitive abstraction of modeled domain
 Easy to learn
 Unifying notation
 Single representation paradigm for all software process stages
 Single, unified modeling language (UML)
Initial Motivation for OO
in Knowledge Representation
 Reasoning at the level of categories
 Inheritance as reasoning task
 Representing structural knowledge with a notation that is more
intuitive than formal logic
 Easier to acquire, understand, maintain, etc.
 Reasoning about classifying instances into categories and inheritance
can internally reuse a logic-based theorem prover, but in a way that is
transparent-hidden from the domain expert
 Benefits of software engineering carrying over to knowledge (base)
engineering
Categories
 The organization of objects in categories is a vital part of knowledge
representation
 Most human reasoning occurs at the abstract level of general categories
(intentional knowledge), rather than at the level of individual objects
(extensional knowledge)
 Partial information:
 coming for example from the sensors of an agent,
 about an object can be sufficient to classify it into a set of fixed categories
 about which general knowledge has been formalized
 The missing information:
 needed for example for an agent to make a decision about how to handle the
object or predict its behavior
 about the object can then be derived from the properties of the category
 Complex taxomonies involving generalization and composition relationships
among categories form a rich network of abstract knowlege onto which to
base the reasoning of an agent
Properties of Categories
 Disjointness
 No common elements
 Ex.: male and female
 Exhaustive decomposition
 Covers the entire set of entities in the represented domain
 Ex.: an animal that is not male, must be female
 Partition
 Exhaustive decomposition into disjoint categories
 Counter-example: citizenships
 Composition
 A category of objects has another category of objects as one of its constituing
parts
 Ex.: Brazil is part of South America, a chapter is part of a book
Semantic Networks
 Knowledge visual modeling category-oriented
Each category and object is represented by a newtwork node
 Each relationship between categories is represented by a network link
 Special hierarchical relationships is-a (inheritance) and part-of
 Efficient algorithms for deriving object properties, according to
category conformance
 Derivation by value inheritance
 Derivation by link path query
Semantic Networks - Example
Logical assertion
n-ary Fly
Semantic network
with four objects
and four categories
Abstract Syntax of semantic networks
in UML
 OOP/OOSE
Classes
& Objects
 OOP/OOSE
subclass & instance
relationships
 OOSE
aggregation &
composition associations
Node
Link
*
*
IS-A
PART-OF
<<enum>>
Certainty
Level
Attribute
Specification
Known
Default
Single
Value
Specification
Multiple
Value
Specification
 OOP/OOSE
attributes
& other associations
Semantic Networks vs. Classical First-Order
Logic (CFOL): intentional knowledge
 Mary FemalePersons
 SisterOf (Mary, John)
 x x Persons  x  Mammals
 x x Persons  [y HasMother (x, y)  y  FemalePersons]
 x x Persons  Legs (x, 2)
Note that this property has only status of default knowledge, since it can be overrided at the instance level to
represent exceptions such as John
Default knowledge reasoning is non-monotonic and as such cannot be represented in CFOL
Semantic Networks vs. CFOL:
extensional knowledge
 Fly (Shankar, NewYork, NewDelhi, Yesterday)
Semantic Networks - limitations




Main Limitations
1) Incomplete to implement the majority of intelligent systems
2) No well founded declarative semantics (shortcut from konwledge level to
implementation level without using logical formalism)
Frames try to overcome first limitation
Description logics try to overcome second limitation
Other Limitations
Search in large semantic networks may be very inefficient
Nodes and links definitions are not homogenous
Inheritance may cause difficulties while handling exceptions
There can be conflicts between inherited features
Behavior and procedural knowledge is difficult to represent – sequence and time
are not defined
 Less expressive than first-order logic – There are no quantifiers





Frames
 A frame has a name as its identification and describes a complex
object using a set of attributes
 A Frame System is a hierarchical organized set of frames.
 They are an evolution of semantic networks
Nodes are replaced by frames
Edges are replaced by attributes (slots)
They implement monotonic reasoning (ex, inheritance without overriding)
and non-monotonic (ex, inheritance with overriding)
Procedures may be attached to a frame
 They describe knowledge or some procedure related to an attribute.
Frames




Categories (classes) and instances (objects) represented by Frames
A frame is composed by slots
A slot is composed by facets
Facets may be:
 Value specification (known or by default)
 Constraint over value (type, cardinality)
 Procedures (triggers for when the slot is acessed, modified or necessary to
derive some fact during reasoning)
 Frames hierarchically organized with multiple inheritance of slots
 Inheritance is complex (without no formal definition) due to the variety of
facets and interactions
 Reasoning is implemented comgining inheritance and triggers
 Frames used for:
 Knowledge representation
 Inference engine implementation
 Knowledge acquisition interface implementation
 Reasoning explanation interface implementation
 Frames are always an extension of some host programming language (Lisp,
C++, Prolog, etc.)
Frames: example
Frame: Course in KB University
Slot: enrolls
Type: Student
Cardinality.Min: 2
Cardinality.Max: 30
Slot: taughtby
Type: (UNION GradStudent
Professor)
Cardinality.Min: 1
Cardinality.Max: 1
Frame: BasCourse in KB University
Is-a: Course
Slot: taughtby
Type: Professor
Frame: AdvCourse in KB University
Is-a: Course
Slot: enrolls
Type: (INTERSECTION
GradStudent
(NOT Undergrad))
Cardinality.Max: 20
Frame: GradStudent in KB University
Is-a: Student
Slot: degree
Default: Bachelor
Frame: Professor in KB University
Slot: degree
Default: PhD.
Frame: Student in KB University
Frame: Undergrad in KB University
Is-a: Student
Abstract Syntax for Frames im UML
 OOP/OOSE
subclass & instance
relationships
 OOP/OOSE
Classes
& Objects
 OOP/OOSE
Attributes
& Associations
No corresponding
concepts in
OOP/OOSE
 OOSE
Constraints
 OOP/OOSE
Methods
& Activities
IS-A
*
Frame
*
Slot
<<enum>>
Certainty
Level
Known
Default
*
Host
Language
Procedure
Facet
Value
Specification
Single
Value
Specification
Multiple
Value
Specification
Constraint
Procedural
Attachment
<<enum>>
Trigger
Missing
Read
Write
Cardinality
Constraint
Min: Int
Max: Int
Type
Constraint
Return
Value
Input
Parameter
Frames: limitations
 Non-declarative Behavior Knowledge prevents direct codification
from domain expert
 No formal semantic
 Implementation ad-hoc of deduction e adbduction, usually
inefficient
 There are no inductive inference engines for frame learning
 It does not include encapsulation concepts nor components from
moder OO programming languages
UML as KR Language
 Class diagram:
 Modern, well-founded version of semantic networks
 Activity diagram
 Modern, well-founded version of flow charts
 Graphical syntax for procedures
 Class diagrams + Activity diagrams :
 Graphical syntax of expressive power approximately equivalent to that of Frames
 Strengths:
 Universal standard, well-thought, well-known and well-tooled (CASE)
 Facilitates convergence between software and knowledge engineering
 Limitations:
 Lack of full UML compilers to executable languages
 Lack of inference engine to automatically reasoning with knowlege represented
only as UML models
 No mathematically defined formal semantics yet
 Thus:
 Only useful at the knowledge level
 Need to be used in conjunction with other language(s) that provide the formalization
and/or implementation level
UML Classifiers: Simplified Meta-Model
Type
generalizes
Classifier
DataType
PrimitiveType
Boolean
Integer
Feature
Interface
Enumeration
Real
Class
Association
AssociationClass
String
StructuralFeature
BehavioralFeature
Property
Operation
AssociationEnd
Attribute
Parameter
Constraint
Classes: Operations
 Common signature of services provided
by the class members
 Fields:
 Visibility
 Name
 Input parameter






Direction
Name
Type
Multiplicity
Default value
Property
 Return type
 Property
 Object methods: called on objects
 Class methods: called to manipulate
class attributes
 Operations for KR: as many fields as
possible!
UML Relations: Simplified Meta-Model
Relation
Association
AssociationClass
QualifiedAssociation
Generalization
Dependency
Aggregation
GeneralizationSet
Realization
Composition
PowerType
Associations
Association:
 Generic relation between N
classifiers
 Fields:
 One or two Names
 Navigation direction
 Two Ends, each with:
 One Multiplicity Range (default = 1)
 Zero to One role
 Zero to one Qualifier
 Qualifier: needed to distinguish
different instances of a one-tomany or many-to-many association
 Navigation:
 Role if present
 Otherwise destination class name
 Associations for KR: as many fields
as possible!
Association Classes
 Class connected to an association and not to
any of its ends
 Allows associating properties and behaviors
to an association
 One object of the association class for each
link of the connected association
 A one-to-many or many-to-many association
class cannot be substituted by a simple class
and a pair of simple associations
 Example:
 Ca has objects A1, A2, A3, A4
 Cb has objects B1, B2, B3, B4
 Extent of association class Cc between Ca and
Cb with * multiplicity at both ends has
necessarily 16 instances
 Class Cc associated to Ca through association
Aca and to Cb through association Acb could
have only 4 instances
Difference with:
?
4
Elevator
control
Queue
Elevator
Ternary Associations
 Single association
between 3 classes
 Different from two
binary associations
 Different from one
binary association class
 Example:




Ca has objects A1, A2
Cb has objects B1, B2
Cc has objects C1, C2
No link in the ternary
association Ca-Cb-Cc
corresponding to pair
of links A1-B1, B2-C1
Aggregation Associations
 Association with “part-whole”
semantics
 Associate composite class to its
building blocks
 Static, definitional characteristic
of the “whole” class
 In contrast to composite
structure diagrams that model
dynamic, configuration
characteristic of the containing
class
 Shared aggregation:
 Many-to-many aggregation
Composition Associations
 Special case of one-to-one or one-to-many aggregation where
part(s) cannot exist(s) without the unique whole
 Deletion of the whole must therefore always be followed by
automatic deletion of the parts
Class generalizations
 Taxonomic relation between a class and one of its more general direct
super-class
 Special case of generalization between any two classifiers
 Several generalizations form a taxonomic tree free of generalization cycles
 Sub-classifier inherits the features from all its direct super-classifiers
 Private attributes and operations not accessible from sub-classes
 Protected attributes and operations accessible from sub-classes but not
from associated classes
 UML generalizations allow multiple inheritance
and overriding
 Instances of a sub-class must
satisfy all the constraints on
all its super-classes
(principle of substitutability)
Abstract Classes
 Class that cannot be instantiated
 Only purpose: factor gradual refinements of common and distinct structures and
behaviors down a taxonomic hierarchy
 Abstract operation: common signatures of distinct implementations specified in
subclasses
 Supports polymorphism: generic call signature to distinct operations, with automatic
dispatch to the implementation appropriate to each specific call instance
Generalization Sets
 Subclass set that can be labeled as:
 complete or incomplete
 overlapping or disjoint
 Complete and disjoint generalization sets form a partition of the
super-class
 Sub-subclass can specialize members of two overlapping
generalization sets
Objects and Links
 Object Diagram contains:
 Specific (named) or generic
(named after role, unnamed)
instances of classes
 Possibly several instances of
the same class
 Specific instances of
associations (links) among
objects
 Possibly several instances of
the same association
 Illustrates specific
instantiation patterns of
associated class diagram
UML x Semantic Networks: Example
 Semantic Network
 Corresponding Class Diagram
UML x Semantic Network: Example
 Semantic Network
 Corresponding Class Diagram
UML x Frames: Example
Frame: Course in KB University
Slot: enrolls
Type: Student
Cardinality.Min: 2
Cardinality.Max: 30
Slot: taughtby
Type: (UNION GradStudent
Professor)
Cardinality.Min: 1
Cardinality.Max: 1
Frame: AdvCourse in KB University
Is-a: Course
Slot: enrolls
Type: (INTERSECTION
GradStudent
(NOT Undergrad))
Cardinality.Max: 20
Frame: BasCourse in KB University
Is-a: Course
Slot: taughtby
Type: Professor
Frame: Student in KB University
Frame: GradStudent in KB University
Is-a: Student
Slot: degree
Default: Bachelor
Frame: Undergrad in KB University
Is-a: Student
Frame: Professor in KB University
Slot: degree
Default: PhD.
UML – Unified Modeling Language
 UML advantages as knowledge representation language
Standard – notation and edition tools
Well-defined Links – composition, agreggation, inheritance, ...
It works at the knowledge level
Graphical – easy modeling
Comparison Table
Semantic
Networks
Frames
UML + OCL
Predicate
Logic
Originated field
IA
IA
SE
IA
Inference engine for automated
reasoning
Yes
Yes
No
Yes
Complete well founded formal
declarative semantics
No
No
No
Yes
Structural
Struc. Declar.
Bheavior.
Procedural
Struct. Declar.
Behavior. Procedural
Struct. Declar.
Yes
No
Yes
No
Knowledge Representation
Easy visual syntax
O que é uma ontologia?
 Definição: especificação (semi-)formal explícita de uma concepção
compartilhada
 Concepção: modelo das entidades, relações, axiomas e regras de algum
domínio
 Formal:
 processável por máquina
 permitindo raciocínio automático
 com semântica lógica formal
 Compartilhada: por uma comunidade, permitindo entendimento
 Conceitos de computação relacionados:
 Base de conhecimento reutilizável
 Esquema de banco de dados
Elementos de uma ontologia
 Hierarquia de conceitos:
 entidades
 cada entidade definida por conjunto de pares atributo-valor
 correspondem:
 as classes dos modelos orientado a objetos
 as entidades do modelo relacional
 aos termos do modelo lógico
 atributos propriedades x atributos relações
 preenchidos por valores atômicas (tipos primitivos) x por outros conceitos
 Status epistemológico do valor
 Exatamente conhecida, default, probabilista
 relações
 sem hierarquia x em hierarquia paralela a hierarquia de entidades
 correspondem:
 associações, agregações e atributos dos modelos OO cujos valores são objetos
 as relações do modelo relacional
 aos predicados do modelo lógico
Elementos de uma ontologia
 Restrições:
 sobre valores possíveis dos atributos dos conceitos
 correspondem:
 as assinaturas de classes em modelos OO
 as axiomas universalmente quantificados em modelos lógicos
 as restrições de integridade nos esquema de BD
 Regras dedutivas:
 sobre atributos de (conjunto de) conceitos
 permitem inferência automática da existência de instâncias de conceitos
a partir da existência de outras instâncias
 correspondem:
 as regras dos sistemas especialistas e programação em lógica
 aos métodos dos modelos OO
 as visões em BD
Elementos de uma ontologia
 Instâncias de conceitos:
 definição de entidade e relações específicos (indivíduos)
 correspondem:
 aos fatos de sistemas especialistas e programação em lógica
 aos objetos dos modelos OO
 aos dados dos BD
Serviços suportados por uma ontologia
 Consultas e manipulação:
 correspondem:
 métodos de acesso a valor e de reflexão em linguagens OO
 consultas de interrogação e manipulação em BD
 ask, tell e retract das bases de conhecimento
 sobre conceitos:
 Quais são as entidades E relacionadas a entidade 0 via relações r1, r2?
 Quais são as relações R mais gerais que r1?
 Definição d de entidade E é consistente com o resto da ontologia?
 sobre instâncias
 um indivíduo I com propriedades P1, ..., Pn é instância de quais conceitos?
 Raciocínio automático
 geralmente dedutivo
Origem e motivação para ontologias
Sistemas
Especialistas
desde 80
Gerenciamento
do Conhecimento
em Organizações
desde 90
Psicologia
Cognitiva
desde 60
Filosofia
desde 350 A.C.
Integração
de Dados
desde 95
Engenharia
de Software:
requisitos e reuso
desde 90
Ontologias
Lingüística
desde 60
Processamento
de Linguagem
Natural
desde 80
Sistemas
Multi-agentes
desde 95
Recuperação
de Informação
na Web
desde 00
Tipologia das ontologias
 Especialista: modela um domínio particular restrito
 Geral:
 modela o conhecimento de senso comum compartilhado por todos os
seres humanos
 parte de mais alto nível, reutilizável em vários domínios
 Conceitual: fundamentada na capacidade de raciocinar
 Lingüística: fundamenta no vocabulário de uma(s) língua(s)
 De meta-dados: “especializada” na descrição de recursos on-line, no
entanto sobre qualquer domínio
 De tarefas e métodos: modela procedimentos e comportamentos
abstratos no lugar de entidades ou relações
Anything
AbstractObjects
Events
Sets
Numbers
RepresentationalObjects
Intervals
Categories
Places
PhysicalObjects
Stuff
Things
Sentences
Measurements
Processes
Moments
Animals
Agents
Humans
Solid
Liquid
Gas
Sub-problemas de modelagem de uma
ontologia geral










Categorias e conjuntos
Medidas
Objetos compostos
Tempo
Espaço
Mudanças
Eventos e processos
Objetos físicos
Substâncias
Objetos mentais e crenças
Problemática geral e questões
sobre ontologias
 Divisão:
 como delimito as classes e os atributos?
 quais são as distinções que trazem valor agregado?
 Escopo:
 qual conhecimento incluir?
 qual a fronteira do meu domínio?
 Granularidade:
 até que nível de detalhe modelar os domínio?
 problema da ramificação?
 Validação:
 como avalio a qualidade do modelo?
 como escolho entre várias modelagem alternativas (as vezes propostas
por pessoas diferentes)?]
 como identificar aspectos importantes que estão faltando?
Problemática geral e questões
sobre ontologias
 Muito difícil responder a essas perguntas porque:
 Almejados reuso e relativa independência de aplicação impedem ser
guiado completamente pelos requisitos de uma aplicação restrita
 Para ontologias gerais de senso comum pior devido a imensidão em
largura e profundidade do conhecimento a modelar
 Metodologias ainda incipientes
 Methontology:
 Sensus: http://www.isi.edu/natural-language/resources/sensus.html
 No entanto, já existe tentativa de padronização: http://suo.ieee.org/
http://www.fipa.org/
What is OCL?
Definition and Role
 A textual specification language to adorn UML and MOF diagrams and make
them far more semantically precise and detailed
 OCL2 integral part of the UML2 standard
 OCL complements UML2 diagrams to make UML2:
 A domain ontology language that is self-sufficient at the knowledge level to
completely specify both structure and behaviors
 A complete input for the automated generation of a formal specification at the
formalization level to be verified by theorem provers
 A complete input for the automated generation of source code at the
implementation level to be executed by a deployment platform
 OCL complements MOF2 diagrams to make MOF2:
 An object-oriented declarative abstract syntax and semantics specification
language that is self-sufficient at the meta-knowledge/meta-modeling level
 OCL forms the basis of model transformation languages
 such as Atlas Transformation Language (ATL) or Query-View-Transform (QVT)
 which declaratively specify through rewrite transformation rules the automated
generation of formal specifications and implementations from a knowledge level
ontology
 OCL expressions are reused in the left-hand side and right-hand side of such
rules
 To specify objects to match in the source ontology of the transformation
 To specify objects to create in the target formal specification or code of the
transformation
What is OCL?
Characteristics
 Formal language with well-defined semantics based on set theory and firstorder predicate logic, yet free of mathematical notation and thus friendly
to mainstream programmers
 Object-oriented functional language: constructors syntactically combined
using functional nesting and object-oriented navigation in expressions that
take objects and/or object collections as parameters and evaluates to an
object and/or an object collection as return value
 Strongly typed language where all expression and sub-expression has a
well-defined type that can be an UML primitive data type, a UML model
classifier or a collection of these
 Semantics of an expression defined by its type mapping
 Declarative language that specifies what properties the software under
construction must satisfy, not how it shall satisfy them
 Side effect free language that cannot alter model elements, but only
specify relations between them (some possibly new but not created by OCL
expressions)
 Pure specification language that cannot alone execute nor program models
but only describe them
 Both a constraint and query language for UML models and MOF metamodels
What is OCL?
How does it complement UML?
 Structural adornments:
 Specify complex invariant constraints (value, multiplicity, type, etc)
between multiple attributes and associations
 Specify deductive rules to define derived attributes, associations and
classes from primitive ones
 Disambiguates association cycles
 Behavioral adornments:




Specify operation pre-conditions
Specify write operation post-conditions
Specify read/query operation bodies
Specify read/query operation initial/default value
OCL: Motivating Examples
 Diagram 1 allows Flight with unlimited
number of passengers
 No way using UML only to express
restriction that the number of
passengers is limited to the number
of seats of the Airplane used for the
Flight
 Similarly, diagram 2 allows:
 A Person to Mortgage the house of
another Person
 A Mortgage start date to be after its
end date
 Two Persons to share same social
security number
 A Person with insufficient income to
Mortgage a house
1
2
OCL: Motivating Examples
context Flight
inv: passengers -> size()
<= plane.numberOfSeats
1
context Person
inv: Person::allInstances() -> isUnique(socSecNr)
context Person::getMortgage(sum:Money,security:House)
pre: self.mortgages.monthlyPayment -> sum() <= self.salary * 0.3
context Mortgage
inv: security.owner = borrower
inv: startDate < endDate
2
OCL Expression Contexts
Operation
OCL Contexts:
Default Value and Query Specifications
Initial values:
 context LoyaltyAccount::points : integer
init: 0
 context LoyaltyAccount::transactions
: Set(Transaction)
init: Set{}
Query operations:
 context LoyaltyAccount::getCustomerName()
: String
body: Membership.card.owner.name
 context LoyaltyProgram::getServices():
Set(Services)
body: partner.deliveredServices -> asSet()
OCL Contexts:
Specifying Invariants on Attributes
The context of an invariant constraint is a class
When it occurs as navigation path prefix, the self
keyword can be omitted:
 context Customer inv: self.name = ‘Edward’
 context Customer inv: name = ‘Edward’
Invariants can be named:
 context Customer inv myInvariant23:
self.name = ‘Edward’
 context LoyaltyAccount
inv oneOwner: transaction.card.owner
-> asSet() -> size() = 1
In some context self keyword is required:
 context Membership
inv:
participants.cards.Membership.includes(self)
OCL Contexts: Invariants for Disambiguating
Association Cycles and Plural Multiplicity
 Cycles of association with plural
multiplicity are often underconstrained
by class diagrams, thus not reflecting
actual modeled domain semantics
 In the real world a person cannot use
the house of another person as security
for a mortgage
 context Person
inv: mortgages.security.owner ->
forall(onwner:Person | owner = self)
Association Navigation
 Association navigation:
 context Transaction
def getCustomer():Customer =
self.card.owner
 Attribute access:
 context Transaction
def getCustomerName():String =
self.card.owner.name
 Abbreviation of collect operator that
creates new collection from existing one, for
example result of navigating association with
plural multiplicity:
 context LoyaltyAccount
inv: transactions -> collect(points) ->
exists(p:Integer | p=500)
 context LoyaltyAccount
inv: transactions.points ->
exists(p:Integer | p=500)
 Use target class name to navigate roleless
association:
 context LoyaltyProgram
inv: levels ->
includesAll(Membership.currentLevel)
 Call UML model and OCL library operations
Generalization Navigation
 OCL constraint to limit points earned
from single service to 10,000
 Cannot be correctly specified using
association navigation:
context ProgramPartner
inv totalPoints:
deliveredServices.transactions
.points -> sum() < 10,000
adds both Earning and Burning points
 Operator oclIsTypeOf allows hybrid
navigation following associations and
specialization links
context ProgramPartner
inv totalPoints:
deliveredServices.transactions
-> select(oclIsTypeOf(Earning))
.points -> sum() < 10,000
OCL Contexts:
Specifying Attribute Derivation Rules
 context CustomerCard::printedName
derive: owner.title.concat(‘ ‘).concat(owner.name)
 context TransactionReportLine: String
derive self.date = transaction.date
 ...
 context TransactionReport
inv dates: lines.date -> forAll(d |
d.isBefore(until) and d.isAfter(from))
 ...
OCL Contexts:
Specifying Pre and Post Conditions
 context LoyaltyAccount::isEmpty(): Boolean
pre: -- none
post: result = (points = 0)
Keyword @pre used to refer in post-condition to
the value of a property before the execution of
the operation:
 context LoyaltyProgram::enroll(c:Customer)
pre: c.name <> ‘ ‘
post: participants = participants@pre ->
including(c)
Keyword oclIsNew used to specify creation of a new
instance (objects or primitive data):
 context LoyaltyProgram::
enrollAndCreateCustomer(n:String,d:Date):Cust
omer
post: result.oclIsNew() and result.name = n and
result.dateOfBirth = d and
participant -> includes(result)
oclIsNew only specifies that the operation created
the new instance, but not how it did it which
cannot be expressed in OCL
Links Between
OCL and UML Meta-Models
ModelElement
+constrainedElement +constraint
0..*
Constraint
0..*
0..1
1
Classifier
+body
Expression
ExpressionInOcl
+bodyExpression
1
OclExpression
The OCL Expressions Meta-Model
The OCL Types Meta-Model
+type
StructuralFeature
0..*
+elementType
Classifier
1
OclMessageType
1
OclModelElementType
TupleType
DataType
Primitive
VoidType
CollectionType
0..4
+collectionTypes
SetType
SequenceType
BagType
OrderedSetType
0..1
+referredSignal
0..1
+referredOperation
UML Metaclass
Signal
Operation
OCL Metaclass
OCL Types
 Value Types:
 UML primitive types (including user-defined enumerations)
 OCL collection types (even of user-defined classifiers ?)
 Their instances never change value
 ex, Integer instance 1 cannot be changed to instance 2, nor can string
instance “Lew Alcindor” be changed to string instance “Kareem Abdul-Jabbar”,
nor can enumeration Grade instance A can be changed to enumeration instance
C.
 Object types: UML classifiers
 Their instances can change value, i.e., the Person instance p1 can have its
name attribute “Lew Alcindor” changed to “Kareem Abdul-Jabbar” yet
remain the same instance p1
 OclAny:
 Most generic OCL type, subsuming all others
 General reflective operations are defined for this type and inherited by
all other OCL types
OCL Types
 Primitive data types (from UML): boolean, string, integer, real
 Type conformance rules:
 t1 conforms to t2 if t1 <= t2 in type hierarchy
 t1 = collection(t2) conforms to t3 = collection(t4) if t2 conforms to t4
 integer <= real
 Type casting:
 Operation oclAsType(s) can be invoked on an expression of type g to
recast it as a type s
 s must conform to g
 OclVoid:
 Undefined value (similar to null values of SQL)
 Tested by oclIsUndefined operation of OclAny type
OCL Types: Collections
 Collection constants can be specified in extension:
 Set{1, 2, 5, 88}, Set{‘apple’, ‘orange’, ‘strawberry’}
 OrderedSet{‘black’, ‘brown’, ‘red’, ‘orange’, ‘yellow’, ‘green’, ‘blue’, ‘purple’}
 Sequence{1, 3, 45, 2, 3}, Bag{1, 3, 4, 3, 5}
 Sequence of consecutive integers can be specified in intension:
 Sequence{1..4} = Sequence{1,2,3,4}
 Collection operations are called using -> instead of .
 Collection operations have value types:
 They do not alter their input only output a new collection which may
contain copies of some input elements
 Most collections operations return flattened collections
 ex, flatten{Set{1,2},Set{3,Set{4,5}}} = Set{1,2,3,4,5}
 Operation collectNested must be used to preserve embedded substructures
 Navigating through several associations with plural multiplicity
results in a bag
OCL Semantics:
Encapsulation and Inheritance
 By default, OCL expressions
ignore attribute visibility
 i.e., an expression that access a
private attribute from another
class is not syntactically rejected
 OCL constraints are inherited
down the classifier hierarchy
 OCL constraints redefined down
the classifier hierarchy must
follow substituability principle
 Invariants and post-condition can
only become more restrictive
 Preconditions can only become less
restrictive
Examples violating substituability principle:
context Stove inv: temperature <= 200
context ElectricStove
inv: temperature <= 300
context Stove::open()
pre: status = StoveState::off
post: status = StoveState::off and isOpen
context ElectricStove::open()
pre: status = StoveState::off and
temperature <= 100
post: isOpen
OCL Expressions: Local Variables
 Let constructor allows creation of aliases
for recurring sub-expressions
context CustomerCard
inv: let correctDate : Boolean =
validFrom.isBefore(Date::now) and
goodThru.isAfter(Date::now)
in if valid then correctDate = false
else correctDate = true
endif
 Syntactic sugar that improves constraint
legibility
OCL Library: Generic Operators
 Operators that apply to expressions of any type
 Defined at the top-level of OclAny
OCL Library: Primitive Type Operators
 Boolean: host, parameter and return type boolean
 Unary: not
 Binary: or, and, xor, =, <>, implies
 Ternary: if-then-else
 Arithmetic: host and parameters integer or real
 Comparison (return type boolean): =, <>, <, > <=, >=,
 Operations (return type integer or real): +, -, *, /, mod, div, abs, max,
min, round, floor
 String: host string
 Comparison (return type boolean): =, <>
 Operation: concat(String), size(), toLower(), toUpper(),
substring(n:integer,m:integer)
OCL Library: Generic Collection Operators
OCL Library: Syntax of Loop Operators
 Loop operators (aka. iterator operations, aka. iterators)
 Common characteristics:
 They are all hosted by an OCL expression of type collection
 They all take an OCL expression as input parameter (called the body of
the loop)
 They optionally take as second parameter an iterator variable
 The return type of the body expression and the type of the iterator
variable must conform to the type of the host collection’s elements
 Loop operators iterate over the elements of the host collection,
applying the body expression to each one of them
 Distinguishing characteristics:
 How they combine the body expression application into a new result
collection
OCL Library:
Specialized Collection Operators
Example of OCL Expressions
with Loop Operators
 context LoyaltyProgram
inv self.Membership.account
-> isUnique(acc: LoyaltyAccount |
acc.number)
 context LoyaltyProgram
inv Membership.account
-> isUnique(acc | acc.number)
 context LoyaltyProgram
inv Membership.account -> isUnique(number)
 Iterator variable clarifies that number
refers to the number attribute of each
collection element and not to the number of
elements in the collection
 Loop expressions with reference to the
iterator requires an iterator variable:
 context ProgramPartner
inv: self.programs.parters
-> select(p:ProgramPartner | p.self)
OCL Constraints vs. UML Constraints
context: ClassicalGuitar inv: strings
-> forAll(s | s.oclIsType(plasticStrings))
context ElectricGuitar inv: strings
-> forAll(s \ s.oclIsType(MetalStrings))
context ClassicGuitar inv: strings
-> forAll(type = StringType::plastic)
context ElectricGuitar inv: strings
-> forAll(type = StringType::metal)
context Guitar
inv: type = GuitarType::classic implies
strings -> forAll(type = StringType::plastic
inv: type = GuitarType::classic implies
strings -> forAll(type = StringType::plastic
OCL vs. Java




1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
Declarative specification of operation post-conditions in OCL is far more concise than
corresponding implementation in mainstream imperative OO language such as Java
This is due mainly to OCL’s powerful collection operators
Example: OCL expression
self.parters -> select(deliveredServices -> forAll(pointsEarned = 0))
Corresponding Java code:
Iterator it = this.getPartners().iterator();
Set selectResult = new HashSet();
while( it.hasNext() ){
ProgramPartner p = (ProgramPartner) it.next();
Iterator services = p.getDeliveredServices().iterator();
boolean forAllresult = true;
while( services.hasNext() ){
Service s = (Service) services.next();
forAllResult = forAllResult && (s.getPointsEarned() == 0);
}
if ( forAllResult ){
selectResult.add(p);
}
}
return result;