Querying the model
Building a model is half the story. The other half is reading it back — to
compute metrics, validate rules, or drive a transformation into some other
format. ontouml-js gives you five families of query methods, from "give me
everything of type X" down to "walk this class's supertypes."
Every example below runs against this small university model:
import { class ProjectAn OntoUML project: the top-level container of an ontology and the entry
point of this library. A project holds every element of a model — classes,
relations, generalizations, packages, properties, notes — as well as the
diagrams and views that depict them, and provides typed access to these
elements by id or by kind.
New elements are created through the fluent builders exposed by the
project (e.g.,
classBuilder
,
binaryRelationBuilder
), which
register the created elements in the project.
A project is also described by the metadata fields of the OntoUML/UFO
Catalog Metadata Vocabulary, such as publisher, license, keywords, themes,
and designed-for tasks.Project } from 'ontouml-js';
const const project: Projectproject = new new Project(): ProjectAn OntoUML project: the top-level container of an ontology and the entry
point of this library. A project holds every element of a model — classes,
relations, generalizations, packages, properties, notes — as well as the
diagrams and views that depict them, and provides typed access to these
elements by id or by kind.
New elements are created through the fluent builders exposed by the
project (e.g.,
classBuilder
,
binaryRelationBuilder
), which
register the created elements in the project.
A project is also described by the metadata fields of the OntoUML/UFO
Catalog Metadata Vocabulary, such as publisher, license, keywords, themes,
and designed-for tasks.Project();
const const model: Packagemodel = const project: Projectproject.Project.packageBuilder(): PackageBuilderCreates a builder for a new
Package
in this project.packageBuilder().PackageBuilder.root(): PackageBuilderSets the package as the root package of its project, i.e., the package
that contains the entire model.root().NamedElementBuilder<PackageBuilder>.name(value: string, language?: string): PackageBuilderAdds a name to the element in the given language.name('University').PackageBuilder.build(): PackageBuilds an instance of
Package
with the parameters passed to the
builder. When no methods are evoked, the created package has the
following defaults:
- `id: "randomly-generated-id",`
- `created: new Date(),`
- `contents: []`build();
const const person: Classperson = const model: Packagemodel.Package.classBuilder(): ClassBuilderCreates a builder for a
Class
contained in this package.classBuilder().ClassBuilder.kind(): ClassBuilderSets the stereotype of the class to «kind», which decorates rigid
classes that provide an identity principle to their instances, which are
functional complexes (e.g., `Person`, `Car`). Also applies the following
defaults:
- `restrictedTo = [ "functional-complex" ]`
- `order = 1`kind().NamedElementBuilder<ClassBuilder>.name(value: string, language?: string): ClassBuilderAdds a name to the element in the given language.name('Person').ClassBuilder.build(): ClassBuilds an instance of
Class
with the parameters passed to the
builder. **WARNING:** the ordering in which methods are evoked may
affect the resulting object. When no methods are evoked, the created
class has the following defaults:
- `id: "randomly-generated-id",`
- `created: new Date(),`
- `isAbstract: false,`
- `isDerived: false,`
- `order: 1,`
- `isPowertype: false,`build();
const const student: Classstudent = const model: Packagemodel.Package.classBuilder(): ClassBuilderCreates a builder for a
Class
contained in this package.classBuilder().ClassBuilder.role(): ClassBuilderSets the stereotype of the class to «role», which decorates anti-rigid
classes whose instances are contingently classified by virtue of a
relational condition (e.g., `Student`, `Employee`).role().NamedElementBuilder<ClassBuilder>.name(value: string, language?: string): ClassBuilderAdds a name to the element in the given language.name('Student').ClassBuilder.build(): ClassBuilds an instance of
Class
with the parameters passed to the
builder. **WARNING:** the ordering in which methods are evoked may
affect the resulting object. When no methods are evoked, the created
class has the following defaults:
- `id: "randomly-generated-id",`
- `created: new Date(),`
- `isAbstract: false,`
- `isDerived: false,`
- `order: 1,`
- `isPowertype: false,`build();
const const university: Classuniversity = const model: Packagemodel.Package.classBuilder(): ClassBuilderCreates a builder for a
Class
contained in this package.classBuilder().ClassBuilder.kind(): ClassBuilderSets the stereotype of the class to «kind», which decorates rigid
classes that provide an identity principle to their instances, which are
functional complexes (e.g., `Person`, `Car`). Also applies the following
defaults:
- `restrictedTo = [ "functional-complex" ]`
- `order = 1`kind().NamedElementBuilder<ClassBuilder>.name(value: string, language?: string): ClassBuilderAdds a name to the element in the given language.name('University').ClassBuilder.build(): ClassBuilds an instance of
Class
with the parameters passed to the
builder. **WARNING:** the ordering in which methods are evoked may
affect the resulting object. When no methods are evoked, the created
class has the following defaults:
- `id: "randomly-generated-id",`
- `created: new Date(),`
- `isAbstract: false,`
- `isDerived: false,`
- `order: 1,`
- `isPowertype: false,`build();
const const enrollment: Classenrollment = const model: Packagemodel.Package.classBuilder(): ClassBuilderCreates a builder for a
Class
contained in this package.classBuilder().ClassBuilder.relator(): ClassBuilderSets the stereotype of the class to «relator», which decorates rigid
classes whose instances are relators, i.e., entities that mediate other
entities and are the truthmakers of material relations (e.g.,
`Marriage`, `Enrollment`). Also applies the following defaults:
- `restrictedTo = [ "relator" ]`
- `order = 1`relator().NamedElementBuilder<ClassBuilder>.name(value: string, language?: string): ClassBuilderAdds a name to the element in the given language.name('Enrollment').ClassBuilder.build(): ClassBuilds an instance of
Class
with the parameters passed to the
builder. **WARNING:** the ordering in which methods are evoked may
affect the resulting object. When no methods are evoked, the created
class has the following defaults:
- `id: "randomly-generated-id",`
- `created: new Date(),`
- `isAbstract: false,`
- `isDerived: false,`
- `order: 1,`
- `isPowertype: false,`build();
// Student is a subtype of Person
const person: Classperson.Classifier<Class, ClassStereotype>.addChild(child: Class): GeneralizationCreates a
Generalization
in which this classifier is the
general and the given classifier is the specific.addChild(const student: Classstudent);
// Enrollment mediates Student and University
const const involvesStudent: BinaryRelationinvolvesStudent = const model: Packagemodel
.Package.binaryRelationBuilder(): BinaryRelationBuilderCreates a builder for a
BinaryRelation
contained in this
package.binaryRelationBuilder()
.BinaryRelationBuilder.mediation(): BinaryRelationBuilderSets the stereotype of the relation to «mediation», which decorates
relations between a relator and an endurant it mediates, such as a
marriage and one of its spouses. Also applies the following defaults:
- `sourceCardinality = "1..*"`
- `targetCardinality = "1"`
- `targetEnd.isReadOnly = true`mediation()
.NamedElementBuilder<BinaryRelationBuilder>.name(value: string, language?: string): BinaryRelationBuilderAdds a name to the element in the given language.name('involves')
.BinaryRelationBuilder.source(classifier: Classifier<any, any>): BinaryRelationBuilderSets the
Classifier
connected to the source end of the relation.source(const enrollment: Classenrollment)
.BinaryRelationBuilder.target(classifier: Classifier<any, any>): BinaryRelationBuilderSets the
Classifier
connected to the target end of the relation.target(const student: Classstudent)
.BinaryRelationBuilder.build(): BinaryRelationBuilds an instance of
BinaryRelation
with the parameters passed
to the builder. Both the source and the target classifiers are required
before `build()` is evoked. **WARNING:** the ordering in which methods
are evoked may affect the resulting object. When no methods are evoked,
the created relation has the following defaults:
- `id: "randomly-generated-id",`
- `created: new Date(),`
- `isAbstract: false,`
- `isDerived: false,`build();
const const enrolledAt: BinaryRelationenrolledAt = const model: Packagemodel
.Package.binaryRelationBuilder(): BinaryRelationBuilderCreates a builder for a
BinaryRelation
contained in this
package.binaryRelationBuilder()
.BinaryRelationBuilder.mediation(): BinaryRelationBuilderSets the stereotype of the relation to «mediation», which decorates
relations between a relator and an endurant it mediates, such as a
marriage and one of its spouses. Also applies the following defaults:
- `sourceCardinality = "1..*"`
- `targetCardinality = "1"`
- `targetEnd.isReadOnly = true`mediation()
.NamedElementBuilder<BinaryRelationBuilder>.name(value: string, language?: string): BinaryRelationBuilderAdds a name to the element in the given language.name('at')
.BinaryRelationBuilder.source(classifier: Classifier<any, any>): BinaryRelationBuilderSets the
Classifier
connected to the source end of the relation.source(const enrollment: Classenrollment)
.BinaryRelationBuilder.target(classifier: Classifier<any, any>): BinaryRelationBuilderSets the
Classifier
connected to the target end of the relation.target(const university: Classuniversity)
.BinaryRelationBuilder.build(): BinaryRelationBuilds an instance of
BinaryRelation
with the parameters passed
to the builder. Both the source and the target classifiers are required
before `build()` is evoked. **WARNING:** the ordering in which methods
are evoked may affect the resulting object. When no methods are evoked,
the created relation has the following defaults:
- `id: "randomly-generated-id",`
- `created: new Date(),`
- `isAbstract: false,`
- `isDerived: false,`build();
1. Collection getters
A Project (and each Package) exposes typed getters that return every
element of a given kind, anywhere in its containment tree. This is the fastest
way to sweep the whole model.
| Getter | Returns |
|---|---|
project.classes | Class[] |
project.relations | Relation[] (binary + n-ary) |
project.binaryRelations | BinaryRelation[] |
project.naryRelations | NaryRelation[] |
project.generalizations | Generalization[] |
project.generalizationSets | GeneralizationSet[] |
project.packages | Package[] |
project.attributes | Property[] |
project.relationEnds | Property[] |
project.literals | Literal[] |
The same getters exist on a Package, scoped to that package's contents:
const const everyClass: Class[]everyClass = const project: Projectproject.Project.classes: Class[]The classes contained in this project.classes; // every class in the project
const const inModel: Class[]inModel = const model: Packagemodel.Package.classes: Class[]The classes directly contained in this package.classes; // only classes in this package
2. Look up a single element by id
When you already know an element's id, fetch it directly. There's a typed
lookup per element kind, plus element(id) for "any element."
const const byClass: ClassbyClass = const project: Projectproject.Project.class(id: string): Class | undefinedRetrieves the class with the given id, if any.class(const person: Classperson.OntoumlElement.id: stringThe unique identifier of this element; a random id by default.id); // Class | undefined
const const byAny: OntoumlElementbyAny = const project: Projectproject.Project.element(id: string): OntoumlElement | undefinedRetrieves the model element with the given id, if any, searching across
classes, relations, generalizations, generalization sets, packages,
properties, literals, notes, and anchors.element(const person: Classperson.OntoumlElement.id: stringThe unique identifier of this element; a random id by default.id); // OntoumlElement | undefined
Also available: binaryRelation(id), naryRelation(id), generalization(id),
generalizationSet(id), package(id), property(id), and more.
3. Query by stereotype and ontological category
Projects and packages answer queries that retrieve classes and relations by their stereotype — and, more powerfully, by ontological category (all sortals, all rigid types, …), which would otherwise take a hand-written filter. On a project they range over the whole model; on a package, over that package and its subpackages.
// By exact stereotype
const const kinds: Class[]kinds = const project: Projectproject.Queries.getKinds(): Class[]Retrieves all classes in scope stereotyped as «kind».getKinds();
const const relators: Class[]relators = const project: Projectproject.Queries.getRelators(): Class[]Retrieves all classes in scope stereotyped as «relator».getRelators();
const const mediations: BinaryRelation[]mediations = const project: Projectproject.Queries.getMediations(): BinaryRelation[]Retrieves all binary relations in scope stereotyped as «mediation».getMediations();
// By ontological category — no manual filtering needed
const const sortals: Class[]sortals = const project: Projectproject.Queries.getSortals(): Class[]Retrieves all classes in scope decorated with a sortal stereotype, i.e., a
stereotype that carries or supplies an identity principle to the instances
of the class.getSortals();
const const rigid: Class[]rigid = const project: Projectproject.Queries.getRigidTypes(): Class[]Retrieves all classes in scope decorated with a rigid stereotype, i.e., a
stereotype of classes whose instances cannot cease to be instances of them
(e.g., «kind», «subkind», «category»).getRigidTypes();
const const antiRigid: Class[]antiRigid = const project: Projectproject.Queries.getAntiRigidTypes(): Class[]Retrieves all classes in scope decorated with an anti-rigid stereotype,
i.e., a stereotype of classes whose instances can cease to be instances of
them (e.g., «role», «phase»).getAntiRigidTypes();
// By an explicit list of stereotypes
const const roles: Class[]roles = const project: Projectproject.Queries.getClassesByStereotype(stereotypes: ClassStereotype[]): Class[]Retrieves all classes in scope whose stereotype is included in
`stereotypes`.getClassesByStereotype([enum ClassStereotypeThe OntoUML stereotypes applicable to a
Class
. Each stereotype
identifies the micro-theory of UFO that governs the class, constraining,
among other things, the ontological natures of its instances (see
Nature
), its rigidity, and the specializations in which it can
participate.ClassStereotype.function (enum member) ClassStereotype.ROLE = "role"An anti-rigid sortal whose instantiation depends on a relational
(extrinsic) condition, e.g., `Student` — a role played by persons while
enrolled in a school.ROLE]);
// The same queries work on a package, scoped to its subtree
const const localKinds: Class[]localKinds = const model: Packagemodel.Queries.getKinds(): Class[]Retrieves all classes in scope stereotyped as «kind».getKinds();
A sampling of what's on offer:
| Category | Methods |
|---|---|
| Ultimate sortals | getKinds, getCollectives, getQuantities, getRelators, getModes, getQualities |
| Base sortals | getSubkinds, getRoles, getPhases |
| Non-sortals | getCategories, getMixins, getRoleMixins, getPhaseMixins |
| Meta-categories | getSortals, getNonSortals, getRigidTypes, getAntiRigidTypes, getSemiRigidTypes |
| Relations | getMediations, getMaterialRelations, getCharacterizations, getComponentOfRelations, … |
| Explicit | getClassesByStereotype, getBinaryRelationsByStereotype, getAttributesByStereotype |
4. Predicates: build your own filters
Each Class answers a family of boolean predicates — the same ones the
stereotype queries use internally. Combine them with Array.filter for
queries the named methods don't cover directly.
// Anti-rigid sortals: roles and phases
const const antiRigidSortals: Class[]antiRigidSortals = const project: Projectproject.Project.classes: Class[]The classes contained in this project.classes.Array<Class>.filter(predicate: (value: Class, index: number, array: Class[]) => unknown, thisArg?: any): Class[] (+1 overload)Returns the elements of an array that meet the condition specified in a callback function.filter(
c: Classc => c: Classc.Class.isSortal(): booleanChecks whether this class is a sortal, i.e., whether all of its
instances follow the same identity principle.isSortal() && c: Classc.Class.isAntiRigid(): booleanChecks whether this class is anti-rigid, i.e., whether every instance
can cease to be classified by it without ceasing to exist.isAntiRigid()
);
Predicates include isKind, isSubkind, isRole, isPhase, isRelator,
isSortal, isNonSortal, isRigid, isAntiRigid, isSemiRigid, isType,
and more.
5. Navigation: taxonomy and relations
The families above start from the whole project. Just as often you start from
one element and walk its neighbourhood — its supertypes, subtypes, or the
relations attached to it. These methods live on any Classifier (so, on every
Class and Relation).
| Method | Returns |
|---|---|
getParents() / getChildren() | direct super/subtypes |
getAncestors() / getDescendants() | transitive super/subtypes |
getRelations() | relations attached to this classifier |
getIncomingRelations() / getOutgoingRelations() | binary relations by direction |
getOwnOppositeRelationEnds() | the far ends of those relations |
And a BinaryRelation exposes its endpoints directly: source, target,
sourceEnd, and targetEnd.
// Walk up the taxonomy: Student -> Person
const const supertypes: string[]supertypes = const student: Classstudent.Classifier<Class, ClassStereotype>.getAncestors(knownAncestors?: Class[]): Class[]Retrieves the direct and indirect supertypes of this classifier.getAncestors().Array<Class>.map<string>(callbackfn: (value: Class, index: number, array: Class[]) => string, thisArg?: any): string[]Calls a defined callback function on each element of an array, and returns an array that contains the results.map(c: Classc => c: Classc.NamedElement.getNameOrId(language?: string): stringReturns the name of this element in the given language, falling back to
its
id
when no suitable name is available.getNameOrId());
// What does the Enrollment relator connect to?
const const mediated: string[]mediated = const enrollment: Classenrollment
.Classifier<Class, ClassStereotype>.getOutgoingRelations(): BinaryRelation[]Retrieves the binary relations whose source is this classifier.getOutgoingRelations()
.Array<BinaryRelation>.map<string>(callbackfn: (value: BinaryRelation, index: number, array: BinaryRelation[]) => string, thisArg?: any): string[]Calls a defined callback function on each element of an array, and returns an array that contains the results.map(rel: BinaryRelationrel => rel: BinaryRelationrel.BinaryRelation.target: Classifier<any, any>The classifier connected at the target end, if typed.target?.NamedElement.getNameOrId(language?: string): stringReturns the name of this element in the given language, falling back to
its
id
when no suitable name is available.getNameOrId());
Putting it together: a lint rule
Query families compose. Here's a real check — every «role» should specialize at least one «kind» — written by combining stereotype queries, navigation, and predicates:
const const orphanRoles: string[]orphanRoles = const project: Projectproject
.Queries.getRoles(): Class[]Retrieves all classes in scope stereotyped as «role».getRoles()
.Array<Class>.filter(predicate: (value: Class, index: number, array: Class[]) => unknown, thisArg?: any): Class[] (+1 overload)Returns the elements of an array that meet the condition specified in a callback function.filter(role: Classrole => !role: Classrole.Classifier<Class, ClassStereotype>.getAncestors(knownAncestors?: Class[]): Class[]Retrieves the direct and indirect supertypes of this classifier.getAncestors().Array<Class>.some(predicate: (value: Class, index: number, array: Class[]) => unknown, thisArg?: any): booleanDetermines whether the specified callback function returns true for any element of an array.some(a: Classa => a: Classa.Class.isKind(): booleanChecks whether this class is stereotyped as «kind».isKind()))
.Array<Class>.map<string>(callbackfn: (value: Class, index: number, array: Class[]) => string, thisArg?: any): string[]Calls a defined callback function on each element of an array, and returns an array that contains the results.map(role: Classrole => role: Classrole.NamedElement.getNameOrId(language?: string): stringReturns the name of this element in the given language, falling back to
its
id
when no suitable name is available.getNameOrId());
This is the shape of most transformations and validators you'll write: pick a
starting set with a stereotype query or a getter, filter with predicates,
and map/navigate to produce your result.
Now you try it
Write a query that lists, for each relator, the names of the classes it mediates. Open the console to see your result.
Show the solution
Recap
- Collection getters (
project.classes, …) sweep the whole model by kind. element(id)and its typed siblings fetch one known element.- Stereotype queries (
getKinds,getRigidTypes, …) retrieve by stereotype and by ontological category, on a project or scoped to a package. - Predicates (
isKind,isSortal, …) power your ownfilters. - Navigation (
getAncestors,getOutgoingRelations,relation.target, …) walks from one element to its neighbours.
Next: generalizations & generalization sets go deeper on the taxonomy these navigation methods traverse.