All files / rdf class-repository.ts

93.02% Statements 120/129
84.61% Branches 66/78
91.3% Functions 21/23
92.96% Lines 119/128

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440              9x           10x                 44x   44x 20816x 8507x   8507x                         2533x 2533x   2533x 1617x 1607x   1607x                     927x   927x                     2522x 1597x 1595x   1595x       927x                 10x 10x   10x 9x 7x       3x                 34x 31x 31x 31x   31x 71x 3x         68x 55x   55x       3x                                                                               6x   6x                       20x   20x 14x   14x   14x                                                   15x   3x         3x 3x   3x 1782x 80x 1702x 160x         3x 64x 18x         12x   12x 77x 51x   51x                             921x 1583x 17x     904x                   3x   3x 1x       2x 1x 1x       1x       4x 4x 2x       2x                   4x   4x 2x       2x 1x 1x       1x       5x 5x 2x     3x 1x       2x                   13x 13x       13x     13x   13x 1366x 1286x     80x   80x 32x   32x   32x     80x     1327x                     5x     5x 3x     2x                     5x                         19x 1x     18x   18x     18x 3x 3x         15x 14x 1x       14x    
import * as rdfjs from "@rdfjs/types";
import { rdf, rdfs, owl } from "../ontologies";
import { Store } from "./store";
import { QueryOptions, DefinitionQueryOptions, TypedInstanceQueryOptions } from "./resource-repository";
import { ConceptRepository } from "./concept-repository";
import { RdfDataFactory } from "./rdf-data-factory";
 
const { namedNode } = RdfDataFactory;
 
/**
 * A repository for retrieving classes from graphs.
 */
export class ClassRepository extends ConceptRepository {
    constructor(store: Store) { super(store); }
 
    /**
     * Get all classes in the repository.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param options Optional query parameters.
     * @returns An iterator of all classes in the repository.
     */
    *getClasses(graphUris: string | string[] | undefined, options?: DefinitionQueryOptions): IterableIterator<string> {
        const yielded = new Set<string>();
 
        for (let q of this.store.matchAll(graphUris, null, rdf.type, rdfs.Class, options?.includeInferred)) {
            if (!this.skip(graphUris, q.subject, options) && !yielded.has(q.subject.value)) {
                yielded.add(q.subject.value);
 
                yield q.subject.value;
            }
        }
    }
 
    /**
     * Get the super classes of a given class.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param subjectUri URI of a class.
     * @param options Optional query parameters.
     * @returns An iterator of super classes of the given class.
     */
    *getSuperClasses(graphUris: string | string[] | undefined, subjectUri: string, options?: DefinitionQueryOptions): IterableIterator<string> {
        const yielded = new Set<string>();
        const s = namedNode(subjectUri);
 
        for (let q of this.store.matchAll(graphUris, s, rdfs.subClassOf, null, options?.includeInferred)) {
            if (!this.skip(graphUris, q.object, options) && !yielded.has(q.object.value)) {
                yielded.add(q.object.value);
 
                yield q.object.value;
            }
        }
    }
 
    /**
     * Get the first discovered path from a given class to a root class.
     * @param subjectUri URI of a class.
     * @returns An iterator containing the first path that is found from the given class to a root class.
     */
    *getRootClassPath(graphUris: string | string[] | undefined, subjectUri: string, options?: DefinitionQueryOptions): IterableIterator<string> {
        const path = this._getRootClassPath(graphUris, subjectUri, [], new Set<string>(), options);
 
        yield* path;
    }
 
    /**
     * Recursively find the first path from a given class to a root class.
     * @param subjectUri URI of a class.
     * @param path The current class path.
     * @param backtrack Set of URIs that have already been visited.
     * @returns The first path that is found from the given class to a root class.
     */
    private _getRootClassPath(graphUris: string | string[] | undefined, subjectUri: string, path: string[], backtrack: Set<string>, options?: DefinitionQueryOptions): string[] {
        for (let o of this.getSuperClasses(graphUris, subjectUri, options)) {
            if (!backtrack.has(o)) {
                backtrack.add(o);
 
                return this._getRootClassPath(graphUris, o, [...path, o], backtrack, options);
            }
        }
 
        return path;
    }
 
    /**
     * Indicate if there are sub classes of a given class.
     * @param subjectUri URI of a class.
     * @returns true if the class has sub classes, false otherwise.
     */
    hasSubClasses(graphUris: string | string[] | undefined, subjectUri: string, options?: DefinitionQueryOptions): boolean {
        const o = namedNode(subjectUri);
        const ontologies = this.getOtherOntologiesOnce(graphUris, options);
 
        for (let q of this.store.matchAll(graphUris, null, rdfs.subClassOf, o)) {
            if (!this.skip(graphUris, q.subject, options) || this.isReferencedAbove(graphUris, q.subject, rdfs.subClassOf, options, ontologies)) {
                return true;
            }
        }
 
        return false;
    }
 
    /**
     * Get the sub classes of a given class or all root classes.
     * @param subjectUri URI of a class or undefined to get all root classes.
     * @returns An iterator of sub classes of the given class, or root classes if no subject is provided.
     */
    *getSubClasses(graphUris: string | string[] | undefined, subjectUri?: string, options?: DefinitionQueryOptions): IterableIterator<string> {
        if (subjectUri) {
            const yielded = new Set<string>();
            const o = namedNode(subjectUri);
            const ontologies = this.getOtherOntologiesOnce(graphUris, options);
 
            for (let q of this.store.matchAll(graphUris, null, rdfs.subClassOf, o, options?.includeInferred)) {
                if (yielded.has(q.subject.value)) {
                    continue;
                }
 
                // A referenced class is listed if it leads to a class of the document, so that
                // the hierarchy from a referenced root class down to the document is not broken.
                if (!this.skip(graphUris, q.subject, options) || this.isReferencedAbove(graphUris, q.subject, rdfs.subClassOf, options, ontologies)) {
                    yielded.add(q.subject.value);
 
                    yield q.subject.value;
                }
            }
        } else {
            yield* this.getRootClasses(graphUris, options);
        }
    }
 
    /**
     * Recursively traverse all sub classes of a given class and invoke a callback.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param superClass The super class to start the traversal from.
     * @param callback A function to call for each sub class. If the function returns `false`, the traversal stops.
     * @param options Optional query parameters.
     * @param visited A set of visited URIs.
     * @returns `true` if the traversal was completed, `false` if it was stopped by the callback.
     */
    private _traverseSubClasses(graphUris: string | string[] | undefined, superClass: rdfjs.Quad_Subject, callback: (s: rdfjs.Quad_Subject) => boolean, options?: DefinitionQueryOptions, visited: Set<string> = new Set<string>()) {
        // Enumerate all sub classes of the given super class.
        for (let q of this.store.matchAll(graphUris, null, rdfs.subClassOf, superClass, options?.includeInferred)) {
            // If it is not skipped and has not been visited yet, we call the callback function.
            if (!this.skip(graphUris, q.subject, options) && !visited.has(q.subject.value)) {
                visited.add(q.subject.value);
 
                // If the callback returns false, we stop the traversal.
                if (callback(q.subject)) {
                    this._traverseSubClasses(graphUris, q.subject, callback, options, visited);
                } else {
                    return false;
                }
            }
        }
 
        return true;
    }
 
    /**
     * Get all sub classes of a given class, including indirect sub classes.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param subjectUri URI of a class.
     * @param options Optional query parameters.
     * @returns An iterator of all sub classes of the given class.
     */
    *getAllSubClasses(graphUris: string | string[] | undefined, subjectUri: string, options?: DefinitionQueryOptions): IterableIterator<string> {
        const visited = new Set<string>();
 
        yield* this._traverseSubClassesGenerator(graphUris, namedNode(subjectUri), options, visited);
    }
 
    /**
     * Recursively traverse all sub classes of a given class and yield them.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param superClass The super class to start the traversal from.
     * @param options Optional query parameters.
     * @param visited A set of visited URIs.
     */
    private *_traverseSubClassesGenerator(graphUris: string | string[] | undefined, superClass: rdfjs.Quad_Subject, options?: DefinitionQueryOptions, visited: Set<string> = new Set<string>()): IterableIterator<string> {
        // Enumerate all sub classes of the given super class.
        for (let q of this.store.matchAll(graphUris, null, rdfs.subClassOf, superClass, options?.includeInferred)) {
            // If it is not skipped and has not been visited yet, we yield it and recurse.
            if (!this.skip(graphUris, q.subject, options) && !visited.has(q.subject.value)) {
                visited.add(q.subject.value);
 
                yield q.subject.value;
 
                yield* this._traverseSubClassesGenerator(graphUris, q.subject, options, visited);
            }
        }
    }
 
    /**
     * Indicate if there are instances of a given class or any of its sub classes.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param typeUri URI of the class.
     * @param options Optional query parameters.
     * @returns `true` if the class has instances, `false` otherwise.
     */
    hasSubjectsOfType(graphUris: string | string[] | undefined, typeUri: string, options?: DefinitionQueryOptions & TypedInstanceQueryOptions): boolean {
        const iterator = this.getSubjectsOfType(graphUris, typeUri, options).next();
 
        return !iterator.done;
    }
 
    /**
     * Get all subjects of a given class in the repository.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param typeUri URI of the class.
     * @param options Optional query parameters.
     * @returns An iterator of all subjects of the given class.
     */
    *getSubjectsOfType(graphUris: string | string[] | undefined, typeUri: string, options?: DefinitionQueryOptions & TypedInstanceQueryOptions): IterableIterator<string> {
        if (options?.includeSubTypes === false) {
            // 1. Get all subclasses of the given type from the repository -> ClassRepository.
            const subclasses = new Set<string>(this.getAllSubClasses(graphUris, typeUri));
 
            // 2. Then get all triples that have a rdf:type predicate.
            //  a) if the object matches the given type, add it to the result.
            //  b) if the object is a subclass of the given type, track it for filtering.
            const result = new Set<string>();
            const filtered = new Set<string>();
 
            for (let q of this.store.matchAll(graphUris, null, rdf.type, null, options?.includeInferred)) {
                if (q.object.value == typeUri && !this.skip(graphUris, q.subject, options)) {
                    result.add(q.subject.value);
                } else if (subclasses.has(q.object.value)) {
                    filtered.add(q.subject.value);
                }
            }
 
            // Yield only items that are not filtered
            for (const item of result) {
                if (!filtered.has(item)) {
                    yield item;
                }
            }
        } else {
            // TODO: This does not explicitly check the sub classes. Implement a unit test.
            const yielded = new Set<string>();
 
            for (let q of this.store.matchAll(graphUris, null, rdf.type, namedNode(typeUri), options?.includeInferred)) {
                if (!this.skip(graphUris, q.subject, options) && !yielded.has(q.subject.value)) {
                    yielded.add(q.subject.value);
 
                    yield q.subject.value;
                }
            }
        }
    }
 
    /**
     * Indicate if a given class is direct or indirect (inferred) sub class of another class.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param subjectUri URI of the sub class.
     * @param classUri URI of the super class.
     * @param options Optional query parameters.
     * @returns `true` if the class is a sub class of the other class, false otherwise.
     */
    isSubClassOf(graphUris: string | string[] | undefined, subjectUri: string, classUri: string, options?: DefinitionQueryOptions): boolean {
        for (const pathClass of this.getRootClassPath(graphUris, subjectUri, options)) {
            if (pathClass === classUri) {
                return true;
            }
        }
        return false;
    }
 
    /**
     * Indicate if a given class is the intersection of classes.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param subjectUri URI of a class.
     * @returns `true` if the class is the intersection of classes, `false` otherwise.
     */
    isIntersectionOfClasses(graphUris: string | string[] | undefined, subjectUri: string): boolean {
        const s = namedNode(subjectUri);
 
        if (this._isIntersectionOfClasses(graphUris, s)) {
            return true;
        }
 
        // Note: The intersection must be defined in the original graphs, so inference is not required.
        for (let q of this.store.matchAll(graphUris, s, owl.equivalentClass, null, false)) {
            Eif (this._isIntersectionOfClasses(graphUris, q.object)) {
                return true;
            }
        }
 
        return false;
    }
 
    private _isIntersectionOfClasses(graphUris: string | string[] | undefined, subject: rdfjs.Quad_Subject | rdfjs.Quad_Object): boolean {
        Eif (subject.termType === "BlankNode" || subject.termType === "NamedNode") {
            for (let _ of this.store.matchAll(graphUris, subject, owl.intersectionOf, null, false)) {
                return true;
            }
        }
 
        return false;
    }
 
    /**
     * Indicate if a given class is a (disjoint) union of classes.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param subjectUri URI of a class.
     * @returns `true` if the class is a (disjoint) union of classes, `false` otherwise.
     */
    isUnionOfClasses(graphUris: string | string[] | undefined, subjectUri: string): boolean {
        const s = namedNode(subjectUri);
 
        if (this._isUnionOfClasses(graphUris, s)) {
            return true;
        }
 
        // Note: The union must be defined in the original graphs, so inference is not required.
        for (let q of this.store.matchAll(graphUris, s, owl.equivalentClass, null, false)) {
            Eif (this._isUnionOfClasses(graphUris, q.object)) {
                return true;
            }
        }
 
        return false;
    }
 
    private _isUnionOfClasses(graphUris: string | string[] | undefined, subject: rdfjs.Quad_Subject | rdfjs.Quad_Object): boolean {
        Eif (subject.termType === "BlankNode" || subject.termType === "NamedNode") {
            for (let _ of this.store.matchAll(graphUris, subject, owl.unionOf, null, false)) {
                return true;
            }
 
            for (let _ of this.store.matchAll(graphUris, subject, owl.disjointUnionOf, null, false)) {
                return true;
            }
        }
 
        return false;
    }
 
    /**
     * Get all classes from the repository that have no super classes.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param options Optional query parameters.
     * @returns An iterator of root classes in the repository.
     */
    *getRootClasses(graphUris: string | string[] | undefined, options?: DefinitionQueryOptions): IterableIterator<string> {
        const classes = new Set<string>(this.getClasses(graphUris, options));
        const ontologies = this.getOtherOntologiesOnce(graphUris, options);
 
        // All super class relations are read in one pass rather than per class, which would
        // query the asserted and the inferred graphs of every class.
        const superClasses = this.getParentMap(graphUris, rdfs.subClassOf, options);
 
        // Whether a super class is shown depends on the node alone, so it is decided once.
        const visible = new Map<string, boolean>();
 
        const isVisible = (iri: string): boolean => {
            if (classes.has(iri)) {
                return true;
            }
 
            let result = visible.get(iri);
 
            if (result === undefined) {
                const node = namedNode(iri);
 
                result = !this.skip(graphUris, node, options) || this.isReferenced(graphUris, node, options, ontologies);
 
                visible.set(iri, result);
            }
 
            return result;
        };
 
        yield* this.getHierarchyRoots(classes, superClasses, iri => classes.has(iri), isVisible);
    }
 
    /**
     * Indicate if there is an equivalent class of a given class.
     * @param graphUris URIs of the graphs to search, `undefined` for the default graph.
     * @param subjectUri URI of a class.
     * @param options Optional query parameters.
     * @returns `true` if the class has an equivalent class, `false` otherwise.
     */
    public hasEquivalentClass(graphUris: string | string[] | undefined, subjectUri: string, options?: QueryOptions): boolean {
        const s = namedNode(subjectUri);
 
        // The OWL resoner will assert the equivalent class relationship in both directions.
        for (let _ of this.store.matchAll(graphUris, s, owl.equivalentClass, null, options?.includeInferred)) {
            return true;
        }
 
        return false;
    }
 
    /**
     * Indicate if a given class has at least one individual defined for it or for one of its sub classes.
     * @param graphUris Graph URIs to search in, undefined for the default graph.
     * @param classUri URI of a class.
     * @param options Optional query parameters.
     * @returns `true` if the class has individuals, `false` otherwise.
     */
    public hasIndividuals(graphUris: string | string[] | undefined, classUri: string, options?: DefinitionQueryOptions): boolean {
        return this._hasIndividuals(new Set<string>(), graphUris, classUri, options);
    }
 
    /**
     * Internal method to check for individuals with cycle detection.
     * @param graphUris Graph URIs to search in, undefined for the default graph.
     * @param classUri URI of a class.
     * @param options Optional query parameters.
     * @param backtrack Set of already visited class URIs to prevent cycles.
     * @returns `true` if the class has individuals, `false` otherwise.
     */
    private _hasIndividuals(backtrack: Set<string>, graphUris: string | string[] | undefined, classUri: string, options?: DefinitionQueryOptions): boolean {
        // Prevent infinite recursion by checking if we've already visited this class
        if (backtrack.has(classUri)) {
            return false;
        }
 
        backtrack.add(classUri);
 
        const s = namedNode(classUri);
 
        // Check for direct individuals of this class
        for (let q of this.store.matchAll(graphUris, null, rdf.type, s, options?.includeInferred)) {
            Eif (!this.skip(graphUris, q.subject, options)) {
                return true;
            }
        }
 
        // Check subclasses recursively with cycle detection
        for (let c of this.getSubClasses(graphUris, classUri, options)) {
            if (this._hasIndividuals(backtrack, graphUris, c, options)) {
                return true;
            }
        }
 
        return false;
    }
}