当前位置: 首页>>代码示例>>Python>>正文


Python Graph.bind方法代码示例

本文整理汇总了Python中rdflib.graph.Graph.bind方法的典型用法代码示例。如果您正苦于以下问题:Python Graph.bind方法的具体用法?Python Graph.bind怎么用?Python Graph.bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rdflib.graph.Graph的用法示例。


在下文中一共展示了Graph.bind方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: UniversalRestrictionTest

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
class UniversalRestrictionTest(unittest.TestCase):
    def setUp(self):
        self.ontGraph = Graph()
        self.ontGraph.bind('ex', EX_NS)
        self.ontGraph.bind('owl', OWL_NS)
        Individual.factoryGraph = self.ontGraph

    def testNegatedDisjunctionTest(self):
        contains=Property(EX_NS.contains)
        omega = EX.Omega
        alpha = EX.Alpha
        innerDisjunct = omega | alpha
        foo = EX.foo
        testClass1 = foo & (contains|only|~innerDisjunct)
        testClass1.identifier = EX_NS.Bar

        self.assertEqual(repr(testClass1),
                "ex:foo that ( ex:contains only ( not ( ex:Omega or ex:Alpha ) ) )")
        NormalFormReduction(self.ontGraph)
        self.assertEqual(repr(testClass1),
                "ex:foo that ( not ( ex:contains some ( ex:Omega or ex:Alpha ) ) )")

        individual1 = BNode()
        individual2 = BNode()
        foo.extent = [individual1]
        contains.extent = [(individual1,individual2)]
        (EX.Baz).extent = [individual2]
        ruleStore,ruleGraph,network=SetupRuleStore(makeNetwork=True)
        posRules,ignored=CalculateStratifiedModel(network,self.ontGraph,[EX_NS.Bar])
        self.failUnless(not posRules,"There should be no rules in the 0 strata!")
        self.assertEqual(len(ignored),2,"There should be 2 'negative' rules")
        testClass1.graph = network.inferredFacts
        self.failUnless(individual1 in testClass1.extent,
                        "%s should be in ex:Bar's extent"%individual1)

    def testNominalPartition(self):
        partition = EnumeratedClass(EX_NS.part,
                                    members=[EX_NS.individual1,
                                             EX_NS.individual2,
                                             EX_NS.individual3])
        subPartition = EnumeratedClass(members=[EX_NS.individual1])
        partitionProp = Property(EX_NS.propFoo,
                                 range=partition.identifier)
        self.testClass = (EX.Bar) & (partitionProp|only|subPartition)
        self.testClass.identifier = EX_NS.Foo
        self.assertEqual(repr(self.testClass),
                        "ex:Bar that ( ex:propFoo only { ex:individual1 } )")
        self.assertEqual(repr(self.testClass.identifier),
                        "rdflib.term.URIRef('http://example.com/Foo')")
        NormalFormReduction(self.ontGraph)
        self.assertEqual(repr(self.testClass),
        "ex:Bar that ( not ( ex:propFoo value ex:individual2 ) ) and ( not ( ex:propFoo value ex:individual3 ) )")
        ruleStore,ruleGraph,network=SetupRuleStore(makeNetwork=True)

        ex = BNode()
        (EX.Bar).extent = [ex]
        self.ontGraph.add((ex,EX_NS.propFoo,EX_NS.individual1))
        CalculateStratifiedModel(network,self.ontGraph,[EX_NS.Foo])
        self.failUnless((ex,RDF.type,EX_NS.Foo) in network.inferredFacts,
                        "Missing level 1 predicate (ex:Foo)")
开发者ID:carnotip,项目名称:FuXi,代码行数:62,代码来源:Negation.py

示例2: setupGraph

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
def setupGraph():
    # setup graph
    store = Graph()
    store.bind('ms', MS)
    store.bind('gmm', GMM)

    return store
开发者ID:ianmcorvidae,项目名称:gmmFuse,代码行数:9,代码来源:rdfgen.py

示例3: team_index

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
def team_index(request, format=None):
            logging.info("Format: %s" % format)

            if format == None:
                best_match = mimeparse.best_match(['application/rdf+xml', 'application/rdf+n3', 'text/html'], request.META['HTTP_ACCEPT'])
                if best_match == 'application/rdf+xml':
                    format = 'rdf+xml'
                elif best_match == 'application/rdf+nt':
                    format = 'rdf+nt'
                else:
                    format = 'html'

            team_list = College.objects.filter(updated=True).order_by('name')

            if ( format != 'html'):
                store = Graph()

                store.bind("cfb", "http://www.cfbreference.com/cfb/0.1/")

                CFB = Namespace("http://www.cfbreference.com/cfb/0.1/")

                for current_team in team_list:
                    team = BNode()

                    store.add((team, RDF.type, CFB["Team"]))
                    store.add((team, CFB["name"], Literal(current_team.name)))
                    store.add((team, CFB["link"], Literal(current_team.get_absolute_url())))
                if ( format == 'rdf+xml'):
                    return HttpResponse(store.serialize(format="pretty-xml"), mimetype='application/rdf+xml')
                if ( format == 'rdf+nt'):
                    return HttpResponse(store.serialize(format="nt"), mimetype='application/rdf+nt')

            return render_to_response('college/teams.html', {'team_list': team_list})
开发者ID:jeremyjbowers,项目名称:cfbreference_com,代码行数:35,代码来源:views.py

示例4: NegationOfAtomicConcept

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
class NegationOfAtomicConcept(unittest.TestCase):
    def setUp(self):
        self.ontGraph = Graph()
        self.ontGraph.bind('ex', EX_NS)
        self.ontGraph.bind('owl', OWL_NS)
        Individual.factoryGraph = self.ontGraph

    def testAtomicNegation(self):
        bar=EX.Bar
        baz=~bar
        baz.identifier = EX_NS.Baz
        ruleStore,ruleGraph,network=SetupRuleStore(makeNetwork=True)
        individual=BNode()
        individual2=BNode()
        (EX.OtherClass).extent = [individual]
        bar.extent = [individual2]
        NormalFormReduction(self.ontGraph)
        self.assertEqual(repr(baz),
                         "Class: ex:Baz DisjointWith ex:Bar\n")
        posRules,negRules=CalculateStratifiedModel(network,self.ontGraph,[EX_NS.Foo])
        self.failUnless(not posRules,"There should be no rules in the 0 strata!")
        self.failUnless(len(negRules)==1,"There should only be one negative rule in a higher strata")
        self.assertEqual(repr(negRules[0]),
                         "Forall ?X ( ex:Baz(?X) :- not ex:Bar(?X) )")
        baz.graph = network.inferredFacts
        self.failUnless(individual in baz.extent,
                        "%s should be a member of ex:Baz"%individual)
        self.failUnless(individual2 not in baz.extent,
                        "%s should *not* be a member of ex:Baz"%individual2)
开发者ID:carnotip,项目名称:FuXi,代码行数:31,代码来源:Negation.py

示例5: testQueryMemoization

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
 def testQueryMemoization(self):
     raise SkipTest("SKIPFAIL testQueryMemoization, see test/testBFPQueryMemoization.py")
     topDownStore = TopDownSPARQLEntailingStore(
                     self.owlGraph.store,
                     self.owlGraph,
                     idb=self.program,
                     DEBUG=False,
                     nsBindings=nsMap,
                     decisionProcedure=BFP_METHOD,
                     identifyHybridPredicates=True)
     targetGraph = Graph(topDownStore)
     for pref, nsUri in nsMap.items():
         targetGraph.bind(pref, nsUri)
     goal = (Variable('SUBJECT'), RDF.type, EX.C)
     queryLiteral = EDBQuery([BuildUnitermFromTuple(goal)],
                             self.owlGraph,
                             [Variable('SUBJECT')])
     query = queryLiteral.asSPARQL()
     # rt=targetGraph.query(query,initNs=nsMap)
     # if len(topDownStore.edbQueries) == len(set(topDownStore.edbQueries)):
     #     pprint(topDownStore.edbQueries)
     print("Queries dispatched against EDB")
     for query in self.owlGraph.queriesDispatched:
         print(query)
     self.failUnlessEqual(
         len(self.owlGraph.queriesDispatched), 4, "Duplicate query")
开发者ID:Web5design,项目名称:FuXi,代码行数:28,代码来源:testBFPQueryMemoization.py

示例6: EARLPlugin

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
class EARLPlugin(Plugin):
    """
    Activate the EARL plugin to generate a report of the test results
    using EARL.
    """
    name = 'EARL'
    
    def begin(self):
        self.graph = Graph()
        self.graph.bind("earl", EARL.uri)

    def finalize(self, result):
        # TODO: add plugin options for specifying where to send
        # output.
        self.graph.serialize("file:results-%s.rdf" % date_time(), format="pretty-xml")

    def addDeprecated(self, test):
        print "Deprecated: %s" % test

    def addError(self, test, err, capt):
        print "Error: %s" % test

    def addFailure(self, test, err, capt, tb_info):
        print "Failure: %s" % test

    def addSkip(self, test):
        print "Skip: %s" % test

    def addSuccess(self, test, capt):
        result = BNode() # TODO: coin URIRef
        self.graph.add((result, RDFS.label, Literal(test)))
        self.graph.add((result, RDFS.comment, Literal(type(test))))
        self.graph.add((result, RDF.type, EARL.TestResult))
        self.graph.add((result, EARL.outcome, EARL["pass"]))
开发者ID:Jonadabe,项目名称:omnidator,代码行数:36,代码来源:EARLPlugin.py

示例7: convert

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
 def convert(self):
   store = Graph()
   store.bind("dc", "http://purl.org/dc/elements/1.1/")
   store.bind("data", "http://data.rpi.edu/vocab/")
   DC = Namespace("http://purl.org/dc/elements/1.1/")
   DATA = Namespace("http://data.rpi.edu/vocab/")
   RDFS = Namespace("http://www.w3.org/2000/01/rdf-schema#")
   FOAF = Namespace("http://xmlns.com/foaf/0.1/")
   header = self.reader.next()   #Skip header  
   minSize = len(header)
   #print header
   for row in self.reader:
     if len(row) != minSize:
       print "Number of columns different than header ({0} vs. {1}). Skipping".format(len(row), minSize)
       continue
     store.add((row[8], DC['identifier'], Literal(row[0])))
     names = row[2].split(", ")
     creator=URIRef("http://data.rpi.edu/people/"+names[0].capitalize()+names[1].capitalize())
     store.add((row[8], DC['creator'], creator))
     store.add((creator, FOAF['firstName'], names[0]))
     store.add((creator, DC['family_name'], names[1]))
     store.add((row[8], DC['dateAccepted'], Literal(row[5])))
     store.add((row[8], RDFS['comments'], Literal(row[6])))
     store.add((row[8], DC['description'], Literal(row[6])))
     store.add((row[8], DC['bibliographicCitation'], Literal(row[7])))
     store.add((row[8], DC['title'], Literal(row[10])))
     store.add((row[8], RDFS['label'], Literal(row[10])))
     store.add((row[8], DC['subject'], URIRef(DATA+re.sub("\s", "_", row[9]))))
   print(store.serialize(format="pretty-xml"))
开发者ID:sridhn,项目名称:dspace_metadata_rdf,代码行数:31,代码来源:ds2rdf.py

示例8: getGraph

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
 def getGraph(self):
   g = Graph()
   g.bind("rdf", RDF)
   g.bind("cs", CS)
   for cs in self.changesets.values():
     g += cs
   return g
开发者ID:iand,项目名称:rdfchangesets,代码行数:9,代码来源:__init__.py

示例9: NegatedDisjunctTest

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
class NegatedDisjunctTest(unittest.TestCase):
    def setUp(self):
        self.ontGraph = Graph()
        self.ontGraph.bind('ex', EX_NS)
        self.ontGraph.bind('owl', OWL_NS)
        Individual.factoryGraph = self.ontGraph

    def testStratified(self):
        bar=EX.Bar
        baz=EX.Baz
        noBarOrBaz = ~(bar|baz)
        omega = EX.Omega
        foo = omega & noBarOrBaz
        foo.identifier = EX_NS.Foo
        ruleStore,ruleGraph,network=SetupRuleStore(makeNetwork=True)
        individual=BNode()
        omega.extent = [individual]
        NormalFormReduction(self.ontGraph)
        self.assertEqual(repr(foo),
                         "ex:Omega that ( not ex:Bar ) and ( not ex:Baz )")
        posRules,negRules=CalculateStratifiedModel(network,self.ontGraph,[EX_NS.Foo])
        foo.graph = network.inferredFacts
        self.failUnless(not posRules,"There should be no rules in the 0 strata!")
        self.assertEqual(repr(negRules[0]),"Forall ?X ( ex:Foo(?X) :- And( ex:Omega(?X) not ex:Bar(?X) not ex:Baz(?X) ) )")
        self.failUnless(len(negRules)==1,"There should only be one negative rule in a higher strata")
        self.failUnless(individual in foo.extent,
                        "%s should be a member of ex:Foo"%individual)
开发者ID:carnotip,项目名称:FuXi,代码行数:29,代码来源:Negation.py

示例10: createTestOntGraph

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
def createTestOntGraph():
    graph = Graph()
    graph.bind('ex',EX_NS,True)
    Individual.factoryGraph = graph
    kneeJoint = EX_CL.KneeJoint
    joint = EX_CL.Joint

    knee  = EX_CL.Knee
    isPartOf = Property(EX_NS.isPartOf)
    graph.add((isPartOf.identifier,RDF.type,OWL_NS.TransitiveProperty))
    structure = EX_CL.Structure
    leg = EX_CL.Leg
    hasLocation = Property(EX_NS.hasLocation,subPropertyOf=[isPartOf])
    # graph.add((hasLocation.identifier,RDFS.subPropertyOf,isPartOf.identifier))

    kneeJoint.equivalentClass = [joint & (isPartOf|some|knee)]
    legStructure = EX_CL.LegStructure
    legStructure.equivalentClass = [structure & (isPartOf|some|leg)]
    structure += leg
    structure += joint
    locatedInLeg = hasLocation|some|leg
    locatedInLeg += knee


    # print graph.serialize(format='n3')

    # newGraph = Graph()
    # newGraph.bind('ex',EX_NS,True)

#    newGraph,conceptMap = StructuralTransformation(graph,newGraph)
#    revDict = dict([(v,k) for k,v in conceptMap.items()])

#    Individual.factoryGraph = newGraph
#    for oldConceptId ,newConceptId in conceptMap.items():
#        if isinstance(oldConceptId,BNode):
#            oldConceptRepr = repr(Class(oldConceptId,graph=graph))
#            if oldConceptRepr.strip() == 'Some Class':
#                oldConceptRepr = manchesterSyntax(
#                    oldConceptId,
#                    graph)
#            print "%s -> %s"%(
#                oldConceptRepr,
#                newConceptId
#            )
#
#        else:
#            print "%s -> %s"%(
#                oldConceptId,
#                newConceptId
#            )
#
#    for c in AllClasses(newGraph):
#        if isinstance(c.identifier,BNode) and c.identifier in conceptMap.values():
#            print "## %s ##"%c.identifier
#        else:
#            print "##" * 10
#        print c.__repr__(True)
#        print "################################"
    return graph
开发者ID:carnotip,项目名称:FuXi,代码行数:61,代码来源:CompletionReasoning.py

示例11: rdf_profile

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
def rdf_profile(request, username):
    '''Profile information comparable to the human-readable content
    returned by :meth:`profile`, but in RDF format.'''

    # retrieve user & publications - same logic as profile above
    user, userprofile = _get_profile_user(username)
    articles = userprofile.recent_articles(limit=10)

    # build an rdf graph with information author & publications
    rdf = RdfGraph()
    for prefix, ns in ns_prefixes.iteritems():
        rdf.bind(prefix, ns)
    author_node = BNode()
    profile_uri = URIRef(request.build_absolute_uri(reverse('accounts:profile',
                                                    kwargs={'username': username})))
    profile_data_uri = URIRef(request.build_absolute_uri(reverse('accounts:profile-data',
                                                         kwargs={'username': username})))

    # author information
    rdf.add((profile_uri, FOAF.primaryTopic, author_node))
    rdf.add((author_node, RDF.type, FOAF.Person))
    rdf.add((author_node, FOAF.nick, Literal(user.username)))
    rdf.add((author_node, FOAF.publications, profile_uri))

    try:
        esd_data = userprofile.esd_data()
    except EsdPerson.DoesNotExist:
        esd_data = None

    if esd_data:
        rdf.add((author_node, FOAF.name, Literal(esd_data.directory_name)))
    else:
        rdf.add((author_node, FOAF.name, Literal(user.get_full_name())))

    if esd_data and not userprofile.suppress_esd_data:
        mbox_sha1sum = hashlib.sha1(esd_data.email).hexdigest()
        rdf.add((author_node, FOAF.mbox_sha1sum, Literal(mbox_sha1sum)))
        if esd_data.phone:
            rdf.add((author_node, FOAF.phone, URIRef('tel:' + esd_data.phone)))

    # TODO: use ESD profile data where appropriate
    # (and honor internet/directory suppressed, suppression override)

    # article information
    repo = Repository(request=request)
    for record in articles:
        obj = repo.get_object(record['pid'], type=Publication)
        obj_node = BNode() # info:fedora/ uri is not public

        # relate to author
        rdf.add((author_node, FRBR.creatorOf, obj_node))
        rdf.add((author_node, FOAF.made, obj_node))
        # add object rdf
        rdf += obj.as_rdf(node=obj_node)

    response = HttpResponse(rdf.serialize(), content_type='application/rdf+xml')
    response['Content-Location'] = profile_data_uri
    return response
开发者ID:emory-libraries,项目名称:OpenEmory,代码行数:60,代码来源:views.py

示例12: ReductionTestA

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
class ReductionTestA(unittest.TestCase):
    def setUp(self):
        self.ontGraph = Graph()
        self.ontGraph.bind('ex', EX_NS)
        self.ontGraph.bind('owl', OWL_NS)
        Individual.factoryGraph = self.ontGraph
        partition = EnumeratedClass(EX_NS.part,
                                    members=[EX_NS.individual1,
                                             EX_NS.individual2,
                                             EX_NS.individual3])
        subPartition = EnumeratedClass(
                EX_NS.partition, members=[EX_NS.individual1])
        partitionProp = Property(EX_NS.propFoo,
                                 range=partition)
        self.foo = EX.foo
        self.foo.subClassOf = [
            partitionProp | only | subPartition]

    def testUnivInversion(self):
        UniversalNominalRangeTransformer().transform(self.ontGraph)
        self.failUnlessEqual(len(list(self.foo.subClassOf)),
                             1,
                             "There should still be one subsumed restriction")
        subC = CastClass(first(self.foo.subClassOf))
        self.failUnless(not isinstance(subC, Restriction),
                        "subclass of a restriction")
        self.failUnless(
                subC.complementOf is not None, "Should be a complement!")
        innerC = CastClass(subC.complementOf)
        self.failUnless(isinstance(innerC, Restriction),
                        "complement of a restriction, not %r" % innerC)
        self.failUnlessEqual(innerC.onProperty,
                             EX_NS.propFoo,
                             "restriction on propFoo")
        self.failUnless(
                innerC.someValuesFrom,
                "converted to an existential restriction not %r" % innerC)
        invertedC = CastClass(innerC.someValuesFrom)
        self.failUnless(
                isinstance(invertedC, EnumeratedClass),
                "existencial restriction on enumerated class")
        self.assertEqual(
            len(invertedC),
                 2,
                "existencial restriction on enumerated class of length 2")
        self.assertEqual(repr(invertedC),
                         "{ ex:individual2 ex:individual3 }",
                         "The negated partition should exclude individual1")
        NominalRangeTransformer().transform(self.ontGraph)
        DemorganTransformer().transform(self.ontGraph)

        subC = CastClass(first(self.foo.subClassOf))
        self.assertEqual(
            repr(subC),
            "( ( not ( ex:propFoo value ex:individual2 ) ) " +
            "and ( not ( ex:propFoo value ex:individual3 ) ) )")
开发者ID:baojie,项目名称:FuXi-1,代码行数:58,代码来源:DLNormalization.py

示例13: EARLPlugin

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
class EARLPlugin(Plugin):
    """
    Activate the EARL plugin to generate a report of the test results
    using EARL.
    """
    name = 'EARL'
    
    def begin(self):
        self.graph = Graph()
        self.graph.bind("earl", EARL.uri)
        tool = BNode('rdflib')
        self.graph.add((tool, RDF.type, EARL.TestTool))
        self.graph.add((tool, RDFS.label, Literal('rdflib.net')))
        self.graph.add((tool, RDFS.comment, Literal('nosetests')))
    
    def finalize(self, result):
        # TODO: add plugin options for specifying where to send
        # output.
        self.graph.serialize("file:results-%s.rdf" % \
                            date_time().replace(':','-'), format="pretty-xml")
    

    def addDeprecated(self, test):
        print "Deprecated: %s" % test

    
    def addError(self, test, err, capt):
        print "Error: %s" % test

    
    def addFailure(self, test, err, capt, tb_info):
        print("FAILED")
        result = BNode() # TODO: coin URIRef
        self.graph.add((result, RDFS.label, Literal(test)))
        self.graph.add((result, RDFS.comment, Literal(type(test))))
        self.graph.add((result, RDF.type, EARL.TestResult))
        self.graph.add((result, EARL.outcome, EARL["fail"]))
    

    def addSkip(self, test):
        print("SKIPPED")
        result = BNode() # TODO: coin URIRef
        self.graph.add((result, RDFS.label, Literal(test)))
        self.graph.add((result, RDFS.comment, Literal(type(test))))
        self.graph.add((result, RDF.type, EARL.TestResult))
        self.graph.add((result, EARL.outcome, EARL["untested"]))
    

    def addSuccess(self, test, capt):
        print("PASSED")
        result = BNode() # TODO: coin URIRef
        self.graph.add((result, RDFS.label, Literal(test)))
        self.graph.add((result, RDFS.comment, Literal(type(test))))
        self.graph.add((result, RDF.type, EARL.TestResult))
        self.graph.add((result, EARL.outcome, EARL["pass"]))
开发者ID:agarrido,项目名称:ro-manager,代码行数:57,代码来源:EARLPlugin.py

示例14: bfp

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
def bfp(defaultDerivedPreds, options, factGraph, ruleSet, network,
        hybridPredicates):
    topDownDPreds = defaultDerivedPreds
    if options.builtinTemplates:
        builtinTemplateGraph = Graph().parse(options.builtinTemplates,
                                             format='n3')
        builtinDict = dict([
            (pred, template) for pred, _ignore, template in
            builtinTemplateGraph.triples(
                (None, TEMPLATES.filterTemplate, None))])
    else:
        builtinDict = None
    topDownStore = TopDownSPARQLEntailingStore(
        factGraph.store,
        factGraph,
        idb=ruleSet,
        DEBUG=options.debug,
        derivedPredicates=topDownDPreds,
        templateMap=builtinDict,
        nsBindings=network.nsMap,
        identifyHybridPredicates=options.hybrid,
        hybridPredicates=hybridPredicates)
    targetGraph = Graph(topDownStore)
    for pref, nsUri in list(network.nsMap.items()):
        targetGraph.bind(pref, nsUri)
    start = time.time()
    sTime = time.time() - start
    result = targetGraph.query(options.why, initNs=network.nsMap)
    if result.askAnswer:
        sTime = time.time() - start
        if sTime > 1:
            sTimeStr = "%s seconds" % sTime
        else:
            sTime = sTime * 1000
            sTimeStr = "%s milli seconds" % sTime
        print("Time to reach answer ground goal answer of %s: %s" % (
            result.askAnswer[0], sTimeStr))
    else:
        for rt in result:
            sTime = time.time() - start
            if sTime > 1:
                sTimeStr = "%s seconds" % sTime
            else:
                sTime = sTime * 1000
                sTimeStr = "%s milli seconds" % sTime
            if options.firstAnswer:
                break
            print("Time to reach answer %s via top-down SPARQL"
                  " sip strategy: %s" % (rt, sTimeStr))
    if options.output == 'conflict' and options.method == 'bfp':
        for _network, _goal in topDownStore.queryNetworks:
            print(network, _goal)
            _network.reportConflictSet(options.debug)
        for query in topDownStore.edbQueries:
            print(query.asSPARQL())
开发者ID:nuoya,项目名称:FuXi,代码行数:57,代码来源:CommandLine.py

示例15: serialize_as_rdf

# 需要导入模块: from rdflib.graph import Graph [as 别名]
# 或者: from rdflib.graph.Graph import bind [as 别名]
def serialize_as_rdf(media_resources):
    """Serialize a list of media resources as RDF triples.

    Args:
        media_resources (list): the list of media resources.

    Returns:
        string: RDF/XML serialization of the media resources.
    """
    g = Graph('IOMemory')
    g.bind('ma', URIRef('http://www.w3.org/ns/ma-ont#'))
    g.bind('foaf', URIRef('http://xmlns.com/foaf/0.1/'))
    ma = Namespace('http://www.w3.org/ns/ma-ont#')
    foaf = Namespace('http://xmlns.com/foaf/0.1/')
    for media in media_resources:
        if not media.id:
            media.id = str(uuid.uuid4()).replace("-", "")
        media.uri = URIRef('http://production.sti2.org/lsi/media/' + media.id)
        g.add((media.uri, ma.title, Literal(media.title)))
        if media.description:
            g.add((media.uri, ma.description, Literal(media.description)))
        g.add((media.uri, ma.locator, Literal(media.locator, datatype=XSD.anyURI)))
        if hasattr(media, 'width') and media.width:
            g.add((media.uri, ma.width, Literal(media.width, datatype=XSD.integer)))
        if hasattr(media, 'height') and media.height:
            g.add((media.uri, ma.height, Literal(media.height, datatype=XSD.integer)))
        if hasattr(media, 'author_uri') and media.author_uri:
            author_uri_ref = URIRef(media.author_uri)
            g.add((media.uri, ma.contributor, author_uri_ref))
            g.add((author_uri_ref, RDF.type, ma.Agent))
            if hasattr(media, 'author_name') and media.author_name:
                g.add((author_uri_ref, RDFS.label, Literal(media.author_name)))
        if hasattr(media, 'created') and media.created:
            g.add((media.uri, ma.creationDate, Literal(str(media.created).replace(' ', 'T'), datatype=XSD.dateTime)))
        if hasattr(media, 'published') and media.published:
            g.add((media.uri, ma.releaseDate, Literal(str(media.published).replace(' ', 'T'), datatype=XSD.dateTime)))
        if hasattr(media, 'latitude') and media.latitude:
            g.add((media.uri, ma.locationLatitude, Literal(media.latitude, datatype=XSD.double)))
        if hasattr(media, 'longitude') and media.longitude:
            g.add((media.uri, ma.locationLongitude, Literal(media.longitude, datatype=XSD.double)))
        if hasattr(media, 'location_name') and media.location_name:
            g.add((media.uri, ma.locationName, Literal(media.location_name)))
        for keyword in media.keywords:
            g.add((media.uri, ma.hasKeyword, URIRef(keyword)))
        if isinstance(media, model.VideoTrack):
            g.add((media.uri, RDF.type, ma.MediaResource))
            g.add((media.uri, foaf.thumbnail, URIRef(media.thumbnail)))
            g.add((media.uri, ma.duration, Literal(media.duration, datatype=XSD.integer)))
        elif isinstance(media, model.Image):
            g.add((media.uri, RDF.type, ma.Image))
        try:
            g.add((media.uri, ma.publisher, URIRef(publisher_uri_dict.get(media.source))))
        except:
            pass
    return g.serialize(format='xml')
开发者ID:lyndonnixon,项目名称:LSI,代码行数:57,代码来源:serializer.py


注:本文中的rdflib.graph.Graph.bind方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。