All files / rdf resource-repository.ts

92.68% Statements 76/82
93.1% Branches 54/58
87.5% Functions 7/8
92.68% Lines 76/82

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            10x                                                                                                                                                                                                 10x                       41092x   41092x   9859x     31233x   31233x   115x     31118x 3180x     3180x 2905x   27938x 704x 833x 681x   23x     27532x                       27584x 27x 27557x 27557x     27584x 27584x 27444x       140x                     4021x   4021x     4x 3x         4017x 764x             3253x 3253x   3253x 48x     3205x     3205x 3475x 143x         3062x 8x 8x         3055x                                                             1x 1x   1x 23x 11x       12x   12x 2x             2x     12x 12x   12x 12x   12x 7x   5x         1x                   4x   4x 14736x 6300x   6300x 21x   6279x         4x               3x 3x     3x 14x 2x 2x       3x    
import { Quad_Subject, Quad_Object } from "@rdfjs/types";
import { Store } from "./store";
import { rdf, rdfs } from "../ontologies";
import { Uri } from "./uri";
import { dataFactory } from "./data-factory";
 
const { namedNode, blankNode } = dataFactory;
 
/**
 * Parameters for matching triples in the store.
 */
export interface QueryOptions {
    /**
     * Indicates if inferred triples should be included in the result. If `undefined`, 
     * the default value is `true` when a reasoner associated with the store and `false` otherwise.
     */
    includeInferred?: boolean;
}
 
/**
 * Parameters for querying resources in the store that have an explicitly asserted type in the document.
 */
export interface DefinitionQueryOptions extends QueryOptions {
    /**
     * URI of the vocabulary that defines the resources. If `null`, returns only resources that have no `rdfs:isDefinedBy` property.
     */
    definedBy?: string | null;
 
    /**
     * URIs of the vocabularies in which the resources must not be defined, either by sharing a namespace or by `rdfs:isDefinedBy`.
     */
    notDefinedBy?: Set<string>;
 
    /**
     * Indicate if terms what are not *defined* in the ontology should be included in the result (default: false).
     */
    includeReferenced?: boolean;
 
    /**
     * Indicate if blank nodes should be included in the result (default: false).
     */
    includeBlankNodes?: boolean;
}
 
/**
 * Parameters for store queries that support filtering on the type of resource.
 */
export interface TypedInstanceQueryOptions extends QueryOptions {
    /**
     * Indicate if instances of a subclasses of the type should be included in the result.
     */
    includeSubTypes?: boolean;
}
 
/**
 * Maps a language tag to the number of occurrences in the document.
 */
export interface LanguageTagUsageStats {
    [key: string]: number;
}
 
/**
 * Maps a predicate IRI to information about its usage in the document.
 */
export interface PredicateUsageStats {
    [key: string]: PredicateUsageInfo;
}
 
/**
 * Information about the usage of a single predicate in a document.
 */
export interface PredicateUsageInfo {
    /**
     * The predicate IRI.
     */
    predicateIri: string;
 
    /**
     * The set of subjects that use the predicate.
     */
    subjects: Set<string>;
 
    /**
     * The number of occurrences of the predicate in a document.
     */
    usageFrequency: number;
 
    /**
     * Information about the language tags used in the object of triples with the predicate.
     */
    languageTags: { [key: string]: number };
}
 
/**
 * A repository for retrieving resources from graphs.
 */
export class ResourceRepository {
    /**
     * The RDF triple store.
     */
    readonly store: Store;
 
    constructor(store: Store) {
        this.store = store;
    }
 
    /**
     * Inidiates if a node should not be included in the result of a definition query.
     * @param graphUris URIs of the graphs to search.
     * @param subject The focus node.
     * @param options Definition query options.
     * @param optionDefaults Custom default values for the query options.
     * @returns 
     */
    protected skip(graphUris: string | string[] | undefined, subject: Quad_Subject | Quad_Object, options?: DefinitionQueryOptions, optionDefaults: DefinitionQueryOptions = { includeBlankNodes: false, includeReferenced: false }): boolean {
        const opts = { ...optionDefaults, ...options };
 
        if (!opts.includeBlankNodes && subject.termType !== "NamedNode") {
            // We are only interested in named nodes.
            return true;
        }
 
        const s = subject as Quad_Subject;
 
        if (!opts.includeReferenced && !this.hasSubject(graphUris, subject)) {
            // Skip the node if it is not explicitly defined in the graph as a subject.
            return true;
        }
 
        if (opts?.definedBy !== undefined) {
            const isDefined = this.isDefinedBy(graphUris, s, opts.definedBy);
 
            // Do not skip the node if it has a different namespace but is *explicitly* defined by the given URI.
            if (opts.definedBy === null && isDefined || opts.definedBy !== null && !isDefined) {
                return true;
            }
        } else if (opts?.notDefinedBy !== undefined) {
            for (const source of opts.notDefinedBy) {
                if (this.isDefinedBy(graphUris, s, source)) {
                    return true;
                }
            } s
        }
 
        return false;
    }
 
    /**
     * Indicate if a given URI exists as the subject of a triple in the graph.
     * @param graphUris URIs of the graphs to search.
     * @param subjectUri URI of the subject to search for.
     * @returns true if the URI is a subject, false otherwise.
     */
    hasSubject(graphUris: string | string[] | undefined, subjectUri: string | Quad_Subject | Quad_Object): boolean {
        let s;
 
        if (typeof subjectUri === "string") {
            s = namedNode(subjectUri);
        } else if (EsubjectUri.termType !== "Literal") {
            s = subjectUri;
        }
 
        Eif (s) {
            for (let _ of this.store.matchAll(graphUris, s, null, null, false)) {
                return true;
            }
        }
 
        return false;
    }
 
    /**
     * Indicate if a node is explicitly defined by the given URI using the `rdfs:isDefinedBy` property, or implicitly by sharing the same namespace.
     * @param graphUris URIs of the graphs to search.
     * @param node A named node to check if it is defined by the given URI.
     * @param definedBy URI of the vocabulary that defines the resource (rdfs:isDefinedBy). Provide `null` to only return resources that have no `rdfs:isDefinedBy` property.
     * @returns `true` if the node is defined by the given URI, `false` otherwise.
     */
    isDefinedBy(graphUris: string | string[] | undefined, node: Quad_Subject, definedBy: string | null): boolean {
        const s = node;
 
        if (definedBy === null) {
            // If there is no definedBy URI, we assume that the resource is not
            // explicitly defined by any ontology.
            for (let _ of this.store.matchAll(graphUris, s, rdfs.isDefinedBy, null)) {
                return true;
            }
        }
        else {
            // We assume that a resource is defined by an ontology if it starts with the namespace of the ontology.
            if (node.value.startsWith(definedBy)) {
                return true;
            }
 
            // If the ontology is something like <http://purl.obolibrary.org/obo/bfo.owl> or <http://www.w3.org/ns/prov#>
            // and the subject is <http://purl.obolibrary.org/obo/BFO_0000001> or <http://www.w3.org/ns/prov#Entity>
            // then we assume that it is defined by the ontology. The OBO case shows that we need to remove the file
            // name in oder to be able to compare the namespace URIs.
            const ontologyNamespace = Uri.getNormalizedUri(Uri.getNamespaceIri(definedBy));
            const subjectNamespace = Uri.getNormalizedUri(Uri.getNamespaceIri(node.value));
 
            if (subjectNamespace === ontologyNamespace) {
                return true;
            }
 
            const o = namedNode(Uri.getNormalizedUri(definedBy));
 
            // The explicit annotation of the definition source has precedence over heuristic checks.
            for (let q of this.store.matchAll(graphUris, s, rdfs.isDefinedBy, null)) {
                if (Uri.getNormalizedUri(q.object.value) === o.value) {
                    return true;
                }
            }
 
            // A blank node is defined in the namespace if it is the object of a triple that is defined by the URI.
            if (s.termType === "BlankNode") {
                for (let q of this.store.matchAll(graphUris, null, null, s, false)) {
                    return this.isDefinedBy(graphUris, q.subject, definedBy)
                }
            }
        }
 
        return false;
    }
 
    /**
     * Indicate if a resource has a given type in the graph.
     * @param graphUris URIs of the graphs to search.
     * @param subjectUri URI or blank node id of the subject to match.
     * @param typeUri URI of the type to match.
     * @param options Optional query parameters.
     * @returns `true` if the resource has the type, `false` otherwise.
     */
    hasType(graphUris: string | string[] | undefined, subjectUri: string, typeUri: string, options?: QueryOptions): boolean {
        const o = namedNode(typeUri);
 
        for (let _ of this.store.matchAll(graphUris, namedNode(subjectUri), rdf.type, o, options?.includeInferred)) {
            return true;
        }
 
        for (let _ of this.store.matchAll(graphUris, blankNode(subjectUri), rdf.type, o, options?.includeInferred)) {
            return true;
        }
 
        return false;
    }
 
    /**
     * Get information about the usage of predicates in the document such as the frequency of use and the use of language tags.
     * @param graphUris URIs of the graphs to search.
     * @param predicateUris URIs of the predicates to match.
     */
    getPredicateUsageStats(graphUris: string | string[] | undefined, predicateUris: string[] | undefined = undefined): PredicateUsageStats {
        const result: PredicateUsageStats = {};
        const predicates = predicateUris ? new Set(predicateUris) : undefined;
 
        for (let q of this.store.matchAll(graphUris, null, null, null, false)) {
            if (predicates && !predicates.has(q.predicate.value)) {
                continue;
            }
 
            // Create stats for all predicates and add language tags for literals if available.
            let predicateStats = result[q.predicate.value];
 
            if (!predicateStats) {
                predicateStats = {
                    predicateIri: q.predicate.value,
                    subjects: new Set<string>(),
                    usageFrequency: 0,
                    languageTags: {}
                };
 
                result[q.predicate.value] = predicateStats;
            }
 
            predicateStats.subjects.add(q.subject.value);
            predicateStats.usageFrequency++;
 
            Eif (q.object.termType === "Literal") {
                let language = q.object.language;
 
                if (!predicateStats.languageTags[language]) {
                    predicateStats.languageTags[language] = 1;
                } else {
                    predicateStats.languageTags[language] += 1;
                }
            }
        }
 
        return result;
    }
 
    /**
     * Get the language tags used in the object of triples with a given set of predicates.
     * @param graphUris URIs of the graphs to search.
     * @param predicateUris URIs of the predicates to match.
     * @returns An array of language tag statistics, sorted by the number of occurrences in descending order.
     */
    getLanguageTagUsageStats(graphUris: string | string[] | undefined): LanguageTagUsageStats {
        const stats: LanguageTagUsageStats = {};
 
        for (let q of this.store.matchAll(graphUris, null, null, null, false)) {
            if (q.object.termType === "Literal" && q.object.language) {
                const language = q.object.language;
 
                if (!stats[language]) {
                    stats[language] = 1;
                } else {
                    stats[language] += 1;
                }
            }
        }
 
        return stats;
    }
 
    /**
     * Get the most frequently used language tag in the object of triples with a given set of predicates.
     * @param graphUris URIs of the graphs to search.
     */
    getMostFrequentLanguageTag(graphUris: string | string[] | undefined): string | undefined {
        let stats = this.getLanguageTagUsageStats(graphUris);
        let max = 0;
        let primary: string | undefined;
 
        for (let language in stats) {
            if (stats[language] > max) {
                max = stats[language];
                primary = language;
            }
        }
 
        return primary;
    }
}