view service/reasoning/graphop.py @ 1699:411f5e013201 0.12.0

release 0.12.0
author drewp@bigasterisk.com
date Tue, 12 Oct 2021 20:18:59 -0700
parents f3f667769aef
children
line wrap: on
line source

import logging
from rdflib import URIRef, ConjunctiveGraph
from typing import List
log = logging.getLogger()


def graphWithoutMetadata(g: ConjunctiveGraph, ignorePredicates=[]):
    """
    graph filter that removes any statements whose subjects are
    contexts in the graph and also any statements with the given
    predicates
    """

    ctxs = [ctx.identifier for ctx in g.contexts()]

    out = ConjunctiveGraph()
    for stmt in g.quads((None, None, None)):
        if stmt[0] not in ctxs and stmt[1] not in ignorePredicates:
            out.addN([stmt])
    return out


def graphEqual(a: ConjunctiveGraph, b: ConjunctiveGraph,
               ignorePredicates: List[URIRef]=[]):
    """
    compare graphs, omitting any metadata statements about contexts
    (especially modification times) and also any statements using the
    given predicates
    """
    stmtsA = set(graphWithoutMetadata(a, ignorePredicates))
    stmtsB = set(graphWithoutMetadata(b, ignorePredicates))
    if stmtsA == stmtsB:
        return True

    if log.getEffectiveLevel() <= logging.INFO:
        lost = stmtsA - stmtsB
        if lost:
            log.info("graph A only:")
            for s in lost:
                log.info("  %s", s)
        new = stmtsB - stmtsA
        if new:
            log.info("graph B only:")
            for s in new:
                log.info("  %s", s)
    return False