cwm-1.2.1/0000755015216600007660000000000010766341520011421 5ustar syosisyosicwm-1.2.1/delta0000755015216600007660000004734710750360777012467 0ustar syosisyosi#! /usr/bin/python """ Find differences between two RDF graphs, using functional and inverse functional properties to identify bnodes in the patch file. --from=uri -f uri from-file --to=uri -t uri file against which to check for differences --meta=uri -m uri file with metadata to be assumed (in addition to schemas) --help -h print this help message --verbose= -v 1 verbose mode (can be 0 to 10, 0 is default) --granularity= -g 0 g=0 - lots of little diffs. g=1, fewer diffs (default) If from-file but not to-file is given, from-file is smushed and output Uris are relative to present working directory. For motivation and explanation, see $Id: delta.py,v 1.11 2007/06/26 02:36:15 syosi Exp $ http://www.w3.org/2000/10/swap/diff.py """ import string, getopt try: Set = set # Python2.4 and on except NameError: from sets import Set # Python2.3 and on import string import sys # http://www.w3.org/2000/10/swap/ try: from swap import llyn, diag from swap.myStore import loadMany from swap.diag import verbosity, setVerbosity, progress from swap import notation3 # N3 parsers and generators from swap.RDFSink import FORMULA, LITERAL, ANONYMOUS, Logic_NS from swap import uripath from swap.uripath import base from swap.myStore import Namespace from swap import myStore from swap.notation3 import RDF_NS_URI from swap.llyn import Formula, CONTEXT, PRED, SUBJ, OBJ except ImportError: import llyn, diag from myStore import loadMany from diag import verbosity, setVerbosity, progress import notation3 # N3 parsers and generators from RDFSink import FORMULA, LITERAL, ANONYMOUS, Logic_NS import uripath from uripath import base from myStore import Namespace import myStore from notation3 import RDF_NS_URI from llyn import Formula, CONTEXT, PRED, SUBJ, OBJ #daml = Namespace("http://www.daml.org/2001/03/daml+oil#") OWL = Namespace("http://www.w3.org/2002/07/owl#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") LOG = Namespace("http://www.w3.org/2000/10/swap/log#") DELTA = Namespace("http://www.w3.org/2004/delta#") def debugBnode(n, f): progress("For node %s" % `n`) for s in f.statementsMatching(subj=n): progress(" %s %s; # could be ifp?" %(`s.predicate()`, `s.object()`)) for s in f.statementsMatching(obj=n): progress(" is %s of %s; # could be fp?" %(`s.predicate()`, `s.subject()`)) def lookUp(predicates, assumptions=Set()): """Look up all the schemas for the predicates given""" global verbose schemas = assumptions for pred in predicates: if verbose > 3: progress("Predicate: %s" % `pred`) u = pred.uriref() hash = u.find("#") if hash <0: if verbose > 1: progress("Warning: Predicate <%s> looks like web resource not Property" % u) else: schemas.add(u[:hash]) if verbose > 2: for r in schemas: progress("Metadata to be loaded: ", r) if schemas: return loadMany([(x) for x in schemas]) return myStore.store.newFormula() # Empty formula def nailFormula(f, assumptions=Set()): """Smush the formula. Build a dictionary of nodes which are indirectly identified by [inverse] functonal properties.""" global verbose cc, predicates, ss, oo = getParts(f) nodes = ss | oo sofar = {} bnodes = Set() for node in nodes: if node.generated() or node in f.existentials(): bnodes.add(node) if verbose >=5: progress("Blank node: %s" % `node`) else: if verbose >=5: progress("Fixed node: %s" % `node`) sofar[node] = [] meta = lookUp(predicates, assumptions) ifps = predicates & Set(meta.each(pred=RDF.type, obj=OWL.InverseFunctionalProperty)) fps = predicates & Set(meta.each(pred=RDF.type, obj=OWL.FunctionalProperty)) if verbose > 1: for p in fps: progress("Functional Property:", p) for p in ifps: progress("Inverse Functional: ", p) definitions = [] if len(bnodes) == 0: if verbose > 0: progress("No bnodes in graph") return bnodes, definitions a = float(len(bnodes))/len(nodes) if verbose > 1: progress("Proportion of bodes which are blank: %f" % a) # if a == 0: return bnodes, definitions loose = bnodes.copy() equivs = Set() # Note possible optmization: First pass only like this, # future passes work from newNodes. while loose: newNailed = Set() for preds, inverse, char in ((fps, 0, "!"), (ifps, 1, "^")): for pred in preds: if verbose > 3: progress("Predicate", pred) ss = f.statementsMatching(pred=pred) for s in ss: if inverse: y, x = s.object(), s.subject() else: x, y = s.object(), s.subject() if not x.generated(): continue # Only anchor bnodes if y not in loose: # y is the possible anchor defi = (x, inverse, pred, y) if x in loose: # this node if verbose > 4: progress(" Nailed %s as %s%s%s" % (`x`, `y`, `char`, `pred`)) loose.discard(x) newNailed.add(x) else: if verbose >=6 : progress( " (ignored %s as %s%s%s)" % (`x`, `y`, `char`, `pred`)) definitions.append(defi) # if verbose > 9: progress(" Definition[x] is now", definition[x]) if inverse: equivalentSet = Set(f.each(obj=y, pred=pred)) else: equivalentSet = Set(f.each(subj=y, pred=pred)) if len(equivalentSet) > 1: equivs.add(equivalentSet) if not newNailed: if verbose > 1: progress("Failed to nail nodes:", loose) if verbose > 3: for n in loose: debugBnode(n, f) break # At this point if we still have loose nodes, we have failed with ifps and fps. # Diff may not be strong. (It might still be: the diffs might not involve weak definitions) weak = loose.copy() # Remember if verbose > 0: progress("\nFailed to directly nail everything, looking for weak nailings.") # sys.exit(-1) #@@@ while loose: newNailed = Set() if verbose>2: progress() progress("Pass: loose = %s" % loose) for x in loose.copy(): if verbose>3: progress("Checking weakly node %s" % x) for s in f.statementsMatching(obj=x): pred, y = s.predicate(), s.subject() if y in loose: if verbose > 4: progress("Can't nail to loose %s" % y) continue # Can't nail to something loose others = f.each(subj=y, pred=pred) # @@ Should ignore redirected equivalent nodes in others if len(others) != 1: if verbose>4: progress("Can't nail: %s all are %s of %s." % (others, pred, y)) continue # Defn would be ambiguous in this graph defi = (x, 0, pred, y) if verbose >4: progress(" Weakly-nailed %s as %s%s%s" % (x, y, "!", pred)) loose.discard(x) newNailed.add(x) definitions.append(defi) break # progress else: for s in f.statementsMatching(subj=x): pred, obj = s.predicate(), s.object() if obj in loose: if verbose >4: progress("Can't nail to loose %s" % obj) continue # Can't nail to something loose others = f.each(obj=obj, pred=pred) # @@ Should ignore redirected equivalent nodes in others if len(others) != 1: if verbose >4: progress( "Can't nail: %s all have %s of %s." % (others, pred, obj)) continue # Defn would be ambiguous in this graph defi = (x, 1, pred, obj) if verbose>2: progress(" Weakly-nailed %s as %s%s%s" % (`x`, `obj`, "^", `pred`)) loose.discard(x) newNailed.add(x) definitions.append(defi) break # progress if not newNailed: if verbose>0: progress("Failed to even weakly nail nodes:", loose) for n in loose: progress("For node %s" % n) for s in f.statementsMatching(subj=n): progress(" %s %s; # could be ifp?" %(`s.predicate()`, `s.object()`)) for s in f.statementsMatching(obj=n): progress(" is %s of %s; # could be fp?" %(s.predicate(), s.subject())) raise ValueError("Graph insufficiently labelled for nodes: %s" % loose) if verbose>0 and not weak: progress("Graph is solid.") if verbose>0 and weak: progress("Graph is NOT solid.") f.reopen() for es in equivs: if verbose>3: progress("Equivalent: ", es) prev = None for x in es: if prev: f.add(x, OWL.sameAs, prev) prev = x return bnodes, definitions def removeCommon(f, g, match): """Find common statements from f and g match gives the dictionary mapping bnodes in f to bnodes in g""" only_f, common_g = Set(), Set() for st in f.statements[:]: s, p, o = st.spo() assert s not in f._redirections assert o not in f._redirections if s.generated(): sg = match.get(s, None) else: sg = s if o.generated(): og = match.get(o, None) else: og = o if og != None and sg != None: gsts = g.statementsMatching(subj=sg, pred=p, obj=og) if len(gsts) == 1: if verbose>4: progress("Statement in both", st) common_g.add(gsts[0]) continue only_f.add(st) return only_f, Set(g.statements)-common_g def patches(delta, f, only_f, originalBnodes, definitions, deleting=0): """Generate patches in patch formula, for the remaining statements in f given the bnodes and definitions for f.""" todo = only_f.copy() if deleting: patchVerb = DELTA.deletion else: patchVerb = DELTA.insertion if verbose>2: progress("*********** PATCHES: %s, with %i to do" %(patchVerb, len(todo))) while todo: # find a contiguous subgraph defined in the given graph bnodesToDo = Set() bnodes = Set() rhs = delta.newFormula() lhs = delta.newFormula() # left hand side of patch newStatements = Set() for seed in todo: break # pick one #@2 fn? statementsToDo = Set([seed]) if verbose>3: progress("Seed:", seed) subgraph = statementsToDo while statementsToDo or bnodesToDo: for st in statementsToDo: s, p, o = st.spo() for x in s, p, o: if x.generated() and x not in bnodes: # and x not in commonBnodes: if verbose>4: progress(" Bnode ", x) bnodesToDo.add(x) bnodes.add(x) rhs.add(s, p, o) statementsToDo = Set() for x in bnodesToDo: bnodes.add(x) ss = (f.statementsMatching(subj=x) + f.statementsMatching(pred=x) + f.statementsMatching(obj=x)) for z in ss: if z in only_f: newStatements.add(z) if verbose>3: progress(" New statements from %s: %s" % (x, newStatements)) statementsToDo = statementsToDo | newStatements subgraph = subgraph |newStatements bnodesToDo = Set() if verbose>3: progress("Subgraph of %i statements (%i left):\n\t%s\n" %(len(subgraph), len(todo), subgraph)) todo = todo - subgraph undefined = bnodes.copy() for x, inverse, pred, y in definitions: if x in undefined: if inverse: s, p, o = x, pred, y else: s, p, o = y, pred, x if verbose > 4: progress("Declaring variable %s" % x.uriref()) if deleting: delta.declareUniversal(x) lhs.add(subj=s, pred=p, obj=o) else: # inserting if x in originalBnodes: delta.declareUniversal(x) lhs.add(subj=s, pred=p, obj=o) else: rhs.declareExistential(x) if y.generated(): undefined.add(y) undefined.discard(x) if undefined: progress("Still haven't defined bnodes %s" % undefined) for n in undefined: debugBnode(n, f) raise RuntimeError("BNodes still undefined", undefined) lhs = lhs.close() rhs = rhs.close() delta.add(subj=lhs, pred=patchVerb, obj=rhs) if verbose >1: progress("PATCH: %s %s %s\n" %(lhs.n3String(), `patchVerb`, rhs.n3String())) return def consolidate(delta, patchVerb): """Consolidate patches Where the same left hand side applies to more than 1 RHS formula, roll those RHS formulae into one, to make the dif file more readable and faster to execute in some implementations """ agenda = {} if verbose >3: progress("Consolidating %s" % patchVerb) for s in delta.statementsMatching(pred=patchVerb): list = agenda.get(s.subject(), None) if list == None: list = [] agenda[s.subject()] = list list.append(s) for lhs, list in agenda.items(): if verbose >3: progress("Patches lhs= %s: %s" %(lhs, list)) if len(list) > 1: rhs = delta.newFormula() for s in list: delta.store.copyFormula(s.object(), rhs) delta.removeStatement(s) delta.add(subj=lhs, pred=patchVerb, obj=rhs.close()) def differences(f, g, assumptions): """Smush the formulae. Compare them, generating patch instructions.""" global lumped # Cross-map nodes: g_bnodes, g_definitions = nailFormula(g, assumptions) bnodes, definitions = nailFormula(f, assumptions) if verbose > 1: progress("\n Done nailing") definitions.reverse() # go back down list @@@ reverse the g list too? @@@ g_definitions.reverse() # @@ needed for the patch generation unmatched = bnodes.copy() match = {} # Mapping of nodes in f to nodes in g for x, inverse, pred, y in definitions: if x in match: continue # done already if x in f._redirections: if verbose > 3: progress("Redirected %s to %s. Ignoring" % (`x`, `f._redirections[x]`)) unmatched.discard(x) continue if verbose > 3: progress("Definition of %s = %s%s%s"% (`x`, `y` , ".!^"[inverse], `pred`)) if y.generated(): while y in f._redirections: y = f._redirections[y] if verbose>4: progress(" redirected to %s = %s%s%s"% (`x`, `y`, "!^"[inverse], `pred`)) yg = match.get(y, None) if yg == None: if verbose>4: progress(" Had definition for %s in terms of %s which is not matched"%(`x`,`y`)) continue else: yg = y if inverse: # Inverse functional property like ssn matches = Set(g.each(obj=yg, pred=pred)) else: matches = Set(g.each(subj=yg, pred=pred)) if len(matches) == 0: continue # This is normal - the node does not exist in the other graph # raise RuntimeError("Can't match %s" % x) if len(matches) > 1: raise RuntimeError("""Rats. Wheras in the first graph %s%s%s uniquely selects %s, in the other graph there are more than 1 matches: %s""" % (`y`, "!^"[inverse], `pred`, `x`, `matches`)) for q in matches: # pick only one @@ python function? z = q break if verbose > 2: progress("Found match for %s in %s " % (`x`,`z`)) match[x] = z unmatched.discard(x) if len(unmatched) > 0: if verbose >1: progress("Failed to match all nodes:", unmatched) for n in unmatched: debugBnode(n, f) # Find common parts only_f, only_g = removeCommon(f,g, match) delta = f.newFormula() if len(only_f) == 0 and len(only_g) == 0: return delta f = f.close() # We are not going to mess with them any more g = g.close() common = Set([match[x] for x in match]) if verbose>2: progress("Common bnodes (as named in g)", common) patches(delta, f, only_f, Set(), definitions, deleting=1) patches(delta, g, only_g, common, g_definitions, deleting=0) if lumped: consolidate(delta, delta.store.insertion) consolidate(delta, delta.store.deletion) return delta def getParts(f, meta=None): """Make lists of all node IDs and arc types """ values = [Set([]),Set([]),Set([]),Set([])] for s in f.statements: for p in SUBJ, PRED, OBJ: x = s[p] values[p].add(x) return values def loadFiles(files): graph = myStore.formula() graph.setClosureMode("e") # Implement sameAs by smushing if verbose>0: progress("Loading %s..." % files) graph = myStore.loadMany(files, openFormula=graph) if verbose>0: progress("Loaded", graph) return graph def usage(): sys.stderr.write(__doc__) def main(): testFiles = [] diffFiles = [] assumptions = Set() global ploughOn # even if error ploughOn = 0 global verbose global lumped verbose = 0 lumped = 1 try: opts, args = getopt.getopt(sys.argv[1:], "hf:t:m:v:g:", ["help", "from=", "to=", "meta=", "verbose=", "granularity="]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) output = None for o, a in opts: if o in ("-h", "--help"): usage() sys.exit(2) if o in ("-v", "--verbose"): try: verbose = int(a) except ValueError: verbose = 10 if o in ("-g", "--granularity"): try: lumped = int(a) except ValueError: lumped = 0 if o in ("-f", "--from"): testFiles.append(a) if o in ("-t", "--to"): diffFiles.append(a) if o in ("-m", "--meta"): assumptions.add(a) # if testFiles == []: testFiles = [ "/dev/stdin" ] if testFiles == []: usage() sys.exit(2) graph = loadFiles(testFiles) version = "$Id: delta.py,v 1.11 2007/06/26 02:36:15 syosi Exp $"[1:-1] if diffFiles == []: nailFormula(graph, assumptions) if verbose > 1: print "# Smush generated by " + version print graph.close().n3String(base=base(), flags="a") sys.exit(0) graph2 = loadFiles(diffFiles) delta = differences(graph, graph2, assumptions) if verbose >1: print "# Differences by " + version print delta.close().n3String(base=base()) # sys.exit(len(delta)) # sys.exit(0) # didn't crash if delta.contains(): # Any statements in delta at all? sys.exit(1) else: sys.exit(0) if __name__ == "__main__": main() cwm-1.2.1/doc/0000755015216600007660000000000010731073447012170 5ustar syosisyosicwm-1.2.1/doc/changes.html0000644015216600007660000005703710352331241014466 0ustar syosisyosi Cwm features wished for and done

W3C | Semantic Web | Advanced Development | SWAP | Tutorial | Comparing Formats

n3 Cwm Changes

See also:

@@which release?

Release 1.1rc1

see 11 Aug announcement

Performance Improvements

Python 2.3 or later now required

Used for Sets

Experimental SPARQL Server support

Cwm can now run as a SPARQL server. This includes:

RDF/XML serialization fixes

A few strange bugs in rdf:xml serialization, many related to the rdf: prefix or xml: prefix, have been fixed

delta exit statuses

delta now returns with similar exit statuses as the diff utility for plaintext files. An exit status of 0 means no differences between the from and to graphs were found. An exit status of 1 means some differences were found. An exit status of 2 means differences were not computed for some reason.

Release 1.0

delta and cwm --patch

General bugfixes

Fixes in decimal support

A bug introduced into 0.8.0 where cwm crashed if no input files were specified has been fixed

Other

A crude hack in WebAccess.py allows a local file system to be used instead of a given website. The intent is to clean this up in the future.

There has been much work on a grammar for n3. grammar/n3.n3 is the grammar, grammar/predictiveParser.n3 can understand it.

RDF/XML support changes

Performance improvements

Performance work has resulted in some tasks taking 1/10 the time that they used to. Much more work is planned in this regard.

Packaging

Cwm now uses python's distutils for distribution. This allows for installation of cwm. As an added bonus, there are now rpm's, windows installers.

Flatten support

--flatten and --unflatten have been rewritten, replacing the old --flat. Flatten minimally reifies an n3 file to make it an rdf graph. Note that the graph may still fail to serialize as rdf, due to literals as subjects.

Release 0.8

This release has some bugfixes, as well as some changed and new functionality.

General bugfixes

Cwm will now do the expected thing on log:uri if given an invalid URI string.

An integer over the platforms native integer size will no longer crash Cwm.

Cwm now understands most xsd datatyped for use in builtins.

By setting the environment variable CWM_RDFLIB to 1, cwm will use rdflib to parse rdf/xml files. Note that this is unsupported, may break in the future, and requrires rdflib be installed. Rdflib supports some rdf features Cwm's parser does not, so this may be useful to you notwithstanding

BNodes scope changes

BNodes given names using the _: notation now have formula scope, not document scope.

Release / Test changes

Cwm is now released in a new file, cwm.tar.gz, which, while being a fraction of the size of the old cwm.tgz, still includes a complete set of tests. It was discovered that Cwm was not actually running all of its tests. This has been fixed, and the tests have been split into tests guarenteed to work in the .tar.gz file (offline) and those which will not.

N3QL support

N3QL support. Initial support for N3QL query language handling in cwm. command line looks like: cwm myKB.n3 --query=myquery.n3ql. Initial test case in swap/test/ql/detailed.tests

N3 serialization changes

The default output form is @forAll, not this log:forAll, @forSome, not this log:forSome. Use --n3=v to force the old obsolete form for variable declations. The parser has for a long time and will for some time support both forms.

Reification support

Reification, after being broken for almost a year, has been rewritten and is better than ever. See reify/detailed.testsThe options, as always, are --reify and --dereify. The tests for this are now in. There is insufficient documentation for this feature, and it has not been completely tested, so there may yet be bugs in it. If there is demand for it, fixing the --flatten feature should be possible now.

2004/6/23:

MIME type changes

Mime type for Notation3 switched to text/rdf+n3. This could be a major change. The application for application/n3 never seemed to get anywhere with IANA anyway. Text has the advantage that browsers will by default dispaly it, and N3 is designed to be readable. Downside is that if it not ASCII, then you must include the charset specification in the mime type. This must be UTF-8, and notation3 is always utf-8.

Release 0.7.3

HTTP errors

Cwm now correctly identifies HTTP 404 errors, throwing an exception, and does not try to parse the returned (HTML) file.

Reflexive statements now work

An n3 statement which references the same universal quantifier twice now does the right thing.

Release 0.7.2

Ooops - nodeID was misspelled nodeid on RDF/XML output.

Patch functionality

The --patch=patchfile command line argument allows a patch file to be applied to the knowledge base (current working formula). See the Diff, Patch, Update and Sync note in the Design Issues series on the motivation for exchanging difference files, and how they work. Diff files can in certain specific circumstances (a well-labeled graph) be produced by the diff.py program included with this distribution. The new tests are in $SWAP/test/delta/detailed.tests

Internationization undefined, Numerics canonicalized

The i18n/detailed.tests have been removed from the test harness. They were not right, and URI/ IRI issues are not clear yet. It is not clear whether cwm should URI-canonicalize, or IRI-canonicalize. (My instinct is that it should - Tim).

Cwm does not canonicalize numerical (xsd:double and xsd:integer) values on N3 output. It uses python's str(float(s)) and str(int(s)). The effect is to reduce some over-precision in the output.

Release 0.7.1, 2004-03-04

RDF Parser improved

The cwm regresssion test now incorporates the RDF Core Positive Parser Tests except for those which deal with reification or with XML literals. In the process, xml:base supposrt was added in the parser.

A new test found in the updated core tests requires RDF to be parsed even when there is no enveloping <rdf:RDF> tag, even if the outermost element is a typed node production, and so not something in the RDF namespace at all. This makes rdf much less self-describing, and makes it more dangerous that one might parse say an HTML file as RDF by accident. Use with care. If need this feature, use the --rdf=R flag.

The RDF core tests are done with --rdf=RT to make the parser parse naked RDF or RDF buried in foreign XML..

nodeid generated on RDF output

This has been a missing feature of the RDF generator for a while. The nodeid feature allows bnodes to be output in RDF/XML. I may not have got this right, as I don't have RDF generation tests, only RDF parse tests.

Ordering of output

The ordering of Terms has been changed. Automatically generated terms with no URIs sort after anything which has a URI.

This will change the order of N3 and RDF/XML output but does not change its semantics.s

Namespace prefix smarts on output

Cwm now does output in a two-pass process. This makes its counting of the number of occurrences of namespaces more acurate, which determines the default namespace it choses. This does take more time, though not as long as the previous method of working out which was going to be most common. To skip this process, use the "d" flag on output (N3 or RDF/XML) to suppress the use of a default namespace.

Because this counting is now accurate, it now suppresses namespace prefix declarations which are not actually needed in the output.

Cwm will also make up prefixes when it needs them for a namespace, and none of the input data uses one. It peeks into the the namespace URI, and looks around for a short string after the last "/", adding numbers if necessary to make the prefix unique.

Namespaces without hashes

Cwm when writing N3 not normally use namespace names for URIs which do not have a "#". Including a "/" in the flags overrides this.

cwm mydcdata.n3 --n3="/"

Namespaces which end in "/" lead (in my opinion) to an unfortunate confusion between the RDF propoerties and the HTTP document they identify. This is related to W3C TAG Issue httpRange-14.

ValueError: You cannot use 'this' except as subject of forAll or forSome

The "this" syntax in a formula refers to the formula itself. It was used for thr pseudo-statements this log:forSome x, and this log;forAll y.

In a few rare cases it actually was used to refer logically to the formula itself. A classic is of course { this a log:falseHood }. I decided that this was going to make more problems than it would solve. The psudostatements have gone anway (in response to popular request), they became just syntax. And the @forAll syntax has been introduced as the way to go. So with this release, while you can still like many N3 files use this to qualify variables, you can't use it for anything else.

Release 0.7, 2004-02-04

Release 0.7. 2004-02-04: This is a first numbered release. After much discussion we picked 0.7 as the number. Added a CVS tag rel-0-7, so that if you have the source through CVS, you up- or down-grade to this by

cvs update -r rel-0-7

The idea is that this release has a well-defined set of bugs, and that we work toward a more community-supported platform with time.

  1. The set of open bugs or request for enhancements (RFEs) which have been sent to the list are now available, every time we run make, in an iCalendar format ToDo list. . This at least tracks the outstanding one. Those for which a "[closed] Re: ..." response exists are given Completed status.
  2. A few have actually been closed. Closure now where appropiate involves including a suitable test in the regression tests. This test currently includes all the n3 format files detailed.tests in subdirectories of $SWAP/test.
  3. New mailing lists have been made.
    public-cwm-announce
    This low-traffic is for announcements about releases of cwm software.
    public-cwm-bugs
    This is for the announcement and brief discussion/clarification of cwm bugs. A mail with subject [closed] Re: .... marks a thread as closed. We may make this protocol more sophistiucaed with time. If responding to only use mailers which send the refernce headers so that the threads on this mail ling list work. For new threads, please make the subject line informative, and use the word "bug" or "RFE" as appopriate. The current plan is to review changes in this monthly and send it to the announce list
    public-cwm-talk
    Discussion by users and/or developers of the use and abuse of project software.

Changes 2003-09

  1. More on-added functionality: --closure=e smushes nodes which are = into one. That is any time the working formula (knowledge base) has a triple added where a = b, the store with "e" in the closure mode will replace all occurrences of b with a. When chosing which of the two to use as the node, the preference will be to literals or lists or formulae, then to symbols with URIs (lexically lowest prefered, e.g. <a> rather than <b>), then blank nodes. It will remember the quality.
  2. --closure=T makes the adding of a triple {F a log:Truth} where F is a formula to cause the content of F to be loaded into the knowledge base.
  3. The ordering of terms has been fixed so that all constants literals, lsits amd formula should all appear before any symbols in a listing.

    (code is formula.compareTerm())

Cwm Changes 2003/08

At this point cwm made a number of changes at once, so we document them here.

@prefix test: <http://www.w3.org/2000/10/swap/test/regression#>.

  1. The namespaces used for lists changed from DAML to RDF. The namespace used for "=" switched to OWL. DAML and DAML+OIL are used no more, though we remember them fondly. This change actually shouldn't change much in many applications, where files use the collection syntax in RDF or the () and = syntaxes in N3. It does affect the order of statements cwm uses to pretty-print files.

  2. Lists are handled differently internally. This is a bit of a an experiment. Instead of being stored in their first/rest forms in the graph, complete lists are stored as List objects. Thse are first class objects. .
    • You can match against lists. Unification of formlae will catch identical lists such as ( <a> <b> ) matching against ( <a> <b> ) because Lists are interned, and also unify ( ?x ?y ) with ( <a> <b> ). This still does not work , however with formulae. Watch this space, though,as this may change.
    • The list-handling is not complete when constructing lists. (test that fail: test/list/gk*.n3 -- sorry Graham!). Lists generated are currently not available to be queried. rdf:first and rdf:rest are built-in functions which work to dismantle lists, but currently not to build them. or, that is, you can build them but you can't directly query them... watch this space. Hopefully this will be fixed, and the lists will behave just as thoug the actual graph contained rdf:first and rdf:rest triples (but be more efficient).
    • You should be able to generate lists from built-ins if you are making new built-in functions. Just return a python sequence from evaluateObject().
    • The unification (query) engine was complicated by the fact that lists in the antecedent can be assumed as all lists exist by axiom. The last release of llyn had a bug (test:t1018b2) with that - and wrapping my head round that caused me to decide it was time for the change. It is nowsimpler in that regard.
    • In canonical comparisons, Lists are greater than literals and smaller than formulae. This may affect the ordering of cwm-generated files. Lists currently compare element by element, or if elements match, shortest is smallest.
  3. New option --data strips the store down to an RDF graph, losing universal variables (forAll's) and any statements which mentoin nested formulae. --purge-rules is now deprocated and does the same thing. (--purge-rules sed to be a just remove things menioning forAll or implies.)
  4. Generated Ids have in the past been generated relative to the current input file (or base) like <#_g0>. This had two problems. The first is that purists point outthat cwm is assertingthings about the user's namespace which aren't necessarily true - why does cwm have the right to do this? The second is pragmatic: when two files already with cwm-generated genids were re-processed using cwm, it could under some cases end up reusing the same id. Now, cwm makes up, by default, much more resilient ones. It imagines a file called something like .run-19435661734.7651234 in the local directory, and uses that file's local space for its names. If you don't like this (eg for repeatable testing) you can set an environment variable CWM_RUN_NS to something like "#", which will create the original behaviour, or a specific namespace you know you won't reuse in related work.

More changes 2003-08-25

  1. 2003-08 Pretty printing split from llyn.py to pretty.py. Interface may change. Pretty printing should be faster now - for some runs it was taking a lot longer than the parsing and inference steps. It had never been designed for speed, but it was getting ridiculous.
  2. 2003-08-30 List processing improved. test/list/append.n3 works, reverse.n3 doesn't yet. substituteEquals supported by all Terms, does substituton of equals, used in compbaintion with F._redirection which is a dictionary of aliases. Preparing for handling of equality and smushing of nodes.

For python cwm developers

  1. The store is being separated into components. llyn.py was too big. The idea is to be able to support a redland underlying store in the future. The unification engine which includes the built-in function operation now uses the store's api to access the store without peeking into internals.
  2. thing.py split into myStore.py and term.py
  3. It used to be that the universal and existential variables in a formula were stored in forAll and forSome psudo-property triples. This was basically a kludge. One had to be always aware that the pseudoproperties didn't act like real ones (no substitution for = etc). So now the lists of variables have goene into the formula objects. This should make it much easir for people tofollow whatis happeningin the code, and removes all kinds of special case code.

Getting an old version

You can get the old version before these 2.0 changes using CVS, by checking out with the tag oldLists .

cvs update -r oldLists

Features done earlier

Done ==== - sucking in the schema (http library?)

--schemas ; - to know about r1 see r2;

- split Query engine out as subclass of RDFStore? (DWC) SQL-equivalent client

- split out separate modules: CGI interface, command-line stuff, built-ins (DWC 30Aug2001)

- (test/retest.sh is another/better list of completed functionality --DWC)

- BUG: a [ b c ] d. gets improperly output. See anon-pred

- Separate the store hash table from the parser.

- DONE - regeneration of genids on output.

- DONE - repreentation of genids and foralls in model - regression test

- DONE (once!) Manipulation: { } as notation for bag of statements - DONE - filter -DONE - graph match

-DONE - recursive dump of nested bags

- DONE - semi-reification - reifying only subexpressions

- DONE - Bug :x :y :z as data should match [ :y :z ] as query. Fixed by stripping forSomes from top of query.

- BUG: {} is a context but that is lost on output!!! statements not enough. See foo2.n3 - change existential representation :-( to make context a real conjunction again? (the forSome triple is special in that you can't remove it and reduce info) - filter out duplicate conclusions

- BUG! - DONE - Validation: validate domain and range constraints against closure of classes and mutually disjoint classes.

- Use unambiguous property to infer synomnyms (see sameDan.n3 test case in test/retest.sh)

- schema validation - done partly but no "no schema for xx predicate". ULTILS WE HAVE DONE

- includes(expr1, expr2) (cf >= , dixitInterAlia )

- indirectlyImplies(expr1, expr2)

- startsWith(x,y)

- uri(x, str)

- usesNamespace(x,y) # find transitive closure for validation - awful function in reality


$Id: changes.html,v 1.48 2005/11/03 22:25:04 connolly Exp $

cwm-1.2.1/cwm_math.html0000644015216600007660000070233410642726420014116 0ustar syosisyosi Python: module cwm_math
 
 
cwm_math (version 1.26)
index
/Users/yosi/CVSROOT/WWW/2000/10/swap/cwm_math.py

Matematical Built-Ins for CWM/Llyn
 
Allows CWM to do addition, multiplication, subtraction, division, 
remainders, negation, exponentiation, count the members in a DAML 
list, and do the normal truth checking functions, only sub classed 
for numeric values.
 
Note: see maths with an s for te string-oriented versions.
 
cf. http://www.w3.org/2000/10/swap/cwm.py and 
http://ilrt.org/discovery/chatlogs/rdfig/2001-12-01.txt from 
"01:20:58" onwards.

 
Modules
       
re
string
sys
traceback
types
urllib

 
Classes
       
term.Function(term.BuiltIn)
BI_absoluteValue(term.LightBuiltIn, term.Function)
BI_bit(term.LightBuiltIn, term.Function)
BI_difference(term.LightBuiltIn, term.Function)
BI_exponentiation(term.LightBuiltIn, term.Function)
BI_integerQuotient(term.LightBuiltIn, term.Function)
BI_memberCount(term.LightBuiltIn, term.Function)
BI_negation(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_product(term.LightBuiltIn, term.Function)
BI_quotient(term.LightBuiltIn, term.Function)
BI_remainder(term.LightBuiltIn, term.Function)
BI_rounded(term.LightBuiltIn, term.Function)
BI_sum(term.LightBuiltIn, term.Function)
term.LightBuiltIn(term.GenericBuiltIn)
BI_absoluteValue(term.LightBuiltIn, term.Function)
BI_bit(term.LightBuiltIn, term.Function)
BI_difference(term.LightBuiltIn, term.Function)
BI_differenceOf(term.LightBuiltIn, term.ReverseFunction)
BI_equalTo
BI_exponentiation(term.LightBuiltIn, term.Function)
BI_exponentiationOf(term.LightBuiltIn, term.ReverseFunction)
BI_factors(term.LightBuiltIn, term.ReverseFunction)
BI_greaterThan
BI_integerQuotient(term.LightBuiltIn, term.Function)
BI_lessThan
BI_memberCount(term.LightBuiltIn, term.Function)
BI_negation(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_notEqualTo
BI_notGreaterThan
BI_notLessThan
BI_product(term.LightBuiltIn, term.Function)
BI_quotient(term.LightBuiltIn, term.Function)
BI_quotientOf(term.LightBuiltIn, term.ReverseFunction)
BI_remainder(term.LightBuiltIn, term.Function)
BI_remainderOf(term.LightBuiltIn, term.ReverseFunction)
BI_rounded(term.LightBuiltIn, term.Function)
BI_sum(term.LightBuiltIn, term.Function)
BI_sumOf(term.LightBuiltIn, term.ReverseFunction)
term.ReverseFunction(term.BuiltIn)
BI_differenceOf(term.LightBuiltIn, term.ReverseFunction)
BI_exponentiationOf(term.LightBuiltIn, term.ReverseFunction)
BI_factors(term.LightBuiltIn, term.ReverseFunction)
BI_negation(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_quotientOf(term.LightBuiltIn, term.ReverseFunction)
BI_remainderOf(term.LightBuiltIn, term.ReverseFunction)
BI_sumOf(term.LightBuiltIn, term.ReverseFunction)

 
class BI_absoluteValue(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_absoluteValue
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_bit(term.LightBuiltIn, term.Function)
    @@needs a test.
 
 
Method resolution order:
BI_bit
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_difference(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_difference
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_differenceOf(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_differenceOf
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_equalTo(term.LightBuiltIn)
    
Method resolution order:
BI_equalTo
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluate(self, subject, object)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_exponentiation(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_exponentiation
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_exponentiationOf(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_exponentiationOf
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_factors(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_factors
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_greaterThan(term.LightBuiltIn)
    
Method resolution order:
BI_greaterThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluate(self, subject, object)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_integerQuotient(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_integerQuotient
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_lessThan(term.LightBuiltIn)
    
Method resolution order:
BI_lessThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluate(self, subject, object)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_memberCount(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_memberCount
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_negation(term.LightBuiltIn, term.Function, term.ReverseFunction)
    
Method resolution order:
BI_negation
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Methods inherited from term.ReverseFunction:
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notEqualTo(term.LightBuiltIn)
    
Method resolution order:
BI_notEqualTo
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluate(self, subject, object)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notGreaterThan(term.LightBuiltIn)
    
Method resolution order:
BI_notGreaterThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluate(self, subject, object)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notLessThan(term.LightBuiltIn)
    
Method resolution order:
BI_notLessThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluate(self, subject, object)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_product(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_product
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_quotient(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_quotient
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_quotientOf(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_quotientOf
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_remainder(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_remainder
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_remainderOf(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_remainderOf
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_rounded(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_rounded
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_sum(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_sum
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_sumOf(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_sumOf
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
Functions
       
isString(x)
numeric(s)
obsolete()
register(store)
tidy(x)

 
Data
        MATH_NS_URI = 'http://www.w3.org/2000/10/swap/math#'
__author__ = 'Sean B. Palmer'
__cvsid__ = '$Id: cwm_math.html,v 1.20 2007/06/27 17:58:39 syosi Exp $'
__version__ = '$Revision: 1.20 $'

 
Author
        Sean B. Palmer
cwm-1.2.1/llyn.html0000644015216600007660000117346110731070067013277 0ustar syosisyosi Python: module llyn
 
 
llyn
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/llyn.py

$Id: llyn.py,v 1.185 2007/12/11 21:18:08 syosi Exp $
 
 
RDF Store and Query engine
 
Logic Lookup: Yet another Name
 
(also, in Wales, a lake - a storage area at the centre of the valley?)
 
This is an engine which knows a certian amount of stuff and can manipulate it.
It is a (forward chaining) query engine, not an (backward chaining) inference engine:
that is, it will apply all rules it can
but won't figure out which ones to apply to prove something.  It is not
optimized particularly.
 
Used by cwm - the closed world machine.
See:  http://www.w3.org/DesignIssues/Notation3
 
Interfaces
==========
 
This store stores many formulae, where one formula is what in
straight RDF implementations is known as a "triple store".
So look at the Formula class for a triple store interface.
 
See also for comparison, a python RDF API for the Redland library (in C):
   http://www.redland.opensource.ac.uk/docs/api/index.html 
and the redfoot/rdflib interface, a python RDF API:
   http://rdflib.net/latest/doc/triple_store.html
 
    
Copyright ()  2000-2004 World Wide Web Consortium, (Massachusetts Institute
of Technology, European Research Consortium for Informatics and Mathematics,
Keio University). All Rights Reserved. This work is distributed under the
W3C Software License [1] in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.

 
Modules
       
StringIO
binascii
diag
httplib
md5
notation3
re
reify
string
sys
time
types
uripath
urllib
weakref
webAccess
_xmlplus

 
Classes
       
RDFSink.RDFSink
RDFStore
__builtin__.object
Disjoint_set
exceptions.ValueError(exceptions.StandardError)
URISyntaxError
formula.Formula(term.AnonymousNode, term.CompoundTerm)
IndexedFormula
DataObject
term.Function(term.BuiltIn)
BI_EqualTo(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_EqualTo(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_conclusion(term.HeavyBuiltIn, term.Function)
BI_conjunction(term.LightBuiltIn, term.Function)
BI_content(term.HeavyBuiltIn, term.Function)
BI_dtlit(term.LightBuiltIn, term.Function)
BI_filter(term.LightBuiltIn, term.Function)
BI_n3String(term.LightBuiltIn, term.Function)
BI_parsedAsN3(term.HeavyBuiltIn, term.Function)
BI_racine(term.LightBuiltIn, term.Function)
BI_rawType(term.LightBuiltIn, term.Function)
BI_reification(term.HeavyBuiltIn, term.Function, term.ReverseFunction)
BI_semantics(term.HeavyBuiltIn, term.Function)
BI_semanticsOrError
BI_semanticsWithImportsClosure(term.HeavyBuiltIn, term.Function)
BI_uri(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_rawUri
BI_vars(term.LightBuiltIn, term.Function)
BI_xmlTree(term.HeavyBuiltIn, term.Function)
term.HeavyBuiltIn(term.GenericBuiltIn)
BI_conclusion(term.HeavyBuiltIn, term.Function)
BI_content(term.HeavyBuiltIn, term.Function)
BI_includes
BI_notIncludes
BI_notIncludesWithBuiltins
BI_parsedAsN3(term.HeavyBuiltIn, term.Function)
BI_reification(term.HeavyBuiltIn, term.Function, term.ReverseFunction)
BI_semantics(term.HeavyBuiltIn, term.Function)
BI_semanticsOrError
BI_semanticsWithImportsClosure(term.HeavyBuiltIn, term.Function)
BI_supports
BI_xmlTree(term.HeavyBuiltIn, term.Function)
term.LightBuiltIn(term.GenericBuiltIn)
BI_EqualTo(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_EqualTo(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_conjunction(term.LightBuiltIn, term.Function)
BI_dtlit(term.LightBuiltIn, term.Function)
BI_filter(term.LightBuiltIn, term.Function)
BI_n3String(term.LightBuiltIn, term.Function)
BI_notEqualTo
BI_racine(term.LightBuiltIn, term.Function)
BI_rawType(term.LightBuiltIn, term.Function)
BI_uri(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_rawUri
BI_vars(term.LightBuiltIn, term.Function)
term.RDFBuiltIn(term.LightBuiltIn)
BI_enforceUniqueBinding
BI_existentialVariableName
BI_universalVariableName
term.ReverseFunction(term.BuiltIn)
BI_EqualTo(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_EqualTo(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_reification(term.HeavyBuiltIn, term.Function, term.ReverseFunction)
BI_uri(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_rawUri

 
class BI_EqualTo(term.LightBuiltIn, term.Function, term.ReverseFunction)
    
Method resolution order:
BI_EqualTo
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
BI_SameAs = class BI_EqualTo(term.LightBuiltIn, term.Function, term.ReverseFunction)
    
Method resolution order:
BI_EqualTo
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_conclusion(term.HeavyBuiltIn, term.Function)
    Deductive Closure
 
Closure under Forward Inference, equivalent to cwm's --think function.
This is a function, so the object is calculated from the subject.
 
 
Method resolution order:
BI_conclusion
term.HeavyBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_conjunction(term.LightBuiltIn, term.Function)
    The conjunction of a set of formulae is the set of statements which is
just the union of the sets of statements
modulo non-duplication of course.
 
 
Method resolution order:
BI_conjunction
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_content(term.HeavyBuiltIn, term.Function)
    
Method resolution order:
BI_content
term.HeavyBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_dtlit(term.LightBuiltIn, term.Function)
    built a datatype literal from a string and a uri
 
 
Method resolution order:
BI_dtlit
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_enforceUniqueBinding(term.RDFBuiltIn)
    Is the mapping from the variable in the subject to the name in the object unique?
 
 
Method resolution order:
BI_enforceUniqueBinding
term.RDFBuiltIn
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_existentialVariableName(term.RDFBuiltIn)
    Is the object the name of a existential variable in the subject?
Can be used as a test, or returns a sequence of values.
Currently gives BNode names too.  Maybe we make sep function for that?
 
 
Method resolution order:
BI_existentialVariableName
term.RDFBuiltIn
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_filter(term.LightBuiltIn, term.Function)
    Filtering of formulae
 
 
Method resolution order:
BI_filter
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_includes(term.HeavyBuiltIn)
    Check that one formula does include the other.
This limits the ability to bind a variable by searching inside another
context. This is quite a limitation in some ways. @@ fix
 
 
Method resolution order:
BI_includes
term.HeavyBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_n3String(term.LightBuiltIn, term.Function)
    The n3 string for a formula is what you get when you
express it in the N3 language without using any URIs.
Note that there is no guarantee that two implementations will
generate the same thing, but whatever they generate should
parse back using parsedAsN3 to exaclty the same original formula.
If we *did* have a canonical form it would be great for signature
A canonical form is possisble but not simple.
 
 
Method resolution order:
BI_n3String
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notEqualTo(term.LightBuiltIn)
    
Method resolution order:
BI_notEqualTo
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notIncludes(term.HeavyBuiltIn)
    Check that one formula does not include the other.
 
notIncludes is a heavy function not only because it may take more time than
a simple search, but also because it must be performed after other work so that
the variables within the object formula have all been subsituted.  It makes no sense
to ask a notIncludes question with variables, "Are there any ?x for which
F does not include foo bar ?x" because of course there will always be an
infinite number for any finite F.  So notIncludes can only be used to check, when a
specific case has been found, that it does not exist in the formula.
This means we have to know that the variables do not occur in obj.
 
As for the subject, it does make sense for the opposite reason.  If F(x)
includes G for all x, then G would have to be infinite.
 
 
Method resolution order:
BI_notIncludes
term.HeavyBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notIncludesWithBuiltins(term.HeavyBuiltIn)
    
Method resolution order:
BI_notIncludesWithBuiltins
term.HeavyBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_parsedAsN3(term.HeavyBuiltIn, term.Function)
    
Method resolution order:
BI_parsedAsN3
term.HeavyBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_racine(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_racine
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_rawType(term.LightBuiltIn, term.Function)
    The raw type is a type from the point of view of the langauge: is
it a formula, list, and so on. Needed for test for formula in finding subformulae
eg see test/includes/check.n3
 
 
Method resolution order:
BI_rawType
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_rawUri(BI_uri)
    This is like  uri except that it allows you to get the internal
identifiers for anonymous nodes and formuale etc.
 
 
Method resolution order:
BI_rawUri
BI_uri
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from BI_uri:
evaluateSubject(self, object)
Return the object which has this string as its URI
 
#@@hm... check string for URI syntax?
# or at least for non-uri chars, such as space?
Note that relative URIs can be OK as the whole process
has a base, which may be irrelevant. Eg see roadmap-test in retest.sh

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.ReverseFunction:
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_reification(term.HeavyBuiltIn, term.Function, term.ReverseFunction)
    
Method resolution order:
BI_reification
term.HeavyBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_semantics(term.HeavyBuiltIn, term.Function)
    The semantics of a resource are its machine-readable meaning, as an
N3 forumula.  The URI is used to find a representation of the resource in
bits which is then parsed according to its content type.
 
 
Method resolution order:
BI_semantics
term.HeavyBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_semanticsOrError(BI_semantics)
    Either get and parse to semantics or return an error message on any error
 
 
Method resolution order:
BI_semanticsOrError
BI_semantics
term.HeavyBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_semanticsWithImportsClosure(term.HeavyBuiltIn, term.Function)
    The semantics of a resource are its machine-readable meaning,
as an N3 forumula.  The URI is used to find a representation of
the resource in bits which is then parsed according to its content
type.  Extension : It also loads all imported URIs
 
 
Method resolution order:
BI_semanticsWithImportsClosure
term.HeavyBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_supports(term.HeavyBuiltIn)
    A more managable version of log:conclusion
The real version of this should appear in query.py
 
 
Method resolution order:
BI_supports
term.HeavyBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_universalVariableName(term.RDFBuiltIn)
    Is the object the name of a universal variable in the subject?
Runs even without interpretBuitins being set.  
Used internally in query.py for testing for 
Can be used as a test, or returns a sequence of values.
 
 
Method resolution order:
BI_universalVariableName
term.RDFBuiltIn
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_uri(term.LightBuiltIn, term.Function, term.ReverseFunction)
    
Method resolution order:
BI_uri
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)
evaluateSubject(self, object)
Return the object which has this string as its URI
 
#@@hm... check string for URI syntax?
# or at least for non-uri chars, such as space?
Note that relative URIs can be OK as the whole process
has a base, which may be irrelevant. Eg see roadmap-test in retest.sh

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.ReverseFunction:
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_vars(term.LightBuiltIn, term.Function)
    Get only the variables from a formula
 
 
Method resolution order:
BI_vars
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_xmlTree(term.HeavyBuiltIn, term.Function)
    
Method resolution order:
BI_xmlTree
term.HeavyBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
flatten(self, sink, why=None)
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unflatten(self, sink, bNodes, why=None)
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class DataObject
    The info about a term in the context of a specific formula
It is created by being passed the formula and the term, and is
then accessed like a python dictionary of sequences of values. Example:
 
F = myWorkingFormula
x = F.theObject(pred=rdfType obj=fooCar)
for y in x[color][label]
 
  Methods defined here:
__getItem__(pred)
__init__(context, term)

 
class Disjoint_set(__builtin__.object)
     Methods defined here:
__init__(self)
add(self, f)
connected(self, f, g)
merge(self, s1, s2)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Disjoint_set' objects>
list of weak references to the object (if defined)
disjoint_set_node = <class 'llyn.disjoint_set_node'>

 
class IndexedFormula(formula.Formula)
    A formula which has indexes to facilitate queries.
 
A formula is either open or closed.  Initially, it is open. In this
state is may be modified - for example, triples may be added to it.
When it is closed, note that a different interned version of itself
may be returned. From then on it is a constant.
 
Only closed formulae may be mentioned in statements in other formuale.
 
There is a reopen() method but it is not recommended, and if desperate should
only be used immediately after a close().
 
 
Method resolution order:
IndexedFormula
formula.Formula
term.AnonymousNode
term.Node
term.CompoundTerm
term.Term
__builtin__.object

Methods defined here:
__init__(self, store, uri=None)
add(self, subj, pred, obj, why=None)
Add a triple to the formula.
 
The formula must be open.
subj, pred and obj must be objects as for example generated by Formula.newSymbol()
and newLiteral(), or else literal values which can be interned.
why     may be a reason for use when a proof will be required.
any(self, subj=None, pred=None, obj=None)
Return None or the value filing the blank in the called parameters.
 
Specifiy exactly two of the arguments.
color = f.any(pred=pantoneColor, subj=myCar)
somethingRed = f.any(pred=pantoneColor, obj=red)
 
Note difference from the old store.any!!
Note SPO order not PSO.
To aboid confusion, use named parameters.
canonicalize(F, cannon=False)
If this formula already exists, return the master version.
If not, record this one and return it.
Call this when the formula is in its final form, with all its
statements.  Make sure no one else has a copy of the pointer to the
smushed one.  In canonical form,
 - the statments are ordered
 - the lists are all internalized as lists
 
Store dependency: Uses store._formulaeOfLength
checkClosure(self, subj, pred, obj)
Check the closure of the formula given new contents
 
The s p o flags cause llyn to follow those parts of the new statement.
i asks it to follow owl:imports
r ask it to follow doc:rules
checkClosureDocument(self, x)
checkClosureOfSymbol(self, y)
contains(self, pred=None, subj=None, obj=None)
Return boolean true iff formula contains statement(s) matching the parts given
 
For example:
if f.contains(pred=pantoneColor):
    print "We've got one statement about something being some color"
debugString(self, already=[])
A simple dump of a formula in debug form.
 
This formula is dumped, using ids for nested formula.
Then, each nested formula mentioned is dumped.
each(self, subj=None, pred=None, obj=None)
Return a list of values value filing the blank in the called parameters
 
Examples:
colors = f.each(pred=pantoneColor, subj=myCar)
 
for redthing in f.each(pred=pantoneColor, obj=red): ...
newCanonicalize(F)
outputStrings(self, channel=None, relation=None)
Fetch output strings from store, sort and output
 
To output a string, associate (using the given relation) with a key
such that the order of the keys is the order in which you want the corresponding
strings output.
removeStatement(self, s)
Removes a statement The formula must be open.
 
This implementation is alas slow, as removal of items from tha hash is slow.
The above statement is false. Removing items from a hash is easily over five times
faster than removing them from a list.
Also, truth mainainance is not done.  You can't undeclare things equal.
This is really a low-level method, used within add() and for cleaning up the store
to save space in purge() etc.
reopen(self)
Make a formula which was once closed oopen for input again.
 
NOT Recommended.  Dangers: this formula will be, because of interning,
the same objet as a formula used elsewhere which happens to have the same content.
You mess with this one, you mess with that one.
Much better to keep teh formula open until you don't needed it open any more.
The trouble is, the parsers close it at the moment automatically. To be fixed.
searchable(self, subj=None, pred=None, obj=None)
A pair of the difficulty of searching and a statement iterator of found statements
 
The difficulty is a store-portable measure of how long the store
thinks (in arbitrary units) it will take to search.
This will only be used for choisng which part of the query to search first.
If it is 0 there is no solution to the query, we know now.
 
In this implementation, we use the length of the sequence to be searched.
setClosureMode(self, x)
statementsMatching(self, pred=None, subj=None, obj=None)
Return a READ-ONLY list of StoredStatement objects matching the parts given
 
For example:
for s in f.statementsMatching(pred=pantoneColor):
    print "We've got one which is ", `s[OBJ]`
    
If none, returns []
substituteEqualsInPlace(self, redirections, why=None)
Slow ... does not use indexes
the(self, subj=None, pred=None, obj=None)
Return None or the value filing the blank in the called parameters
 
This is just like any() except it checks that there is only
one answer in the store. It wise to use this when you expect only one.
 
color = f.the(pred=pantoneColor, subj=myCar)
redCar = f.the(pred=pantoneColor, obj=red)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source)

Methods inherited from formula.Formula:
__iter__(self)
The internal method which allows one to iterate over the statements
as though a formula were a sequence.
__len__(self)
How many statements?
__repr__(self)
bind(self, prefix, uri)
Give a prefix and associated URI as a hint for output
 
The store does not use prefixes internally, but keeping track
of those usedd in the input data makes for more human-readable output.
classOrder(self)
close(self)
No more to add. Please return interned value.
NOTE You must now use the interned one, not the original!
compareTerm(self, other)
Assume is also a Formula - see function compareTerm below
declareExistential(self, v)
declareUniversal(self, v, key=None)
doesNodeAppear(self, symbol)
Does that particular node appear anywhere in this formula
 
This function is necessarily recursive, and is useful for the pretty printer
It will also be useful for the flattener, when we write it.
existentials(self)
Return a list of existential variables with this formula as scope.
 
Implementation:
we may move to an internal storage rather than these pseudo-statements
flatten(self, sink, why=None)
freeVariables(self)
generated(self)
Yes, any identifier you see for this is arbitrary.
intern(self, value)
loadFormulaWithSubstitution(self, old, bindings={}, why=None, cannon=False)
Load information from another formula, subsituting as we go
returns number of statements added (roughly)
n3EntailedBy(pattern, kb, vars=set([]), existentials=set([]), bindings={})
See Term.unify() and term.matchSet()
 
KB is a stronger statement han other.
Bindings map variables in pattern onto kb.
Self n3-entails other.
Criteria:  Subset of self statements must match other statements.
  Self's exisetntials must be subset of other's
  Self's universals must be superset.
n3String(self, base=None, flags='')
Dump the formula to an absolute string in N3
newBlankNode(self, uri=None, why=None)
Create a new unnamed node with this formula as context.
 
The URI is typically omitted, and the system will make up an internal idnetifier.
If given is used as the (arbitrary) internal identifier of the node.
newExistential(self, uri=None, why=None)
Create a named variable existentially qualified within this formula
 
See also: existentials()  and newBlankNode().
newFormula(self, uri=None)
Create a new open, empty, formula in the same store as this one.
 
The URI is typically omitted, and the system will make up an internal idnetifier.
If given is used as the (arbitrary) internal identifier of the formula.
newList(self, list)
newLiteral(self, str, dt=None, lang=None)
Create or reuse the internal representation of the RDF literal whose string is given
 
The literal is created in the same store as the formula.
newSymbol(self, uri)
Create or reuse the internal representation of the RDF node whose uri is given
 
The symbol is created in the same store as the formula.
newUniversal(self, uri=None, why=None)
Create a named variable universally qualified within this formula
 
See also: universals()
newXMLLiteral(self, doc)
Create or reuse the internal representation of the RDF literal whose string is given
 
The literal is created in the same store as the formula.
ntString(self, base=None, flags='bravestpun')
Dump the formula to an absolute string in N3
objects(self, pred=None, subj=None)
Obsolete - use each(subj=..., pred=...)
occurringIn(self, vars)
Which variables in the list occur in this?
predicates(self, subj=None, obj=None)
Obsolete - use each(subj=..., obj=...)
rdfString(self, base=None, flags='')
Dump the formula to an absolute string in RDF/XML
reification(self, sink, bnodeMap={}, why=None)
Describe myself in RDF to the given context
renameVars(self)
size(self)
Return the number statements.
Obsolete: use len(F).
subSet(self, statements, why=None)
subjects(self, pred=None, obj=None)
Obsolete - use each(pred=..., obj=...)
substituteEquals(self, bindings, newBindings)
Return this or a version of me with subsitution made
 
Subsitution of = for = does NOT happen inside a formula,
as the formula is a form of quotation.
substitution(self, bindings, why=None, cannon=False, keepOpen=False)
Return this or a version of me with subsitution made
universals(self)
Return a set of variables universally quantified with this formula as scope.
 
Implementation:
We may move to an internal storage rather than these statements.
variables(self)
Return a set of all variables quantified within this scope.

Static methods inherited from formula.Formula:
resetRenames(reset=True)

Methods inherited from term.AnonymousNode:
asPair(self)
unflatten(self, sink, bNodes, why=None)
uriref(self)

Methods inherited from term.Term:
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
representation(self, base=None)
The string represnting this in N3
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class RDFStore(RDFSink.RDFSink)
    Absorbs RDF stream and saves in triple store
 
  Methods defined here:
__init__(self, genPrefix=None, metaURI=None, argv=None, crypto=0)
any(self, q)
Query the store for the first match.
 
Quad contains one None as wildcard. Returns first value
matching in that position.
bind(self, prefix, uri)
checkNewId(self, urirefString)
Raise an exception if the id is not in fact new.
 
This is useful because it is usfeul
to generate IDs with useful diagnostic ways but this lays them
open to possibly clashing in pathalogical cases.
clear(self)
Remove all formulas from the store     @@@ DOESN'T ACTUALLY DO IT/BROKEN
copyFormula(self, old, new, why=None)
dumpBySubject(self, context, sink, sorting=1)
Dump by order of subject except forSome's first for n3=a mode
dumpChronological(self, context, sink)
Fast as possible. Only dumps data. No formulae or universals.
dumpNested(self, context, sink, flags='')
Iterates over all URIs ever seen looking for statements
endDoc(self, rootFormulaPair)
genId(self)
Generate a new identifier
 
This uses the inherited class, but also checks that we haven't for some pathalogical reason
ended up generating the same one as for example in another run of the same system.
intern(self, what, dt=None, lang=None, why=None)
find-or-create a Fragment or a Symbol or Literal or list as appropriate
 
returns URISyntaxError if, for example, the URIref has
two #'s.
 
This is the way they are actually made.
internURI(self, str, why=None)
load(store, uri=None, openFormula=None, asIfFrom=None, contentType=None, remember=1, flags='', referer=None, why=None, topLevel=False)
Get and parse document.  Guesses format if necessary.
 
uri:      if None, load from standard input.
remember: if 1, store as metadata the relationship between this URI and this formula.
 
Returns:  top-level formula of the parsed document.
Raises:   IOError, SyntaxError, DocumentError
 
This was and could be an independent function, as it is fairly independent
of the store. However, it is natural to call it as a method on the store.
And a proliferation of APIs confuses.
loadMany(self, uris, openFormula=None, referer=None)
Get, parse and merge serveral documents, given a list of URIs. 
 
Guesses format if necessary.
Returns top-level formula which is the parse result.
Raises IOError, SyntaxError
makeComment(self, str)
makeStatement(self, tuple, why=None)
Add a quad to the store, each part of the quad being in pair form.
newBlankNode(self, context, uri=None, why=None)
Create or reuse, in the default store, a new unnamed node within the given
formula as context, and return it for future use
newExistential(self, context, uri=None, why=None)
Create or reuse, in the default store, a new named variable
existentially qualified within the given
formula as context, and return it for future use
newFormula(self, uri=None)
newList(self, value, context=None)
newLiteral(self, str, dt=None, lang=None)
Interned version: generate new literal object as stored in this store
newSet(self, iterator=[], context=None)
newSymbol(self, uri)
newUniversal(self, context, uri=None, why=None)
Create or reuse, in the default store, a named variable
universally qualified within the given
formula as context, and return it for future use
newXMLLiteral(self, dom)
purge(self, context, boringClass=None)
Clean up intermediate results
 
Statements in the given context that a term is a Chaff cause
any mentions of that term to be removed from the context.
purgeExceptData(self, context)
Remove anything which can't be expressed in plain RDF
purgeSymbol(self, context, subj)
Purge all triples in which a symbol occurs.
reopen(self, F)
reset(self, metaURI)
startDoc(self)
storeQuad(self, q, why=None)
intern quads, in that dupliates are eliminated.
 
subject, predicate and object are terms - or atomic values to be interned.
Builds the indexes and does stuff for lists.
Deprocated: use Formula.add()
symbol(self, str, why=None)
Intern a URI for a symvol, returning a symbol object

Methods inherited from RDFSink.RDFSink:
countNamespace(self, namesp)
On output, count how many times each namespace is used
namespaceCounts(self)
setDefaultNamespace(self, uri)
Pass on a binding hint for later use in output
 
This really is just a hint. The parser calls this to pass on
the default namespace which it came across, as this is a
useful hint for a human readable prefix for output of the same
namespace. Otherwise, output processors will have to invent or
avoid useing namespaces, which will look ugly.
setGenPrefix(self, genPrefix)

 
class URISyntaxError(exceptions.ValueError)
    A parameter is passed to a routine that requires a URI reference
 
 
Method resolution order:
URISyntaxError
exceptions.ValueError
exceptions.StandardError
exceptions.Exception

Methods inherited from exceptions.Exception:
__getitem__(...)
__init__(...)
__str__(...)

 
Functions
       
arg_hash(arg)
comparePair(self, other)
Used only in outputString
isString(x)
loadToStore(term, types)
load content from the web and keep it in the store's experience.
return resulting literal term
 
raises IOError
 
<DanC> the log:content built-in could keep an HTTP response
       object around a la tabulator too.
<timbl> yes.
<timbl> You learn a lot from a recode.
memoize(f)

 
Data
        ALL4 = (0, 1, 2, 3)
ANONYMOUS = 3
BACKWARD_CHAINING = False
BOOL_DATATYPE = 'http://www.w3.org/2001/XMLSchema#boolean'
CONTEXT = 0
DAML_sameAs_URI = 'http://www.w3.org/2002/07/owl#sameAs'
DECIMAL_DATATYPE = 'http://www.w3.org/2001/XMLSchema#decimal'
Delta_NS = 'http://www.w3.org/2004/delta#'
FLOAT_DATATYPE = 'http://www.w3.org/2001/XMLSchema#double'
FORMULA = 1
INTEGER_DATATYPE = 'http://www.w3.org/2001/XMLSchema#integer'
LITERAL = 2
LITERAL_DT = 21
LITERAL_LANG = 22
LITERAL_URI_prefix = 'data:application/rdf+n3-literal;'
List_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
Logic_NS = 'http://www.w3.org/2000/10/swap/log#'
META_NS_URI = 'http://www.w3.org/2000/10/swap/meta#'
META_mergedWith = 'http://www.w3.org/2000/10/swap/meta#mergedWith'
META_run = 'http://www.w3.org/2000/10/swap/meta#run'
META_source = 'http://www.w3.org/2000/10/swap/meta#source'
N3_Empty = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#Empty')
N3_List = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#List')
N3_first = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first')
N3_li = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#li')
N3_nil = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil')
N3_rest = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest')
OBJ = 3
OWL_NS = 'http://www.w3.org/2002/07/owl#'
PARTS = (1, 2, 3)
PRED = 1
RDF_NS_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
RDF_type_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
STRING_NS_URI = 'http://www.w3.org/2000/10/swap/string#'
SUBJ = 2
SYMBOL = 0
VARHASH = VAR
becauseSubexpression = <why.BecauseSubexpression instance>
cvsRevision = '$Revision: 1.185 $'
doMeta = 0
forAllSym = 'http://www.w3.org/2000/10/swap/log#forAll'
forSomeSym = 'http://www.w3.org/2000/10/swap/log#forSome'
generators = _Feature((2, 2, 0, 'alpha', 1), (2, 3, 0, 'final', 0), 4096)
tracking = 0
cwm-1.2.1/README0000644015216600007660000001251110750360731012277 0ustar syosisyosi$Id: README,v 1.11 2005/11/21 22:19:31 vkolovsk Exp $ Cwm is a general-purpose data processor for the semantic web, somewhat like sed, awk, etc. for text files or XSLT for XML. It is a forward chaining reasoner which can be used for querying, checking, transforming and filtering information. Its core language is RDF, extended to include rules, and it uses RDF/XML or RDF/N3 (see Notation3 Primer) serializations as required. To find out more about Cwm, visit http://www.w3.org/2000/10/swap/doc/cwm == Getting Started == Unpack this tarball in a useful place. cd to that directory and type: cd test; make post-install at the command line. It should spend a while testing to make sure the program is working. The test files should give you a good idea of commands to get Cwm to work. If you run ./setup.py install, it will install cwm. Other possibilities are evident from running ./setup.py --help-commands If a test fails: There are three possiblilities: 1. Your Python setup is borked / sufficiently different from the one used in development. This is a distinct possiblility. It is also possibly a bug in our code, if your we should in fact be supporting you platform. 2. You tarball was corrupted / not generated properly. This is also a distinct possiblility. The latter case is a bug. 3. We knowingly published a version of Cwm that failed our own tests. This is highly unlikely. == What's New In this Release (1.2.0) == For a complete list of changes, look at doc/changes.html Release 1.2.0 == Proof updates Putting --why at the end of a command line will generate a proof, and has had much debugging. == General bugfixes. Release 1.1.0 (never released) ==Performance Improvements * Cwm now uses Python Sets instead of lists to store many things * Speed improvements to some tests are orders of magnitude * Output is not as stable as it once was ==Python 2.3 or later now required Used for Sets ==Experimental SPARQL Server support Cwm can now run as a SPARQL server. This includes: * A preview cwm --sparqlServer, which runs a server on port 8000 * cwm --sparql=, which behaves like --query= * builtins for doing sparql queries from within n3. ==RDF/XML serialization fixes A few strange bugs in rdf:xml serialization, many related to the rdf: prefix or xml: prefix, have been fixed ==delta exit statuses delta now returns with similar exit statuses as the diff utility for plaintext files. An exit status of 0 means no differences between the from and to graphs were found. An exit status of 1 means some differences were found. An exit status of 2 means differences were not computed for some reason. Release 1.0.0 ==General bugfixes Fixes in decimal support A bug introduced into 0.8.0 where cwm crashed if no input files were specified has been fixed ==delta and cwm --patch diff.py is renamed delta.py to avoid confusion with diff(1). delta.py now will make a difference file even in cases where nodes cannot be be uniquely identified (from [inverse] function properties) but can be uniquely identified in the context of the graph. So, delta.py can generate weak deltas rather than strong ones under these circumstances. Bug fix to cwm's --patch function. ==RDF/XML support changes cwm's rdf/xml output will now output any file that can be outputted in xml 1.0. Failing that, it will output it in xml 1.1. Failing that, it will throw an exception. The previous behavior of generating empty tags was a bug. Cwm will throw an excpetion if told to output rdf/xml for a file that uses literals as subjects Tests have been added for rdflib. It is now supported to a degree. Cwm now successfully fails to parse all but four of the rdf negative parser tests ==Performance improvements Performance work has resulted in some tasks taking 1/10 the time that they used to. Much more work is planned in this regard. ==Packaging Cwm now uses python's distutils for distribution. This allows for installation of cwm. As an added bonus, there are now rpm's, windows installers . ==Flatten support --flatten and --unflatten have been rewritten, replacing the old --flat. Flatten minimally reifies an n3 file to make it an rdf graph. Note that the graph may still fail to serialize as rdf, due to literals as subjects ==Other A crude hack in WebAccess.py allows a local file system to be used instead of a given website. The intent is to clean this up in the future. There has been much work on a grammar for n3. grammar/n3.n3 is the grammar, grammar/predictiveParser.n3 can understand it. == Submitting Bugs == Cwm is very much a work in progress and has many bugs. Some of them we already know about. Cwm bugs are tracked on the public Cwm bug mail list, http://lists.w3.org/Archives/Public/public-cwm-bugs/ . Submit any bugs you find there, assuming they have not already been submitted. Reply to a previous bug report if you have something to add. == License == cwm is open source. Share and Enjoy. For details, see the attached files, LICENSE.n3 and LICENSE == Contributors == Tim Berners-Lee Dan Connolly Sean Palmer Mark Nottingham Eric Prud'hommeaux Sandro Hawke Dan Brickley Karl Dubost Yosi Scharf Development of cwm is supported in part by funding from US Defense Advanced Research Projects Agency (DARPA) and Air Force Research Laboratory, Air Force Materiel Command, USAF, under agreement number F30602-00-2-0593, "Semantic Web Development". cwm-1.2.1/sax2rdf.html0000644015216600007660000011714410713431300013654 0ustar syosisyosi Python: module sax2rdf
 
 
sax2rdf
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/sax2rdf.py

  A parser for RDF/XML built on the sax2 interface;
  derived from a parser for RDF/XML built on the xmllib XML parser.
 
  To do: Passing on namesapce bindings!
       (dwc: @@huh?)
       (tbl: The bind call in the RDF stream API is used to pass
        on the prefixes found, as hints only for generating readable output code)
 
  - Add parsing of RDF bags
 
 parses DAML_ONT_NS or List_NS lists, generates List_NS
 
 References:
 
 Python/XML HOWTO
                The Python/XML Special Interest Group
                                   xml-sig@python.org 
                               (edited by amk1@bigfoot.com)
 http://py-howto.sourceforge.net/xml-howto/xml-howto.html
 
 http://www.megginson.com/SAX/applications.html#python.parsers
 http://www.python.org/sigs/xml-sig/
 
 How to on xmllib:
 http://www.python.org/doc/howto/xml/node7.html
 
 
 RDF grammar http://www.w3.org/TR/rdf-syntax-grammar/ esp sections 6 and 7
    
##################################### SAX pointers
 First hit on Python SAX parser
 http://www.gca.org/papers/xmleurope2000/papers/s28-04.html#N84395
 
 Howto use SAX in python:
 http://www.python.org/doc/howto/xml/SAX.html

 
Modules
       
RDFSink
diag
isXML
string
sys
uripath
_xmlplus

 
Classes
       
exceptions.SyntaxError(exceptions.StandardError)
BadSyntax
xml.sax.handler.ContentHandler
RDFHandler
RDFXMLParser
XMLDOMParser

 
class BadSyntax(exceptions.SyntaxError)
    
Method resolution order:
BadSyntax
exceptions.SyntaxError
exceptions.StandardError
exceptions.Exception

Methods defined here:
__init__(self, info, message)
__str__(self)

Data and other attributes inherited from exceptions.SyntaxError:
filename = None
lineno = None
msg = ''
offset = None
print_file_and_line = None
text = None

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class RDFHandler(xml.sax.handler.ContentHandler)
    RDF Parser using SAX API for XML parsing
 
  Methods defined here:
__init__(self, sink, openFormula, thisDoc, baseURI=None, flags='', why=None)
characters(self, data)
endDocument(self, f=None)
endElementNS(self, name, qname)
Handle end element event
endPrefixMapping(self, prefix)
flush(self)
idAboutAttr(self, attrs)
set up subject and maybe context from attributes
literal_element_end(self, name, qname)
literal_element_end_DOM(self, name, qname)
literal_element_start(self, name, qname, attrs)
literal_element_start_DOM(self, name, qname, attrs)
literal_element_start_DOM_OLD(self, name, qname, attrs)
newBlankNode(self)
processingInstruction(self, name, data)
startElementNS(self, name, qname, attrs)
Handle start tag.
startPrefixMapping(self, prefix, uri)
Performance note:
We make a new dictionary for every binding.
This makes lookup quick and easy, but
it takes extra space and more time to
set up a new binding.
uriref(self, str)
Generate uri from uriref in this document
unicode strings OK.

Methods inherited from xml.sax.handler.ContentHandler:
endElement(self, name)
Signals the end of an element in non-namespace mode.
 
The name parameter contains the name of the element type, just
as with the startElement event.
ignorableWhitespace(self, whitespace)
Receive notification of ignorable whitespace in element content.
 
Validating Parsers must use this method to report each chunk
of ignorable whitespace (see the W3C XML 1.0 recommendation,
section 2.10): non-validating parsers may also use this method
if they are capable of parsing and using content models.
 
SAX parsers may return all contiguous whitespace in a single
chunk, or they may split it into several chunks; however, all
of the characters in any single event must come from the same
external entity, so that the Locator provides useful
information.
 
The application must not attempt to read from the array
outside of the specified range.
setDocumentLocator(self, locator)
Called by the parser to give the application a locator for
locating the origin of document events.
 
SAX parsers are strongly encouraged (though not absolutely
required) to supply a locator: if it does so, it must supply
the locator to the application by invoking this method before
invoking any of the other methods in the DocumentHandler
interface.
 
The locator allows the application to determine the end
position of any document-related event, even if the parser is
not reporting an error. Typically, the application will use
this information for reporting its own errors (such as
character content that does not match an application's
business rules). The information returned by the locator is
probably not sufficient for use with a search engine.
 
Note that the locator will return correct information only
during the invocation of the events in this interface. The
application should not attempt to use it at any other time.
skippedEntity(self, name)
Receive notification of a skipped entity.
 
The Parser will invoke this method once for each entity
skipped. Non-validating processors may skip entities if they
have not seen the declarations (because, for example, the
entity was declared in an external DTD subset). All processors
may skip external entities, depending on the values of the
http://xml.org/sax/features/external-general-entities and the
http://xml.org/sax/features/external-parameter-entities
properties.
startDocument(self)
Receive notification of the beginning of a document.
 
The SAX parser will invoke this method only once, before any
other methods in this interface or in DTDHandler (except for
setDocumentLocator).
startElement(self, name, attrs)
Signals the start of an element in non-namespace mode.
 
The name parameter contains the raw XML 1.0 name of the
element type as a string and the attrs parameter holds an
instance of the Attributes class containing the attributes of
the element.

 
class RDFXMLParser(RDFHandler)
    XML/RDF parser based on sax XML interface
 
 
Method resolution order:
RDFXMLParser
RDFHandler
xml.sax.handler.ContentHandler

Methods defined here:
__init__(self, sink, openFormula, thisDoc=None, flags='', why=None)
close(self)
feed(self, data)
loadStream(self, stream)

Data and other attributes defined here:
flagDocumentation = '\n Flags to control RDF/XML INPUT (after --rdf...t of RDF inc. datatypes, xml:lang, and nodeIds.\n\n'

Methods inherited from RDFHandler:
characters(self, data)
endDocument(self, f=None)
endElementNS(self, name, qname)
Handle end element event
endPrefixMapping(self, prefix)
flush(self)
idAboutAttr(self, attrs)
set up subject and maybe context from attributes
literal_element_end(self, name, qname)
literal_element_end_DOM(self, name, qname)
literal_element_start(self, name, qname, attrs)
literal_element_start_DOM(self, name, qname, attrs)
literal_element_start_DOM_OLD(self, name, qname, attrs)
newBlankNode(self)
processingInstruction(self, name, data)
startElementNS(self, name, qname, attrs)
Handle start tag.
startPrefixMapping(self, prefix, uri)
Performance note:
We make a new dictionary for every binding.
This makes lookup quick and easy, but
it takes extra space and more time to
set up a new binding.
uriref(self, str)
Generate uri from uriref in this document
unicode strings OK.

Methods inherited from xml.sax.handler.ContentHandler:
endElement(self, name)
Signals the end of an element in non-namespace mode.
 
The name parameter contains the name of the element type, just
as with the startElement event.
ignorableWhitespace(self, whitespace)
Receive notification of ignorable whitespace in element content.
 
Validating Parsers must use this method to report each chunk
of ignorable whitespace (see the W3C XML 1.0 recommendation,
section 2.10): non-validating parsers may also use this method
if they are capable of parsing and using content models.
 
SAX parsers may return all contiguous whitespace in a single
chunk, or they may split it into several chunks; however, all
of the characters in any single event must come from the same
external entity, so that the Locator provides useful
information.
 
The application must not attempt to read from the array
outside of the specified range.
setDocumentLocator(self, locator)
Called by the parser to give the application a locator for
locating the origin of document events.
 
SAX parsers are strongly encouraged (though not absolutely
required) to supply a locator: if it does so, it must supply
the locator to the application by invoking this method before
invoking any of the other methods in the DocumentHandler
interface.
 
The locator allows the application to determine the end
position of any document-related event, even if the parser is
not reporting an error. Typically, the application will use
this information for reporting its own errors (such as
character content that does not match an application's
business rules). The information returned by the locator is
probably not sufficient for use with a search engine.
 
Note that the locator will return correct information only
during the invocation of the events in this interface. The
application should not attempt to use it at any other time.
skippedEntity(self, name)
Receive notification of a skipped entity.
 
The Parser will invoke this method once for each entity
skipped. Non-validating processors may skip entities if they
have not seen the declarations (because, for example, the
entity was declared in an external DTD subset). All processors
may skip external entities, depending on the values of the
http://xml.org/sax/features/external-general-entities and the
http://xml.org/sax/features/external-parameter-entities
properties.
startDocument(self)
Receive notification of the beginning of a document.
 
The SAX parser will invoke this method only once, before any
other methods in this interface or in DTDHandler (except for
setDocumentLocator).
startElement(self, name, attrs)
Signals the start of an element in non-namespace mode.
 
The name parameter contains the raw XML 1.0 name of the
element type as a string and the attrs parameter holds an
instance of the Attributes class containing the attributes of
the element.

 
class XMLDOMParser(RDFXMLParser)
    XML format to RDF Graph parser based on sax XML interface
 
 
Method resolution order:
XMLDOMParser
RDFXMLParser
RDFHandler
xml.sax.handler.ContentHandler

Methods defined here:
__init__(self, thisDoc=None, flags='', why=None)

Methods inherited from RDFXMLParser:
close(self)
feed(self, data)
loadStream(self, stream)

Data and other attributes inherited from RDFXMLParser:
flagDocumentation = '\n Flags to control RDF/XML INPUT (after --rdf...t of RDF inc. datatypes, xml:lang, and nodeIds.\n\n'

Methods inherited from RDFHandler:
characters(self, data)
endDocument(self, f=None)
endElementNS(self, name, qname)
Handle end element event
endPrefixMapping(self, prefix)
flush(self)
idAboutAttr(self, attrs)
set up subject and maybe context from attributes
literal_element_end(self, name, qname)
literal_element_end_DOM(self, name, qname)
literal_element_start(self, name, qname, attrs)
literal_element_start_DOM(self, name, qname, attrs)
literal_element_start_DOM_OLD(self, name, qname, attrs)
newBlankNode(self)
processingInstruction(self, name, data)
startElementNS(self, name, qname, attrs)
Handle start tag.
startPrefixMapping(self, prefix, uri)
Performance note:
We make a new dictionary for every binding.
This makes lookup quick and easy, but
it takes extra space and more time to
set up a new binding.
uriref(self, str)
Generate uri from uriref in this document
unicode strings OK.

Methods inherited from xml.sax.handler.ContentHandler:
endElement(self, name)
Signals the end of an element in non-namespace mode.
 
The name parameter contains the name of the element type, just
as with the startElement event.
ignorableWhitespace(self, whitespace)
Receive notification of ignorable whitespace in element content.
 
Validating Parsers must use this method to report each chunk
of ignorable whitespace (see the W3C XML 1.0 recommendation,
section 2.10): non-validating parsers may also use this method
if they are capable of parsing and using content models.
 
SAX parsers may return all contiguous whitespace in a single
chunk, or they may split it into several chunks; however, all
of the characters in any single event must come from the same
external entity, so that the Locator provides useful
information.
 
The application must not attempt to read from the array
outside of the specified range.
setDocumentLocator(self, locator)
Called by the parser to give the application a locator for
locating the origin of document events.
 
SAX parsers are strongly encouraged (though not absolutely
required) to supply a locator: if it does so, it must supply
the locator to the application by invoking this method before
invoking any of the other methods in the DocumentHandler
interface.
 
The locator allows the application to determine the end
position of any document-related event, even if the parser is
not reporting an error. Typically, the application will use
this information for reporting its own errors (such as
character content that does not match an application's
business rules). The information returned by the locator is
probably not sufficient for use with a search engine.
 
Note that the locator will return correct information only
during the invocation of the events in this interface. The
application should not attempt to use it at any other time.
skippedEntity(self, name)
Receive notification of a skipped entity.
 
The Parser will invoke this method once for each entity
skipped. Non-validating processors may skip entities if they
have not seen the declarations (because, for example, the
entity was declared in an external DTD subset). All processors
may skip external entities, depending on the values of the
http://xml.org/sax/features/external-general-entities and the
http://xml.org/sax/features/external-parameter-entities
properties.
startDocument(self)
Receive notification of the beginning of a document.
 
The SAX parser will invoke this method only once, before any
other methods in this interface or in DTDHandler (except for
setDocumentLocator).
startElement(self, name, attrs)
Signals the start of an element in non-namespace mode.
 
The name parameter contains the raw XML 1.0 name of the
element type as a string and the attrs parameter holds an
instance of the Attributes class containing the attributes of
the element.

 
Functions
       
XMLtoDOM(str)
test(args=None)

 
Data
        ANONYMOUS = 3
DAML_ONT_NS = 'http://www.daml.org/2000/10/daml-ont#'
DPO_NS = 'http://www.daml.org/2001/03/daml+oil#'
FORMULA = 1
List_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
NODE_MERGE_URI = 'http://www.w3.org/2000/10/swap/log#is'
OWL_NS = 'http://www.w3.org/2002/07/owl#'
RDF_NS_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
RDF_Specification = 'http://www.w3.org/TR/REC-rdf-syntax/'
STATE_DESCRIPTION = 'Description (have subject)'
STATE_LIST = 'within list'
STATE_LITERAL = 'within XML literal'
STATE_NOT_RDF = 'not RDF'
STATE_NOVALUE = 'no value'
STATE_NO_SUBJECT = 'no context'
STATE_OUTERMOST = 'outermost level'
STATE_VALUE = 'plain value'
XMLLiteralsAsDomTrees = 1
XML_NS_URI = 'http://www.w3.org/XML/1998/namespace'
a = 'bagID'
coreSyntaxTerms = ['RDF', 'ID', 'about', 'parseType', 'resource', 'nodeID', 'datatype']
feature_namespaces = 'http://xml.org/sax/features/namespaces'
nodeElementExceptions = {'http://www.w3.org/1999/02/22-rdf-syntax-ns#ID': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#RDF': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#about': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#aboutEach': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#aboutEachPrefix': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#bagID': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#datatype': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#li': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nodeID': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#parseType': True, ...}
oldTerms = ['aboutEach', 'aboutEachPrefix', 'bagID']
propertyAttributeExceptions = {'http://www.w3.org/1999/02/22-rdf-syntax-ns#Description': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#ID': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#RDF': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#about': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#aboutEach': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#aboutEachPrefix': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#bagID': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#datatype': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#li': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nodeID': True, ...}
propertyElementExceptions = {'http://www.w3.org/1999/02/22-rdf-syntax-ns#Description': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#ID': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#RDF': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#about': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#aboutEach': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#aboutEachPrefix': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#bagID': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#datatype': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nodeID': True, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#parseType': True, ...}
syntaxTerms = ['RDF', 'ID', 'about', 'parseType', 'resource', 'nodeID', 'datatype', 'Description', 'li']
tracking = 0
cwm-1.2.1/RDFSink.html0000644015216600007660000006656210642726415013571 0ustar syosisyosi Python: module RDFSink
 
 
RDFSink (version $Id: RDFSink.html,v 1.22 2007/06/27 17:58:39 syosi Exp $)
index
/Users/yosi/CVSROOT/WWW/2000/10/swap/RDFSink.py

RDFSink -- RDF parser/serializer/store interface
 
This is a simple API for a push-stream of RDF data. It doesn't use
a particular classof obejcts, but just uses python pairs.
It is kinda crude but it does allow for example data to be squirted efficiently 
between modules which use different python classes for RDF.
 
HISTORY
 
This module was factored out of notation3.py
 
REFERENCES
  Python Style Guide
  Author: Guido van Rossum
  http://www.python.org/doc/essays/styleguide.html

 
Modules
       
uripath

 
Classes
       
RDFSink
RDFStructuredOutput
TracingRDFSink
exceptions.ValueError(exceptions.StandardError)
URISyntaxError

 
class RDFSink
    interface to connect modules in RDF processing.
OBSOLETE
 
This is a superclass for other RDF processors which accept RDF events
or indeed Swell events. It is superceded, effectively, by the class Formula,
as a sink of data and a soiurce of new symbols.
 
Keeps track of prefixes.
 
This interface has the advantage that it does n ot have any dependencies
on object types, it is really one-way (easily serialized as no return values).
It has the disadvantages that
    - It uses the pseudoproperties log:forSome and log:forAll to
      make variables, which is a bit of a kludge.
    - It may involve on the receiver side the same thing being interned
      many times, which wastes time searching hash tables.
The superclass handles common functions such as craeting new arbitray
identifiers
 
  Methods defined here:
__init__(self, genPrefix=None)
If you give it a URI prefix to use for generated IDs it
will use one; otherwise, it will use the name of an imaginary temporary file
in the current directory.
bind(self, prefix, uri)
Pass on a binding hint for later use in output
 
This really is just a hint. The parser calls bind to pass on
the prefix which it came across, as this is a useful hint for
a human readable prefix for output of the same
namespace. Otherwise, output processors will have to invent or
avoid useing namespaces, which will look ugly
checkNewId(self, uri)
The store can override this to raise an exception if the
id is not in fact new. This is useful because it is usfeul
to generate IDs with useful diagnostic ways but this lays them
open to possibly clashing in pathalogical cases.
countNamespace(self, namesp)
On output, count how many times each namespace is used
endDoc(self, rootFormulaPair)
End a document
 
Call this once only at the end of parsing so that the receiver can wrap
things up, oprimize, intern, index and so on.  The pair given is the (type, value)
identifier of the root formula of the thing parsed.
genId(self)
intern(self, something)
makeComment(self, str)
This passes on a comment line which of course has no semantics.
 
This is only useful in direct piping of parsers to output, to preserve
comments in the original file.
makeStatement(self, tuple, why=None)
add a statement to a stream/store.
 
raises URISyntaxError on bad URIs
tuple is a quad (context, predicate, subject, object) of things generated by calls to newLiteral etc
why is reason for the statement.
namespaceCounts(self)
newBlankNode(self, context, uri=None, why=None)
newExistential(self, context, uri=None, why=None)
newFormula(self, uri=None)
newList(self, l, context)
newLiteral(self, str, dt=None, lang=None)
newSymbol(self, uri)
newUniversal(self, context, uri=None, why=None)
newXMLLiteral(self, doc)
reopen(self)
Un-End a document
 
If you have added stuff to a document, thought you were done, and
then want to add more, call this to get back into the sate that makeSatement
is again acceptable. Remember to end the document again when done.
setDefaultNamespace(self, uri)
Pass on a binding hint for later use in output
 
This really is just a hint. The parser calls this to pass on
the default namespace which it came across, as this is a
useful hint for a human readable prefix for output of the same
namespace. Otherwise, output processors will have to invent or
avoid useing namespaces, which will look ugly.
setGenPrefix(self, genPrefix)
startDoc(self)

 
class RDFStructuredOutput(RDFSink)
     Methods defined here:
endAnonymous(self, subject, verb)
endAnonymousNode(self, endAnonymousNode)
endFormulaObject(self, pred, subj)
endFormulaSubject(self, subj)
startAnonymous(self, triple, isList=0)
startAnonymousNode(self, subj)
startFormulaObject(self, triple)
startFormulaSubject(self, context)

Methods inherited from RDFSink:
__init__(self, genPrefix=None)
If you give it a URI prefix to use for generated IDs it
will use one; otherwise, it will use the name of an imaginary temporary file
in the current directory.
bind(self, prefix, uri)
Pass on a binding hint for later use in output
 
This really is just a hint. The parser calls bind to pass on
the prefix which it came across, as this is a useful hint for
a human readable prefix for output of the same
namespace. Otherwise, output processors will have to invent or
avoid useing namespaces, which will look ugly
checkNewId(self, uri)
The store can override this to raise an exception if the
id is not in fact new. This is useful because it is usfeul
to generate IDs with useful diagnostic ways but this lays them
open to possibly clashing in pathalogical cases.
countNamespace(self, namesp)
On output, count how many times each namespace is used
endDoc(self, rootFormulaPair)
End a document
 
Call this once only at the end of parsing so that the receiver can wrap
things up, oprimize, intern, index and so on.  The pair given is the (type, value)
identifier of the root formula of the thing parsed.
genId(self)
intern(self, something)
makeComment(self, str)
This passes on a comment line which of course has no semantics.
 
This is only useful in direct piping of parsers to output, to preserve
comments in the original file.
makeStatement(self, tuple, why=None)
add a statement to a stream/store.
 
raises URISyntaxError on bad URIs
tuple is a quad (context, predicate, subject, object) of things generated by calls to newLiteral etc
why is reason for the statement.
namespaceCounts(self)
newBlankNode(self, context, uri=None, why=None)
newExistential(self, context, uri=None, why=None)
newFormula(self, uri=None)
newList(self, l, context)
newLiteral(self, str, dt=None, lang=None)
newSymbol(self, uri)
newUniversal(self, context, uri=None, why=None)
newXMLLiteral(self, doc)
reopen(self)
Un-End a document
 
If you have added stuff to a document, thought you were done, and
then want to add more, call this to get back into the sate that makeSatement
is again acceptable. Remember to end the document again when done.
setDefaultNamespace(self, uri)
Pass on a binding hint for later use in output
 
This really is just a hint. The parser calls this to pass on
the default namespace which it came across, as this is a
useful hint for a human readable prefix for output of the same
namespace. Otherwise, output processors will have to invent or
avoid useing namespaces, which will look ugly.
setGenPrefix(self, genPrefix)
startDoc(self)

 
class TracingRDFSink
    An implementation of the RDFSink interface which helps me
understand it, especially how it gets used by parsers vs. by an
RDF store.    [ -sandro ]
 
Set .backing to be some other RDFSink if you want to get proper
results while tracing.
 
Try:
 
bash-2.04$ python cwm.py test/rules12.n3 --language=trace
bash-2.04$ python cwm.py --pipe test/rules12.n3 --language=trace
bash-2.04$ python cwm.py test/rules12.n3 --bySubject --language=trace
 
... and see the different outputs
 
  Methods defined here:
__init__(self, outURI, base=None, flags=None)
bind(self, prefix, uri)
endDoc(self, rootFormulaPair='<<strangely omitted>>')
endFormulaObject(self, pred, subj)
endFormulaSubject(self, subj)
makeComment(self, comment)
makeStatement(self, tuple, why=None)
newFormula(self, uri=None)
newLiteral(self, str, dt=None, lang=None)
newSymbol(self, uri)
setDefaultNamespace(self, ns)
startDoc(self)
startFormulaObject(self, triple)
startFormulaSubject(self, context)

 
class URISyntaxError(exceptions.ValueError)
    A parameter is passed to a routine that requires a URI reference
 
 
Method resolution order:
URISyntaxError
exceptions.ValueError
exceptions.StandardError
exceptions.Exception

Methods inherited from exceptions.Exception:
__getitem__(...)
__init__(...)
__str__(...)

 
Functions
       
getpid(...)
getpid() -> pid
 
Return the current process id
runNamespace()
Return a URI suitable as a namespace for run-local objects
time(...)
time() -> floating point number
 
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
uniqueURI()
A unique URI

 
Data
        ALL4 = (0, 1, 2, 3)
ANONYMOUS = 3
CONTEXT = 0
DAML_sameAs_URI = 'http://www.w3.org/2002/07/owl#sameAs'
FORMULA = 1
LITERAL = 2
LITERAL_DT = 21
LITERAL_LANG = 22
List_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
Logic_NS = 'http://www.w3.org/2000/10/swap/log#'
N3_Empty = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#Empty')
N3_List = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#List')
N3_first = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first')
N3_li = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#li')
N3_nil = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil')
N3_rest = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest')
NODE_MERGE_URI = 'http://www.w3.org/2000/10/swap/log#is'
OBJ = 3
OWL_NS = 'http://www.w3.org/2002/07/owl#'
PARTS = (1, 2, 3)
PRED = 1
RDF_NS_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
RDF_spec = 'http://www.w3.org/TR/REC-rdf-syntax/'
RDF_type_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
SUBJ = 2
SYMBOL = 0
XMLLITERAL = 25
__version__ = '$Id: RDFSink.html,v 1.22 2007/06/27 17:58:39 syosi Exp $'
environ = {'XDG_DATA_HOME': '/Users/yosi/.local/share', 'T...P', 'SGML_CATALOG_FILES': '/sw/etc/sgml/catalog'}
forAllSym = 'http://www.w3.org/2000/10/swap/log#forAll'
forSomeSym = 'http://www.w3.org/2000/10/swap/log#forSome'
nextu = 0
parsesTo_URI = 'http://www.w3.org/2000/10/swap/log#parsesTo'
runNamespaceValue = None
cwm-1.2.1/cwm_time.html0000644015216600007660000046317410642726421014132 0ustar syosisyosi Python: module cwm_time
 
 
cwm_time (version 0.3)
index
/Users/yosi/CVSROOT/WWW/2000/10/swap/cwm_time.py

The time built-ins concern dates and times expressed in a specific
version of ISO date-time format.  These functions allow the various
parts of the date and time to be compared, and converted
into interger second GMT era format for arithmetic.
 
Be aware that ISo times carry timezone offset information:  they cannot be
converted to integer second times without a valid timezone offset, such as "Z".

 
Modules
       
calendar
isodate
notation3
re
string
time

 
Classes
       
term.Function(term.BuiltIn)
BI_date(term.LightBuiltIn, term.Function)
BI_day(term.LightBuiltIn, term.Function)
BI_dayOfWeek(term.LightBuiltIn, term.Function)
BI_format(term.LightBuiltIn, term.Function)
BI_formatSeconds(term.LightBuiltIn, term.Function)
BI_gmTime(term.LightBuiltIn, term.Function)
BI_hour(term.LightBuiltIn, term.Function)
BI_inSeconds(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_localTime(term.LightBuiltIn, term.Function)
BI_minute(term.LightBuiltIn, term.Function)
BI_month(term.LightBuiltIn, term.Function)
BI_parseToSeconds(term.LightBuiltIn, term.Function)
BI_second(term.LightBuiltIn, term.Function)
BI_timeZone(term.LightBuiltIn, term.Function)
BI_year(term.LightBuiltIn, term.Function)
term.LightBuiltIn(term.GenericBuiltIn)
BI_date(term.LightBuiltIn, term.Function)
BI_day(term.LightBuiltIn, term.Function)
BI_dayOfWeek(term.LightBuiltIn, term.Function)
BI_equalTo
BI_format(term.LightBuiltIn, term.Function)
BI_formatSeconds(term.LightBuiltIn, term.Function)
BI_gmTime(term.LightBuiltIn, term.Function)
BI_hour(term.LightBuiltIn, term.Function)
BI_inSeconds(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_localTime(term.LightBuiltIn, term.Function)
BI_minute(term.LightBuiltIn, term.Function)
BI_month(term.LightBuiltIn, term.Function)
BI_parseToSeconds(term.LightBuiltIn, term.Function)
BI_second(term.LightBuiltIn, term.Function)
BI_timeZone(term.LightBuiltIn, term.Function)
BI_year(term.LightBuiltIn, term.Function)
term.ReverseFunction(term.BuiltIn)
BI_inSeconds(term.LightBuiltIn, term.Function, term.ReverseFunction)

 
class BI_date(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_date
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_day(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_day
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_dayOfWeek(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_dayOfWeek
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_equalTo(term.LightBuiltIn)
    
Method resolution order:
BI_equalTo
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluate(self, subj_py, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_format(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_format
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
params are ISO time string, format string. Returns reformatted. Ignores TZ@@

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_formatSeconds(term.LightBuiltIn, term.Function)
    #  original things from mNot's cwm_time.py:
#
#  these ise Integer time in seconds from epoch.
 
 
Method resolution order:
BI_formatSeconds
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
params are epoch-seconds time string, format string. Returns reformatted

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_gmTime(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_gmTime
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
Subject is  (empty string for standard formatting or) format string.
Returns formatted.

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_hour(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_hour
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_inSeconds(term.LightBuiltIn, term.Function, term.ReverseFunction)
    For a time string, the number of seconds from the era start as an integer-representing string.
 
 
Method resolution order:
BI_inSeconds
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Methods inherited from term.ReverseFunction:
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_localTime(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_localTime
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
Subject is format string or empty string for std formatting.
Returns reformatted. @@@@ Ignores TZ

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_minute(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_minute
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_month(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_month
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_parseToSeconds(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_parseToSeconds
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_second(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_second
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_timeZone(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_timeZone
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_year(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_year
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
Functions
       
register(store)
#  Register the string built-ins with the store

 
Data
        DAY = 86400
TIME_NS_URI = 'http://www.w3.org/2000/10/swap/time#'
__version__ = '0.3'
tzone = <_sre.SRE_Pattern object>
cwm-1.2.1/reify.html0000644015216600007660000001251710731070070013422 0ustar syosisyosi Python: module reify
 
 
reify
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/reify.py

Functions to reify and dereify a graph.
These functions should be perfect inverses of each other.
 
The strategy used is different from that of the reifier
in notation3.py, that tries to reify what it outputs.
This simply puts the reification into the sink given,
or a new one, depending on the function called.
$Id: reify.py,v 1.19 2007/12/11 21:18:08 syosi Exp $

 
Modules
       
diag
uripath

 
Functions
       
dereification(x, f, sink, bnodes={}, xList=[])
dereify(formula, sink=None, xList=[])
#### Alternative method
# Shortcuts are too messy and don't work with lists
flatten(formula)
Flatten a formula
 
This will minimally change a formula to make it valid RDF
flattening a flattened formula should thus be the unity
reify(formula)
Reify a formula
 
Returns an RDF formula with the same semantics
as the given formula
unflatten(formula, sink=None)
Undo the effects of the flatten function.
 
Note that this still requires helper methods scattered throughout the
Term heriarchy. 
 
Our life is made much more difficult by the necessity of removing all
triples that have been dereified --- this required a modification to dereification()

 
Data
        ALL4 = (0, 1, 2, 3)
CONTEXT = 0
Mixin = <mixin.mixinClass object>
OBJ = 3
PARTS = (1, 2, 3)
PRED = 1
RDF_type_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
REIFY_NS = 'http://www.w3.org/2004/06/rei#'
SUBJ = 2
owlOneOf = 'http://www.w3.org/2002/07/owl#oneOf'
rAnonymousNode = <mixin.mixinClass object>
rFormula = <mixin.mixinClass object>
rLabelledNode = <mixin.mixinClass object>
rList = <mixin.mixinClass object>
rLiteral = <mixin.mixinClass object>
rN3Set = <mixin.mixinClass object>
rTerm = <mixin.mixinClass object>
reifyNS = 'http://www.w3.org/2004/06/rei#'
cwm-1.2.1/test/0000755015216600007660000000000010731073450012374 5ustar syosisyosicwm-1.2.1/test/string/0000755015216600007660000000000010731073450013702 5ustar syosisyosicwm-1.2.1/test/string/endsWith.n30000644015216600007660000000205010066677544015745 0ustar syosisyosi @prefix contact: . @prefix rcs: . @prefix doc: . <> rcs:id "$Id: endsWith.n3,v 1.3 2004/06/25 01:27:00 timbl Exp $"; doc:creator [ contact:fullName "Tim berners-Lee"; contact:homePage ; contact:mailbox ]. @prefix log: . @prefix string: . @prefix : <#>. @forAll :x, :y, :z, :p, :q. { "asdfghjkl" string:endsWith "jkl" } log:implies { :test1 a :success }. { "asdfghjkl" string:endsWith "jkk" } log:implies { :test2 a :FAILURE }. { "jkl" string:endsWith "jkl" } log:implies { :test3 a :success }. { "asdfghjkl" string:endsWith "aaajkl" } log:implies { :test4 a :FAILURE }. { "asdfjhkh" string:endsWith "asd" } log:implies { :test5 a :FAILURE }. { "foobar" string:endsWith "" } log:implies { :test6 a :success }. { "" string:endsWith "" } log:implies { :test7 a :success }. #ends cwm-1.2.1/test/string/detailed.tests0000644015216600007660000000155410357241405016547 0ustar syosisyosi# List of regression tests # # String tests # # Note: Command lines must be for running in the directory above. # @prefix : <#>. @prefix x: <#>. @prefix test: . @prefix dc: . # yuk - under protest - no hash :t103 a test:CwmTest; test:referenceOutput <../ref/endsWith-out.n3>; test:description "string:endsWith"; test:arguments """string/endsWith.n3 -rules""". :t104 a test:CwmTest; test:referenceOutput <../ref/roughly-out.n3>; test:description "string:containsRoughly ignores case smart whitespace"; test:arguments """string/roughly.n3 -rules""". :t108 a test:CwmTest; test:referenceOutput <../ref/uriEncode.n3>; test:description "string:encodeForURI and encodeForFragID"; test:arguments """string/uriEncode.n3 -rules""". #ends cwm-1.2.1/test/string/roughly.n30000644015216600007660000000256710066677544015666 0ustar syosisyosi@prefix dc: . @prefix contact: . @prefix rcs: . <> dc:description """Test string:containsRoughly"""; rcs:id "$Id: roughly.n3,v 1.2 2004/06/25 01:27:00 timbl Exp $"; dc:creator [ contact:fullName "Tim berners-Lee"; contact:homePage ; contact:mailbox ]; dc:rights "copyright (c) 2001 W3C (MIT, Keio, INRIA)". @prefix log: . @prefix string: . @prefix : <#>. @forAll :x, :y, :z, :p, :q. { "A green party" string:containsRoughly "green Party" } log:implies { :test1 a :success }. { "all good people to come to" string:containsRoughly "gooood" } log:implies { :test2 a :FAILURE }. { "jkl" string:containsRoughly "jkl" } log:implies { :test3 a :success }. { "foo" string:containsRoughly "foo bar" } log:implies { :test4 a :FAILURE }. { "asd" string:containsRoughly "asdfjhkjhasd" } log:implies { :test5 a :FAILURE }. { "" string:containsRoughly "" } log:implies { :test6 a :success }. { "supercalifragilisticexpialidocious" string:containsRoughly "" } log:implies { :test7 a :success }. { """THE WIDE AND THE narrowEST OF PLACES""" string:containsRoughly "wide and the" } log:implies { :test8 a :success }. #ends cwm-1.2.1/test/string/uriEncode.n30000644015216600007660000000366110357241405016070 0ustar syosisyosi @prefix contact: . @prefix rcs: . @prefix doc: . <> rcs:id "$Id: uriEncode.n3,v 1.1 2006/01/05 16:02:13 timbl Exp $"; doc:creator [ contact:fullName "Tim berners-Lee"; contact:homePage ; contact:mailbox ]. @prefix log: . @prefix string: . @prefix : <#>. { "asd#jkl" string:encodeForURI ?x } log:implies { "asd#jkl" :AS_URI ?x }. { "asd/jkl" string:encodeForURI ?x } log:implies { "asd/jkl" :AS_URI ?x }. { "asd(jkl" string:encodeForURI ?x } log:implies { "asd(jkl" :AS_URI ?x }. { "asd'jkl" string:encodeForURI ?x } log:implies { "asd'jkl" :AS_URI ?x }. { "asd)jkl" string:encodeForURI ?x } log:implies { "asd)jkl" :AS_URI ?x }. { "asd_jkl" string:encodeForURI ?x } log:implies { "asd_jkl" :AS_URI ?x }. { "asd~jkl" string:encodeForURI ?x } log:implies { "asd~jkl" :AS_URI ?x }. { "asd-jkl" string:encodeForURI ?x } log:implies { "asd-jkl" :AS_URI ?x }. { "asd.jkl" string:encodeForURI ?x } log:implies { "asd.jkl" :AS_URI ?x }. ### { "asd#jkl" string:encodeForFragID ?x } log:implies { "asd#jkl" :AS_FragID ?x }. { "asd/jkl" string:encodeForFragID ?x } log:implies { "asd/jkl" :AS_FragID ?x }. { "asd(jkl" string:encodeForFragID ?x } log:implies { "asd(jkl" :AS_FragID ?x }. { "asd'jkl" string:encodeForFragID ?x } log:implies { "asd'jkl" :AS_FragID ?x }. { "asd)jkl" string:encodeForFragID ?x } log:implies { "asd)jkl" :AS_FragID ?x }. { "asd_jkl" string:encodeForFragID ?x } log:implies { "asd_jkl" :AS_FragID ?x }. { "asd~jkl" string:encodeForFragID ?x } log:implies { "asd~jkl" :AS_FragID ?x }. { "asd-jkl" string:encodeForFragID ?x } log:implies { "asd-jkl" :AS_FragID ?x }. { "asd.jkl" string:encodeForFragID ?x } log:implies { "asd.jkl" :AS_FragID ?x }. #ends cwm-1.2.1/test/testmeta.n30000644015216600007660000001057010653414734014476 0ustar syosisyosi#Processed by Id: cwm.py,v 1.193 2007/06/26 02:36:15 syosi Exp # using base file:///Users/yosi/CVSROOT/WWW/2000/10/swap/test/rdfcore-tests.n3 # Notation3 generation by # notation3.py,v 1.195 2007/06/26 02:36:15 syosi Exp # Base was: file:///Users/yosi/CVSROOT/WWW/2000/10/swap/test/rdfcore-tests.n3 @prefix : . @prefix M: . @prefix Man13: . @prefix Man14: . @prefix Man18: . @prefix Man19: . @prefix Man2: . @prefix Man23: . @prefix Man24: . @prefix Man25: . @prefix Man3: . @prefix Man8: . @prefix Manif: . Manif:test004 a :BoringTest, :ParseTypeLiteralTest, :ReificationTest . Man14:test0002 a :BoringTest, :ReificationTest . Man23:test003 a :ParseTypeLiteralTest . Man23:test005 a :BoringTest, :ReificationTest . Man23:test006 a :BoringTest, :ReificationTest . Man23:test009 a :ParseTypeLiteralTest . Man23:test011 a :BoringTest, :ReificationTest . Man23:test012 a :BoringTest, :ReificationTest . Man2:test001 a :ParseTypeLiteralTest . Man2:test002 a :ParseTypeLiteralTest . Man2:test003 a :ParseTypeLiteralTest . Man2:test004 a :ParseTypeLiteralTest . Man8:test001 a :BoringTest, :ReificationTest . Man8:test002 a :BoringTest, :ReificationTest . Man8:test003 a :BoringTest, :ReificationTest . Man8:test004 a :BoringTest, :ReificationTest . Man8:test005 a :BoringTest, :ReificationTest . Man8:test006 a :BoringTest, :ReificationTest . Man8:test008 a :BoringTest, :ReificationTest . Man8:test009 a :BoringTest, :ReificationTest . Man8:test010a a :BoringTest, :ReificationTest . Man8:test010b a :BoringTest, :ReificationTest . Man8:test011a a :BoringTest, :ReificationTest . Man8:test011b a :BoringTest, :ReificationTest . Man8:test012a a :BoringTest, :ReificationTest . Man8:test012b a :BoringTest, :ReificationTest . Man24:test001 a :BoringTest, :ReificationTest . Man24:test003 a :BoringTest, :ReificationTest . Man24:test004 a :BoringTest, :ReificationTest . Man24:test005 a :BoringTest, :ReificationTest . Man18:error007 a :BoringTest, :ReificationTest . M:test-024 a :BoringTest, :ReificationTest . Man13:test004 a :BoringTest, :ReificationTest . Man25:test001 a :ParseTypeLiteralTest . Man25:test002 a :ParseTypeLiteralTest . Man19:test001 a :ParseTypeLiteralTest . Man19:test002 a :ParseTypeLiteralTest . a :ParseTypeLiteralTest . Man3:test004 a :BoringTest, :ReificationTest . #ENDS cwm-1.2.1/test/delta/0000755015216600007660000000000010731073447013473 5ustar syosisyosicwm-1.2.1/test/delta/t3/0000755015216600007660000000000010731073447014021 5ustar syosisyosicwm-1.2.1/test/delta/t3/from.n30000644015216600007660000000004310254403442015213 0ustar syosisyosi@prefix : <#> . :a :b [ :c :d ] . cwm-1.2.1/test/delta/t3/to-same.n30000644015216600007660000000006010254403442015614 0ustar syosisyosi@prefix : . :a :b _:x . _:x :c :d . cwm-1.2.1/test/delta/t3/to-diff.n30000644015216600007660000000005610254403442015604 0ustar syosisyosi@prefix : . :a :b :x . :y :c :d . cwm-1.2.1/test/delta/detailed.tests0000644015216600007660000000240610265042213016321 0ustar syosisyosi# delta/detailed.tests - tests of delta # # N.B. Beware in writing test:arguments; all tests are run in the directory # above this one. @prefix : <#>. @prefix test: . :t001 a test:CwmTest; test:referenceOutput ; test:description "Reconsitute file from patch."; test:arguments "delta/t2/from-smushed.n3 --patch=delta/t2/smushed-patch.n3 --ntriples". :t3 a test:CwmTest ; test:referenceOutput ; test:description "exit status test" ; test:arguments "delta/t3/test.n3 --think --with `../delta.py -f delta/t3/from.n3 -t delta/t3/to-same.n3 &> /dev/null; echo $?` `../delta.py -f delta/t3/from.n3 -t delta/t3/to-diff.n3 &> /dev/null; echo $?`" . :t4 a test:CwmTest ; test:referenceOutput ; test:description "granularity cmdline option test" ; test:arguments """delta/t4/test.n3 --think --with "`../delta.py -f delta/t4/from.n3 -t delta/t4/to.n3`" "`../delta.py -g 1 -f delta/t4/from.n3 -t delta/t4/to.n3`" "`../delta.py --granularity=1 -f delta/t4/from.n3 -t delta/t4/to.n3`" "`../delta.py -g 0 -f delta/t4/from.n3 -t delta/t4/to.n3`" "`../delta.py --granularity=0 -f delta/t4/from.n3 -t delta/t4/to.n3`" """ . #ENDS cwm-1.2.1/test/os/0000755015216600007660000000000010731073450013015 5ustar syosisyosicwm-1.2.1/test/os/environ.n30000644015216600007660000000170310066677544014757 0ustar syosisyosi# Test whether a schema mentions the predicates used in this data # This involves searching in files for statements being present or absent. @prefix rdf: . @prefix s: . # @prefix daml: . # @prefix dpo: . # @prefix ex: . @prefix log: . @prefix os: . @prefix : . # Local stuff @prefix foo: . # Local stuff # Usage: cwm t11.n3 -think # # Output should conclude all test* a :success and no failures. # @forAll :x. { "TEST_PARAMETER_1" os:environ :x } log:implies { :test_param_1 :is :x }. { "THIS_gotta_BE_undefined" os:environ :x } log:implies { :test2 a :FAILURE }. # { :x os:environ "TARGET"} log:implies { :testparameter1 :goop :x }. #ends cwm-1.2.1/test/os/argv.n30000644015216600007660000000231310303444700014210 0ustar syosisyosi# Test whether a schema mentions the predicates used in this data # This involves searching in files for statements being present or absent. @prefix rdf: . @prefix s: . # @prefix daml: . # @prefix dpo: . # @prefix ex: . @prefix log: . @prefix os: . @prefix : <#>. # Local stuff @prefix foo: <#>. # Local stuff # Usage: cwm argv.n3 --think --with foo bar baz # # Output should conclude all test* a :success and no failures. # @forAll :x. { 1 os:argv :x } log:implies { :test_param_1 :is :x }. { "1" os:argv "foo"} log:implies { :test1 a :sucess }. { "1" os:argv "foot"} log:implies { :test1b a :FAILURE }. { "1" os:argv [ log:notEqualTo "foo"] } log:implies { :test1c a :FAILURE }. { 2 os:argv "bar"} log:implies { :test2 a :sucess }. { "3" os:argv "baz"} log:implies { :test3 a :sucess }. { 4 os:argv :x} log:implies { :test3 a :FAILURE }. { "THIS is not a valid number" os:argv :x } log:implies { :test4 a :FAILURE }. #ends cwm-1.2.1/test/ref/0000755015216600007660000000000010731073450013150 5ustar syosisyosicwm-1.2.1/test/ref/bi-t4.n30000644015216600007660000000057510066677544014357 0ustar syosisyosi @prefix : <#> . @prefix log: . @forAll :x . :test4 a :success . :thesis :is {:theSky :is :blue . } . { :thesis :is :x . :x log:notIncludes {:theSky :is :green . } . } log:implies {:test4 a :success . } . cwm-1.2.1/test/ref/numbers-n.n30000644015216600007660000000242210361736746015335 0ustar syosisyosi "Le chat"@fr "The french phrase 'Le chat'" . "800/600"^^ "800/600 with datatype http://example.com/types#rational" . "2"^^ "The number 2.0" . "2"^^ "The number 2.0 expressed with extra trailing zeroes" . "2000.0"^^ "The double precision floating point 2.0e3" . "-2"^^ "The integer -2" . "0"^^ "Zero" . "2"^^ "The integer 2" . "2"^^ "The integer 2 expressed with leading zeroes" . cwm-1.2.1/test/ref/reason-t06check.n30000644015216600007660000000073010327177764016324 0ustar syosisyosi @prefix : . @prefix log: . @prefix math: . @forAll :h, :x . :joe a :player; :friend :kev; :height "1.6" . { :h math:greaterThan "1.3" . :x :friend :kev; :height :h . } log:implies {:x a :player . } . cwm-1.2.1/test/ref/list-construct.n30000644015216600007660000000050410022433417016402 0ustar syosisyosi @prefix : <#> . @prefix rdf: . :A rdf:first 1; rdf:rest () . :B rdf:first 1; rdf:rest ( 2 3 ) . :C a :ListOfIntegers; rdf:first 1; rdf:rest ( 2 3 ) . cwm-1.2.1/test/ref/in-xml-t.n30000644015216600007660000000020610453463155015063 0ustar syosisyosi <%s> "45"; "%s" . cwm-1.2.1/test/ref/timet1.n30000644015216600007660000000320210361736746014627 0ustar syosisyosi @prefix : . @prefix v: <#> . @forAll v:f, v:t, v:x, v:y, v:z . "" a v:TestFormat . "1999-12-31T23:59:59.99Z" a v:TestDate; :day 31; :dayOfWeek 4; :hour 23; :inSeconds 946684799.0e+00; :minute 59; :month 12; :second 59; :year 1999 . "2000-01-01T00:00:00Z" a v:TestDate; :day 1; :dayOfWeek 5; :hour 0; :inSeconds 946684800.0e+00; :minute 0; :month 1; :second 0; :year 2000 . "2001-09-09T01:46:40Z" :inSeconds "1000000000" . "2002" a v:TestDate; :dayOfWeek 1; :inSeconds 1009843200.0e+00; :year 2002 . "2002-06" a v:TestDate; :dayOfWeek 5; :inSeconds 1022889600.0e+00; :month 6; :year 2002 . "2002-06-22" a v:TestDate; :day 22; :dayOfWeek 5; :inSeconds 1024704000.0e+00; :month 6; :year 2002 . "2002-06-22T12:34Z" a v:TestDate; :day 22; :dayOfWeek 5; :hour 12; :inSeconds 1024749240.0e+00; :minute 34; :month 6; :year 2002 . "2002-06-22T22:09:32-05:00" a v:TestDate; :day 22; :dayOfWeek 6; :hour 22; :inSeconds 1024801772.0e+00; :minute 9; :month 6; :second 32; :timeZone "-05:00"; :year 2002 . "year %Y month %M day %d date: %D" a v:TestFormat . cwm-1.2.1/test/ref/bi-t9.n30000644015216600007660000000111010066677544014346 0ustar syosisyosi @prefix : <#> . @prefix log: . @prefix string: . @forAll :d, :e . :e1 a :Sep2001Event; :date "2001-09-27" . :t1 a :Success . { :e1 a :Sep2001Event . } log:implies {:t1 a :Success . } . { :d string:lessThan "2001-10"; string:notLessThan "2001-09" . :e :date :d . } log:implies {:e a :Sep2001Event . } . cwm-1.2.1/test/ref/roughly-out.n30000644015216600007660000000412710066677544015733 0ustar syosisyosi @prefix : <#> . @prefix contact: . @prefix log: . @prefix rcs: . @prefix string: . @forAll :p, :q, :x, :y, :z . <> [ contact:fullName "Tim berners-Lee"; contact:homePage ; contact:mailbox ]; "Test string:containsRoughly"; "copyright (c) 2001 W3C (MIT, Keio, INRIA)"; rcs:id "" . :test1 a :success . :test3 a :success . :test6 a :success . :test7 a :success . :test8 a :success . { "" string:containsRoughly "" . } log:implies {:test6 a :success . } . { "A green party" string:containsRoughly "green Party" . } log:implies {:test1 a :success . } . { """THE WIDE AND THE narrowEST OF PLACES""" string:containsRoughly "wide and the" . } log:implies {:test8 a :success . } . { "all good people to come to" string:containsRoughly "gooood" . } log:implies {:test2 a :FAILURE . } . { "asd" string:containsRoughly "asdfjhkjhasd" . } log:implies {:test5 a :FAILURE . } . { "foo" string:containsRoughly "foo bar" . } log:implies {:test4 a :FAILURE . } . { "jkl" string:containsRoughly "jkl" . } log:implies {:test3 a :success . } . { "supercalifragilisticexpialidocious" string:containsRoughly "" . } log:implies {:test7 a :success . } . cwm-1.2.1/test/ref/bnode.rdf0000644015216600007660000000105210061705667014742 0ustar syosisyosi Dave Beckett RDF/XML Syntax Specification (Revised) cwm-1.2.1/test/ref/rules12-n.n30000644015216600007660000000147010453454067015154 0ustar syosisyosi @prefix : <#> . @prefix daml: . @prefix log: . @forAll :_g0, :_g1, :_g2, :p . :ancestor a daml:TransitiveProperty . :granpa :ancestor :bill, :pa . :pa :ancestor :bill . { :p a daml:TransitiveProperty . } log:implies { @forAll :x, :y, :z . { :x :p :y . :y :p :z . } log:implies {:x :p :z . } . } . { :_g0 :ancestor :_g1 . :_g1 :ancestor :_g2 . } log:implies {:_g0 :ancestor :_g2 . } . cwm-1.2.1/test/ref/xmllit.nt0000644015216600007660000000057010642726425015036 0ustar syosisyosi "\n \n John\n \n "^^ . cwm-1.2.1/test/ref/djb1a-out.n30000644015216600007660000000011207763722422015205 0ustar syosisyosi @prefix : . :a :b :c . cwm-1.2.1/test/ref/xml-base3.n30000644015216600007660000000042310270206263015202 0ustar syosisyosi ; ; "World Wide Web Consortium" . cwm-1.2.1/test/ref/rules12-1.n30000644015216600007660000000144110453454067015055 0ustar syosisyosi @prefix : <#> . @prefix daml: . @prefix log: . @forAll :_g0, :_g1, :_g2, :p . :ancestor a daml:TransitiveProperty . :granpa :ancestor :pa . :pa :ancestor :bill . { :p a daml:TransitiveProperty . } log:implies { @forAll :x, :y, :z . { :x :p :y . :y :p :z . } log:implies {:x :p :z . } . } . { :_g0 :ancestor :_g1 . :_g1 :ancestor :_g2 . } log:implies {:_g0 :ancestor :_g2 . } . cwm-1.2.1/test/ref/bi-t8.n30000644015216600007660000000435007442022114014333 0ustar syosisyosi @prefix : <#> . @prefix log: . @prefix string: . :testh1 a :success . :testh2 a :success . :testh3 a :success . :testh4 a :success . :testh5 a :success . :testh6 a :success . :testh7 a :success . :testh8 a :success . { "a" string:startsWith "abc" . } log:implies {:testh_7 a :FAILURE . } . { "aaa" string:greaterThan "abc" . } log:implies {:testh_2 a :FAILURE . } . { "aaa" string:lessThan "abc" . } log:implies {:testh4 a :success . } . { "aaa" string:notGreaterThan "abc" . } log:implies {:testh3 a :success . } . { "aaa" string:notLessThan "abc" . } log:implies {:testh_6 a :FAILURE . } . { "abc" string:greaterThan "aaa" . } log:implies {:testh1 a :success . } . { "abc" string:greaterThan "abc" . } log:implies {:testh_1 a :FAILURE . } . { "abc" string:lessThan "aaa" . } log:implies {:testh_4 a :FAILURE . } . { "abc" string:lessThan "abc" . } log:implies {:testh_5 a :FAILURE . } . { "abc" string:notGreaterThan "aaa" . } log:implies {:testh_3 a :FAILURE . } . { "abc" string:notGreaterThan "abc" . } log:implies {:testh2 a :success . } . { "abc" string:notLessThan "aaa" . } log:implies {:testh5 a :success . } . { "abc" string:notLessThan "abc" . } log:implies {:testh6 a :success . } . { "abc" string:startsWith "a" . } log:implies {:testh7 a :success . } . { "def" string:startsWith "def" . } log:implies {:testh8 a :success . } . cwm-1.2.1/test/ref/conclusion.n30000644015216600007660000001714110663332735015602 0ustar syosisyosi @prefix : <../daml-ex.n3#> . @prefix con: <#> . @prefix dpo: . @prefix foo: . @prefix inv: <../invalid-ex.n3#> . @prefix log: . @prefix s: . @prefix v: <../schema-rules.n3#> . @forAll foo:F, foo:G, foo:d, foo:x, foo:y . foo:result foo:is { @forAll con:_g0, con:_g1, con:_g2, con:_g3, con:_g4, con:_g5, con:_g6, con:_g7, con:_g8, con:_g9, con:_g10, con:_g11, v:c, v:c1, v:c2, v:p, v:p1, v:p2, v:x, v:y, v:z. @forSome con:_g12 . <../daml-ex.n3> a dpo:Ontology; dpo:comment "An example ontology"; dpo:imports ; dpo:versionInfo "" . :Adam a dpo:Person; dpo:comment "Adam is a person."; dpo:label "Adam" . :Animal a dpo:Class; dpo:comment """This class of animals is illustrative of a number of ontological idioms."""; dpo:label "Animal" . :Car a dpo:Class; dpo:comment "no car is a person"; dpo:subClassOf con:_g12; s:subClassOf con:_g12 . :Female a dpo:Class; dpo:disjointFrom :Male; dpo:subClassOf :Animal; s:subClassOf :Animal . :Height a dpo:Class; dpo:oneOf ( :short :medium :tall ) . :Male a dpo:Class; dpo:subClassOf :Animal; s:subClassOf :Animal . :Man a dpo:Class; dpo:subClassOf :Male, :Person; s:subClassOf :Animal, :Male, :Person . :Person a dpo:Class; dpo:comment "every person is a man or a woman"; dpo:disjointUnionOf ( :Man :Woman ); dpo:restrictedBy [ a dpo:Restriction; dpo:onProperty :parent; dpo:toClass :Person ]; dpo:subClassOf :Animal; s:subClassOf :Animal . :TallMan a dpo:Class; dpo:intersectionOf ( :TallThing :Man ) . :TallThing a dpo:Class; dpo:restrictedBy [ a dpo:Restriction; dpo:onProperty :height; dpo:toValue :tall ] . :Woman a dpo:Class; dpo:subClassOf :Female, :Person; s:subClassOf :Animal, :Female, :Person . :ancestor a dpo:TransitiveProperty; dpo:label "ancestor" . :child a dpo:Property; dpo:inverseOf :parent . :descendant a dpo:TransitiveProperty . :father a dpo:Property; dpo:cardinality "1"; dpo:range :Man; dpo:subProperty :parent; s:range :Man . :height a dpo:Property; dpo:domain :Person; dpo:range :Height; s:domain :Person; s:range :Height . :mom a dpo:Property; = :mother . :mother a dpo:UniqueProperty; dpo:range :Woman; dpo:subProperty :parent; s:range :Woman . :occupation a dpo:Property; dpo:maxCardinality "1" . :parent a dpo:Property; dpo:cardinality "2"; dpo:domain :Animal; s:domain :Animal . <../invalid-ex.n3> dpo:imports <../daml-ex.n3> . inv:alex :father inv:joe . inv:bill :mother inv:joe . inv:disjointTest a :Animal, :Female, :Male, :Man, :Person, :Woman, v:schemaInconsistency . inv:joe a :Animal, :Female, :Male, :Man, :Person, :Woman, v:schemaInconsistency . v:schemaInconsistency dpo:subPropertyOf log:Falsehood; s:subPropertyOf log:Falsehood . dpo:domain = s:domain . dpo:range = s:range . dpo:subClassOf = s:subClassOf . dpo:subPropertyOf = s:subPropertyOf . s:subClassOf a dpo:TransitiveProperty . s:subPropertyOf a dpo:TransitiveProperty . con:_g12 a dpo:Class; dpo:complementOf :Person . { v:p a dpo:TransitiveProperty . } log:implies { @forAll v:xx, v:yx, v:zx . { v:xx v:p v:yx . v:yx v:p v:zx . } log:implies {v:xx v:p v:zx . } . } . { con:_g0 s:subClassOf con:_g1 . con:_g1 s:subClassOf con:_g2 . } log:implies {con:_g0 s:subClassOf con:_g2 . } . { con:_g3 s:subPropertyOf con:_g4 . con:_g4 s:subPropertyOf con:_g5 . } log:implies {con:_g3 s:subPropertyOf con:_g5 . } . { con:_g6 :descendant con:_g7 . con:_g7 :descendant con:_g8 . } log:implies {con:_g6 :descendant con:_g8 . } . { con:_g9 :ancestor con:_g10 . con:_g10 :ancestor con:_g11 . } log:implies {con:_g9 :ancestor con:_g11 . } . { v:c1 s:subClassOf v:c2 . v:x a v:c1 . } log:implies {v:x a v:c2 . } . { v:p s:domain v:c . v:x v:p v:y . } log:implies {v:x a v:c . } . { v:p s:range v:c . v:x v:p v:y . } log:implies {v:y a v:c . } . { v:p1 s:range v:c . v:p2 s:subPropertyOf v:p1 . } log:implies {v:p2 s:range v:c . } . { v:p1 = v:p2 . v:x v:p1 v:y . } log:implies {v:x v:p2 v:y . } . { v:x a v:y, v:z . v:y dpo:disjointFrom v:z . } log:implies {v:x a v:schemaInconsistency . } . } . { @forSome con:_g13, con:_g14, con:_g15 . ( con:_g13 con:_g14 con:_g15 ) log:conjunction [ log:conclusion foo:G ] . <../daml-ex.n3> log:semantics con:_g13 . <../invalid-ex.n3> log:semantics con:_g14 . <../schema-rules.n3> log:semantics con:_g15 . } log:implies {foo:result foo:is foo:G . } . cwm-1.2.1/test/ref/filter-bnode.n30000644015216600007660000000030310704677573016000 0ustar syosisyosi @prefix : <#> . @forSome :_g0 . :a1 :_g0 :c1 . :a3 :b3 [ ] . :a4 :b4 ( [ ] ) . [ :b2 :c2 ]. cwm-1.2.1/test/ref/bi-t1.n30000644015216600007660000000135310022433417014324 0ustar syosisyosi @prefix : <#> . @prefix log: . @prefix rdf: . @prefix s: . :test1 a :success . log:includes a rdf:Property; s:comment """ The includes property indicates that one formula either is, or is a conjunction of several subformulae one of which is, the other forumla or its equivalent by the renaming of variables. It can be calculated if one knows the formulae involved. """ . { { :a :b :c . } log:includes {:a :b :c . } . } log:implies {:test1 a :success . } . cwm-1.2.1/test/ref/list-bug1.n30000644015216600007660000000053410066677544015242 0ustar syosisyosi @prefix : <#> . @prefix log: . @forAll :x, :y . ( ) a . :RESULT . { ( :x :y ) a . } log:implies {:x :RESULT :y . } . cwm-1.2.1/test/ref/bi-t6.n30000644015216600007660000000057610022433417014337 0ustar syosisyosi @prefix : <#> . @prefix log: . :TEST1 a :success . { { :foo :bar [ :baz :bam ] . } log:includes {:foo :bar [ :baz :bam ] . } . } log:implies {:TEST1 a :success . } . cwm-1.2.1/test/ref/reason-poor-urop.n30000644015216600007660000000143710655653256016663 0ustar syosisyosi @prefix : . @prefix log: . @prefix owl: . @forAll :O, :O2, :P, :P2, :S, :S2 . owl:sameAs a owl:SymmetricProperty . { @forSome :_g_L14C13, :_g_L16C12 . log:semantics :_g_L16C12 . :_g_L14C13 log:supports {:S :P :O . } . :_g_L16C12 log:supports {:S :P :O . } . log:semantics :_g_L14C13 . } log:implies {:S :P :O . } . cwm-1.2.1/test/ref/reason-t04check.n30000644015216600007660000000044010327177764016320 0ustar syosisyosi @prefix : . @prefix log: . @forAll :x . :a :b :c . :c :d :e . { :a :b :x . } log:implies {:x :d :e . } . cwm-1.2.1/test/ref/animal-1.rdf0000644015216600007660000000102310022433417015234 0ustar syosisyosi 2 Animal cwm-1.2.1/test/ref/itemType.n30000644015216600007660000000035210040042541015200 0ustar syosisyosi @prefix : . <#2414> a :event; :reminders ( [ a :reminders_item; :seconds_prior 432000 ] ) . cwm-1.2.1/test/ref/argv-1.n30000644015216600007660000000231410303444701014503 0ustar syosisyosi @prefix : <#> . @prefix log: . @prefix os: . @forAll :x . :test1 a :sucess . :test2 a :sucess . :test3 a :sucess . :test_param_1 :is "foo" . { "1" os:argv "foo" . } log:implies {:test1 a :sucess . } . { "1" os:argv "foot" . } log:implies {:test1b a :FAILURE . } . { "3" os:argv "baz" . } log:implies {:test3 a :sucess . } . { "THIS is not a valid number" os:argv :x . } log:implies {:test4 a :FAILURE . } . { 1 os:argv :x . } log:implies {:test_param_1 :is :x . } . { 2 os:argv "bar" . } log:implies {:test2 a :sucess . } . { 4 os:argv :x . } log:implies {:test3 a :FAILURE . } . { "1" os:argv [ log:notEqualTo "foo" ] . } log:implies {:test1c a :FAILURE . } . cwm-1.2.1/test/ref/colon-in-uri.n30000644015216600007660000000147210170602732015727 0ustar syosisyosi @prefix : . @prefix CIM: . @prefix cims: . @prefix rdf: . a rdf:Property; cims:inverseRoleName ; cims:multiplicity ; cims:profile "Nerc"; :comment """A CAES air compressor is driven by combustion turbine"""; :domain CIM:AirCompressor; :label "DrivenBy_CombustionTurbine"@en; :range CIM:CombustionTurbine . cwm-1.2.1/test/ref/li-r1.n30000644015216600007660000000076210066677544014362 0ustar syosisyosi @prefix : . @prefix log: . @forAll :a, :b, :c, :x, :y, :z . "one" a :SUCCESS . "two" a :SUCCESS . ( "one" "two" ) a :whatever . { ( :a :b ) a :whatever . } log:implies {:a a :SUCCESS . :b a :SUCCESS . } . cwm-1.2.1/test/ref/reason-t05check.n30000644015216600007660000000060010331501247016275 0ustar syosisyosi @prefix : . @prefix log: . @forAll :x, :y . :a :b :c . :c :b . { :a :y :x . } log:implies {:x :y . } . cwm-1.2.1/test/ref/bi-t2.n30000644015216600007660000000126510022433417014327 0ustar syosisyosi @prefix : <#> . @prefix log: . @prefix rdf: . @prefix s: . :a :b :c . :test2 a :success . log:includes a rdf:Property; s:comment """ The includes property indicates that one formula either is, or is a conjunction of several subformulae one of which is, the other forumla or its equivalent by the renaming of variables. It can be calculated if one knows the formulae involved. """ . { [ :b :c ]. } log:implies {:test2 a :success . } . cwm-1.2.1/test/ref/xml-syntax-basic-serialization.rdf0000644015216600007660000000044210256050024021715 0ustar syosisyosi

3

cwm-1.2.1/test/ref/includes-builtins.n30000644015216600007660000000023610303444701017044 0ustar syosisyosi @prefix : <#> . :test1 a :Success . :test2 a :Success . :test3 a :Success . :test4 a :Success . cwm-1.2.1/test/ref/norm-av1.n30000644015216600007660000000770510137460165015066 0ustar syosisyosi A/B Switch black box Cable Box black box CATV black box DVD black box Signal Selector black box Splitter black box TV black box VCR black box cwm-1.2.1/test/ref/animal.n30000644015216600007660000000052510022433417014651 0ustar syosisyosi @prefix : . @prefix ani: <#> . @prefix rdfs: . ani:Animal a rdfs:Class; :restrictedBy [ a :Restriction; :cardinality "2"; :onProperty ani:parent ]; rdfs:label "Animal" . cwm-1.2.1/test/ref/reason-single-gen.n30000644015216600007660000000056610655644305016746 0ustar syosisyosi @prefix : . @prefix log: . @forAll :X . :a :b "A noun", 3.14159265359 . [ a :Thing ]. { :a :b :X . } log:implies { @forSome :_g_L2C17 . :_g_L2C17 a :Thing . } . cwm-1.2.1/test/ref/list-builtin_generated_match.n30000644015216600007660000000021010245226755021224 0ustar syosisyosi @prefix : <#> . () a :Thing . ( ( :q ) ) a :Thing . :q a :GreatThing . cwm-1.2.1/test/ref/roadmap-test.dot0000644015216600007660000000103707402526533016267 0ustar syosisyosi /* transformed by: */ /* Id: rdf2dot.xsl,v 1.13 2001/05/23 19:46:25 connolly Exp */ digraph i__1483 { label="W3C Technology Roadmap"; "http://www.w3.org/2001/04/roadmap/swws#k_dep" [ label="X depends on this", color="gold1", style="filled", ]; "http://www.w3.org/2001/04/roadmap/swws#k_something" [ label="the\nspec X", color="gold1", style="filled", ]; "http://www.w3.org/2001/04/roadmap/swws#k_something" -> "http://www.w3.org/2001/04/roadmap/swws#k_dep" [color="black", ] } /* End of generated .dot file. */cwm-1.2.1/test/ref/path1.n30000644015216600007660000000036307604230047014433 0ustar syosisyosi @prefix : . @prefix fam: . :albert fam:mother [ fam:sister :auntieAnne ] . [ fam:father :albert; fam:sister :nieceBertha ]. cwm-1.2.1/test/ref/reason-rename-loop.n30000644015216600007660000000107710453454067017132 0ustar syosisyosi @prefix : . @prefix log: . @forAll :X, :Y, :Z . { @forAll :A . :A :b :c . } a :Thing2 . { @forAll :A . :A :b :c . } a :Thing . { :X log:includes { [ :b :Y ]. } . :Z a :Thing; log:conclusion :X . } log:implies {:X a :Thing2 . } . cwm-1.2.1/test/ref/anon-prop-1.n30000644015216600007660000000020110066677544015471 0ustar syosisyosi @prefix : <#> . @forSome :_g0 . :anySubj :_g0 :anyObj . :_g0 :propProp "red" . cwm-1.2.1/test/ref/two-route.n30000644015216600007660000000102310066677544015372 0ustar syosisyosi @prefix : . @prefix log: . @forAll :x, :y, :z . :grass :color :blue; :is :relaxing; :sounds :quiet . :sky :color :blue; :is :relaxing; :sounds :quiet . { :x :color :blue . } log:implies {:x :is :relaxing . } . { :x :sounds :quiet . } log:implies {:x :is :relaxing . } . cwm-1.2.1/test/ref/rdf-redefine.rdf0000644015216600007660000000035110271233360016173 0ustar syosisyosi cwm-1.2.1/test/ref/path2.n30000644015216600007660000000166710066677544014461 0ustar syosisyosi @prefix : <#> . @prefix fam: . @prefix foo: . @prefix lang: . @prefix math: . @prefix s: . @forSome :_g0, :_g1, :_g2, :_g3 . ( "1" "2" ) math:sum [ a foo:THREE ] . ( :_g2 [ ] ) :relatedTo ( :_g3 ) . :_g2 . [ :_g3 ] . foo:admires foo:converse :_g1 . foo:albert fam:mother [ :_g0 foo:auntieAnne ]; :_g1 foo:grumpy . foo:mentor foo:inverse :_g0 . foo:x s:label [ lang:eng "Help!" ], [ lang:fr "foo" ] . cwm-1.2.1/test/ref/list-unify2.n30000644015216600007660000000013210022433417015567 0ustar syosisyosi @prefix : <#> . 4 a :RESULT . :THIS_TEST a :SUCCESS . cwm-1.2.1/test/ref/schema1.n30000644015216600007660000001461710663332735014754 0ustar syosisyosi @prefix : . @prefix daml: . @prefix inv: . @prefix log: . @prefix rdfs: . @prefix v: . @forAll <#_g0>, <#_g1>, <#_g2>, <#_g3>, <#_g4>, <#_g5>, <#_g6>, <#_g7>, <#_g8>, <#_g9>, <#_g10>, <#_g11>, v:c, v:c1, v:c2, v:p, v:p1, v:p2, v:x, v:y, v:z. @forSome <#_g12> . a daml:Ontology; daml:comment "An example ontology"; daml:imports ; daml:versionInfo "" . :Adam a daml:Person; daml:comment "Adam is a person."; daml:label "Adam" . :Animal a daml:Class; daml:comment """This class of animals is illustrative of a number of ontological idioms."""; daml:label "Animal" . :Car a daml:Class; daml:comment "no car is a person"; daml:subClassOf <#_g12>; rdfs:subClassOf <#_g12> . :Female a daml:Class; daml:disjointFrom :Male; daml:subClassOf :Animal; rdfs:subClassOf :Animal . :Height a daml:Class; daml:oneOf ( :short :medium :tall ) . :Male a daml:Class; daml:subClassOf :Animal; rdfs:subClassOf :Animal . :Man a daml:Class; daml:subClassOf :Male, :Person; rdfs:subClassOf :Animal, :Male, :Person . :Person a daml:Class; daml:comment "every person is a man or a woman"; daml:disjointUnionOf ( :Man :Woman ); daml:restrictedBy [ a daml:Restriction; daml:onProperty :parent; daml:toClass :Person ]; daml:subClassOf :Animal; rdfs:subClassOf :Animal . :TallMan a daml:Class; daml:intersectionOf ( :TallThing :Man ) . :TallThing a daml:Class; daml:restrictedBy [ a daml:Restriction; daml:onProperty :height; daml:toValue :tall ] . :Woman a daml:Class; daml:subClassOf :Female, :Person; rdfs:subClassOf :Animal, :Female, :Person . :ancestor a daml:TransitiveProperty; daml:label "ancestor" . :child a daml:Property; daml:inverseOf :parent . :descendant a daml:TransitiveProperty . :father a daml:Property; daml:cardinality "1"; daml:range :Man; daml:subProperty :parent; rdfs:range :Man . :height a daml:Property; daml:domain :Person; daml:range :Height; rdfs:domain :Person; rdfs:range :Height . :mom a daml:Property; = :mother . :mother a daml:UniqueProperty; daml:range :Woman; daml:subProperty :parent; rdfs:range :Woman . :occupation a daml:Property; daml:maxCardinality "1" . :parent a daml:Property; daml:cardinality "2"; daml:domain :Animal; rdfs:domain :Animal . daml:imports . inv:alex :father inv:joe . inv:bill :mother inv:joe . inv:disjointTest a :Animal, :Female, :Male, :Man, :Person, :Woman, v:schemaInconsistency . inv:joe a :Animal, :Female, :Male, :Man, :Person, :Woman, v:schemaInconsistency . v:schemaInconsistency daml:subPropertyOf log:Falsehood; rdfs:subPropertyOf log:Falsehood . daml:domain = rdfs:domain . daml:range = rdfs:range . daml:subClassOf = rdfs:subClassOf . daml:subPropertyOf = rdfs:subPropertyOf . rdfs:subClassOf a daml:TransitiveProperty . rdfs:subPropertyOf a daml:TransitiveProperty . <#_g12> a daml:Class; daml:complementOf :Person . { v:p a daml:TransitiveProperty . } log:implies { @forAll v:xx, v:yx, v:zx . { v:xx v:p v:yx . v:yx v:p v:zx . } log:implies {v:xx v:p v:zx . } . } . { <#_g0> rdfs:subClassOf <#_g1> . <#_g1> rdfs:subClassOf <#_g2> . } log:implies {<#_g0> rdfs:subClassOf <#_g2> . } . { <#_g3> rdfs:subPropertyOf <#_g4> . <#_g4> rdfs:subPropertyOf <#_g5> . } log:implies {<#_g3> rdfs:subPropertyOf <#_g5> . } . { <#_g6> :descendant <#_g7> . <#_g7> :descendant <#_g8> . } log:implies {<#_g6> :descendant <#_g8> . } . { <#_g9> :ancestor <#_g10> . <#_g10> :ancestor <#_g11> . } log:implies {<#_g9> :ancestor <#_g11> . } . { v:c1 rdfs:subClassOf v:c2 . v:x a v:c1 . } log:implies {v:x a v:c2 . } . { v:p rdfs:domain v:c . v:x v:p v:y . } log:implies {v:x a v:c . } . { v:p rdfs:range v:c . v:x v:p v:y . } log:implies {v:y a v:c . } . { v:p1 rdfs:range v:c . v:p2 rdfs:subPropertyOf v:p1 . } log:implies {v:p2 rdfs:range v:c . } . { v:p1 = v:p2 . v:x v:p1 v:y . } log:implies {v:x v:p2 v:y . } . { v:x a v:y, v:z . v:y daml:disjointFrom v:z . } log:implies {v:x a v:schemaInconsistency . } . cwm-1.2.1/test/ref/list-unify1.n30000644015216600007660000000013210022433417015566 0ustar syosisyosi @prefix : <#> . 4 a :RESULT . :THIS_TEST a :SUCCESS . cwm-1.2.1/test/ref/list-last.n30000644015216600007660000000126510256021704015327 0ustar syosisyosi @prefix : <#> . ( :bar :baz ) :prop2 :trap4 . ( :foo :bar :baz ) :prop2 :test6a . ( :foo ) :prop2 :test6b . :test1 a :SUCCESS . :test2 a :SUCCESS . :test3 :isa "Success" . :test4a a :SUCCESS . :test4b a :SUCCESS . :test4c a :SUCCESS . :test4d a :SUCCESS . :test5a a :SUCCESS . :test5b a :SUCCESS . :test5c a :SUCCESS . :test6a a :SUCCESS . :test6b a :SUCCESS . :thing1 :prop1 ( :test5a :test5b :test5c ) . cwm-1.2.1/test/ref/no-last-nl.n30000644015216600007660000000004007616042170015373 0ustar syosisyosi . cwm-1.2.1/test/ref/animal-ntriples.n30000644015216600007660000000133210137460165016513 0ustar syosisyosi . _:L10C8 . "Animal" . _:L10C8 . _:L10C8 "2" . _:L10C8 . cwm-1.2.1/test/ref/n3ExprFor-out.n30000644015216600007660000000062010066677544016062 0ustar syosisyosi @prefix : <#> . @prefix log: . @forAll :x . :Blargh_b :semantics { . } . { """@prefix : . :x :y :z .""" log:n3ExprFor :x . } log:implies {:Blargh_b :semantics :x . } . cwm-1.2.1/test/ref/lstring-out.n30000644015216600007660000000164407470326765015726 0ustar syosisyosi @prefix : <#> . """ @prefix : . @prefix crypto: . @prefix log: . @prefix os: . @prefix string: . \""" MzE5MDcKCjM2ODkyMzAyMDE1MzgwMjY2NTU5MzgzNjMyMDQyOTM1Mjc4MDk3MzAwNzE4ODMzOTY3 NTY3NTk1Njg5MjE2Mjk0NzkyMzUyNTQ3OTQzMjI4MjM2MDEwNjQwMTAyMjcxODk0OTY2MzgzNjQ1 NDQyODQ5Njg3MzUzOTM2NzAyMTI5NDgxNDg4MzIxMzUyODEyMTc1NjIxNjE0NjE5Mzk2MDY4MjE2 Nzk1MzY0NjAxNjE0MzM5NDYzOTIyMDMwMDE4NTEyODMyMTg0NDIyMzI3MzcxNzE5MjcxMzY0ODY1 MjEzMzU1OTc4Nzk0OTIyMzQ4NDU5NTUxMTQ2MTcyNjE0MTk3ODI2NTg0NDA2Mzg2OTQwMTcwNTE4 OTY0MDQzNzMxNzEyODc1OTk3NjAyNjE4ODUzNDQ1Mw=3D=3D \""" a :RequestKey; :authorityName ; :junk "327462sjsdfjsakdhfkjsafd32164321" . """ a :test_string . cwm-1.2.1/test/ref/sameDan.n30000644015216600007660000000614110453454067014774 0ustar syosisyosi @prefix : . @prefix contact: . @prefix dc: . @prefix log: . @prefix ont: . @prefix rcs: . @prefix sam: . @forAll sam:x, :p, :q, :x, :y, :z. @forSome <#_g0> . dc:creator <#_g0>; dc:description """rules for determining when two terms denote the same thing."""; dc:relation ; dc:rights "copyright (c) 2001 W3C (MIT, Keio, INRIA)"; rcs:id "" . sam:test1 a sam:Success . dc:creator <#_g0>; dc:description "substituion of equals for equals in triples, plus some rules for unambiguous/unique properties (@@that probably belong elsewhere)"; dc:relation ; dc:rights "copyright (c) 2001 W3C (MIT, Keio, INRIA)"; rcs:id "" . contact:homePageAddress a ont:UnambiguousProperty . contact:mailbox a ont:UnambiguousProperty . <#_g0> sam:birthPlace sam:KC; sam:hairColor sam:red; contact:fullName "Dan Connolly"; contact:homePage ; contact:mailbox ; = <#_g0> . { :p a ont:UnambiguousProperty . } log:implies {{ :x :p :z . :y :p :z . } log:implies {:x = :y . } . } . { :p a ont:UniqueProperty . } log:implies {{ :x :p :y, :z . } log:implies {:y = :z . } . } . { :x = :y . } log:implies {:y = :x . } . { :x = :z . } log:implies {:x = :z . } . { sam:x sam:birthPlace sam:KC; sam:hairColor sam:red . } log:implies {sam:test1 a sam:Success . } . { :x contact:homePageAddress :z . :y contact:homePageAddress :z . } log:implies {:x = :y . } . { :x contact:mailbox :z . :y contact:mailbox :z . } log:implies {:x = :y . } . { :p log:notEqualTo log:forAll, log:forSome; = :q . :x :p :y . } log:implies {:x :q :y . } . { :p log:notEqualTo log:forAll, log:forSome . :x = :z; :p :y . } log:implies {:z :p :y . } . { :p log:notEqualTo log:forAll, log:forSome . :x :p :y . :y = :z . } log:implies {:x :p :z . } . cwm-1.2.1/test/ref/bi-concat.n30000644015216600007660000000123310022433417015244 0ustar syosisyosi @prefix : <#> . @prefix log: . :TEST13 a :success . :emptyString :is "" . :fooString :is "foo" . :test13a a :success . :test13b a :success . :test13c a :success . :test13d a :success . :test13e a :success . :test13f a :success . :test13g a :success . :test13h a :success . :www :is "WorldWideWeb" . :www2 :is "WorldWideWeb" . :www3 :is "WorldWIDEWeb" . :www5 :is "WorldWideWeb" . log:implies a log:Chaff . cwm-1.2.1/test/ref/strquot.n30000644015216600007660000000114410022433417015127 0ustar syosisyosi @prefix : <#> . <> """testing string parsing in N3. Hmm... how much of this is in the primer? How much should be there? @@ Holding off on unicode until support in python is sufficiently deployed (e.g. python on tux doesn't grok, nor does pythonwin on TimBL's laptop). """ . :martin :surname "D\u00FCrst" . :x :prop "simple string" . :y :prop """triple quoted string with newlines in it.""" . :z :prop """string with " escaped quote marks""" . :zz :escapes "\\\"\a\b\f\r\t\v" . cwm-1.2.1/test/ref/schema2.n30000644015216600007660000000025510022433417014732 0ustar syosisyosi @prefix : . @prefix v: . :disjointTest a v:schemaInconsistency . :joe a v:schemaInconsistency . cwm-1.2.1/test/ref/xml-redefine2.rdf0000644015216600007660000000135110271233360016303 0ustar syosisyosi

cwm-1.2.1/test/ref/bnode_in_list_in_list.ref0000644015216600007660000000015510153747730020207 0ustar syosisyosi @prefix : <#> . :a :b ( ( [ :c :d ] ) ) . cwm-1.2.1/test/ref/reason-t02check.n30000644015216600007660000000042710327177764016323 0ustar syosisyosi . . cwm-1.2.1/test/ref/colon-no-qname.n30000644015216600007660000000007410254356131016236 0ustar syosisyosi @prefix : . :q :r . cwm-1.2.1/test/ref/lists-simple.n30000644015216600007660000000137210022433417016036 0ustar syosisyosi @prefix : . () :verb0 :object0 . ( "subj1" ) :verb1 :object1 . ( "subj2a" "subj2b" ) :verb2 :object2 . :a_threebrackets = ( ( ( :fff ) ) ) . :emptyList = () . :listOf2Empties = ( () () ) . :nested = ( :first :second ( :left3 :right3 ) :fourth ) . :threeItems = ( :b :c :d ) . :twoAnons = ( [ a :mother ] [ a :father ] ) . [ :anonVerb12 :anonObj12; :verb12 :obj12 ]. cwm-1.2.1/test/ref/socrates.n30000644015216600007660000000061210642726425015244 0ustar syosisyosi @prefix : . @prefix log: . @prefix vars: . @forAll vars:who . :socrates a :Man, :Mortal . { vars:who a :Man . } log:implies {vars:who a :Mortal . } . cwm-1.2.1/test/ref/base64.n30000644015216600007660000000023110300162432014461 0ustar syosisyosi @prefix : <#> . @prefix log: . { } log:implies {:a :b :c . } . cwm-1.2.1/test/ref/li-double.n30000644015216600007660000000073110066677544015306 0ustar syosisyosi @prefix : <#> . @prefix log: . @prefix string: . @forAll :a, :s . "00" log:outputString "OstrichOstrich" . "Ostrich" a :foobar . { ( :a :a ) string:concatenation :s . :a a :foobar . } log:implies {"00" log:outputString :s . } . cwm-1.2.1/test/ref/lists.n30000644015216600007660000000137210022433417014547 0ustar syosisyosi @prefix : . () :verb0 :object0 . ( "subj1" ) :verb1 :object1 . ( "subj2a" "subj2b" ) :verb2 :object2 . ( 1 ) <#linksEqualLists> ( 1 ) . :emptyList = () . :listOf2Empties = ( () () ) . :nested = ( :first :second ( :left3 :right3 ) :fourth ) . :threeItems = ( :b :c :d ) . :twoAnons = ( [ a :mother ] [ a :father ] ) . :twoFormulae = ( {:a a :mother . } {:b a :father . } ) . cwm-1.2.1/test/ref/resolves-rdf.n30000644015216600007660000000064210066677544016046 0ustar syosisyosi @prefix : <#> . @prefix log: . @prefix u: . @forAll :x . a :ClassInAnimal_rdf . { log:semantics [ log:includes {:x a u:Class . } ] . } log:implies {:x a :ClassInAnimal_rdf . } . cwm-1.2.1/test/ref/strquot_a.n30000644015216600007660000000114010134756402015431 0ustar syosisyosi @prefix : <#> . <> """testing string parsing in N3. Hmm... how much of this is in the primer? How much should be there? @@ Holding off on unicode until support in python is sufficiently deployed (e.g. python on tux doesn't grok, nor does pythonwin on TimBL's laptop). """ . :martin :surname "Dürst" . :x :prop "simple string" . :y :prop """triple quoted string with newlines in it.""" . :z :prop """string with " escaped quote marks""" . :zz :escapes "\\\"\a\b\f\r\t\v" . cwm-1.2.1/test/ref/qvars1.n30000644015216600007660000000037310066677544014651 0ustar syosisyosi @prefix : <#> . @forAll :a, :b, :c . { :a :mother :b; :sister :c . } {:b :aunt :c . } . cwm-1.2.1/test/ref/bi-t10.n30000644015216600007660000000202010453454067014410 0ustar syosisyosi @prefix : . @prefix local: <#> . @prefix log: . @forAll :F, :G, :d, :x, :y . :fred local:favoriteColor :blue . :test10a a :success . :test10b a :success . { :fred local:favoriteColor :blue . } log:implies {:test10b a :success . } . { log:semantics :F . :F log:includes {:theSky :is :blue . } . } log:implies {:test10a a :success . } . { log:semantics :F . :F log:includes {:theSky :is :green . } . } log:implies {:test10-bis a :FAILURE . } . { log:semantics :F . :F log:includes {:theSky :is :x . } . } log:implies {:fred local:favoriteColor :x . } . cwm-1.2.1/test/ref/environ.n30000644015216600007660000000073410066677544015115 0ustar syosisyosi @prefix : . @prefix log: . @prefix os: . @forAll :x . :test_param_1 :is "TEST_VALUE_1" . { "TEST_PARAMETER_1" os:environ :x . } log:implies {:test_param_1 :is :x . } . { "THIS_gotta_BE_undefined" os:environ :x . } log:implies {:test2 a :FAILURE . } . cwm-1.2.1/test/ref/daml-ex.n30000644015216600007660000000471210050276561014747 0ustar syosisyosi @prefix : . @prefix ex: <#> . <> a :Ontology; :comment "An example ontology"; :imports ; :versionInfo "" . ex:Adam a :Person; :comment "Adam is a person."; :label "Adam" . ex:Animal a :Class; :comment """This class of animals is illustrative of a number of ontological idioms."""; :label "Animal" . ex:Car a :Class; :comment "no car is a person"; :subClassOf [ a :Class; :complementOf ex:Person ] . ex:Female a :Class; :disjointFrom ex:Male; :subClassOf ex:Animal . ex:Height a :Class; :oneOf ( ex:short ex:medium ex:tall ) . ex:Male a :Class; :subClassOf ex:Animal . ex:Man a :Class; :subClassOf ex:Male, ex:Person . ex:Person a :Class; :comment "every person is a man or a woman"; :disjointUnionOf ( ex:Man ex:Woman ); :restrictedBy [ a :Restriction; :onProperty ex:parent; :toClass ex:Person ]; :subClassOf ex:Animal . ex:TallMan a :Class; :intersectionOf ( ex:TallThing ex:Man ) . ex:TallThing a :Class; :restrictedBy [ a :Restriction; :onProperty ex:height; :toValue ex:tall ] . ex:Woman a :Class; :subClassOf ex:Female, ex:Person . ex:ancestor a :TransitiveProperty; :label "ancestor" . ex:child a :Property; :inverseOf ex:parent . ex:descendant a :TransitiveProperty . ex:father a :Property; :cardinality "1"; :range ex:Man; :subProperty ex:parent . ex:height a :Property; :domain ex:Person; :range ex:Height . ex:medium a :Height . ex:mom a :Property; = ex:mother . ex:mother a :UniqueProperty; :range ex:Woman; :subProperty ex:parent . ex:occupation a :Property; :maxCardinality "1" . ex:parent a :Property; :cardinality "2"; :domain ex:Animal . ex:short a :Height . ex:tall a :Height . cwm-1.2.1/test/ref/reason-t90check.n30000644015216600007660000002013310663332735016320 0ustar syosisyosi @prefix : . @prefix con: . @prefix dpo: . @prefix fo: . @prefix foo: . @prefix inv: . @prefix log: . @prefix s: . @prefix v: . @forAll foo:F, foo:G, foo:d, foo:x, foo:y . foo:result foo:is { @forAll fo:_g10, fo:_g11, fo:_g12, fo:_g13, fo:_g14, fo:_g15, fo:_g16, fo:_g17, fo:_g18, fo:_g19, fo:_g20, fo:_g9, v:c, v:c1, v:c2, v:p, v:p1, v:p2, v:x, v:y, v:z. @forSome fo:_g6, fo:_g7, fo:_g8 . fo:_g6 a dpo:Class; dpo:complementOf :Person . fo:_g7 a dpo:Restriction; dpo:onProperty :parent; dpo:toClass :Person . fo:_g8 a dpo:Restriction; dpo:onProperty :height; dpo:toValue :tall . a dpo:Ontology; dpo:comment "An example ontology"; dpo:imports ; dpo:versionInfo "" . :Adam a dpo:Person; dpo:comment "Adam is a person."; dpo:label "Adam" . :Animal a dpo:Class; dpo:comment """This class of animals is illustrative of a number of ontological idioms."""; dpo:label "Animal" . :Car a dpo:Class; dpo:comment "no car is a person"; dpo:subClassOf fo:_g6; s:subClassOf fo:_g6 . :Female a dpo:Class; dpo:disjointFrom :Male; dpo:subClassOf :Animal; s:subClassOf :Animal . :Height a dpo:Class; dpo:oneOf ( :short :medium :tall ) . :Male a dpo:Class; dpo:subClassOf :Animal; s:subClassOf :Animal . :Man a dpo:Class; dpo:subClassOf :Male, :Person; s:subClassOf :Animal, :Male, :Person . :Person a dpo:Class; dpo:comment "every person is a man or a woman"; dpo:disjointUnionOf ( :Man :Woman ); dpo:restrictedBy fo:_g7; dpo:subClassOf :Animal; s:subClassOf :Animal . :TallMan a dpo:Class; dpo:intersectionOf ( :TallThing :Man ) . :TallThing a dpo:Class; dpo:restrictedBy fo:_g8 . :Woman a dpo:Class; dpo:subClassOf :Female, :Person; s:subClassOf :Animal, :Female, :Person . :ancestor a dpo:TransitiveProperty; dpo:label "ancestor" . :child a dpo:Property; dpo:inverseOf :parent . :descendant a dpo:TransitiveProperty . :father a dpo:Property; dpo:cardinality "1"; dpo:range :Man; dpo:subProperty :parent; s:range :Man . :height a dpo:Property; dpo:domain :Person; dpo:range :Height; s:domain :Person; s:range :Height . :mom a dpo:Property; = :mother . :mother a dpo:UniqueProperty; dpo:range :Woman; dpo:subProperty :parent; s:range :Woman . :occupation a dpo:Property; dpo:maxCardinality "1" . :parent a dpo:Property; dpo:cardinality "2"; dpo:domain :Animal; s:domain :Animal . dpo:imports . inv:alex :father inv:joe . inv:bill :mother inv:joe . inv:disjointTest a :Animal, :Female, :Male, :Man, :Person, :Woman, v:schemaInconsistency . inv:joe a :Animal, :Female, :Male, :Man, :Person, :Woman, v:schemaInconsistency . v:schemaInconsistency dpo:subPropertyOf log:Falsehood; s:subPropertyOf log:Falsehood . dpo:domain = s:domain . dpo:range = s:range . dpo:subClassOf = s:subClassOf . dpo:subPropertyOf = s:subPropertyOf . s:subClassOf a dpo:TransitiveProperty . s:subPropertyOf a dpo:TransitiveProperty . { v:p a dpo:TransitiveProperty . } log:implies { @forAll v:xx, v:yx, v:zx . { v:xx v:p v:yx . v:yx v:p v:zx . } log:implies {v:xx v:p v:zx . } . } . { fo:_g10 s:subClassOf fo:_g11 . fo:_g9 s:subClassOf fo:_g10 . } log:implies {fo:_g9 s:subClassOf fo:_g11 . } . { fo:_g12 s:subPropertyOf fo:_g13 . fo:_g13 s:subPropertyOf fo:_g14 . } log:implies {fo:_g12 s:subPropertyOf fo:_g14 . } . { fo:_g15 :descendant fo:_g16 . fo:_g16 :descendant fo:_g17 . } log:implies {fo:_g15 :descendant fo:_g17 . } . { fo:_g18 :ancestor fo:_g19 . fo:_g19 :ancestor fo:_g20 . } log:implies {fo:_g18 :ancestor fo:_g20 . } . { v:c1 s:subClassOf v:c2 . v:x a v:c1 . } log:implies {v:x a v:c2 . } . { v:p s:domain v:c . v:x v:p v:y . } log:implies {v:x a v:c . } . { v:p s:range v:c . v:x v:p v:y . } log:implies {v:y a v:c . } . { v:p1 s:range v:c . v:p2 s:subPropertyOf v:p1 . } log:implies {v:p2 s:range v:c . } . { v:p1 = v:p2 . v:x v:p1 v:y . } log:implies {v:x v:p2 v:y . } . { v:x a v:y, v:z . v:y dpo:disjointFrom v:z . } log:implies {v:x a v:schemaInconsistency . } . } . { @forSome con:_g_L31C5, con:_g_L32C5, con:_g_L33C5, con:_g_L34C25 . ( con:_g_L31C5 con:_g_L32C5 con:_g_L33C5 ) log:conjunction con:_g_L34C25 . log:semantics con:_g_L31C5 . con:_g_L34C25 log:conclusion foo:G . log:semantics con:_g_L32C5 . log:semantics con:_g_L33C5 . } log:implies {foo:result foo:is foo:G . } . cwm-1.2.1/test/ref/smush.rdf0000644015216600007660000000061410022433417015001 0ustar syosisyosi cwm-1.2.1/test/ref/lists-simple-1.rdf0000644015216600007660000001140410154115636016432 0ustar syosisyosi subj1 subj2a subj2b cwm-1.2.1/test/ref/reason-t03check.n30000644015216600007660000000041710327177764016323 0ustar syosisyosi @prefix : . @prefix log: . :a :b :c . :a2 :b2 :c2 . { :a :b :c . } log:implies {:a2 :b2 :c2 . } . cwm-1.2.1/test/ref/in-xml.n30000644015216600007660000000000510022433417014605 0ustar syosisyosi cwm-1.2.1/test/ref/list-bug2.n30000644015216600007660000000064510066677544015246 0ustar syosisyosi @prefix : <#> . @prefix log: . @prefix string: . @forAll :s, :x, :y . "fred whatever " a :RESULT . { ( "fred" " whatever " ) string:concatenation :s . } log:implies {:s a :RESULT . } . cwm-1.2.1/test/ref/list-unify3.n30000644015216600007660000000013210022433417015570 0ustar syosisyosi @prefix : <#> . 4 a :RESULT . :THIS_TEST a :SUCCESS . cwm-1.2.1/test/ref/keywords1.n30000644015216600007660000000027110066677544015361 0ustar syosisyosi @prefix : . @forAll :x, :y, :z. @forSome :a, :b, :c . :b :a :c . cwm-1.2.1/test/ref/prefix2.rdf0000644015216600007660000000342310563115071015225 0ustar syosisyosi 2 2002 cwm-1.2.1/test/ref/keywords2.n30000644015216600007660000000026510653414735015356 0ustar syosisyosi @prefix : . @forAll :x, :y, :z. @forSome :a, :b, :c . :b :a :c . cwm-1.2.1/test/ref/conjunction.n30000644015216600007660000000101210066677544015754 0ustar syosisyosi @prefix : . @prefix log: . @forAll :F, :G, :d, :x, :y . { ( {:sky :color :blue . } {:sky :color :green . } ) log:conjunction :F . } log:implies {:F a :result . } . { :sky :color :blue, :green . } a :result . cwm-1.2.1/test/ref/qvars2.n30000644015216600007660000000036710066677544014655 0ustar syosisyosi @prefix : <#> . @forAll :b, :c . { [ :parent :b; :sister :c ]. } {:b :aunt :c . } . cwm-1.2.1/test/ref/reason-t01check.n30000644015216600007660000000021510302437726016303 0ustar syosisyosi . cwm-1.2.1/test/ref/dec-div.ref.n30000644015216600007660000000357510453454067015522 0ustar syosisyosi @prefix : <#> . @prefix k: . @prefix log: . @prefix m: . @prefix math: . @prefix qif: . @prefix time: . @prefix xsdt: . @forAll :EXCH, :FOREIGN, :M, :NATIVE, :P, :Q2, :QTY, :RATE, :TRX, :X, :Y . :exch1 k:startingDate [ xsdt:date "2004-08-08" ]; m:buyCurrency m:USD; m:rate 1.91666666667e+00; m:sellCurrency m:CAD . :priceCAD m:priceCurrency m:CAD . :trx :priceCAD "12.43"; k:startingDate [ xsdt:date "2004-08-12" ]; qif:amount 6.4852173913e+00 . qif:amount m:priceCurrency m:USD . { ( "2.3" "1.2" ) math:quotient :X . } log:implies {:exch1 m:rate :X . } . { ( :QTY :RATE ) math:quotient :Q2 . qif:amount m:priceCurrency :NATIVE . :EXCH k:startingDate [ xsdt:date [ time:month :M; time:year :Y ] ]; m:buyCurrency :NATIVE; m:rate :RATE; m:sellCurrency :FOREIGN . :P m:priceCurrency :FOREIGN . :TRX k:startingDate [ xsdt:date [ time:month :M; time:year :Y ] ]; :P :QTY . } log:implies {:TRX qif:amount :Q2 . } . cwm-1.2.1/test/ref/rules-flag-t.n30000644015216600007660000000126510066677544015737 0ustar syosisyosi @prefix : <#> . @prefix daml: . @prefix log: . @forAll :p . :ancestor daml:TransitiveProperty . :granpa :ancestor :pa . :pa :ancestor :bill . { :p daml:TransitiveProperty . } log:implies { @forAll :x, :y, :z . { :x :p :y . :y :p :z . } log:implies {:x :p :z . } . } . cwm-1.2.1/test/ref/anonymous_loop.ref0000644015216600007660000000014510166344015016727 0ustar syosisyosi @prefix : <#> . @forSome :_g0 . :_g0 :z [ :y :_g0 ] . cwm-1.2.1/test/ref/bi-t11.n30000644015216600007660000000657210453454067014431 0ustar syosisyosi @prefix : . @prefix log: . @prefix rdf: . @prefix s: . @forAll :F, :G, :H, :S, :d, :o, :p, :s, :s1, :x, :y . :blue a :ERROR_PROPERTY_NOT_DECLARED, :UsedProperty; :schema ; :schemaFormula {:blue s:isDefinedBy . :is a rdf:Property; s:isDefinedBy . :theSky s:isDefinedBy . } . :includesTest2 a :success . :includesTest3 a :success . :is a :Property_declared, :UsedProperty; :schema ; :schemaFormula {:blue s:isDefinedBy . :is a rdf:Property; s:isDefinedBy . :theSky s:isDefinedBy . } . :test_undefined a :ERROR_CANT_GET_SCHEMA, :UsedProperty . log:implies a log:Chaff . { log:semantics :F . :F log:includes {:blue a rdf:Property . } . } log:implies {:includesTest a :FAILURE . } . { log:semantics :F . :F log:includes {:is a rdf:Property . } . } log:implies {:includesTest3 a :success . } . { log:semantics :F . :F log:notIncludes {:blue a rdf:Property . } . } log:implies {:includesTest2 a :success . } . { log:semantics :F . :F log:notIncludes {:is a rdf:Property . } . } log:implies {:includesTest4 a :FAILURE . } . { log:semantics :F . :F log:includes {:s :p :o . } . } log:implies {:p a :UsedProperty . } . { :F log:includes {:p a rdf:Property . } . :p :schemaFormula :F . } log:implies {:p a :Property_declared . } . { :F log:notIncludes {:p a rdf:Property . } . :p :schemaFormula :F . } log:implies {:p a :ERROR_PROPERTY_NOT_DECLARED . } . { :p :schema [ log:semantics :F ] . } log:implies {:p :schemaFormula :F . } . { :p a :UsedProperty; log:semantics [ log:includes {:p s:isDefinedBy :s . } ] . } log:implies {:p :schema :s . } . { :p a :UsedProperty; log:semantics [ log:notIncludes {:p s:isDefinedBy [ ] . } ] . } log:implies {:p a :ERROR_CANT_GET_SCHEMA . } . { :F log:includes {:p s:isDefinedBy :s . } . :p a :UsedProperty; log:semantics :F . :s log:semantics :G . } log:implies {:p :schemaFormula :G . } . cwm-1.2.1/test/ref/bi-t3.n30000644015216600007660000000103610022433417014324 0ustar syosisyosi @prefix : <#> . @prefix log: . :test3 a :success . { { :theSky :is :blue . } log:includes {:theSky :is :blue . } . } log:implies {:test3 a :success . } . { { :theSky :is :blue . } log:notIncludes {:theSky :is :blue . } . } log:implies {:test3_bis a :FAILURE . } . cwm-1.2.1/test/ref/xml-redefine.rdf0000644015216600007660000000110010271564162016220 0ustar syosisyosi cwm-1.2.1/test/ref/reason-t09filtercheck.n30000644015216600007660000000016410327177764017536 0ustar syosisyosi a . cwm-1.2.1/test/ref/uriEncode.n30000644015216600007660000000704210361736726015345 0ustar syosisyosi @prefix : <#> . @prefix contact: . @prefix doc: . @prefix log: . @prefix rcs: . @prefix string: . @forAll :x . "asd#jkl" :AS_FragID "asd%23jkl"; :AS_URI "asd#jkl" . "asd'jkl" :AS_FragID "asd%27jkl"; :AS_URI "asd'jkl" . "asd(jkl" :AS_FragID "asd%28jkl"; :AS_URI "asd(jkl" . "asd)jkl" :AS_FragID "asd%29jkl"; :AS_URI "asd)jkl" . "asd-jkl" :AS_FragID "asd-jkl"; :AS_URI "asd-jkl" . "asd.jkl" :AS_FragID "asd.jkl"; :AS_URI "asd.jkl" . "asd/jkl" :AS_FragID "asd/jkl"; :AS_URI "asd%2Fjkl" . "asd_jkl" :AS_FragID "asd_jkl"; :AS_URI "asd_jkl" . "asd~jkl" :AS_FragID "asd%7Ejkl"; :AS_URI "asd~jkl" . <> doc:creator [ contact:fullName "Tim berners-Lee"; contact:homePage ; contact:mailbox ]; rcs:id "" . { "asd#jkl" string:encodeForFragID :x . } log:implies {"asd#jkl" :AS_FragID :x . } . { "asd#jkl" string:encodeForURI :x . } log:implies {"asd#jkl" :AS_URI :x . } . { "asd'jkl" string:encodeForFragID :x . } log:implies {"asd'jkl" :AS_FragID :x . } . { "asd'jkl" string:encodeForURI :x . } log:implies {"asd'jkl" :AS_URI :x . } . { "asd(jkl" string:encodeForFragID :x . } log:implies {"asd(jkl" :AS_FragID :x . } . { "asd(jkl" string:encodeForURI :x . } log:implies {"asd(jkl" :AS_URI :x . } . { "asd)jkl" string:encodeForFragID :x . } log:implies {"asd)jkl" :AS_FragID :x . } . { "asd)jkl" string:encodeForURI :x . } log:implies {"asd)jkl" :AS_URI :x . } . { "asd-jkl" string:encodeForFragID :x . } log:implies {"asd-jkl" :AS_FragID :x . } . { "asd-jkl" string:encodeForURI :x . } log:implies {"asd-jkl" :AS_URI :x . } . { "asd.jkl" string:encodeForFragID :x . } log:implies {"asd.jkl" :AS_FragID :x . } . { "asd.jkl" string:encodeForURI :x . } log:implies {"asd.jkl" :AS_URI :x . } . { "asd/jkl" string:encodeForFragID :x . } log:implies {"asd/jkl" :AS_FragID :x . } . { "asd/jkl" string:encodeForURI :x . } log:implies {"asd/jkl" :AS_URI :x . } . { "asd_jkl" string:encodeForFragID :x . } log:implies {"asd_jkl" :AS_FragID :x . } . { "asd_jkl" string:encodeForURI :x . } log:implies {"asd_jkl" :AS_URI :x . } . { "asd~jkl" string:encodeForFragID :x . } log:implies {"asd~jkl" :AS_FragID :x . } . { "asd~jkl" string:encodeForURI :x . } log:implies {"asd~jkl" :AS_URI :x . } . cwm-1.2.1/test/ref/vblsNotURIs-out.n30000644015216600007660000000225510453454070016417 0ustar syosisyosi @prefix : . @prefix ani: . @prefix d12: . @prefix log: . @prefix rdfs: . @forAll :i, :o . ani:Animal a rdfs:Class; d12:restrictedBy [ a :Found, d12:Restriction; d12:cardinality "2"; d12:onProperty ani:parent ]; rdfs:label "Animal" . """test that log:uri only gives URIs that somebody actually used, not variable names run it ala: python cwm.py --rdf test/animal.rdf --n3 test/vblsNotURIs.n3 --think """; "" . :x d12:restrictedBy [ a :Found, :Something ] . { [ d12:restrictedBy :o ]. } log:implies {:o a :Found . } . { [ d12:restrictedBy :o ]. :o log:uri :i . } log:implies {:o :called :i . } . cwm-1.2.1/test/ref/bi-quant.n30000644015216600007660000000067510365566554015161 0ustar syosisyosi @prefix : <#> . :testa1 a :success . :testa1nd a :success . :testa2 a :success . :testa2d a :success . :testb1n a :success . :testb1nd a :success . :testb2 a :success . :testb2d a :success . :testc1n a :FAILURE . :testc1nd a :FAILURE . :testc2 a :success . :testc2d a :success . cwm-1.2.1/test/ref/equiv-syntax.n30000644015216600007660000000104310022433417016061 0ustar syosisyosi testing = short-hand syntax in N3. I'm adding this test in particular to track changes regarding which DAML+OIL namespace we use. cwm-1.2.1/test/ref/endsWith-out.n30000644015216600007660000000317210066677544016026 0ustar syosisyosi @prefix : <#> . @prefix contact: . @prefix doc: . @prefix log: . @prefix rcs: . @prefix string: . @forAll :p, :q, :x, :y, :z . <> doc:creator [ contact:fullName "Tim berners-Lee"; contact:homePage ; contact:mailbox ]; rcs:id "" . :test1 a :success . :test3 a :success . :test6 a :success . :test7 a :success . { "" string:endsWith "" . } log:implies {:test7 a :success . } . { "asdfghjkl" string:endsWith "aaajkl" . } log:implies {:test4 a :FAILURE . } . { "asdfghjkl" string:endsWith "jkk" . } log:implies {:test2 a :FAILURE . } . { "asdfghjkl" string:endsWith "jkl" . } log:implies {:test1 a :success . } . { "asdfjhkh" string:endsWith "asd" . } log:implies {:test5 a :FAILURE . } . { "foobar" string:endsWith "" . } log:implies {:test6 a :success . } . { "jkl" string:endsWith "jkl" . } log:implies {:test3 a :success . } . cwm-1.2.1/test/ref/smush6.n30000644015216600007660000000127510027214405014637 0ustar syosisyosi @prefix : <#> . "86%" :is :TooDamp . 34 :is :TooHot . ( 1 2 3 ) :is :ListOfThreeNumbers . ( 20 20 ) :is :OkVision . <> a :testFile . :Grey = :Gray . :a a :Hatchback; :color :Gray . :b = :a . :c :color :Gray . :colour = :color . :firstThree = ( 1 2 3 ) . :node1 :called "Bnode1" . :theHumidity = "86%" . :theTemperature = 34 . :vision = ( 20 20 ) . [ a :Gentleman, :Scholar ]. cwm-1.2.1/test/ref/rules13-n.n30000644015216600007660000000035310022433417015140 0ustar syosisyosi @prefix : <#> . @prefix daml: . :ancestor a daml:TransitiveProperty . :bill :ancestor :granpa, :pa . :pa :ancestor :granpa . cwm-1.2.1/test/ref/timet1s.n30000644015216600007660000000370110066677544015020 0ustar syosisyosi @prefix : . @prefix v: <#> . @forAll v:f, v:t, v:x, v:y, v:z . "" a v:TestFormat . "1999-12-31T23:59:59.99Z" a v:TestDate; :day "31"; :dayOfWeek "4"; :hour "23"; :inSeconds "946684799"; :minute "59"; :month "12"; :second "59"; :year "1999" . "2000-01-01T00:00:00Z" a v:TestDate; :day "01"; :dayOfWeek "5"; :hour "00"; :inSeconds "946684800"; :minute "00"; :month "01"; :second "00"; :year "2000" . "2001-09-09T01:46:40Z" :inSeconds "1000000000" . "2002" a v:TestDate; :day ""; :dayOfWeek "1"; :hour ""; :inSeconds "1009843200"; :minute ""; :month ""; :second ""; :year "2002" . "2002-06" a v:TestDate; :day ""; :dayOfWeek "5"; :hour ""; :inSeconds "1022889600"; :minute ""; :month "06"; :second ""; :year "2002" . "2002-06-22" a v:TestDate; :day "22"; :dayOfWeek "5"; :hour ""; :inSeconds "1024704000"; :minute ""; :month "06"; :second ""; :year "2002" . "2002-06-22T12:34Z" a v:TestDate; :day "22"; :dayOfWeek "5"; :hour "12"; :inSeconds "1024749240"; :minute "34"; :month "06"; :second ""; :year "2002" . "2002-06-22T22:09:32-05:00" a v:TestDate; :day "22"; :dayOfWeek "6"; :hour "22"; :inSeconds "1024801772"; :minute "09"; :month "06"; :second "32"; :timeZone "-05:00"; :year "2002" . "year %Y month %M day %d date: %D" a v:TestFormat . cwm-1.2.1/test/ref/norm-av2.n30000644015216600007660000000770510137460165015067 0ustar syosisyosi A/B Switch black box Cable Box black box CATV black box DVD black box Signal Selector black box Splitter black box TV black box VCR black box cwm-1.2.1/test/ref/quotient_string.ref.n30000644015216600007660000000051710357372606017437 0ustar syosisyosi @prefix : <#> . @prefix math: . @forAll :X . 4.34782608696e+00 a :Answer . { ( "10" "2.3" ) math:quotient :X . } {:X a :Answer . } . cwm-1.2.1/test/ref/daml-ont.n30000644015216600007660000002167610022433417015135 0ustar syosisyosi @prefix : . @prefix dam: . @prefix rdf: . @prefix s: . a :Ontology; :imports ; :versionInfo "" . dam:Class a :Class; :sameClassAs s:Class . dam:Disjoint a :Class; :comment """for type(L, Disjoint) read: the classes in L are pairwise disjoint. i.e. if type(L, Disjoint), and C1 in L and C2 in L, then disjointWith(C1, C2). """; :label "Disjoint"; :subClassOf dam:List . dam:Empty a :Class; :asClass dam:Nothing . dam:List a :Class; :subClassOf rdf:Seq . dam:Literal a :Class; :sameClassAs s:Literal . dam:Nothing a :Class; :comment "the class with no things in it."; :complementOf dam:Thing . dam:Ontology a :Class; :comment """An Ontology is a document that describes a vocabulary of terms for communication between (human and) automated agents. """; :label "Ontology" . dam:Property a :Class; :sameClassAs rdf:Property . dam:Qualification a :Class . dam:Restriction a :Class . dam:Thing a :Class; :comment "The most general class in DAML."; :label "Thing" . dam:TransitiveProperty a :Class . dam:UnambiguousProperty a :Class; :comment """if P is an UnambiguousProperty, then if P(x, y) and P(z, y) then x=z. aka injective. e.g. if nameOfMonth(m, "Feb") and nameOfMonth(n, "Feb") then m and n are the same month. """; :label "UnambiguousProperty"@en; :subClassOf dam:Property . dam:UniqueProperty a :Class; :comment """compare with maxCardinality=1; e.g. integer successor: if P is a UniqueProperty, then if P(x, y) and P(x, z) then y=z. aka functional. """; :label "UniqueProperty"; :subClassOf dam:Property . dam:cardinality a :Property; :comment """for cardinality(P, N) read: P has cardinality N; i.e. everything x in the domain of P has N things y such that P(x, y). """; :domain dam:Property; :label "cardinality" . dam:comment a :Property; :samePropertyAs s:comment . dam:complementOf a :Property; :comment """ for complementOf(X, Y) read: X is the complement of Y; if something is in Y, then it's not in X, and vice versa. cf OIL NOT"""; :domain dam:Class; :range dam:Class . dam:default a :Property; :comment """default(X, Y) suggests that Y be considered a/the default value for the X property. This can be considered documentation (ala label, comment) but we don't specify any logical impact. """; :label "default" . dam:disjointUnionOf a :Property; :comment """ for disjointUnionOf(X, Y) read: X is the disjoint union of the classes in the list Y: (a) for any c1 and c2 in Y, disjointWith(c1, c2), and (b) i.e. if something is in any of the classes in Y, it's in X, and vice versa. cf OIL disjoint-covered """; :domain dam:Class; :label "disjointUnionOf"; :range dam:List . dam:disjointWith a :Property; :comment """for disjointWith(X, Y) read: X and Y have no members in common. """; :domain dam:Class; :label "disjointWith"; :range dam:Class . dam:domain a :Property; :samePropertyAs s:domain . dam:equivalentTo a :Property; :comment """for equivalentTo(X, Y), read X is an equivalent term to Y. """ . dam:first a :Property; :domain dam:List . dam:hasValue a :Property; :comment """for hasValue(Q, C), read: Q is a hasValue qualification to C."""; :domain dam:Qualification; :label "hasValue"; :range dam:Class . dam:imports a :Property; :comment """for imports(X, Y) read: X imports Y; i.e. X asserts the* contents of Y by reference; i.e. if imports(X, Y) and you believe X and Y says something, then you should believe it. Note: "the contents" is, in the general case, an il-formed definite description. Different interactions with a resource may expose contents that vary with time, data format, preferred language, requestor credentials, etc. So for "the contents", read "any contents". """; :label "imports" . dam:intersectionOf a :Property; :comment """ for intersectionOf(X, Y) read: X is the intersection of the classes in the list Y; i.e. if something is in all the classes in Y, then it's in X, and vice versa. cf OIL AND"""; :domain dam:Class; :range dam:List . dam:inverseOf a :Property; :comment """for inverseOf(R, S) read: R is the inverse of S; i.e. if R(x, y) then S(y, x) and vice versa."""; :domain dam:Property; :range dam:Property . dam:isDefinedBy a :Property; :samePropertyAs s:isDefinedBy; :subPropertyOf dam:seeAlso . dam:item a :Property; :comment """for item(L, I) read: I is an item in L; either first(L, I) or item(R, I) where rest(L, R)."""; :domain dam:List . dam:label a :Property; :samePropertyAs s:label . dam:maxCardinality a :Property; :comment """for maxCardinality(P, N) read: P has maximum cardinality N; i.e. everything x in the domain of P has at most N things y such that P(x, y). """; :domain dam:Property; :label "maxCardinality" . dam:minCardinality a :Property; :comment """for minCardinality(P, N) read: P has minimum cardinality N; i.e. everything x in the domain of P has at least N things y such that P(x, y). """; :domain dam:Property . dam:onProperty a :Property; :comment """for onProperty(R, P), read: R is a restriction/qualification on P."""; :domain dam:Qualification, dam:Restriction; :range dam:Property . dam:oneOf a :Property; :comment """for oneOf(C, L) read everything in C is one of the things in L; This lets us define classes by enumerating the members. """; :domain dam:Class; :range dam:List . dam:qualifiedBy a :Property; :comment """for qualifiedBy(C, Q), read: C is qualified by Q; i.e. the qualification Q applies to C; if onProperty(Q, P) and hasValue(Q, C2) then for every i in C, there is some V so that type(V, C2) and P(i, V). """; :domain dam:Class; :label "qualifiedBy"; :range dam:Qualification . dam:range a :Property; :samePropertyAs s:range . dam:rest a :Property; :domain dam:List; :range dam:List . dam:restrictedBy a :Property; :comment """for restrictedBy(C, R), read: C is restricted by R; i.e. the restriction R applies to c; if onProperty(R, P) and toValue(R, V) then for every i in C, we have P(i, V). if onProperty(R, P) and toClass(R, C2) then for every i in C and for all j, if P(i, j) then type(j, C2). """; :domain dam:Class; :label "restrictedBy"; :range dam:Restriction . dam:sameClassAs a :Property; :subPropertyOf dam:equivalentTo, dam:subClassOf . dam:samePropertyAs a :Property; :subPropertyOf dam:equivalentTo, dam:subPropertyOf . dam:seeAlso a :Property; :samePropertyAs s:seeAlso . dam:subClassOf a :Property; :samePropertyAs s:subClassOf . dam:subPropertyOf a :Property; :samePropertyAs s:subPropertyOf; :subPropertyOf s:subPropertyOf . dam:toClass a :Property; :comment "for toClass(R, C), read: R is a restriction to C."; :domain dam:Restriction; :range dam:Class . dam:toValue a :Property; :comment "for toValue(R, V), read: R is a restriction to V."; :domain dam:Restriction; :range dam:Class . dam:type a :Property; :samePropertyAs rdf:type . dam:unionOf a :Property; :comment """ for unionOf(X, Y) read: X is the union of the classes in the list Y; i.e. if something is in any of the classes in Y, it's in X, and vice versa. cf OIL OR"""; :domain dam:Class; :label "unionOf"; :range dam:List . dam:value a :Property; :samePropertyAs rdf:value . dam:versionInfo a :Property; :comment """generally, a string giving information about this version; e.g. RCS/CVS keywords """; :label "versionInfo" . cwm-1.2.1/test/ref/argv-2.n30000644015216600007660000000221710303444701014506 0ustar syosisyosi @prefix : <#> . @prefix log: . @prefix os: . @forAll :x . :test1c a :FAILURE . :test_param_1 :is "boof" . { "1" os:argv "foo" . } log:implies {:test1 a :sucess . } . { "1" os:argv "foot" . } log:implies {:test1b a :FAILURE . } . { "3" os:argv "baz" . } log:implies {:test3 a :sucess . } . { "THIS is not a valid number" os:argv :x . } log:implies {:test4 a :FAILURE . } . { 1 os:argv :x . } log:implies {:test_param_1 :is :x . } . { 2 os:argv "bar" . } log:implies {:test2 a :sucess . } . { 4 os:argv :x . } log:implies {:test3 a :FAILURE . } . { "1" os:argv [ log:notEqualTo "foo" ] . } log:implies {:test1c a :FAILURE . } . cwm-1.2.1/test/ref/dtlit1.n30000644015216600007660000000056210255410744014620 0ustar syosisyosi @prefix : . @prefix dtlit: <#> . @prefix log: . @forAll dtlit:X . "2005-03-30T11:00:00"^^:tz a :Answer . { ( "2005-03-30T11:00:00" :tz ) log:dtlit dtlit:X . } log:implies {dtlit:X a :Answer . } . cwm-1.2.1/test/ref/underbarscope-out.n30000644015216600007660000000047410070621112017046 0ustar syosisyosi @prefix : <#> . @prefix log: . @forSome :x . <> a :Success . :x log:notEqualTo [ a :Thing1 ] . { [ log:equalTo :x ]. } log:implies {<> a :Success . } . cwm-1.2.1/test/ref/numbers.n30000644015216600007660000000106410361736746015103 0ustar syosisyosi @prefix : <#> . "Le chat"@fr :is "The french phrase 'Le chat'" . "800/600"^^ :is "800/600 with datatype http://example.com/types#rational" . 2.0 :is "The number 2.0", "The number 2.0 expressed with extra trailing zeroes" . 2000.0e+00 :is "The double precision floating point 2.0e3" . -2 :is "The integer -2" . 0 :is "Zero" . 2 :is "The integer 2", "The integer 2 expressed with leading zeroes" . cwm-1.2.1/test/ref/contexts-1.n30000644015216600007660000000043007346025770015426 0ustar syosisyosi @prefix : <#> . @prefix u: . :assumption = {:fred u:knows :john . :john u:knows :mary . } . :conclusion = {:fred u:knows :mary . } . :trivialTruth = {} . cwm-1.2.1/test/ref/bi-quant-imp.n30000644015216600007660000000067510066677544015744 0ustar syosisyosi @prefix : <#> . @prefix log: . @forAll :x . :today a :Greatday, :Sunnyday . [ a :Birthday, :Greatday, :Sunnyday ]. [ a :God ]. { :x a :Sunnyday . } log:implies {:x a :Greatday . }, { [ a :God ]. } . cwm-1.2.1/test/ref/reason-t09check.n30000644015216600007660000000113010352331242016277 0ustar syosisyosi @prefix : . @prefix log: . a ; . { @forSome :_g_L4C10 . :_g_L4C10 . } log:implies { a . } . cwm-1.2.1/test/ref/math1.n30000644015216600007660000000641710361736746014451 0ustar syosisyosi @prefix : <#> . "0" a :testValue; :worksWith 3.1415926, 10000000.0e+00, 0, 1729 . "0 + 0 = 0" a :RESULT . "0 + 1.0e7 = 10000000.0" a :RESULT . "0 + 10000000.0 = 10000000.0" a :RESULT . "0 + 1729 = 1729" a :RESULT . "0 + 3.1415926 = 3.1415926" a :RESULT . "1.0e7" a :testValue; :worksWith 10000000.0e+00 . "1.0e7 + 0 = 10000000.0" a :RESULT . "1.0e7 + 1.0e7 = 20000000.0" a :RESULT . "1.0e7 + 10000000.0 = 20000000.0" a :RESULT . "1.0e7 + 1729 = 10001729.0" a :RESULT . "1.0e7 + 3.1415926 = 10000003.141592599" a :RESULT . "10000000.0 + 0 = 10000000.0" a :RESULT . "10000000.0 + 1.0e7 = 20000000.0" a :RESULT . "10000000.0 + 10000000.0 = 20000000.0" a :RESULT . "10000000.0 + 1729 = 10001729.0" a :RESULT . "10000000.0 + 3.1415926 = 10000003.141592599" a :RESULT . "1729" a :testValue; :worksWith 3.1415926, 10000000.0e+00, 0, 1729 . "1729 + 0 = 1729" a :RESULT . "1729 + 1.0e7 = 10001729.0" a :RESULT . "1729 + 10000000.0 = 10001729.0" a :RESULT . "1729 + 1729 = 3458" a :RESULT . "1729 + 3.1415926 = 1732.1415926" a :RESULT . "3.1415926" a :testValue; :worksWith 3.1415926, 10000000.0e+00 . "3.1415926 + 0 = 3.1415926" a :RESULT . "3.1415926 + 1.0e7 = 10000003.141592599" a :RESULT . "3.1415926 + 10000000.0 = 10000003.141592599" a :RESULT . "3.1415926 + 1729 = 1732.1415926" a :RESULT . "3.1415926 + 3.1415926 = 6.2831852" a :RESULT . 3.1415926 a :testValue; :worksWith 3.1415926, 10000000.0e+00 . 10000000.0e+00 a :testValue; :worksWith 10000000.0e+00 . 3.5e+00 :valueOf "7 / 2" . 9.5e+00 :valueOf "(7 / 2) + ((7 % 2)^10000000) + 5 [should be 9.5]" . -3 :valueOf "3 negated" . 0 a :testValue; :valuOf " () math:sum ?x --- should be 0"; :worksWith 3.1415926, 10000000.0e+00, 0, 1729 . 1 :valuOf " () math:product ?x --- should be 1"; :valueOf "7 % 2" . 1024 :valueOf "2^10" . 108 :valueOf "3 + 5 + 100" . 1729 a :testValue; :worksWith 3.1415926, 10000000.0e+00, 0, 1729 . 3 :valueOf "sum(3) = 3", "what -3's the - of" . 30 :valueOf "5 * 3 * 2" . 5 :valueOf "8 - 3" . 8 :valueOf "3 + (8 - 3)", "3 + 5", "3 + 5 = 8" . ( "1.0e7" "3.1415926" ) :SumDifferenceFAILS 3.14159259945e+00 . ( "1.0e7" 3.1415926 ) :SumDifferenceFAILS 3.14159259945e+00 . ( 10000000.0e+00 "3.1415926" ) :SumDifferenceFAILS 3.14159259945e+00 . ( 10000000.0e+00 3.1415926 ) :SumDifferenceFAILS 3.14159259945e+00 . :test10 a :success . cwm-1.2.1/test/ref/prefix1.rdf0000644015216600007660000000322310551560616015230 0ustar syosisyosi 2 2002 cwm-1.2.1/test/ref/reason-t08check.n30000644015216600007660000000116410327177764016330 0ustar syosisyosi @prefix : . @prefix log: . @forAll :x. @forSome :_g_L2C9 . :_g_L2C9 . :_g_L2C9 . { :x . } log:implies {:x . } . cwm-1.2.1/test/ref/n3string.n30000644015216600007660000000042110247137543015164 0ustar syosisyosi @prefix : <#> . @prefix log: . @forAll :x . { { :㐭 :b :c . } log:n3String :x . } log:implies {:x a :interesting . } . cwm-1.2.1/test/ref/bi-uri-startswith.n30000644015216600007660000000116610066677544017036 0ustar syosisyosi @prefix : <#> . @prefix aacl: . @prefix c: . @prefix log: . @prefix string: . @forAll :doc . c:archive . [ c:mailbox ]. { :doc log:uri [ string:startsWith "http://lists.w3.org/Archives/Public/" ] . } log:implies {:doc a aacl:PubliclyReadable . } . cwm-1.2.1/test/ref/append-out.n30000644015216600007660000000101710022433417015461 0ustar syosisyosi @prefix : <#> . @prefix rdf: . ( "only" ) :append ( () "only" ) . ( 1 2 ) :append ( ( 1 ) 2 ) . ( 2 ) :append ( () 2 ) . :A0 :RESULT ( "only" ) . :A1 :RESULT ( 1 2 ) . :B0 :append ( () "onlyB" ); rdf:first "onlyB"; rdf:rest () . cwm-1.2.1/test/ref/list-unify5.n30000644015216600007660000000057210302437726015612 0ustar syosisyosi @prefix : <#> . 2 a :RESULT . ( 1 13 ) :crinks ( 2 14 ) . ( 1 14 ) :crinks ( 2 13 ) . ( 1 2 ) :crinks ( 7 2 ) . ( 1 3 ) :crinks ( 999 999 ) . :THIS_TEST a :SUCCESS . cwm-1.2.1/test/ref/list-unify4.n30000644015216600007660000000057210022433417015601 0ustar syosisyosi @prefix : <#> . 2 a :RESULT . ( 1 13 ) :crinks ( 2 14 ) . ( 1 14 ) :crinks ( 2 13 ) . ( 1 2 ) :crinks ( 7 2 ) . ( 1 3 ) :crinks ( 999 999 ) . :THIS_TEST a :SUCCESS . cwm-1.2.1/test/ref/prefix3.rdf0000644015216600007660000000322310563115071015224 0ustar syosisyosi 2 2002 cwm-1.2.1/test/ref/piped-t016-out.n30000644015216600007660000003510210563115071016010 0ustar syosisyosi @prefix rdfs: . @prefix rdf: . @prefix daml: . @prefix : . a rdfs:Class; rdfs:label "Animal" . @forSome . a :Restriction . :restrictedBy . :onProperty ; :cardinality "2" . @prefix rdf: . @prefix : . @prefix dpo: . @prefix ex: . a dpo:Ontology; dpo:versionInfo ""; dpo:comment "An example ontology"; dpo:imports . ex:Animal a dpo:Class; dpo:label "Animal"; dpo:comment """This class of animals is illustrative of a number of ontological idioms.""" . ex:Male a dpo:Class; dpo:subClassOf ex:Animal . ex:Female a dpo:Class; dpo:subClassOf ex:Animal; dpo:disjointFrom ex:Male . ex:parent a dpo:Property; dpo:domain ex:Animal; dpo:cardinality "2" . ex:Person a dpo:Class; dpo:subClassOf ex:Animal . @forSome ex:_L43C4 . ex:_L43C4 a dpo:Restriction . ex:Person dpo:restrictedBy ex:_L43C4 . ex:_L43C4 dpo:onProperty ex:parent; dpo:toClass ex:Person . ex:father a dpo:Property; dpo:subProperty ex:parent; dpo:range ex:Man; dpo:cardinality "1" . ex:mother a dpo:UniqueProperty; dpo:subProperty ex:parent; dpo:range ex:Woman . ex:child a dpo:Property; dpo:inverseOf ex:parent . ex:ancestor a dpo:TransitiveProperty; dpo:label "ancestor" . ex:descendant a dpo:TransitiveProperty . ex:mom a dpo:Property; = ex:mother . ex:occupation a dpo:Property; dpo:maxCardinality "1" . ex:Car a dpo:Class; dpo:comment "no car is a person" . @forSome ex:_L84C4 . ex:_L84C4 a dpo:Class . ex:Car dpo:subClassOf ex:_L84C4 . ex:_L84C4 dpo:complementOf ex:Person . ex:Man a dpo:Class; dpo:subClassOf ex:Person, ex:Male . ex:Woman a dpo:Class; dpo:subClassOf ex:Person, ex:Female . ex:Person a dpo:Class; dpo:comment "every person is a man or a woman" . @forSome ex:_L103C4 . ex:Person dpo:disjointUnionOf ex:_L103C4 . ex:Man a dpo:Class . ex:_L103C4 rdf:first ex:Man . @forSome ex:_L104C4 . ex:_L103C4 rdf:rest ex:_L104C4 . ex:Woman a dpo:Class . ex:_L104C4 rdf:first ex:Woman; rdf:rest () . ex:Adam a dpo:Person; dpo:label "Adam"; dpo:comment "Adam is a person." . ex:height a dpo:Property; dpo:domain ex:Person; dpo:range ex:Height . ex:Height a dpo:Class . @forSome ex:_L120C4 . ex:Height dpo:oneOf ex:_L120C4 . ex:short a dpo:Height . ex:_L120C4 rdf:first ex:short . @forSome ex:_L121C4 . ex:_L120C4 rdf:rest ex:_L121C4 . ex:medium a dpo:Height . ex:_L121C4 rdf:first ex:medium . @forSome ex:_L122C4 . ex:_L121C4 rdf:rest ex:_L122C4 . ex:tall a dpo:Height . ex:_L122C4 rdf:first ex:tall; rdf:rest () . ex:TallThing a dpo:Class . @forSome ex:_L128C4 . ex:_L128C4 a dpo:Restriction . ex:TallThing dpo:restrictedBy ex:_L128C4 . ex:_L128C4 dpo:onProperty ex:height; dpo:toValue ex:tall . ex:TallMan a dpo:Class . @forSome ex:_L141C4 . ex:TallMan dpo:intersectionOf ex:_L141C4 . ex:TallThing a dpo:Class . ex:_L141C4 rdf:first ex:TallThing . @forSome ex:_L142C4 . ex:_L141C4 rdf:rest ex:_L142C4 . ex:Man a dpo:Class . ex:_L142C4 rdf:first ex:Man; rdf:rest () . @prefix web: . @prefix : . @forSome . a :Company; :corporateHomepage ; :name "MegaCorp Inc."; :ticker "MEGA" . @forSome . a :Person . :owner . :name "Mr Mega"; :personalMailbox ; :personalHomepage ; :age "50" . @forSome . a :User; :personalMailbox ; :technologyInterest , , . @forSome . a :Organisation; :corporateHomepage . a :PolicyStatement . :ethicalPolicy . :title "Ethical Business Shared Guidelines 1.1" . @prefix : . @prefix rdfs: . @prefix rdf: . :versionInfo ""; :imports ; a :Ontology . :first a :Property; :domain :List . :UniqueProperty a :Class; :label "UniqueProperty"; :comment """compare with maxCardinality=1; e.g. integer successor: if P is a UniqueProperty, then if P(x, y) and P(x, z) then y=z. aka functional. """; :subClassOf :Property . :subClassOf a :Property; :samePropertyAs rdfs:subClassOf . :unionOf a :Property; :label "unionOf"; :comment """ for unionOf(X, Y) read: X is the union of the classes in the list Y; i.e. if something is in any of the classes in Y, it's in X, and vice versa. cf OIL OR"""; :domain :Class; :range :List . :Disjoint a :Class; :label "Disjoint"; :subClassOf :List; :comment """for type(L, Disjoint) read: the classes in L are pairwise disjoint. i.e. if type(L, Disjoint), and C1 in L and C2 in L, then disjointWith(C1, C2). """ . :UnambiguousProperty a :Class; :label "UnambiguousProperty"; :comment """if P is an UnambiguousProperty, then if P(x, y) and P(z, y) then x=z. aka injective. e.g. if nameOfMonth(m, "Feb") and nameOfMonth(n, "Feb") then m and n are the same month. """; :subClassOf :Property . :intersectionOf a :Property; :comment """ for intersectionOf(X, Y) read: X is the intersection of the classes in the list Y; i.e. if something is in all the classes in Y, then it's in X, and vice versa. cf OIL AND"""; :domain :Class; :range :List . :restrictedBy a :Property; :label "restrictedBy"; :comment """for restrictedBy(C, R), read: C is restricted by R; i.e. the restriction R applies to c; if onProperty(R, P) and toValue(R, V) then for every i in C, we have P(i, V). if onProperty(R, P) and toClass(R, C2) then for every i in C and for all j, if P(i, j) then type(j, C2). """; :domain :Class; :range :Restriction . :minCardinality a :Property; :comment """for minCardinality(P, N) read: P has minimum cardinality N; i.e. everything x in the domain of P has at least N things y such that P(x, y). """; :domain :Property . :item a :Property; :comment """for item(L, I) read: I is an item in L; either first(L, I) or item(R, I) where rest(L, R)."""; :domain :List . :value a :Property; :samePropertyAs rdf:value . :cardinality a :Property; :label "cardinality"; :comment """for cardinality(P, N) read: P has cardinality N; i.e. everything x in the domain of P has N things y such that P(x, y). """; :domain :Property . :default a :Property; :label "default"; :comment """default(X, Y) suggests that Y be considered a/the default value for the X property. This can be considered documentation (ala label, comment) but we don't specify any logical impact. """ . :oneOf a :Property; :comment """for oneOf(C, L) read everything in C is one of the things in L; This lets us define classes by enumerating the members. """; :domain :Class; :range :List . :Restriction a :Class . :disjointWith a :Property; :label "disjointWith"; :comment """for disjointWith(X, Y) read: X and Y have no members in common. """; :domain :Class; :range :Class . :equivalentTo a :Property; :comment """for equivalentTo(X, Y), read X is an equivalent term to Y. """ . :TransitiveProperty a :Class . :Property a :Class; :sameClassAs rdf:Property . :Qualification a :Class . :sameClassAs a :Property; :subPropertyOf :equivalentTo, :subClassOf . :Thing a :Class; :label "Thing"; :comment "The most general class in DAML." . :List a :Class; :subClassOf rdf:Seq . :versionInfo a :Property; :label "versionInfo"; :comment """generally, a string giving information about this version; e.g. RCS/CVS keywords """ . :range a :Property; :samePropertyAs rdfs:range . :subPropertyOf a :Property; :samePropertyAs rdfs:subPropertyOf; :subPropertyOf rdfs:subPropertyOf . :seeAlso a :Property; :samePropertyAs rdfs:seeAlso . :Class a :Class; :sameClassAs rdfs:Class . :type a :Property; :samePropertyAs rdf:type . :Ontology a :Class; :label "Ontology"; :comment """An Ontology is a document that describes a vocabulary of terms for communication between (human and) automated agents. """ . :Nothing a :Class; :comment "the class with no things in it."; :complementOf :Thing . :maxCardinality a :Property; :label "maxCardinality"; :comment """for maxCardinality(P, N) read: P has maximum cardinality N; i.e. everything x in the domain of P has at most N things y such that P(x, y). """; :domain :Property . :label a :Property; :samePropertyAs rdfs:label . :onProperty a :Property; :comment """for onProperty(R, P), read: R is a restriction/qualification on P."""; :domain :Restriction, :Qualification; :range :Property . :hasValue a :Property; :label "hasValue"; :comment """for hasValue(Q, C), read: Q is a hasValue qualification to C."""; :domain :Qualification; :range :Class . :inverseOf a :Property; :comment """for inverseOf(R, S) read: R is the inverse of S; i.e. if R(x, y) then S(y, x) and vice versa."""; :domain :Property; :range :Property . :toValue a :Property; :comment "for toValue(R, V), read: R is a restriction to V."; :domain :Restriction; :range :Class . :Empty a :Class; :asClass :Nothing . :isDefinedBy a :Property; :samePropertyAs rdfs:isDefinedBy; :subPropertyOf :seeAlso . :qualifiedBy a :Property; :label "qualifiedBy"; :comment """for qualifiedBy(C, Q), read: C is qualified by Q; i.e. the qualification Q applies to C; if onProperty(Q, P) and hasValue(Q, C2) then for every i in C, there is some V so that type(V, C2) and P(i, V). """; :domain :Class; :range :Qualification . :samePropertyAs a :Property; :subPropertyOf :equivalentTo, :subPropertyOf . :Literal a :Class; :sameClassAs rdfs:Literal . :rest a :Property; :domain :List; :range :List . :imports a :Property; :label "imports"; :comment """for imports(X, Y) read: X imports Y; i.e. X asserts the* contents of Y by reference; i.e. if imports(X, Y) and you believe X and Y says something, then you should believe it. Note: "the contents" is, in the general case, an il-formed definite description. Different interactions with a resource may expose contents that vary with time, data format, preferred language, requestor credentials, etc. So for "the contents", read "any contents". """ . :complementOf a :Property; :comment """ for complementOf(X, Y) read: X is the complement of Y; if something is in Y, then it's not in X, and vice versa. cf OIL NOT"""; :domain :Class; :range :Class . :toClass a :Property; :comment "for toClass(R, C), read: R is a restriction to C."; :domain :Restriction; :range :Class . :disjointUnionOf a :Property; :label "disjointUnionOf"; :domain :Class; :range :List; :comment """ for disjointUnionOf(X, Y) read: X is the disjoint union of the classes in the list Y: (a) for any c1 and c2 in Y, disjointWith(c1, c2), and (b) i.e. if something is in any of the classes in Y, it's in X, and vice versa. cf OIL disjoint-covered """ . :domain a :Property; :samePropertyAs rdfs:domain . :comment a :Property; :samePropertyAs rdfs:comment . cwm-1.2.1/test/ref/genBnodeInNestedFormula-out.n30000644015216600007660000000053310453454067020731 0ustar syosisyosi @prefix : <#> . @forAll :x. @forSome :_g0 . :_g0 a :Mother; :name "Mary"; :says {:You :listenTo :_g0 . } . { :x a :Mother . } {:x :says {:You :listenTo :x . } . } . cwm-1.2.1/test/ref/dot-dash.n30000644015216600007660000000035707711361176015133 0ustar syosisyosi @prefix : . :a :b :c . :hyphen-ated . :minus-_underscore :under_score :underscore_-minus . cwm-1.2.1/test/ref/reluri-1.rdf0000644015216600007660000000124610022433417015304 0ustar syosisyosi Fred cwm-1.2.1/test/ref/bnode.n30000644015216600007660000000053410022433417014477 0ustar syosisyosi [ "Dave Beckett"; ]; "RDF/XML Syntax Specification (Revised)" . cwm-1.2.1/test/ref/rules-flag-a.n30000644015216600007660000000111310066677544015704 0ustar syosisyosi @prefix : <#> . @prefix daml: . @prefix log: . @forAll :p . :ancestor a daml:TransitiveProperty . :granpa :ancestor :pa . :pa :ancestor :bill . { :p a daml:TransitiveProperty . } log:implies {@forAll :x, :y, :z . { :x :p :y . :y :p :z . } log:implies {:x :p :z . } . } . cwm-1.2.1/test/unify/0000755015216600007660000000000010731073450013526 5ustar syosisyosicwm-1.2.1/test/unify/reflexive.n30000644015216600007660000000023710061112715015755 0ustar syosisyosi@prefix log: . @prefix : <#>. :Steve :talksTo :Joe . { ?s :talksTo ?s } log:implies {?s :admits "I talk to myself"} . cwm-1.2.1/test/unify/reflexive-ref.n30000644015216600007660000000040510066677544016551 0ustar syosisyosi @prefix : <#> . @prefix log: . @forAll :s . :Steve :talksTo :Joe . { :s :talksTo :s . } log:implies {:s :admits "I talk to myself" . } . cwm-1.2.1/test/norm/0000755015216600007660000000000010731073447013355 5ustar syosisyosicwm-1.2.1/test/norm/t-200401-unicode.rdf0000644015216600007660000000107510005772015016457 0ustar syosisyosi Copyright © 2004 Norman Walsh. All rights reserved. André cwm-1.2.1/test/norm/fix.rdf0000644015216600007660000000353307616044604014645 0ustar syosisyosi <_4 rdf:resource="file:/home79536262/ndw/.xmlDate.rdf#id193"/> <_5 rdf:resource="file:/home79536262/ndw/.xmlDate.rdf#id192"/> <_6 rdf:resource="file:/home79536262/ndw/.xmlDate.rdf#id104"/> <_7 rdf:resource="file:/home79536262/ndw/.xmlDate.rdf#id157"/> <_8 rdf:resource="file:/home79536262/ndw/.xmlDate.rdf#id32"/> 2 2002 <_1 rdf:resource="http://nwalsh.com/pim/Palm/Calendar#_week_2002_2_1"/> <_2 rdf:resource="http://nwalsh.com/pim/Palm/Calendar#_week_2002_2_2"/> <_3 rdf:resource="http://nwalsh.com/pim/Palm/Calendar#_week_2002_2_3"/> <_4 rdf:resource="http://nwalsh.com/pim/Palm/Calendar#_week_2002_2_4"/> <_5 rdf:resource="http://nwalsh.com/pim/Palm/Calendar#_week_2002_2_5"/> cwm-1.2.1/test/norm/av.n30000644015216600007660000000355110066677544014242 0ustar syosisyosi@prefix : . @prefix rdfs: . @prefix log: . @prefix gv: . # The root :AV a rdfs:Class . :input a rdfs:Property . :output a rdfs:Property . :title a rdfs:Property . # Rules :catv a :AV; :title "CATV" . :splitter a :AV; :title "Splitter"; :output :ab . :selector a :AV; :title "Signal Selector"; :output :tv . :cable a :AV; :title "Cable Box"; :output :vcr . :vcr a :AV; :title "VCR"; :output :ab . :ab a :AV; :title "A/B Switch"; :output :selector . :tv a :AV; :title "TV" . :dvd a :AV; :title "DVD"; :output :selector . @forAll :p, :s, :o, :t . # Graph rules { :p :output :s } log:implies { :p :solidEdge :s } . { :p :title :s } log:implies { :p gv:label :s } . # Style rules { :s a :AV } log:implies { :s gv:color "black"; gv:shape "box" } . #{ :s a :DocumentSet } log:implies { :s gv:color "black"; # gv:shape "polygon"; # gv:sides "5" } . # #{ :s a :Result } log:implies { :s gv:color "blue"; # gv:style "filled"; # gv:fontcolor "white" } . # #{ :s a :Source } log:implies { :s gv:shape "Mdiamond" } . # #{ :s a :Optional } log:implies { :s gv:shape "diamond" } . # #{ :s a :Temporary } log:implies { :s gv:color "gray"; # gv:style "filled"; # gv:fontcolor "white" } . :solidEdge gv:style "solid" . :dottedEdge gv:style "dotted" . # The graph information <> gv:digraph [ gv:label "AV Diagram"; gv:subgraph [ gv:label "" ; gv:hasNode :catv, :splitter, :cable, :vcr, :ab, :tv, :dvd; gv:hasEdgeProperty :solidEdge ; gv:hasEdgeProperty :dottedEdge ; ] ] . cwm-1.2.1/test/norm/detailed.tests0000644015216600007660000000157710006245351016214 0ustar syosisyosi# List of regression tests # # - was in bash script retest.sh # @prefix : <#>. @prefix x: <#>. @prefix test: . @prefix dc: . # yuk - under protest - no hash :norm10 a test:CwmTest; test:shortFileName "norm-av1.n3"; test:description "Bug with RDF output in bySubject mode"; test:arguments """norm/av.n3 --think --base=bogus: --purge --rdf --bySubject""". :norm11 a test:CwmTest; test:shortFileName "norm-av2.n3"; test:description "Bug with --chatty=200 after --base=bogus:"; test:arguments """norm/av.n3 --think --base=bogus: --purge --chatty=200 --rdf --bySubject""". :norm12 a test:CwmTest; test:referenceOutput ; test:description "Unicode non-ascii characters in RDF/XML"; test:arguments """--rdf norm/t-200401-unicode.rdf""". #ends cwm-1.2.1/test/norm/t-200401-unicode.ref0000644015216600007660000000110610022433416016451 0ustar syosisyosi Copyright © 2004 Norman Walsh. All rights reserved. André cwm-1.2.1/test/xml-syntax/0000755015216600007660000000000010731073450014520 5ustar syosisyosicwm-1.2.1/test/xml-syntax/non-ascii-pred.rdf0000644015216600007660000000051310140440702020014 0ustar syosisyosi Joerg <名前>ヨーク cwm-1.2.1/test/xml-syntax/xmlbase3.rdf0000644015216600007660000000062210270205124016724 0ustar syosisyosi World Wide Web Consortium cwm-1.2.1/test/xml-syntax/in-xml.xml0000644015216600007660000000064107616042126016453 0ustar syosisyosi This is non-RDF content %s 45 cwm-1.2.1/test/xml-syntax/xml_prefix.n30000644015216600007660000000017610205444721017142 0ustar syosisyosi@prefix : . @prefix a: . a:a a:b a:c . a:y a:n a:i . a:q a :P; :v :r . cwm-1.2.1/test/xml-syntax/xml_prefix2.n30000644015216600007660000000030610271233360017215 0ustar syosisyosi@prefix xml: . @prefix a: . @prefix xmlns: . a:a a:b a:c . a:y a:n a:i . a:q a :P; xml:v xml:r; xmlns:w xmlns:t . cwm-1.2.1/test/xml-syntax/rdf_prefix.n30000644015216600007660000000006410271233360017107 0ustar syosisyosi@prefix rdf: . :a rdf:b :c . cwm-1.2.1/test/xml-syntax/basic-serialization.n30000644015216600007660000000032410256050024020707 0ustar syosisyosi# Used in regression.n3#t1063 # # An extremely basic RDF/XML serialization test. # # Issue originally raised in the following bug: # http://lists.w3.org/Archives/Public/public-cwm-bugs/2005Jan/0004 <#s> <#p> 3. cwm-1.2.1/test/xml-syntax/xmllit.rdf0000644015216600007660000000200310305663725016530 0ustar syosisyosi John cwm-1.2.1/test/datatypes/0000755015216600007660000000000010731073447014400 5ustar syosisyosicwm-1.2.1/test/datatypes/dec-div.n30000644015216600007660000000210610135232444016144 0ustar syosisyosi@prefix math: . @prefix k: . @prefix m: . @prefix qif: . @prefix xsdt: . @prefix time: . @prefix : <#>. :exch1 k:startingDate [ xsdt:date "2004-08-08" ]; m:buyCurrency m:USD; m:sellCurrency m:CAD. { ?X is math:quotient of ("2.3" "1.2") } => { :exch1 m:rate ?X }. :priceCAD m:priceCurrency m:CAD. qif:amount m:priceCurrency m:USD. :trx :priceCAD "12.43"; k:startingDate [ xsdt:date "2004-08-12" ] . { ?P m:priceCurrency ?FOREIGN. qif:amount m:priceCurrency ?NATIVE. ?EXCH m:sellCurrency ?FOREIGN; m:buyCurrency ?NATIVE; m:rate ?RATE; k:startingDate [ xsdt:date [ time:year ?Y; time:month ?M ]]. ?TRX ?P ?QTY; k:startingDate [ xsdt:date [ time:year ?Y; time:month ?M ]]. (?QTY ?RATE) math:quotient ?Q2. } => { ?TRX qif:amount ?Q2 }. cwm-1.2.1/test/owl-ex.rdf0000644015216600007660000000634210065611216014307 0ustar syosisyosi $Id: owl-ex.rdf,v 1.3 2004/06/21 16:53:34 syosi Exp $ An example ontology This class of animals is illustrative of a number of ontological idioms. 2 1 1 no car is a person every person is a man or a woman Adam is a person. cwm-1.2.1/test/sameThing.n30000644015216600007660000000275110066677543014600 0ustar syosisyosi@prefix dc: . @prefix contact: . @prefix rcs: . <> dc:description """substituion of equals for equals in triples, plus some rules for unambiguous/unique properties (@@that probably belong elsewhere)"""; rcs:id "$Id: sameThing.n3,v 1.6 2004/06/25 01:26:59 timbl Exp $"; dc:creator [ contact:fullName "Dan Connolly"; contact:homePage ; contact:mailbox ]; dc:relation ; #@@ or is dc:relation a class of properties? # should I be using rdfs:seeAlso? dc:rights "copyright (c) 2001 W3C (MIT, Keio, INRIA)". @prefix ont: . @prefix log: . @prefix : <#>. # These should be derivable from the axiomatic semantics for DAML+OIL @forAll :x, :y, :z, :p, :q. { :x = :y } log:implies { :y = :x }. # symmetric { :x = [ = :z] } log:implies { :x = :z }. # transitive { :x :p :y. :x = :z. :p log:notEqualTo log:forAll, log:forSome} log:implies { :z :p :y }. { :x :p :y. :p = :q. :p log:notEqualTo log:forAll, log:forSome} log:implies { :x :q :y }. { :x :p :y. :y = :z. :p log:notEqualTo log:forAll, log:forSome} log:implies { :x :p :z }. { :p a ont:UniqueProperty. } log:implies { { :x :p :y. :x :p :z. } log:implies { :y = :z } }. { :p a ont:UnambiguousProperty. } log:implies { { :x :p :z. :y :p :z. } log:implies { :x = :y } }. cwm-1.2.1/test/schema-filter.n30000644015216600007660000000216210066677543015400 0ustar syosisyosi# Schema validator in N3 # # There is not on the semantic web a single meaning of # the term "schema valid", as one can make different choices # about what information is used for validation, and what lengths # are gone to to try to find inconsitencies. In general, one cannot # for any set of rules, just prove that a document does not violate # a given set of constraints. However, we can set the bar at a # particular height. For example # - Retrieve schemata for any namesapces used in the target # - apply a given set of rules (a certian limite number of times?) # - check the result has no inconsistencies. # # See schema-rules.n3 # # This file just filters out the error messages from everything else. # @prefix log: . #bind daml: . #bind : <> . # For our use @prefix val: . # Hint for others use # # This is what we will flag: # @@@ neater syntax for this # @@@ way of specifiying the whole process in one file. @forAll <#x> . {<#x> a val:schemaInconsistency} log:implies {<#x> a val:schemaInconsistency}. # ENDS cwm-1.2.1/test/Makefile0000644015216600007660000000471610655653252014055 0ustar syosisyosi# Makefile # P=python2.4 W=../../../.. C=../cwm.py RC=../../rdf-tests/rdfcore CODE=retest.py #../cwm.py ../notation3.py ../query.py ../llyn.py # etc ... OFFLINETESTS=regression.n3 list/detailed.tests \ sparql/detailed.tests \ reason/detailed.tests \ sets/detailed.tests \ ql/detailed.tests \ math/detailed.tests \ norm/detailed.tests \ cwm/detailed.tests \ ntriples/detailed.tests \ string/detailed.tests \ syntax/detailed.tests \ includes/detailed.tests # reify/detailed.tests \ # i18n/detailed.tests \ TESTS=online.tests rdfcore-tests.n3 delta/detailed.tests paw/detailed.tests testmeta.n3 \ $(OFFLINETESTS) #n3parser.tests quick : pyc-check $(CODE) $(OFFLINETESTS) PYTHONPATH=`/bin/pwd`/..:`/bin/pwd`/../.. $P retest.py $(OFFLINETESTS) pre-release : pyc-check $(CODE) $(TESTS) rdflib PYTHONPATH=`/bin/pwd`/..:`/bin/pwd`/../.. $P retest.py -c $(TESTS) post-install : pyc-check $(CODE) $(OFFLINETESTS) PYTHONPATH=`/bin/pwd`/..:`/bin/pwd`/../.. $P retest.py --cwm=../cwm $(OFFLINETESTS) filelist : pyc-check $(CODE) $(OFFLINETESTS) export CWM_LIST_FILES=1; PYTHONPATH=`/bin/pwd`/..:`/bin/pwd`/../.. $P retest.py --cwm=./file_list.py $(OFFLINETESTS) sort testfilelist > testfilelist3 uniq testfilelist3 > testfilelist rm testfilelist3 rdflib: rdfcore-tests.n3 CWM_RDF_PARSER="rdflib" PYTHONPATH=`/bin/pwd`/..:`/bin/pwd`/../.. $P retest.py -c rdfcore-tests.n3 mellow : pyc-check $(CODE) $(TESTS) PYTHONPATH=`/bin/pwd`/..:`/bin/pwd`/../.. $P retest.py --ignoreErrors $(TESTS) just_work : pyc-check $(CODE) $(TESTS) PYTHONPATH=`/bin/pwd`/..:`/bin/pwd`/../.. $P retest.py --overwrite -c $(TESTS) fast : $(CODE) regression.n3 PYTHONPATH=`/bin/pwd`/..:`/bin/pwd`/../.. $P retest.py -n -f regression.n3 pyc-check : $(CODE) rm -f ../*.pyc touch pyc-check loopback : ./n3-xml-test.sh `cat tests-work.txt` rules12.rdf : rules12.n3 cwm rules12.n3 -rdf > rules12.rdf rdfcore-tests.n3: ../../rdf-tests/rdfcore/Manifest.rdf $P $C --rdf ../../rdf-tests/rdfcore/Manifest.rdf --n3 > $@ testmeta.n3 : rdfcore-tests.n3 triage.n3 $P $C rdfcore-tests.n3 --filter=triage.n3 > $@ rdfcore-tests.sh: rdfcore-tests.n3 gentest.n3 $P $C rdfcore-tests.n3 gentest.n3 -think --strings | sed -e 's?http://www.w3.org?/devel/WWW?g' > $@ annotation.n3 : find $(RC) -name "*.nt" -exec grep -l "22-rdf-syntax-ns#predicate" {} \; | \ sed -e 's/^/ a <#ReificationFile>./' > $@ flatten:: PYTHONPATH=`/bin/pwd`/..:`/bin/pwd`/../.. $P retest.py -n -c -f flatten-tests.n3 cwm-1.2.1/test/list/0000755015216600007660000000000010731073447013355 5ustar syosisyosicwm-1.2.1/test/list/itemType.rdf0000644015216600007660000000063310065611216015644 0ustar syosisyosi 432000 cwm-1.2.1/test/list/unify4.n30000644015216600007660000000066110066677544015051 0ustar syosisyosi# test the handling os lists which are in the store # # use with --think @prefix : <#>. @prefix log: . @prefix math: . @forAll :x, :y. ( 1 2 ) :crinks ( 7 2 ). ( 1 3 ) :crinks ( 999 999 ) . ( 1 13 ) :crinks ( 2 14 ). ( 1 14 ) :crinks ( 2 13 ). { ( 1 ?x ) :crinks ( 7 ?x ) } => { ?x a :RESULT }. { 2 a :RESULT } => { :THIS_TEST a :SUCCESS }. # cwm-1.2.1/test/list/builtin_generated_match.n30000644015216600007660000000034210245226462020453 0ustar syosisyosi@keywords a, of, the, is, has, prefix . @prefix rdf: . ((q)) a Thing . {?X a Thing . ?X rdf:rest ?Y} => {?Y a Thing } . {?X a Thing; rdf:first (?B)} => {?B a GreatThing} . cwm-1.2.1/test/list/construct.n30000644015216600007660000000104007731131677015644 0ustar syosisyosi# $Id: construct.n3,v 1.1 2003/09/14 18:30:23 timbl Exp $ # # When you construct lists, if someone has labelled the # node which is a list, then we note the equality between the list # and the symbol. # @prefix rdf: . @prefix rdfs: . @prefix log: . @prefix : <#> . :A rdf:first 1; rdf:rest (). :B rdf:first 1; rdf:rest ( 2 3 ). :C rdf:first 1; rdf:rest ( 2 3 ); a :ListOfIntegers. # ends cwm-1.2.1/test/list/list-bug1.n30000644015216600007660000000040010066677544015431 0ustar syosisyosi@prefix : <#>. @prefix log: . @forAll :x, :y. (
) a . { (:x :y) a } log:implies { :x :RESULT :y }. # Result should be # :RESULT . # and should NOT include :RESULT . cwm-1.2.1/test/list/r1.n30000644015216600007660000000121110066677544014145 0ustar syosisyosi@prefix r: . @prefix s: . @prefix doc: . @prefix log: . @prefix daml: . @prefix xml: . @prefix contact: . @prefix : . @forAll :a, :b, :c, :x, :y, :z. ( "one" "two" ) a :whatever. { (:a :b) a :whatever } log:implies { :a a :SUCCESS. :b a :SUCCESS }. # { :x a :whatever } log:implies { :x :is """ The list ( "one" "two" )""" }. cwm-1.2.1/test/list/last.n30000644015216600007660000000166010256021702014552 0ustar syosisyosi# test list built in @prefix rdf: . @prefix : <#>. @prefix list: . @keywords a. { ( 1 2 3 4 5 6 ) list:last 6 } => { test1 a SUCCESS }. { ( 1 2 3 4 5 "Z" ) list:last "Z" } => { test2 a SUCCESS }. { ( "wrong" "WongAgain" "Success" ) list:last ?x }=>{ test3 isa ?x}. { 1 list:in ( 1 2 3 4 5 ) } => { test4a a SUCCESS }. { 2 list:in ( 1 2 3 4 5 ) } => { test4b a SUCCESS }. { 3 list:in ( 1 2 3 4 5 ) } => { test4c a SUCCESS }. { 4 list:in ( 1 2 3 4 5 ) } => { test4d a SUCCESS }. { 1 list:in () } => { trap1 a FAILURE}. { 0 list:in ( 1 2 3 4 5 ) } => { trap2 a FAILURE }. thing1 prop1 ( test5a test5b test5c ) . { ?item list:in [ @is prop1 @of thing1 ] } => { ?item a SUCCESS } . ( foo bar baz ) prop2 test6a . ( foo ) prop2 test6b . ( bar baz ) prop2 trap4 . { foo list:in ?a_list . ?a_list prop2 ?thing } => { ?thing a SUCCESS } . #ends cwm-1.2.1/test/list/unify1.n30000644015216600007660000000063110066677544015043 0ustar syosisyosi# test the handling os lists which are bound as other things get calculated # # use with --think @prefix : <#>. @prefix log: . @prefix math: . @forAll :x, :y. # Cause llyn to search the store for a list: { ?x math:negation 1. ( ?x 5 ) math:sum ?y } => { ?y a :RESULT }. { 4 a :RESULT } => { :THIS_TEST a :SUCCESS }. # cwm-1.2.1/test/list/list-bug2.n30000644015216600007660000000071310066677544015441 0ustar syosisyosi# test the handling os lists which are bound as other things get calculated @prefix : <#>. @prefix log: . @prefix string: . @forAll :x, :y. # Cause llyn to search the store for a list: ( "1" ) . { # log:uri ?u. ( "fred" " whatever ") string:concatenation ?s } => { ?s a :RESULT }. # Result should be # "fred whatever " a :RESULT . # cwm-1.2.1/test/list/detailed.tests0000644015216600007660000000636110303444700016207 0ustar syosisyosi# List of regression tests # # - was in bash script retest.sh # @prefix : <#>. @prefix x: <#>. @prefix test: . :t1017 a test:CwmTest; test:shortFileName "lists-simple.n3"; test:description "parsing and generation of N3 list syntax"; test:arguments """-n3 lists-simple.n3""". :t1018 a test:CwmTest; test:shortFileName "lists-simple-1.rdf"; test:description "conversion of N3 list syntax to RDF"; test:arguments """-n3 lists-simple.n3 -rdf""". :t1018b1 a test:CwmTest; test:shortFileName "list-bug1.n3"; test:description "List processing bug check 1"; test:arguments """list/list-bug1.n3 --think""". :t1018b2 a test:CwmTest; test:shortFileName "list-bug2.n3"; test:description "List processing bug check 2"; test:arguments """list/list-bug2.n3 --think""". :t1020 a test:CwmTest; test:shortFileName "list-construct.n3"; test:description "What to do with URI-labelled lists"; test:arguments """list/construct.n3""". :t1021 a test:CwmTest; test:shortFileName "bnode_in_list_in_list.ref"; test:description "Anonymous nodes in nested lists"; test:arguments """list/bnode_in_list_in_list.n3""". # Test list handling in inference :t1031 a test:CwmTest; test:shortFileName "li-r1.n3"; test:description "Inference using lists"; test:arguments """list/r1.n3 -think""". #:t1032 a test:CwmTest; # test:shortFileName "li-gk3.n3"; # test:description "Iterative ops on lists"; # test:arguments """list/gk3.n3 -think""". :t1032a a test:CwmTest; test:shortFileName "li-double.n3"; test:description "Query with list with the same var in >once"; test:arguments """list/double.n3 -think""". :t2004u1 a test:CwmTest; test:shortFileName "list-unify1.n3"; test:description "List unification 1"; test:arguments """list/unify1.n3 --think --data""". :t2004u2 a test:CwmTest; test:shortFileName "list-unify2.n3"; test:description "List unification 2 - variable in list"; test:arguments """list/unify1.n3 --think --data""". :t2004u3 a test:CwmTest; test:shortFileName "list-unify3.n3"; test:description "List unification 3 - nested lists"; test:arguments """list/unify1.n3 --think --data""". :t2004u4 a test:CwmTest; test:shortFileName "list-unify4.n3"; test:description "List unification 4 - nested lists"; test:arguments """list/unify4.n3 --think --data""". :t2004u5 a test:CwmTest; test:shortFileName "list-unify5.n3"; test:description "List unification 5 - multiple values"; test:arguments """list/unify4.n3 --think --data""". :t2005 a test:CwmTest; test:shortFileName "append-out.n3"; test:description "Iterative ops on lists"; test:arguments """list/append.n3 --think --data""". # Test other builtins :t2006 a test:CwmTest; test:shortFileName "list-last.n3"; test:description "last, in builtins on lists"; test:arguments """list/last.n3 --think --data""". :t2007 a test:CwmTest; test:shortFileName "list-builtin_generated_match.n3"; test:description "last, in builtins on lists"; test:arguments """list/builtin_generated_match.n3 --think --data""". #ends cwm-1.2.1/test/list/append.n30000644015216600007660000000127107724163440015070 0ustar syosisyosi# $Id: append.n3,v 1.1 2003/08/30 18:04:16 timbl Exp $ @prefix rdf: . @prefix rdfs: . @prefix log: . @prefix : <#> . #{ ?A :append ( ?L ?X ) => { ?A :append ( [ rdf:first ?H ; rdf:rest ?T ] ?S ) . } => { ?A rdf:first ?H ; rdf:rest [ :append ( ?T ?S ) ] . } . { ?A :append ( () ?S ) . } => { ?A rdf:first ?S ; rdf:rest () . } . # Test cases :A0 :RESULT [ :append ( () "only" ) ]. :B0 :append ( () "onlyB" ) . :A1 :RESULT [ :append ( ( 1 ) 2 ) ] . #:A2 :append ( :A1 "L2" ) . #:A3 :append ( :A1 "L3" ) . cwm-1.2.1/test/list/double.n30000644015216600007660000000066310066677544015107 0ustar syosisyosi# Isolating a bug # The problem was gtaht the rule didn't fire if vraible :a # occured twice in the same list. @prefix log: . @prefix string: . @prefix os: . @prefix : <#>. @forAll :a, :s. "Ostrich" a :foobar. { :a a :foobar. ( :a :a ) string:concatenation :s. }=>{ "00" log:outputString :s }. #ends cwm-1.2.1/test/list/bnode_in_list_in_list.n30000644015216600007660000000002410153747226020145 0ustar syosisyosi:a :b (([:c :d])) . cwm-1.2.1/test/rdfcore-tests.n30000644015216600007660000054355210563115066015443 0ustar syosisyosi#Processed by Id: cwm.py,v 1.190 2006/08/09 23:20:42 syosi Exp # using base file:///Users/yosi/CVSROOT/WWW/2000/10/rdf-tests/rdfcore/Manifest.rdf # Notation3 generation by # notation3.py,v 1.191 2006/08/01 01:14:04 syosi Exp # Base was: file:///Users/yosi/CVSROOT/WWW/2000/10/rdf-tests/rdfcore/Manifest.rdf @prefix : . @prefix M: . @prefix Ma: . @prefix Man: . @prefix Man10: . @prefix Man11: . @prefix Man12: . @prefix Man13: . @prefix Man14: . @prefix Man15: . @prefix Man16: . @prefix Man17: . @prefix Man18: . @prefix Man19: . @prefix Man2: . @prefix Man20: . @prefix Man21: . @prefix Man22: . @prefix Man23: . @prefix Man24: . @prefix Man25: . @prefix Man3: . @prefix Man4: . @prefix Man5: . @prefix Man6: . @prefix Man7: . @prefix Man8: . @prefix Man9: . @prefix Mani: . @prefix Manif: . @prefix XML: . @prefix dat: . @prefix rdf: . @prefix rdfs: . a :PositiveParserTest; :approval ; :inputDocument ; :outputDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . Man6:xsd-integer-decimal-compatible a :NegativeEntailmentTest; :approval ; :conclusionDocument [ a :False-Document ]; :datatypeSupport XML:decimal, XML:integer; :description """ The claim that xsd:integer is a subClassOF xsd:decimal is not incompatible with using the intensional semantics for datatypes. """; :entailmentRules rdf:, rdfs:, dat:; :premiseDocument ; :status "APPROVED" . Man6:xsd-integer-string-incompatible a :PositiveEntailmentTest; :approval ; :conclusionDocument [ a :False-Document ]; :datatypeSupport XML:integer, XML:string; :description """ The claim that xsd:integer is a subClassOF xsd:string is incompatible with using the intensional semantics for datatypes. """; :entailmentRules rdf:, rdfs:, dat:; :premiseDocument ; :status "APPROVED" . a :NT-Document . a :NT-Document . Man7:language-and-xml-literal a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :datatypeSupport rdf:XMLLiteral; :description """ Language does not affect the denotation of rdf:XMLLiteral. NOTE that this is a change from previous versions of the spec. Langauge tags do not live on XMLLiterals. """; :entailmentRules rdf:, rdfs:, dat:; :premiseDocument ; :status "OBSOLETE" . Man7:language-ignored-for-numeric-types-1 a :PositiveEntailmentTest; :conclusionDocument ; :datatypeSupport XML:integer; :description """ Obsoleted: datatyped literals have no language tag. """; :entailmentRules rdf:, dat:; :premiseDocument ; :status "OBSOLETE" . Man7:language-ignored-for-numeric-types-2 a :PositiveEntailmentTest; :conclusionDocument ; :datatypeSupport XML:integer; :description """ Obsoleted: datatyped literals have no language tag. """; :entailmentRules rdf:, dat:; :premiseDocument ; :status "OBSOLETE" . Man7:language-ignored-for-numeric-types-3 a :PositiveEntailmentTest; :conclusionDocument ; :datatypeSupport XML:integer; :description """ Obsoleted: datatyped literals have no language tag. """; :entailmentRules rdf:, dat:; :premiseDocument ; :status "OBSOLETE" . Man7:language-important-for-non-dt-entailment-1 a :NegativeEntailmentTest; :conclusionDocument ; :description """ This test used to claim: Language attributes on a datatyped literal make them distinct for the purposes of non-datatype-aware entailments. There are no longer language tags on datatyped literals. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "OBSOLETE" . Man7:language-important-for-non-dt-entailment-2 a :NegativeEntailmentTest; :conclusionDocument ; :description """ This test used to claim: Language attributes on a datatyped literal make them distinct for the purposes of non-datatype-aware entailments. There are no longer language tags on datatyped literals. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "OBSOLETE" . Man7:non-well-formed-literal-1 a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ Without datatype knowledge, a 'badly-formed' datatyped literal cannot be detected. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "APPROVED" . Man7:non-well-formed-literal-2 a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :datatypeSupport XML:integer; :description """ With appropriate datatype knowledge, a 'badly-formed' datatyped literal can be detected. """; :entailmentRules rdf:, rdfs:, dat:; :premiseDocument ; :status "APPROVED" . Man7:plain-literal-and-xsd-string a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :datatypeSupport XML:string; :description """ A plain literal denotes the same thing as its corresponding xsd:string, where one exists. """; :entailmentRules rdf:, rdfs:, dat:; :premiseDocument ; :status "APPROVED" . Man7:range-clash a :PositiveEntailmentTest; :approval ; :conclusionDocument [ a :False-Document ]; :datatypeSupport XML:decimal, XML:string; :description """ Where sufficient DT knowledge is available, a range clash may be detected; the document then contains a contradiction. """; :entailmentRules rdf:, rdfs:, dat:; :premiseDocument ; :status "APPROVED" . Man7:semantic-equivalence-between-datatypes a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :datatypeSupport XML:decimal, XML:integer; :description """ Members of different datatypes may be semantically equivalent. """; :entailmentRules rdf:, dat:; :premiseDocument ; :status "APPROVED" . Man7:semantic-equivalence-within-type-1 a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :datatypeSupport XML:integer; :description """ Demonstrating the semantic equivalence of two lexical forms of the same datatyped value. """; :entailmentRules rdf:, dat:; :premiseDocument ; :status "APPROVED" . Man7:semantic-equivalence-within-type-2 a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :datatypeSupport XML:integer; :description """ As semantic-equivalence-within-type-1; the entailment works both ways. """; :entailmentRules rdf:, dat:; :premiseDocument ; :status "APPROVED" . Man7:test001 a :PositiveParserTest; :approval ; :description """ A simple datatype production; a language+datatype production. Simply duplicate the constructs under http://www.w3.org/2000/10/rdf-tests/rdfcore/ntriples/test.nt """; :inputDocument ; :outputDocument ; :status "APPROVED" . Man7:test002 a :PositiveParserTest; :approval ; :description """ A parser is not required to know about well-formed datatyped literals. """; :inputDocument ; :outputDocument ; :status "APPROVED" . Man7:test008 a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ From decisions listed in http://lists.w3.org/Archives/Public/w3c-rdfcore-wg/2002Oct/0098.html """; :entailmentRules :simpleEntailment; :premiseDocument ; :status "APPROVED" . Man7:test009 a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ From decisions listed in http://lists.w3.org/Archives/Public/w3c-rdfcore-wg/2002Oct/0098.html """; :entailmentRules :simpleEntailment; :premiseDocument ; :status "APPROVED" . Man7:test010 a :PositiveEntailmentTest; :approval ; :conclusionDocument [ a :False-Document ]; :datatypeSupport rdf:XMLLiteral; :description """ From decisions listed in http://lists.w3.org/Archives/Public/w3c-rdfcore-wg/2002Oct/0098.html """; :entailmentRules rdf:, rdfs:, dat:; :premiseDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . Man10:subClassOf-intensional a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ rdfs:subClassOf has intensional semantics, not extensional. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "APPROVED" . Man10:subPropertyOf-intensional a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :datatypeSupport XML:integer, XML:string; :description """ rdfs:subPropertyOf has intensional semantics, not extensional. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ Test that ICEXT(I(rdfs:Literal)) is a subset of LV. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "APPROVED" . a :NT-Document . a :NT-Document . Man17:error001 a :NegativeParserTest; :approval ; :description """ Does the treatment of literals conform to charmod ? Test for failure for literal not in Normal Form C This test case has been WITHDRAWN in light of changes to NFC handling in concepts """; :discussion ; :inputDocument ; :issue ; :status "WITHDRAWN" . Man17:error002 a :NegativeParserTest; :approval ; :description """ Does the treatment of literals conform to charmod ? Test for failure for literal not in Normal Form C This test case has been WITHDRAWN in light of changes to NFC handling in concepts """; :discussion ; :inputDocument ; :issue ; :status "WITHDRAWN" . Man17:test001 a :PositiveParserTest; :approval ; :description """ Does the treatment of literals conform to charmod ? Test for success of legal Normal Form C literal """; :discussion ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . Ma:error001 a :NegativeParserTest; :approval ; :description """ Test for failure for uriref not in Normal Form C. """; :discussion ; :inputDocument ; :issue ; :status "OBSOLETE" . Ma:test001 a :PositiveParserTest; :approval ; :description """ A uriref is allowed to match non-US ASCII forms conforming to Unicode Normal Form C. No escaping algorithm is applied. """; :discussion ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Ma:test002 a :PositiveParserTest; :approval ; :description """ A uriref which already has % escaping is permitted. No unescaping algorithm is applied. """; :discussion ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Ma:test003 a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ An international URI ref and its %-escaped form label different nodes in the graph. No model theoretic relationship holds between them. """; :discussion ; :entailmentRules rdf:; :issue ; :premiseDocument ; :status "APPROVED" . Ma:test004 a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ An international URI ref and its %-escaped form label different nodes in the graph. No model theoretic relationship holds between them. """; :discussion ; :entailmentRules rdf:; :issue ; :premiseDocument ; :status "APPROVED" . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . Manif:error001 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . Manif:error002 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . Manif:test001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Manif:test002 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Manif:test003 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Manif:test004 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Manif:test005 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETED" . Manif:test006 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Manif:test007 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Manif:test008 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :PositiveParserTest; :approval ; :description """ A surrounding rdf:RDF element is no longer mandatory. """; :inputDocument ; :outputDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . Man14:error0001 a :NegativeParserTest; :description """ This is again legal RDF """; :inputDocument ; :issue ; :status "OBSOLETE" . Man14:error0002 a :NegativeParserTest; :description """ This is again legal RDF """; :inputDocument ; :issue ; :status "OBSOLETE" . Man14:error0003 a :NegativeParserTest; :description """ This is again legal RDF """; :inputDocument ; :issue ; :status "OBSOLETE" . Man14:error0004 a :NegativeParserTest; :description """ This is again legal RDF """; :inputDocument ; :issue ; :status "OBSOLETE" . Man14:error0005 a :NegativeParserTest; :description """ This is again legal RDF """; :inputDocument ; :issue ; :status "OBSOLETE" . Man14:error0006 a :NegativeParserTest; :description """ This is again legal RDF """; :inputDocument ; :issue ; :status "OBSOLETE" . Man14:error0007 a :NegativeParserTest; :description """ This is again legal RDF """; :inputDocument ; :issue ; :status "OBSOLETE" . Man14:error0008 a :NegativeParserTest; :description """ This is again legal RDF """; :inputDocument ; :issue ; :status "OBSOLETE" . Man14:error0009 a :NegativeParserTest; :description """ This is again legal RDF """; :inputDocument ; :issue ; :status "OBSOLETE" . Man14:test0001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man14:test0002 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man14:test0003 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man14:test0004 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man14:test0005 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man14:test0006 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man14:test0007 a :PositiveParserTest; :description """ rdf:aboutEach no longer valid. """; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man14:test0008 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man14:test0009 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man14:test0010 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man14:test0011 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man14:test0012 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man14:test0013 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man14:test0014 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . Man20:error001 a :NegativeParserTest; :approval ; :inputDocument ; :status "APPROVED" . Man20:error002 a :NegativeParserTest; :approval ; :inputDocument ; :status "APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . Man16:error1 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . Man16:test1 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man16:test2 a :PositiveParserTest; :approval ; :description """ This test shows the treatment of non-ASCII characters in the value of rdf:ID attribute. """; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man16:test3 a :PositiveParserTest; :approval ; :description """ This test shows the treatment of non-ASCII characters in the value of rdf:about attribute. """; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :PositiveParserTest; :approval ; :description """ The question posed to the RDF WG was: should an RDF document containing multiple rdf:_n properties (with the same n) on an element be rejected as illegal? The WG decided that a parser should accept that case as legal RDF. """; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . Man23:error001 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . Man23:error002 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . Man23:error003 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . Man23:test001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test002 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test003 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test004 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test005 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test006 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test007 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test008 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test009 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test010 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test011 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test012 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test013 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test014 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test015 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test016 a :PositiveParserTest; :approval ; :description """ Like rdfms-empty-property-elements/test001.rdf but with a processing instruction as the only content of the otherwise empty element. """; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man23:test017 a :PositiveParserTest; :approval ; :description """ Like rdfms-empty-property-elements/test001.rdf but with a comment as the only content of the otherwise empty element. """; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . Man:test001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man:test002 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man:test003 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man:test004 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man:test005 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . Man2:test001 a :PositiveParserTest; :inputDocument ; :issue ; :outputDocument ; :status "NOT_APPROVED" . Man2:test002 a :PositiveParserTest; :inputDocument ; :issue ; :outputDocument ; :status "NOT_APPROVED" . Man2:test003 a :PositiveParserTest; :inputDocument ; :issue ; :outputDocument ; :status "NOT_APPROVED" . Man2:test004 a :PositiveParserTest; :inputDocument ; :issue ; :outputDocument ; :status "NOT_APPROVED" . Man2:test005 a :PositiveParserTest; :inputDocument ; :issue ; :outputDocument ; :status "NOT_APPROVED" . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . Man8:test001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test002 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test003 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test004 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test005 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test006 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test007 a :NegativeParserTest; :approval ; :description """ rdf:bagID is forbidden on property element prop with an rdf:resource or rdf:parseType attribute: the following is in error. """; :inputDocument ; :issue ; :status "OBSOLETE" . Man8:test008 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test009 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test010a a :PositiveParserTest; :approval ; :description """ Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. One of test010a and test010b SHOULD pass, at least. """; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test010b a :PositiveParserTest; :approval ; :description """ Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. """; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test011a a :PositiveParserTest; :approval ; :description """ Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. One of test011a and test011b SHOULD pass, at least. """; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test011b a :PositiveParserTest; :approval ; :description """ Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. """; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test012a a :PositiveParserTest; :approval ; :description """ Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. One of test012a and test012b SHOULD pass, at least. """; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man8:test012b a :PositiveParserTest; :approval ; :description """ Two property attributes and a property element on an rdf:Description. Since the property attributes are not ordered under document order, two different n-triples files corresponding to both possible orderings are permitted. """; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :NT-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :NT-Document . Man24:test001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man24:test002 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man24:test003 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man24:test004 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man24:test005 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . Man12:error001 a :NegativeParserTest; :inputDocument ; :status "NOT_APPROVED" . Man12:error002 a :NegativeParserTest; :inputDocument ; :status "NOT_APPROVED" . Man12:error003 a :NegativeParserTest; :inputDocument ; :status "NOT_APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . Man18:error001 a :NegativeParserTest; :approval ; :description """ The value of rdf:ID must match the XML Name production, (as modified by XML Namespaces). """; :inputDocument ; :status "APPROVED" . Man18:error002 a :NegativeParserTest; :approval ; :description """ The value of rdf:ID must match the XML Name production, (as modified by XML Namespaces). """; :inputDocument ; :status "APPROVED" . Man18:error003 a :NegativeParserTest; :approval ; :description """ The value of rdf:ID must match the XML Name production, (as modified by XML Namespaces). """; :inputDocument ; :status "APPROVED" . Man18:error004 a :NegativeParserTest; :approval ; :description """ The value of rdf:ID must match the XML Name production, (as modified by XML Namespaces). """; :inputDocument ; :status "APPROVED" . Man18:error005 a :NegativeParserTest; :approval ; :description """ The value of rdf:ID must match the XML Name production, (as modified by XML Namespaces). """; :inputDocument ; :status "APPROVED" . Man18:error006 a :NegativeParserTest; :approval ; :description """ The value of rdf:bagID must match the XML Name production, (as modified by XML Namespaces). """; :inputDocument ; :status "APPROVED" . Man18:error007 a :NegativeParserTest; :approval ; :description """ The value of rdf:bagID must match the XML Name production, (as modified by XML Namespaces). """; :inputDocument ; :status "APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . M:error-001 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-002 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-003 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-004 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-005 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-006 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-007 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-008 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-009 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-010 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-011 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-012 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-013 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-014 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-015 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-016 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-017 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-018 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-019 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:error-020 a :NegativeParserTest; :approval ; :inputDocument ; :issue ; :status "APPROVED" . M:test-001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-002 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-003 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-004 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-005 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-006 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-007 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-008 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-009 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-010 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-011 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-012 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-013 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-014 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-015 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-016 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-017 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-018 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-019 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-020 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-021 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-022 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-023 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-024 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-025 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-026 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-027 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-028 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-029 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-030 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-031 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-032 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-033 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-034 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-035 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-036 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:test-037 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . M:warn-001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED"; :warning " allowed with warnings " . M:warn-002 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED"; :warning " allowed with warnings " . M:warn-003 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED"; :warning " allowed with warnings " . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :PositiveParserTest; :approval ; :inputDocument ; :outputDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . Man9:test001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man9:test002 a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ Statement of the MT closure rule. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "APPROVED" . Man9:test003 a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ Statement of the MT closure rule. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "APPROVED" . Man9:test004 a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ Statement of the MT closure rule. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "APPROVED" . a :NT-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . Man13:error001 a :NegativeParserTest; :approval ; :description """ The value of rdf:nodeID must match the XML Name production, (as modified by XML Namespaces). """; :inputDocument ; :issue ; :status "APPROVED" . Man13:error002 a :NegativeParserTest; :approval ; :description """ The value of rdf:nodeID must match the XML Name production, (as modified by XML Namespaces). """; :inputDocument ; :issue ; :status "APPROVED" . Man13:error003 a :NegativeParserTest; :approval ; :description """ The value of rdf:nodeID must match the XML Name production, (as modified by XML Namespaces). """; :inputDocument ; :issue ; :status "APPROVED" . Man13:error004 a :NegativeParserTest; :approval ; :description """ Cannot have rdf:nodeID and rdf:ID. """; :inputDocument ; :issue ; :status "APPROVED" . Man13:error005 a :NegativeParserTest; :approval ; :description """ Cannot have rdf:nodeID and rdf:about. """; :inputDocument ; :issue ; :status "APPROVED" . Man13:error006 a :NegativeParserTest; :approval ; :description """ Cannot have rdf:nodeID and rdf:resource. """; :inputDocument ; :issue ; :status "APPROVED" . Man13:test001 a :PositiveParserTest; :approval ; :description """ rdf:nodeID can be used to label a blank node. """; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man13:test002 a :PositiveParserTest; :approval ; :description """ rdf:nodeID can be used to label a blank node. These have file scope and are distinct from any unlabelled blank nodes. """; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man13:test003 a :PositiveParserTest; :approval ; :description """ On an rdf:Description or typed node rdf:nodeID behaves similarly to an rdf:about. """; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man13:test004 a :PositiveParserTest; :approval ; :description """ On a property element rdf:nodeID behaves similarly to rdf:resource. """; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . Man21:error001 a :MiscellaneousTest; :approval ; :description """ An RDF/XML serlializer is recommended to produce an exception if asked to serialize the following graph since there is no way to represent it in the RDF/XML syntax. """; :document ; :status "APPROVED"; :warning """ An RDF/XML serlializer is recommended to produce an exception if asked to serialize the following graph since there is no way to represent it in the RDF/XML syntax. """ . Man21:test001 a :PositiveParserTest; :approval ; :inputDocument ; :outputDocument ; :status "APPROVED" . a :NT-Document . a :NT-Document . a :RDF-XML-Document . Man25:test001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man25:test002 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . Man19:test001 a :PositiveParserTest; :approval ; :inputDocument ; :outputDocument ; :status "APPROVED" . Man19:test002 a :PositiveParserTest; :approval ; :inputDocument ; :outputDocument ; :status "APPROVED" . Man19:test003 a :PositiveParserTest; :approval ; :inputDocument ; :outputDocument ; :status "APPROVED" . Man19:test004 a :PositiveParserTest; :approval ; :inputDocument ; :outputDocument ; :status "APPROVED" . Man19:test005 a :PositiveParserTest; :approval ; :inputDocument ; :outputDocument ; :status "APPROVED" . Man19:test006 a :PositiveParserTest; :approval ; :inputDocument ; :outputDocument ; :status "APPROVED" . Man19:test007a a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ Plain literals are distinguishable on the basis of language tags. """; :entailmentRules :simpleEntailment; :premiseDocument ; :status "APPROVED" . Man19:test007b a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ Plain literals are distinguishable on the basis of language tags. """; :entailmentRules :simpleEntailment; :premiseDocument ; :status "APPROVED" . Man19:test007c a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ Plain literals are distinguishable on the basis of language tags. """; :entailmentRules :simpleEntailment; :premiseDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :NT-Document . a :NT-Document . a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ While it is a superproperty, _:a _:b . does NOT entail _:a _:b . for any _n. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . Man5:conjunction-test a :PositiveEntailmentTest; :conclusionDocument ; :description """ Should a property be allowed more than one rdfs:range property? What should the semantics of multiple domain and range properties be? -> Multiple domain and range constraints are permissable and will have conjunctive semantics. test001 describes a property with rdfs:domain the intersection of 2 domains test002 describes a property with rdfs:range the intersection of 2 ranges test003 sample statement test004 entailed description using test001, test002, test003 and the rules for RDF and RDFS entailment (see http://www.w3.org/2000/10/rdf-tests/rdfcore/entailment/ ) """; :entailmentRules rdf:, rdfs:; :issue ; :premiseDocument , , ; :status "NOT_APPROVED" . Man5:intensionality-domain a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ RDF Semantics defines rdfs:range to have an intensional reading of domain. However, semantic extensions may give an extensional reading to domain. The premise/conclusion pair is a non-entailment for RDFS reasoning, but may hold in semantic extensions. """; :entailmentRules rdf:, rdfs:; :issue , ; :premiseDocument ; :status "APPROVED" . Man5:intensionality-range a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ RDF Semantics defines rdfs:range to have an intensional reading. However, semantic extensions may give an extensional reading to range. The premise/conclusion pair is a non-entailment for RDFS reasoning, but may hold in semantic extensions. """; :entailmentRules rdf:, rdfs:; :issue , ; :premiseDocument ; :status "APPROVED" . Man5:test001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man5:test002 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man5:test003 a :PositiveParserTest; :inputDocument ; :issue ; :outputDocument ; :status "NOT_APPROVED" . Man5:test004 a :PositiveParserTest; :inputDocument ; :issue ; :outputDocument ; :status "NOT_APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . Man22:test001 a :PositiveEntailmentTest; :approval ; :conclusionDocument [ a :False-Document ]; :description """ Indicating a simple inconsistency drawn from RDFS. RDFS can only produce inconsistencies through badly-formed XMLLiteral datatypes. """; :entailmentRules rdf:, rdfs:; :issue ; :premiseDocument ; :status "APPROVED" . Man22:test002 a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ From an inconsistent graph, any entailment can be drawn. This is an example. """; :entailmentRules rdf:, rdfs:; :issue ; :premiseDocument [ a :False-Document ]; :status "APPROVED" . a :NT-Document . a :NT-Document . a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ Cycles are permitted in subClassOf; therefore, no error occurs and the following entailment holds trivially. """; :entailmentRules rdf:, rdfs:; :issue ; :premiseDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ Cycles are permitted in subPropertyOf; therefore, no error occurs and the following entailment holds trivially. """; :entailmentRules rdf:, rdfs:; :issue ; :premiseDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . a :NegativeEntailmentTest; :approval ; :conclusionDocument [ a :False-Document ]; :description """ an instance of the Property class may have an rdfs:subClassOf property. the meaning of such a property is defined by the model theory. The wording of the formal resolution is a bit bare, so let me add a few words of explanation. What this means is that a resource can be both a class and a property. This test is encoded as follows: a Property may have a subclass (that is, such an RDF graph is satisfiable) """; :entailmentRules rdf:, rdfs:; :issue ; :premiseDocument ; :status "APPROVED" . a :NT-Document . a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ The inheritance semantics of the subPropertyOf relationship needs to be clarified. => subProperties inherit conjunctively the domain and range of their superproperties """; :entailmentRules rdf:, rdfs:; :issue ; :premiseDocument ; :status "APPROVED" . a :NT-Document . a :NT-Document . Man4:test001 a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ RDFCore WG RESOLVED that a reified statement was a stating, not a statement. The following entailment does not, therefore, hold. """; :entailmentRules rdf:; :premiseDocument ; :status "APPROVED" . Man4:test002 a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ RDFCore WG RESOLVED that a statement does NOT entail its reification. The following entailment does not, therefore, hold. """; :entailmentRules rdf:; :premiseDocument ; :status "APPROVED" . Man4:test003 a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ RDFCore WG RESOLVED that a reified statement was a stating, not a statement. The following entailment does not, therefore, hold. This is the same as test001, but using RDFS-entailment. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "APPROVED" . Man4:test004 a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :description """ RDFCore WG RESOLVED that a statement does NOT entail its reification. The following entailment does not, therefore, hold. This is the same as test002, but using RDFS-entailment. """; :entailmentRules rdf:, rdfs:; :premiseDocument ; :status "APPROVED" . a :NT-Document . a :NT-Document . a :NT-Document . a :NT-Document . Man15:language-tag-case-1 a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ The case of the language tag is not significant. """; :entailmentRules rdf:; :premiseDocument ; :status "APPROVED" . Man15:language-tag-case-2 a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :description """ The case of the language tag is not significant. """; :entailmentRules rdf:; :premiseDocument ; :status "APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . Mani:test001 a :PositiveParserTest; :approval ; :inputDocument ; :outputDocument ; :status "APPROVED" . Mani:test002 a :PositiveParserTest; :approval ; :inputDocument ; :outputDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :PositiveParserTest; :approval ; :description """ Demonstrating the canonicalisation of XMLLiterals. """; :inputDocument ; :outputDocument ; :status "APPROVED" . a :NT-Document . a :RDF-XML-Document . Man3:error001 a :NegativeParserTest; :description """ This test case concerns URIs relative to a non-relative URI scheme base. It's beyond the scope of the WG to deal with this; it has therefore not been approved. """; :inputDocument ; :issue ; :status "NOT_APPROVED" . Man3:test001 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test002 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test003 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test004 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test005 a :PositiveParserTest; :description """ This is not valid rdf/xml. The embedding of RDF/XML in other XML formats is beyond the scope of these test cases. Test case withdrawn. """; :inputDocument ; :issue ; :outputDocument ; :status "OBSOLETE" . Man3:test006 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test007 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test008 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test009 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test010 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test011 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test012 a :PositiveParserTest; :approval ; :description """ Test case WITHDRAWN in light of 2396bis """; :inputDocument ; :issue ; :outputDocument ; :status "WITHDRAWN" . Man3:test013 a :PositiveParserTest; :approval ; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test014 a :PositiveParserTest; :approval ; :description """ Test output corrected to use correct base URL. """; :inputDocument ; :issue ; :outputDocument ; :status "APPROVED" . Man3:test015 a :PositiveParserTest; :approval ; :description """ This test case is deprecated. The use of mailto: URIs with xml:base is not within the scope of RDFCore's charter to sort out. """; :inputDocument ; :issue ; :outputDocument ; :status "NOT_APPROVED" . Man3:test016 a :PositiveParserTest; :approval ; :description """ This test case is deprecated. The use of mailto: URIs with xml:base is not within the scope of RDFCore's charter to sort out. """; :inputDocument ; :issue ; :outputDocument ; :status "NOT_APPROVED" . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . a :NT-Document . a :RDF-XML-Document . Man11:whitespace-facet-1 a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :datatypeSupport XML:int; :description """ A well-formed typed literal is not related to an ill-formed literal. Even if they only differ by whitespace. """; :entailmentRules rdf:, rdfs:, dat:; :premiseDocument ; :status "APPROVED" . Man11:whitespace-facet-2 a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :datatypeSupport XML:int; :description """ A well-formed typed literal is not related to an ill-formed literal. Even if they only differ by whitespace. """; :entailmentRules rdf:, rdfs:, dat:; :premiseDocument ; :status "APPROVED" . Man11:whitespace-facet-3 a :PositiveEntailmentTest; :approval ; :conclusionDocument ; :datatypeSupport XML:int; :description """ A simple test for well-formedness of a typed literal. """; :entailmentRules rdf:, rdfs:, dat:; :premiseDocument ; :status "APPROVED" . Man11:whitespace-facet-4 a :NegativeEntailmentTest; :approval ; :conclusionDocument ; :datatypeSupport XML:int; :description """ An integer with whitespace is ill-formed. """; :entailmentRules rdf:, rdfs:, dat:; :premiseDocument ; :status "APPROVED" . a :RDF-XML-Document . a :RDF-XML-Document . a :RDF-XML-Document . #ENDS cwm-1.2.1/test/underbarscope.n30000644015216600007660000000026110070621112015457 0ustar syosisyosi@prefix : <#> . @prefix log: . @forSome :x . _:a a :Thing1 . :x log:notEqualTo _:a . {_:a log:equalTo :x} log:implies {<> a :Success} . cwm-1.2.1/test/vblsNotURIs.n30000644015216600007660000000117010066677543015045 0ustar syosisyosi@prefix dc: . <> dc:description """test that log:uri only gives URIs that somebody actually used, not variable names run it ala: python cwm.py --rdf test/animal.rdf --n3 test/vblsNotURIs.n3 --think """; dc:version "$Id: vblsNotURIs.n3,v 1.3 2004/06/25 01:26:59 timbl Exp $". @prefix d12: . @prefix log: . @prefix : <#>. @forAll :i, :o. :x d12:restrictedBy [ a :Something ]. { [] d12:restrictedBy :o } log:implies { :o a :Found }. { [] d12:restrictedBy :o. :o log:uri :i } log:implies { :o :called :i }. cwm-1.2.1/test/regression.n30000644015216600007660000005542310713412507015027 0ustar syosisyosi# List of regression tests # # - was in bash script retest.sh # @prefix : <#>. @prefix x: <#>. @prefix test: . @prefix dc: . # yuk - under protest - no hash # a test:CwmProofTest must have output in N3. It can't use --rdf=T etc for input. # retest.py will run a test as a proof test with -p if it is a test:CwmProofTest. :t1001 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Parse a small RDF file, generate N3"; test:arguments """-rdf animal.rdf -n3""". :t1001b a test:CwmTest; test:referenceOutput ; test:description "Ignore superfluous #stuff at end of URI"; test:arguments """ ref/animal.n3#something """ . :t1001a a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Read a data: uri"; test:arguments """'data:text/rdf+n3;charset=utf-8;base64,QHByZWZpeCBsb2c6IDxodHRwOi8vd3d3LnczLm9yZy8yMDAwLzEwL3N3YXAvbG9nIz4gLgp7fSA9PiB7OmEgOmIgOmN9IC4g'""". :t1002 a test:CwmTest; test:referenceOutput ; test:description "Parse a small RDF file and regenerate RDF"; test:arguments """-rdf=z animal.rdf""". :t1002a a test:CwmTest; test:referenceOutput ; test:description "Do not redefine the xml: prefix"; test:arguments """--n3 xml-syntax/xml_prefix.n3 --rdf""". :t1002b a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Allow for relative xml:base"; test:arguments """--rdf xml-syntax/xmlbase3.rdf --n3""". :t1002c a test:CwmTest; test:referenceOutput ; test:description "do not redefine xml: and xmlns: even if told to"; test:arguments """--n3 xml-syntax/xml_prefix2.n3 --rdf""". :t1002d a test:CwmTest; test:referenceOutput ; test:description "Allow for redefinition of rdf:"; test:arguments """--n3 xml-syntax/rdf_prefix.n3 --rdf""". :t1002e a test:CwmTest; test:referenceOutput ; test:description "rdf:parseType=\"Literal\""; test:arguments """--rdf xml-syntax/xmllit.rdf --ntriples""". :t1003 a test:CwmTest; test:referenceOutput ; test:description "Parse RDF embedded in foreign XML"; test:arguments """--rdf=T xml-syntax/in-xml.xml -n3""". :t1004 a test:CwmTest; test:referenceOutput ; test:description "Ignore RDF embedded in foreign XML -> empty formula"; test:arguments """--rdf xml-syntax/in-xml.xml -n3""". :t1005 a test:CwmTest; test:referenceOutput ; test:description "test generation of relative URIs"; test:arguments """reluri-1.n3 --rdf""". :t1005a a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "An N3 file with no final newline character"; test:arguments "syntax/no-last-nl.n3". :t1005b a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "combinations of - and _ in identifiers"; test:arguments "syntax/dot-dash.n3". :t1005c a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "@keywords in n3"; test:arguments "syntax/keywords1.n3". :t1005d a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "using no keywords in n3"; test:arguments "syntax/keywords2.n3". :t1005e a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "djb noticed a:b was parsed as rdf:type token"; test:arguments "syntax/djb1a.n3". #:t1005h a test:CwmTest; # test:referenceOutput ; # test:description "dumping data only fast with --ugly"; # test:arguments "daml-ex.n3 rules12.n3 --ugly". :t1006 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Parse and generate simple contexts"; test:arguments """contexts.n3""". :t1006a a test:CwmTest; test:referenceOutput ; test:description "reading data from stdin"; test:arguments """-rdf=z < animal.rdf""". :t1007 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Parse and regen anonymous property"; test:arguments """anon-prop.n3""". :t1007a a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Parse RDF/XML nodeID to N3"; test:arguments """--rdf nodeID/ex1.rdf --n3""". :t1007b a test:CwmTest; test:referenceOutput ; test:description "Parse RDF/XML nodeID and regen RDF/XML"; test:arguments """--rdf nodeID/ex1.rdf""". :t1007c a test:CwmTest; test:referenceOutput ; test:description "use nodeID's with classes"; test:arguments """nodeID/classes.n3 -rdf""". :t1007d a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "A loop of anonymous nodes wasn't being printed at all"; test:arguments """anonymous_loop.n3""". :t1008 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Convert some RDF/XML into RDF/N3"; test:arguments """daml-pref.n3 -rdf daml-ont.rdf -n3""". :t1008a a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "When rdf/xml localnames are not valid qNames"; test:arguments """--rdf syntax/colon-in-uri.rdf --n3""". :t1009 a test:CwmTest; test:referenceOutput ; test:description "N3 string quoting with escaping"; test:arguments """-n3=e strquot.n3""". # Now in i18n/detailed.tests # #:t1009a a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "N3 string, qname and IRI with utf-8 non-ascii characters"; # test:arguments "i18n/hiragana.n3". # #until i18n/detailed.tests are fully functional, the below will stay where it is :t1009aa a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "N3 string quoting with utf-8 literals"; test:arguments """-n3 strquot.n3""". :t1009ab a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "log:n3string genertating utf-8 literals was double encoding"; test:arguments """-n3 i18n/n3string.n3""". :t1009b a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "XML to XML with utf-8 non-ascii characters"; test:arguments "--rdf xml-syntax/non-ascii-pred.rdf". :t1010 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Path syntax, simple"; test:arguments """syntax/path1.n3""". :t1011 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Path syntax, more"; test:arguments """syntax/path2.n3""". :t10115 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Number syntax"; test:arguments "syntax/numbers.n3". :t10116 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Number syntax suppressed on output"; test:arguments "syntax/numbers.n3 --ntriples". #:t10117 a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "Number syntax to RDF output"; # test:arguments "syntax/numbers.n3 --rdf". :t1012 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Quick variable syntax, simple"; test:arguments """syntax/qvars1.n3""". :t1013 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Quick variable syntax, more"; test:arguments """syntax/qvars2.n3""". :t1014 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "N3 string nested triple quoting"; test:arguments """--n3 syntax/lstring.n3""". :t1015 a test:CwmTest; test:referenceOutput ; test:description "conversion of N3 = to RDF"; test:arguments """-n3 equiv-syntax.n3 -rdf""". :t1016 a test:CwmTest; test:referenceOutput ; test:description "Pipe mode for flat rdf and flat n3 to n3"; test:arguments """--pipe --rdf animal.rdf owl-ex.rdf smush-examples.rdf --n3 daml-ont.n3""". :t1017 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "parsing and generation of N3 list syntax"; test:arguments """-n3 lists.n3""". :t1018 a test:CwmTest; test:referenceOutput ; test:description "conversion of subset of N3 list syntax to RDF"; test:arguments """-n3 lists-simple.n3 -rdf""". :t1018a1 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "make sure typeNodes in RDF/XML Collections are parsed"; test:arguments """-rdf list/itemType.rdf -n3""". #:t1018b1 a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "List processing bug check 1"; # test:arguments """list/list-bug1.n3 --think""". # #:t1018b2 a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "List processing bug check 2"; # test:arguments """list/list-bug2.n3 --think""". :t1019 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Avoiding default namespace on attrs"; test:arguments """-rdf norm/fix.rdf""". :t1020 a test:CwmTest; test:referenceOutput ; test:description "Avoiding default namespace on attrs"; test:arguments """-rdf norm/fix.rdf -rdf=d""". :t1021 a test:CwmTest; test:referenceOutput ; test:description "Avoiding default namespace on attrs"; test:arguments """-rdf norm/fix.rdf -rdf=p""". :t1022 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Early DAML (now OWL) example in XML/RDF"; test:arguments """-rdf owl-ex.rdf -n3""". # Test log:implies rules: :t1023 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "log:implies Rules - try one iteration first."; test:arguments """rules12.n3 -rules""". :t1024 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "log:implies rules, iterating"; test:arguments """rules12.n3 -think""". :t1024a a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "match same variable twice in one statement"; test:arguments """unify/reflexive.n3 -think""". # Removed, because the set of things done on --rules is rather indeterminate # in the case of a file in which ne rule can lead to another. #:t1025 a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "log:implies rules more complex, with means, once"; # test:arguments """--closure=T rules13.n3 --rules""". :t1026 a test:CwmTest; test:referenceOutput ; test:description "log:implies and log:Truth rules, with means, many times"; test:arguments """--closure=T rules13.n3 --think --data""". :t1027 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "test different rules giving same result"; test:arguments """two-route.n3 -think""". :t1028 a test:CwmTest; test:referenceOutput ; test:description "Schema validity 1"; test:arguments """--closure=T daml-ex.n3 invalid-ex.n3 schema-rules.n3 -think""". :t1029 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Schema validity using filtering out essential output"; test:arguments """daml-ex.n3 invalid-ex.n3 schema-rules.n3 -think -filter=schema-filter.n3""". :t1029a a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "the --solve= option"; test:arguments """daml-ex.n3 invalid-ex.n3 schema-rules.n3 --solve=schema-filter.n3""". :t1029b a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "log:filter should do the same thing as --filter"; test:arguments """log-filter.n3 --think --data""". :t1029c a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "--filter should work with bnodes"; test:arguments "query/filter-bnodes.n3 --filter=query/trivial-filter.n3" . :t1030 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "The scope of _:me should be the formula"; test:arguments """underbarscope.n3 --think""". :t103005 a test:CwmTest; test:referenceOutput ; test:description "Generation of var. exist'ly quant'd in nested formulae"; test:arguments """includes/genBnodeInNestedFormula.n3 --think""". # Test output flags :t10301a a test:CwmTest; test:referenceOutput ; test:description "Test the --ntriples output flag"; test:arguments "--rdf animal.rdf --ntriples". :t10301b a test:CwmTest; test:referenceOutput ; test:description "Test the --n3=a output flag"; test:arguments "rules12.n3 --n3=a". :t10301c a test:CwmTest; test:referenceOutput ; test:description "Test the --n3=t output flag"; test:arguments "rules12.n3 --n3=t". # Test list handling #:t1031 a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "Inference using lists"; # test:arguments """list/r1.n3 -think""". #:t1032 a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "Iterative ops on lists"; # test:arguments """list/gk3.n3 -think""". #:t1032a a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "Query with list with the same var in >once"; # test:arguments """list/double.n3 -think""". # Test builtins: :t1033 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Simple use of log:includes"; test:arguments """includes/t1.n3 -think""". :t1034 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Simple use of log:includes"; test:arguments """includes/t2.n3 -think""". :t1035 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Simple use of log:includes"; test:arguments """includes/t3.n3 -think""". :t1036 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Simple use of log:includes - negative test"; test:arguments """includes/t4.n3 -think""". :t1037 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Simple use of log:includes"; test:arguments """includes/t6.n3 --think""". # Can't query query for "forall x" 2003-07-28 #:t1038 a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "Simple use of log:includes"; # test:arguments """includes/t7.n3 --think""". :t1039 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Simple use of string built-ins"; test:arguments """includes/t8.n3 --think""". :t1039a a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Builtins and log:includes"; test:arguments """includes/builtins.n3 --think --data""". :t1040 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Filter event by date using strcmp BI's"; test:arguments """includes/t9br.n3 -think""". :t1041 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "log:resolvesTo and log:includes"; test:arguments """includes/t10.n3 -think""". :t1042 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "log:resolvesTo and log:includes - schema checking"; test:arguments """includes/t11.n3 -think""". :t1044 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "log:includes handling of univ./exist. quantifiers"; test:arguments """includes/quantifiers_limited.n3 --think --purge-rules""". :t1045 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "log:implies handling of quantifiers"; test:arguments """includes/quant-implies.n3 --think""". :t1046 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Test string concatetnation built-in"; test:arguments """includes/concat.n3 --think --data""". :t1047 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Dan's bug case with uri and startswith"; test:arguments """includes/uri-startswith.n3 -think""". :t1048 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "log:resolvesTo with RDF/xml syntax"; test:arguments """resolves-rdf.n3 -think""". :t1048a a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Cwm builtins should support most xsd datatypes"; test:arguments "includes/xsd.n3 --think --strings". :t1048b a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "trying to match log:uri of a non-string simply matches None"; test:arguments "includes/uri-object-invalid.n3 --think" . :t1049 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Smushing multiple descriptions of the same thing using log:lessThan, log:uri, daml:equivalentTo"; test:arguments """sameDan.n3 sameThing.n3 --think --apply=forgetDups.n3 --purge --n3="/" """. #:t10495 a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "Smushing multiple descriptions of the same thing using owl:equivalentTo and --closure=e"; # test:arguments """--closure=e sameDan.n3 on-add/unique.n3 --think --data""". :t10497 a test:CwmTest; test:referenceOutput ; test:description "Smushing things which are = using --closure=e"; test:arguments """--closure=e on-add/smush.n3 --data""". :t1050 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "basic ISo time handling functions"; test:arguments """time/t1.n3 --think --purge""". :t1050s a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "basic ISo time handling functions - stringy"; test:arguments """time/t1s.n3 --think --purge""". :t1051 a test:CwmTest; test:referenceOutput ; test:description "Data aggregation challenge from Jan 2001"; test:arguments """--rdf smush-examples.rdf --n3 smush-schema.n3 sameThing.n3 --think --apply=forgetDups.n3 --purge --filter=smush-query.n3 --rdf""". :t1052 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Should not get URIs of anonymous nodes"; test:arguments """--rdf animal.rdf --n3 vblsNotURIs.n3 --think""". :t1053 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "Parsing strings with n3ExprFor"; test:arguments """includes/n3ExprFor.n3 --think""". :t1054 a test:CwmTest; test:referenceOutput ; test:description "Read operating system environment variable"; test:environment "TEST_PARAMETER_1=TEST_VALUE_1"; test:arguments """os/environ.n3 -think""". :t1055 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "using notIncludes and --strings to make a graphviz file"; test:environment "TARGET=roadmap/test.graph"; test:arguments """roadmap/todot.n3 --think --strings""". :t1056 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "log:conjunction of formulae"; test:arguments """includes/conjunction.n3 --think""". :t1057 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "log:conclusion deductive closure"; test:arguments """includes/conclusion.n3 --think""". :t1058 a test:CwmTest; test:referenceOutput ; test:description "os:argv argument values"; test:arguments """os/argv.n3 --think --with foo bar baz""". :t1059 a test:CwmTest; test:referenceOutput ; test:description "os:argv argument other values"; test:arguments """os/argv.n3 --think --with boof""". :t1060 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "don't make QNames with more than 1 colon"; test:arguments """syntax/colon-no-qname.n3""". #:t1061 a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "literals & formulae can't be predicates"; # test:arguments """syntax/bad-preds.n3 --think""". :t1062 a test:CwmTest, test:CwmProofTest; test:referenceOutput ; test:description "simple test for log:dtlit"; test:arguments """dt/dtlit1.n3 --think""". :t1063 a test:CwmTest; test:referenceOutput ; test:description "extremely basic RDF serialization test"; test:arguments """xml-syntax/basic-serialization.n3 --rdf""". #:t3001 a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "Parse lbase, serialize as otter (no llyn involvement)"; # test:arguments """--language=lbase lbase/note-long-example.lbase --language=otter""". # Test proof generation -- see also the -p option of retest.py and all the test:CwmProofTest #:t2060 a test:CwmTest, test:CwmProofTest; # test:referenceOutput ; # test:description "Proof for one simple rule"; # test:arguments """reason/t5.n3 --think --base=foo --why""". #ends cwm-1.2.1/test/schema-rules.n30000644015216600007660000000562310453454063015240 0ustar syosisyosi# Schema validator in N3 # # There is not on the semantic web a single meaning of # the term "schema valid", as one can make different choices # about what information is used for validation, and what lengths # are gone to to try to find inconsitencies. In general, one cannot # for any set of rules, just prove that a document does not violate # a given set of constraints. However, we can set the bar at a # particular height. For example # - Retrieve schemata for any namesapces used in the target # - apply a given set of rules (a certian limite number of times?) # - check the result has no inconsistencies. # # The basic strategy is that which ontology systems seem to assume: # Find all classes to which everything belongs, and deduce things from that. # @prefix log: . @prefix daml: . @prefix rdfs: . @prefix : <#> . # For our use @prefix v: <#> . # Hint for others use # # This is what we will flag: :schemaInconsistency daml:subPropertyOf log:Falsehood . @forAll <#p>, <#p1>, <#p2>, # Properties <#c>, <#c1>, <#c2>. # Classes @forAll <#x>, <#y>, <#z> . # The following is a su bset of the properties of =, which should not need stating. # But cwm currently doesn't know a lot about = inherently. @@ { <#x> <#p1> <#y> . <#p1> = <#p2> . } log:implies {<#x> <#p2> <#y> } . # Duh # Can deduce RDFS from daml versions: # (The example uses daml: and the groups seems to change its mind on which is best) daml:subPropertyOf = rdfs:subPropertyOf . daml:subClassOf = rdfs:subClassOf . daml:range = rdfs:range . daml:domain = rdfs:domain . # Implication of transitivity: { <#p> a daml:TransitiveProperty . } log:implies { @forAll <#xx> , <#yx> , <#zx>. { <#xx> <#p> <#yx>. <#yx> <#p> <#zx>. } log:implies { <#xx> <#p> <#zx>} } . rdfs:subPropertyOf a daml:TransitiveProperty . rdfs:subClassOf a daml:TransitiveProperty . # Implication of subclass: { <#x> a <#c1>. <#c1> rdfs:subClassOf <#c2> . } log:implies { <#x> a <#c2> } . # Implication of subPropertyOf: { <#p1> has rdfs:range <#c>. <#p2> rdfs:subPropertyOf <#p1> . } log:implies { <#p2> has rdfs:range <#c> } . # Implication of Range and domain # From domain to range { <#p> rdfs:domain <#c>. <#x> <#p> <#y> . } log:implies { <#x> a <#c> } . { <#p> rdfs:range <#c>. <#x> <#p> <#y> . } log:implies { <#y> a <#c> } . # From the above once can conclude the specific propagation rules # for of subclasss and subproperties, such as: # #rule1 # log:forAll <#x> <#y> ; # a log:Truth; # = { # { <#x> rdfs:subProperty <#y>. <#y> rdfs:subProperty <#z>. } log:implies # { <#x> rdfs:subProperty <#z>. } # } . # The first NOT we come across is disjointWith: { <#x> a <#y> . <#x> a <#z> . <#y> daml:disjointFrom <#z> } log:implies { <#x> a v:schemaInconsistency } . # <> daml:imports . #?@@@@@@@@@@@ cwm-1.2.1/test/rules13.n30000644015216600007660000000170510070616352014137 0ustar syosisyosi# Test filter in N3 # @prefix log: . @prefix daml: . @prefix : <#> . @prefix rules: <#> . # Full DanC challenge @forAll <#a>, <#b>, <#p> . { <#p> a daml:TransitiveProperty . } :means { { @forAll <#x> , <#y> , <#z>. { <#x> <#p> <#y>. <#y> <#p> <#z>. } log:implies { <#x> <#p> <#z>. } } a log:Truth. } . # Intoduce a symmetric implication for convienience { <#a> :means <#b>. } log:implies { <#a> log:implies <#b> . <#b> log:implies <#a> . } . { <#a> log:implies <#b> . <#b> log:implies <#a> . } log:implies { <#a> :means <#b>. } . # and in fact, though it is not axiomatic... # #{ <#x> :means <#y>. } :means { <#x> log:implies <#y> . # <#y> log:implies <#x> . } . # <#ancestor> a daml:TransitiveProperty . # (Was the wrong way around for a long time, just confused people.) <#pa> <#ancestor> <#granpa> . <#bill> <#ancestor> <#pa> . #ends cwm-1.2.1/test/two-route.n30000644015216600007660000000151210066677543014620 0ustar syosisyosi# Double conclusion test # # I had/ve a problem that the engine would conclude a rule # and add it to the store even though it matched one already there. # This is a test case to get to the bottom of that one. # # cwm double-concludion.n3 -size -rules -size -rules -size # # should show the store not growing after the first application of the rules. # # @prefix log: . @prefix daml: . @prefix rdfs: . @prefix : . # For our use @prefix v: . # Hint for others use @forAll :x, :y, :z. # :sky :color :blue. :grass :color :blue. :sky :sounds :quiet. :grass :sounds :quiet. { :x :color :blue } log:implies { :x :is :relaxing }. { :x :sounds :quiet } log:implies { :x :is :relaxing }. #ends cwm-1.2.1/test/cwm/0000755015216600007660000000000010731073447013170 5ustar syosisyosicwm-1.2.1/test/cwm/fam-rules.n30000644015216600007660000000022610006500551015307 0ustar syosisyosi@prefix : . @keywords is, of, a. { ?x begat ?y } => { ?y ancestor ?x }. { ?x ancestor ?y. ?y ancestor ?z } => { ?x ancestor ?z }. #ends cwm-1.2.1/test/cwm/detailed.tests0000644015216600007660000000107610010231165016012 0ustar syosisyosi# List of regression tests # # Teset for cwm command line features # # Note: Command lines must be for running in the directory above. # @prefix : <#>. @prefix x: <#>. @prefix test: . @prefix dc: . # yuk - under protest - no hash :cwm001 a test:CwmTest; test:referenceOutput ; test:addressesProblemRaisedBy <>; test:description "Use think=rules.n3 to iterate using separate rules"; test:arguments """cwm/fam.n3 --think=cwm/fam-rules.n3""". #ends cwm-1.2.1/test/cwm/fam-thinkwith.ref0000644015216600007660000000174210006500551016426 0ustar syosisyosi @prefix : <#> . :albert :begat :bevan, :bill . :bertha :begat :carol, :charlie . :bevan :ancestor :albert; :begat :chaude, :christine . :bill :ancestor :albert; :begat :carol, :charlie . :carol :ancestor :albert, :bertha, :bill . :charlie :ancestor :albert, :bertha, :bill . :chaude :ancestor :albert, :bevan . :christine :ancestor :albert, :bevan; :begat :david, :diana, :douglas . :david :ancestor :albert, :bevan, :christine . :diana :ancestor :albert, :bevan, :christine . :douglas :ancestor :albert, :bevan, :christine . cwm-1.2.1/test/cwm/fam.n30000644015216600007660000000031210006500551014153 0ustar syosisyosi@prefix : . @keywords is, of, a. albert begat bill, bevan. bill begat carol, charlie. bertha begat carol, charlie. bevan begat chaude, christine. christine begat david, diana, douglas. #ends cwm-1.2.1/test/query/0000755015216600007660000000000010731073450013541 5ustar syosisyosicwm-1.2.1/test/query/filter-bnodes.n30000644015216600007660000000006610704677573016562 0ustar syosisyosi:a1 [] :c1 . [] :b2 :c2 . :a3 :b3 [] . :a4 :b4 ([]) . cwm-1.2.1/test/query/trivial-filter.n30000644015216600007660000000003410704677573016755 0ustar syosisyosi{?s ?p ?o} => {?s ?p ?o} . cwm-1.2.1/test/sparql/0000755015216600007660000000000010731073450013676 5ustar syosisyosicwm-1.2.1/test/sparql/data.n30000644015216600007660000000124110271235033015043 0ustar syosisyosi@prefix foaf: . @prefix rdf: . @prefix rdfs: . @prefix ex: . _:a foaf:name "Alice" . _:a foaf:homepage . _:a foaf:mbox "" . _:a ex:blurb "

My name is Alice

"^^rdf:XMLLiteral . _:a foaf:knows _:b . _:b foaf:name "Bob"@en . _:b foaf:mbox . _:b foaf:homepage . _:b ex:ageInYears 30 . _:b foaf:knows _:a . cwm-1.2.1/test/sparql/mixing_egl.n30000644015216600007660000001404610276520127016271 0ustar syosisyosi#Processed by Id: cwm.py,v 1.171 2005/07/12 18:47:01 syosi Exp # using base file:/home/syosi/mixing-eg1.xml # Notation3 generation by # notation3.py,v 1.180 2005/06/09 21:05:14 syosi Exp # Base was: file:/home/syosi/mixing-eg1.xml @prefix : <#> . @prefix rdfs: . @forSome :_g0 . a ; "Clifton Suspension Bridge over the River Avon in Bristol, England. The bridge was designed by the great Victorian engineer Isambard Kingdom Brunel. Although not visible here, the Clifton Gorge below the bridge is about 240 feet deep (73 metres). Taken by Adrian Pingstone in October 2003 and released to the public domain."; "Clifton Suspension Bridge over the River Avon in Bristol, England."; ; rdfs:seeAlso . "application/rdf+xml" . [ a ; ( [ a ; ( [ a ; "400 400" ] [ a ; "500 500" ] [ a ; "600 600" ] [ a ; "700 800" ] ); "The Clifton Suspension Bridge is a suspension bridge spanning the Avon Gorge and linking Clifton in Bristol to Leigh Woods in North Somerset. Designed by Isambard Kingdom Brunel, it is a distinctive landmark that is often used as a symbol of Bristol. It is a grade I listed building."; "Clifton Suspension Bridge"; "suspension"; ; ; :_g0 ] [ a ; ( [ a ; "600 800" ] [ a ; "600 700" ] ); "Bristol Temple Meads is a railway station in Bristol, England. It is situated about a mile south-east of the city centre, and is the main station for central Bristol. Bristol's other main-line station, Bristol Parkway, is situated on the northern outskirts of the town."; "Bristol Temple Meads railway station"; ; :_g0 ] ); "http://www.commonobjects.example.org/gmlrss/CommonObjectFramework.xsd" ]. :_g0 a ; [ a ; "1806-04-09"; "Portsmouth, England" ], [ a ; "1859-09-15" ]; "An important figure in the history of engineering, he was noted for the creation of the Great Western Railway, a series of famous steamships, and important bridges."; [ a ; ; "Marc Isambard Brunel"; "Sir" ]; ; "04-09"; ; "male"; ; "Isambard Kingdom Brunel" . #ENDS cwm-1.2.1/test/sparql/construct.sparql0000644015216600007660000000056710265100471017152 0ustar syosisyosiPREFIX foaf: PREFIX vcard: CONSTRUCT { ?x vcard:N _:v . _:v vcard:givenName ?gname . _:v vcard:familyName ?fname } WHERE { { ?x foaf:firstname ?gname } UNION { ?x foaf:givenname ?gname } . { ?x foaf:surname ?fname } UNION { ?x foaf:family_name ?fname } . } cwm-1.2.1/test/sparql/datatype.sparql0000644015216600007660000000014510352334020016725 0ustar syosisyosiPREFIX xsd: SELECT ?s WHERE { ?s ?p "b"^^xsd:string, "hi" } cwm-1.2.1/test/sparql/filter6.sparql0000644015216600007660000000036010267737351016507 0ustar syosisyosiPREFIX dc: PREFIX ns: SELECT ?title ?price WHERE { ?x ns:price ?price . FILTER ((?price < 30 || ((?x + 2) * 3) = "4") = false) . ?x dc:title ?title . } cwm-1.2.1/test/sparql/data_construct1.n30000644015216600007660000000026710466502001017235 0ustar syosisyosi@prefix foaf: . :a foaf:givenname "Alice" . :a foaf:family_name "Hacker" . _:b foaf:firstname "Bob" . _:b foaf:surname "Hacker" . cwm-1.2.1/test/sparql/optional1-result.n30000644015216600007660000000101210276214064017356 0ustar syosisyosi @prefix : . { "Bob" :bound "foafName" . :bound "mbox" . } a :Result . { "Eleanor" :bound "gname" . "Ella" :bound "foafName" . } a :Result . { "Alice" :bound "foafName", "gname" . "Hacker" :bound "fname" . :bound "mbox" . } a :Result . cwm-1.2.1/test/sparql/sparql_builtin1.n30000644015216600007660000000033510277134346017261 0ustar syosisyosi@prefix sparql: . @prefix log: . {(!log:semantics !sparql:semantics) sparql:query ?x} => {"1" log:outputString ?x} . cwm-1.2.1/test/sparql/datatype.n30000644015216600007660000000015710352336256015763 0ustar syosisyosi@prefix : . @prefix xsd: . :A :p1 "a" . :B :p2 "b"^^xsd:string, "hi" . cwm-1.2.1/test/sparql/example.rq0000644015216600007660000000057310267765735015724 0ustar syosisyosiPREFIX foaf: PREFIX ex: SELECT ?x ?hpage ?name ?mbox ?age ?blurb ?friend #FROM WHERE { ?x foaf:name ?name . ?x foaf:mbox ?mbox . ?x foaf:homepage ?hpage . ?x foaf:knows ?friend . OPTIONAL { ?x ex:ageInYears ?age } . OPTIONAL { ?x ex:blurb ?blurb } } # ORDER BY ?name cwm-1.2.1/test/sparql/optional.sparql0000644015216600007660000000054610256050147016754 0ustar syosisyosiPREFIX foaf: PREFIX vcard: SELECT ?foafName ?mbox ?gname ?fname WHERE { ?x foaf:name ?foafName . OPTIONAL { ?x foaf:mbox ?mbox } . OPTIONAL { ?x vcard:N ?vc . ?vc vcard:Given ?gname . OPTIONAL { ?vc vcard:Family ?fname } } } cwm-1.2.1/test/sparql/mixing_egl.rq0000644015216600007660000000130610277157422016373 0ustar syosisyosiPREFIX : PREFIX gml: PREFIX foaf: PREFIX cc: PREFIX rdf: PREFIX wikipedia: SELECT DISTINCT ?name ?desc ?featurepic ?maker ?makerpic ?license ?a ?b WHERE { [ :name ?name ; :description ?desc ; foaf:depiction ?featurepic ; foaf:isPrimaryTopicOf wikipedia:Clifton_Suspension_Bridge ; foaf:maker [ foaf:name ?maker; foaf:depiction ?makerpic ] ; :centerLine [ rdf:first [ gml:pos ?a ]; rdf:rest [ rdf:first [ gml:pos ?b]]] #. ] . ?featurepic cc:license ?license ; } cwm-1.2.1/test/sparql/notIncludes4-result.n30000644015216600007660000000022710277134346020037 0ustar syosisyosi @prefix : . { :bound "x" . } a :Result . cwm-1.2.1/test/sparql/construct1-result.n30000644015216600007660000000037610466502001017561 0ustar syosisyosi @prefix : . <#a> :N [ :familyName "Hacker"; :givenName "Alice" ] . [ :N [ :familyName "Hacker"; :givenName "Bob" ] ]. cwm-1.2.1/test/sparql/mixing-egl-result.n30000644015216600007660000000165210277134346017527 0ustar syosisyosi @prefix : . { "400 400" :bound "a" . "500 500" :bound "b" . "Clifton Suspension Bridge" :bound "name" . "Isambard Kingdom Brunel" :bound "maker" . "The Clifton Suspension Bridge is a suspension bridge spanning the Avon Gorge and linking Clifton in Bristol to Leigh Woods in North Somerset. Designed by Isambard Kingdom Brunel, it is a distinctive landmark that is often used as a symbol of Bristol. It is a grade I listed building." :bound "desc" . :bound "license" . :bound "featurepic" . :bound "makerpic" . } a :Result . cwm-1.2.1/test/sparql/filter6-result.n30000644015216600007660000000027210276214064017032 0ustar syosisyosi @prefix : . { "SPARQL Tutorial" :bound "title" . 42 :bound "price" . } a :Result . cwm-1.2.1/test/sparql/detailed.tests0000644015216600007660000000311510352335511016533 0ustar syosisyosi# List of regression tests # # - was in bash script retest.sh # @prefix : <#>. @prefix x: <#>. @prefix test: . :t1001 a test:CwmTest; test:referenceOutput ; test:description "sparql builtins from cwm"; test:arguments """-n3 sparql/sparql_builtin1.n3 --think --strings""". :t1002 a test:CwmTest; test:referenceOutput ; test:description "Command line use"; test:arguments """-n3 sparql/mixing_egl.n3 --sparql=sparql/mixing_egl.rq""". :t1003 a test:CwmTest; test:referenceOutput ; test:description "not inclusion of FILTER"; test:arguments """-n3 sparql/notIncludes4_data.n3 --sparql=sparql/notIncludes4.sparql""". :t1004 a test:CwmTest; test:referenceOutput ; test:description "CONSTRUCT"; test:arguments """-n3 sparql/data_construct1.n3 --sparql=sparql/construct.sparql""". :t1005 a test:CwmTest; test:referenceOutput ; test:description "complex FILTER expression with errors"; test:arguments """-n3 sparql/filter6_data.n3 --sparql=sparql/filter6.sparql""". :t1006 a test:CwmTest; test:referenceOutput ; test:description "OPTIONAL in query"; test:arguments """-n3 sparql/optional_data.n3 --sparql=sparql/optional.sparql""". :t1007 a test:CwmTest; test:referenceOutput ; test:description "OPTIONAL in query"; test:arguments """-n3 sparql/datatype.n3 --sparql=sparql/datatype.sparql""". #ends cwm-1.2.1/test/sparql/optional_data.n30000644015216600007660000000116410276520127016762 0ustar syosisyosi @prefix foaf: . @prefix rdf: . @prefix rdfs: . @prefix vcard: . _:a foaf:name "Alice" . _:a foaf:mbox . _:a vcard:N _:x . _:x vcard:Family "Hacker" . _:x vcard:Given "Alice" . _:b foaf:name "Bob" . _:b foaf:mbox . _:b foaf:N _:z . _:z vcard:Family "Hacker" . _:e foaf:name "Ella" . _:e vcard:N _:y . _:y vcard:Given "Eleanor" . cwm-1.2.1/test/sparql/filter6_data.n30000644015216600007660000000040510276520127016505 0ustar syosisyosi@prefix dc: . @prefix : . @prefix ns: . :book1 dc:title "SPARQL Tutorial" . :book1 ns:price 42 . :book2 dc:title "The Semantic Web" . :book2 ns:price 23 . cwm-1.2.1/test/sparql/notIncludes4_data.n30000644015216600007660000000005310274204036017500 0ustar syosisyosi@prefix : . :a :b :c . cwm-1.2.1/test/sparql/query1_result.rl0000644015216600007660000000372510717336013017071 0ustar syosisyosi http://example.com/swap/test/run#_bnode_0 <p xmlns="http://www.w3.org/1999/xhtml">My name is <em>Alice</em></p> Alice http://work.example.org/alice/ http://example.com/swap/test/run#_bnode_1 http://example.com/swap/test/run#_bnode_2 30 mailto:bob@work.example.org Bob http://work.example.org/bob/ http://example.com/swap/test/run#_bnode_3 cwm-1.2.1/test/sparql/notIncludes4.sparql0000644015216600007660000000016210274204036017472 0ustar syosisyosiPREFIX : SELECT * WHERE { OPTIONAL {?x :b :c FILTER (?x = :a) } # FILTER (!bound(?x)) } cwm-1.2.1/test/sparql/datatype-result.n30000644015216600007660000000021310352336276017272 0ustar syosisyosi @prefix : . { :bound "s" . } a :Result . cwm-1.2.1/test/daml-pref.n30000644015216600007660000000057107346026310014511 0ustar syosisyosi# Suitable prefixes for DAML-ONT etc @prefix rdf: . @prefix s: . @prefix daml: . @prefix dpo: . @prefix ex: . @prefix log: . cwm-1.2.1/test/contexts.n30000644015216600007660000000057307346025770014524 0ustar syosisyosi# Test data in notation3 http://www.w3.org/DesignIssues/Notation3.html # @prefix u: . @prefix : <#> . :assumption = { :fred u:knows :john . :john u:knows :mary .} . :conclusion = { :fred u:knows :mary . } . # The empty context is trivially true. # Check that we can input it and output it! :trivialTruth = { }. # ENDS cwm-1.2.1/test/roadmap/0000755015216600007660000000000010731073450014017 5ustar syosisyosicwm-1.2.1/test/roadmap/test.graph0000644015216600007660000000404010717716426016032 0ustar syosisyosi#Processed by Id: cwm.py,v 1.82 2001/11/15 22:11:23 timbl Exp # using base file:/cygdrive/c/devel/WWW/2001/04/roadmap/sw.rdf # Notation3 generation by # notation3.py,v 1.98 2001/11/15 22:11:24 timbl Exp # Base was: file:/cygdrive/c/devel/WWW/2001/04/roadmap/sw.rdf @prefix : . @prefix doc: . @prefix gv: . @prefix log: . @prefix rdf: . @prefix rm: . @prefix swws: . @prefix u: . @prefix v: . doc:version "$Id: test.graph,v 1.2 2007/11/18 02:01:58 syosi Exp $"; gv:digraph swws:theGraph . @forAll swws:n1, swws:n2, swws:p, swws:type, v:n1, v:n2, v:p, v:s . doc:version "$Id: test.graph,v 1.2 2007/11/18 02:01:58 syosi Exp $" . swws:k_dep a rm:current; gv:color "gold1"; gv:label "X depends on this"; gv:style "filled" . swws:k_something a rm:current; gv:color "gold1"; gv:label "the\\nspec X"; gv:style "filled"; rm:needs swws:k_dep . swws:theGraph gv:hasNode swws:k_dep, swws:k_something; gv:label "W3C Semantic Web Planned Components $Date: 2007/11/18 02:01:58 $"; gv:subgraph swws:key; swws:likes rm:current, rm:external, rm:goal, rm:planned, rm:prototyped, rm:subgoal . rm:needs a gv:EdgeProperty; gv:color "black" . rm:prototypes gv:color "green1"; gv:style "bold" . #ENDS cwm-1.2.1/test/roadmap/todot.n30000644015216600007660000001276010466115353015424 0ustar syosisyosi# Dot format generation with Default values for GraphViz properties # @prefix str: . @prefix os: . @prefix gv: . @prefix doc: . # Documentation control #@prefix contact: . # Contact address book @prefix log: . #@prefix s: . # RDF Schema #@prefix ont: . # Ontology #@prefix rm: . # @@@@@@@@@@@@@ @prefix w: . # Specs @prefix st: . @prefix : <#>. @prefix todot: <#>. # @prefix h: . @prefix rdf: . @prefix dc: . @prefix org: . # Vocab for org structure @forAll :a, :b, :c, :d, :e, :F, :g, :n, :n1, :n2, :p, :s, :s1, :s2, :s3, :s4, :u, :u1, :u2, :v, :x, :y, :z. # Should be moved to gv: schema: # # The default values are not actually used, only the fact that they exist. # gv:label gv:attributeName "label"; gv:default "?label?"; a gv:nodeAttribute; a gv:edgeAttribute. gv:color gv:attributeName "color"; gv:default "black"; a gv:nodeAttribute; a gv:edgeAttribute. gv:fontcolor gv:attributeName "fontcolor"; gv:default "black"; a gv:nodeAttribute. gv:fontname gv:attributeName "fontname"; gv:default "Times-Roman"; a gv:nodeAttribute. gv:shape gv:attributeName "shape"; gv:default "ellipse"; a gv:nodeAttribute. gv:style gv:attributeName "style"; gv:default "none"; a gv:nodeAttribute; a gv:edgeAttribute. gv:url gv:attributeName "url"; gv:default "none"; a gv:nodeAttribute. { :x log:uri [is os:baseAbsolute of [is os:environ of "TARGET"]] } log:implies { :x a :target_resource }. { :F is log:semantics of [a :target_resource] } log:implies { :F a :target }. # The following is the way historically the (a) root graph has been tagged using # <> gv:diGraph :whatever in the source. { :F a :target. :F log:includes {:x gv:digraph :g} } log:implies{:F :hasGraph :g. :g :source :x}. @prefix w3c: . #{ :x a :target_resource; log:semantics :F. # :F log:notIncludes { w3c:logic gv:fontcolor [] }} log:implies { :x a :OK1 }. # # #{ [a :target] log:notIncludes { w3c:logic gv:fontcolor [] }} log:implies { :foobar a :OK2 }. # # #{ :n log:equalTo w3c:logic. # :p log:equalTo gv:color. # [a :target] log:notIncludes { :n :p [] }} log:implies { :p :PROBLEM3 :n }. #{ :n log:equalTo w3c:logic. # :p log:equalTo gv:color. # [a :target] log:notIncludes { :n :p [] }} log:implies { :x a :PROBLEM35 }. # #{ :n log:equalTo w3c:logic. # :p a gv:nodeAttribute. # [a :target] log:notIncludes { :n :p [] }} log:implies { :p a :PROBLEM39 }. # #{ :n log:equalTo w3c:logic. # :p a gv:nodeAttribute. # [a :target] log:notIncludes { :n :p [] }} log:implies { :n :NODATAFOR :p }. # Rules for creating GraphViz input format: # # # Header: :result0 log:outputString """ /* transformed by: */ /* Id: rdf2dot.xsl,v 1.13 2001/05/23 19:46:25 connolly Exp */ digraph i__1483 { label="W3C Technology Roadmap"; """. # Nodes and default attributes: # The case where the value is not given, allow dot to supply default # though we could just as easily insert our own default value. { :F a :target; :hasGraph :g; log:includes { :g gv:hasNode :n. }. } log:implies { :F :includesNode :n }. { :p a gv:nodeAttribute. :F a :target . :F :includesNode :n; log:notIncludes { :n :p [] }. } log:implies { [:fornode :n; :property :p; :nstring ""] }. { [a :target] :includesNode :n; log:includes { :n :p :v}. :p a gv:nodeAttribute; gv:attributeName :x. ( :x "=\"" :v "\", " ) str:concatenation :s . } log:implies { [:fornode :n; :property :p; :nstring :s] }. # Declarations of nodes: { [a :target] :includesNode :n; log:includes {:n gv:label :x}. # Ignore nodes with no labels :n log:uri :u. [:fornode :n; :property gv:color; :nstring :s1]. [:fornode :n; :property gv:shape; :nstring :s2]. [:fornode :n; :property gv:style; :nstring :s3]. [:fornode :n; :property gv:url; :nstring :s4]. ( " \"" :u "\" [ label=\"" :x "\", " :s1 :s2 :s3 :s4 "];\n" ) str:concatenation :y. } log:implies { :result1 log:outputString :y. }. ########## Edges: { [a :target] log:includes { :p a gv:EdgeProperty }; log:notIncludes { :p :e [] }. :e a gv:edgeAttribute. } log:implies { [:edgeProp :p; :attribute :e; :string ""] }. { [a :target] log:includes { :p a gv:EdgeProperty; :e :v }. :e gv:attributeName :x. ( :x "=\"" :v "\", " ) str:concatenation :s . } log:implies { [:edgeProp :p; :attribute :e; :string :s] }. # Declarations of edges in dot format: { [a :target] :includesNode :n1, :n2; log:includes {:p a gv:EdgeProperty. :n1 :p :n2}. :n1 log:uri :u1. :n2 log:uri :u2. [ :edgeProp :p; :attribute gv:label; :string :s1]. [ :edgeProp :p; :attribute gv:color; :string :s2]. [ :edgeProp :p; :attribute gv:style; :string :s3]. ( "\"" :u1 "\" -> \"" :u2 "\"\n [" :s1 :s2 :s3 " ]\n" ) str:concatenation :x } log:implies { :result2 log:outputString :x }. # Trailer: :result9 log:outputString "\n}\n\n/* End of generated .dot file. */". # Cleanup: log:implies a log:Chaff. # ENDS cwm-1.2.1/test/animal.rdf0000644015216600007660000000103607302103277014333 0ustar syosisyosi Animal 2 cwm-1.2.1/test/sameDan.n30000644015216600007660000000206510066677543014227 0ustar syosisyosi@prefix dc: . @prefix contact: . @prefix rcs: . <> dc:description """rules for determining when two terms denote the same thing."""; rcs:id "$Id: sameDan.n3,v 1.3 2004/06/25 01:26:59 timbl Exp $"; dc:creator [ contact:fullName "Dan Connolly"; contact:homePage ; contact:mailbox ]; dc:relation ; #@@ or is dc:relation a class of properties? # should I be using rdfs:seeAlso? dc:rights "copyright (c) 2001 W3C (MIT, Keio, INRIA)". @prefix ont: . @prefix : <#>. contact:mailbox a ont:UnambiguousProperty. contact:homePageAddress a ont:UnambiguousProperty. [ contact:mailbox ] :hairColor :red. [ contact:mailbox ] :birthPlace :KC. @prefix log: . @forAll :x. { :x :hairColor :red; :birthPlace :KC } log:implies { :test1 a :Success }. cwm-1.2.1/test/strquot.n30000644015216600007660000000112610442042561014355 0ustar syosisyosi@prefix dc: . <#x> <#prop> "simple string". <#y> <#prop> """triple quoted string with newlines in it.""". <#z> <#prop> "string with \" escaped quote marks". <#zz> <#escapes> "\\\"\a\b\f\r\t\v". <#martin> <#surname> "D\u00fcrst". <> dc:description """testing string parsing in N3. Hmm... how much of this is in the primer? How much should be there? @@ Holding off on unicode until support in python is sufficiently deployed (e.g. python on tux doesn't grok, nor does pythonwin on TimBL's laptop). """. # $Id: strquot.n3,v 1.4 2006/06/07 20:24:46 syosi Exp $ cwm-1.2.1/test/anon-prop.n30000644015216600007660000000103507246472266014565 0ustar syosisyosi# $Id: anon-prop.n3,v 1.1 2001/02/26 15:22:30 connolly Exp $ # # I discovered a bug in cwm.py while writing # http://www.w3.org/2001/02pd/gv.n3 (rev/date) # at or before gv.n3,v 1.3 2001/02/22 06:17:55 # # notation3.py reads it in and spits out just what I'd expect # (by naming the anonymous node and using log:forSome) # but running it thru cwm.py -think causes the property # of the property to get lost altogether, and the anonymous # property gets a name without an existential quantifier. <#anySubj> [ <#propProp> "red" ] <#anyObj>. cwm-1.2.1/test/syntax/0000755015216600007660000000000010731073450013722 5ustar syosisyosicwm-1.2.1/test/syntax/colon-in-uri.rdf0000644015216600007660000000174110153657345016746 0ustar syosisyosi DrivenBy_CombustionTurbine A CAES air compressor is driven by combustion turbine Nerc cwm-1.2.1/test/syntax/decimal.n30000644015216600007660000000127610357046162015574 0ustar syosisyosi 132843470257498573895734985734891345872934592849874935738957 a :Integer1 . 132843470257498573895734985734891345872934592849874935738957.0 a :Decimal1 . 132843470257498573895734985734891345872934592849874935738957.293429048094934029483429058349058249058459034850 a :Decimal1 . 132843470257498573895734985734891345872934592849874935738957.293429048094934029483429058349058249058459034850e-4 a :Double2 . 132843470257498573895734985734891345872934592849874935738957e-4 a :Double2 . 1e0 a :Double3 . 1 a :Integer3 . 1.0 a :Decimal3 . 1.0000000000000000000000000000000000000000000000000000000000000000001 a :Decimal4 . 1.0000000000000000000000000000000000000000000000000000000000000000001e0 a :Double4 . cwm-1.2.1/test/syntax/decimal-ref.n30000644015216600007660000000113110357046162016334 0ustar syosisyosi @prefix : <#> . 1.0 a :Decimal3 . 1.0000000000000000000000000000000000000000000000000000000000000000001 a :Decimal4 . 132843470257498573895734985734891345872934592849874935738957.0 a :Decimal1 . 132843470257498573895734985734891345872934592849874935738957.29342904809493402948342905834905824905845903485 a :Decimal1 . 1.0e+00 a :Double3, :Double4 . 1.32843470257e+55 a :Double2 . 1 a :Integer3 . 132843470257498573895734985734891345872934592849874935738957 a :Integer1 . cwm-1.2.1/test/syntax/boolean.n30000644015216600007660000000035310365253630015607 0ustar syosisyosi@prefix xsd: . @keywords a, true . #true isNot false . :true a JustASymbol. true a TrueBoolean2. @false a :FalseBoolean2 . "1"^^xsd:boolean a TrueBoolean . "0"^^xsd:boolean a FalseBoolean . cwm-1.2.1/test/syntax/space-in-uri-ref.n30000644015216600007660000000016710445073315017240 0ustar syosisyosi @prefix : . a :C, :D . cwm-1.2.1/test/syntax/this-quantifiers-ref2.n30000644015216600007660000002235410453454070020327 0ustar syosisyosi @prefix : <#> . @prefix log: . log:implies a log:Chaff . { { :fee :bar :baz . } log:includes {:foo :bar :baz . } . } log:implies {:testa1d a :FAILURE . } . { { :fee :bar :baz . } log:includes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testa2d a :success . } . { { :fee :bar :baz . } log:includes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testa3d a :FAILURE . } . { { :fee :bar :baz . } log:notIncludes {:foo :bar :baz . } . } log:implies {:testa1nd a :success . } . { { :fee :bar :baz . } log:notIncludes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testa2nd a :FAILURE . } . { { :fee :bar :baz . } log:notIncludes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testa3nd a :success . } . { { :foo :bar :baz . } log:includes {:foo :bar :baz . } . } log:implies {:testa1 a :success . } . { { :foo :bar :baz . } log:includes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testa2 a :success . } . { { :foo :bar :baz . } log:includes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testa3 a :FAILURE . } . { { :foo :bar :baz . } log:notIncludes {:foo :bar :baz . } . } log:implies {:testa1n a :FAILURE . } . { { :foo :bar :baz . } log:notIncludes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testa2n a :FAILURE . } . { { :foo :bar :baz . } log:notIncludes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testa3n a :success . } . { { this log:forSome :fee . :fee :bar :baz . } log:includes {:foo :bar :baz . } . } log:implies {:testb1d a :FAILURE . } . { { this log:forSome :fee . :fee :bar :baz . } log:includes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testb2d a :success . } . { { this log:forSome :fee . :fee :bar :baz . } log:includes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testb3d a :FAILURE . } . { { this log:forSome :fee . :fee :bar :baz . } log:notIncludes {:foo :bar :baz . } . } log:implies {:testb1nd a :success . } . { { this log:forSome :fee . :fee :bar :baz . } log:notIncludes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testb2nd a :FAILURE . } . { { this log:forSome :fee . :fee :bar :baz . } log:notIncludes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testb3nd a :success . } . { { this log:forSome :foo . :foo :bar :baz . } log:includes {:foo :bar :baz . } . } log:implies {:testb1 a :FAILURE . } . { { this log:forSome :foo . :foo :bar :baz . } log:includes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testb2 a :success . } . { { this log:forSome :foo . :foo :bar :baz . } log:includes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testb3 a :FAILURE . } . { { this log:forSome :foo . :foo :bar :baz . } log:notIncludes {:foo :bar :baz . } . } log:implies {:testb1n a :success . } . { { this log:forSome :foo . :foo :bar :baz . } log:notIncludes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testb2n a :FAILURE . } . { { this log:forSome :foo . :foo :bar :baz . } log:notIncludes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testb3n a :success . } . { { this log:forAll :fee . :fee :bar :baz . } log:includes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testc2d a :success . } . { { this log:forAll :fee . :fee :bar :baz . } log:includes {:foo :bar :baz . } . } log:implies {:testc1d a :success . } . { { this log:forAll :fee . :fee :bar :baz . } log:includes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testc3d a :success . } . { { this log:forAll :fee . :fee :bar :baz . } log:notIncludes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testc2nd a :FAILURE . } . { { this log:forAll :fee . :fee :bar :baz . } log:notIncludes {:foo :bar :baz . } . } log:implies {:testc1nd a :FAILURE . } . { { this log:forAll :fee . :fee :bar :baz . } log:notIncludes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testc3nd a :FAILURE . } . { { this log:forAll :foo . :foo :bar :baz . } log:includes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testc2 a :success . } . { { this log:forAll :foo . :foo :bar :baz . } log:includes {:foo :bar :baz . } . } log:implies {:testc1 a :success . } . { { this log:forAll :foo . :foo :bar :baz . } log:includes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testc3 a :success . } . { { this log:forAll :foo . :foo :bar :baz . } log:notIncludes {this log:forSome :foo . :foo :bar :baz . } . } log:implies {:testc2n a :FAILURE . } . { { this log:forAll :foo . :foo :bar :baz . } log:notIncludes {:foo :bar :baz . } . } log:implies {:testc1n a :FAILURE . } . { { this log:forAll :foo . :foo :bar :baz . } log:notIncludes {this log:forAll :foo . :foo :bar :baz . } . } log:implies {:testc3n a :FAILURE . } . cwm-1.2.1/test/syntax/space-in-uri.n30000644015216600007660000000027110445041473016462 0ustar syosisyosi# See what a parser does with (a) a space and (b) an encoded space @prefix : . a :C. a :D. #ends cwm-1.2.1/test/syntax/base.n30000644015216600007660000000022710671555577015121 0ustar syosisyosi@base .
:b . @base . :b2 . @prefix : <#>. :b3 . #ends cwm-1.2.1/test/syntax/lstring.n30000644015216600007660000000177007472312011015650 0ustar syosisyosi# Just see whether this can be input and re-output # # usage: cwm lstring.n3 | cwm # @prefix : <#>. """ @prefix : . @prefix crypto: . @prefix log: . @prefix os: . @prefix string: . \"\"\" MzE5MDcKCjM2ODkyMzAyMDE1MzgwMjY2NTU5MzgzNjMyMDQyOTM1Mjc4MDk3MzAwNzE4ODMzOTY3 NTY3NTk1Njg5MjE2Mjk0NzkyMzUyNTQ3OTQzMjI4MjM2MDEwNjQwMTAyMjcxODk0OTY2MzgzNjQ1 NDQyODQ5Njg3MzUzOTM2NzAyMTI5NDgxNDg4MzIxMzUyODEyMTc1NjIxNjE0NjE5Mzk2MDY4MjE2 Nzk1MzY0NjAxNjE0MzM5NDYzOTIyMDMwMDE4NTEyODMyMTg0NDIyMzI3MzcxNzE5MjcxMzY0ODY1 MjEzMzU1OTc4Nzk0OTIyMzQ4NDU5NTUxMTQ2MTcyNjE0MTk3ODI2NTg0NDA2Mzg2OTQwMTcwNTE4 OTY0MDQzNzMxNzEyODc1OTk3NjAyNjE4ODUzNDQ1Mw=3D=3D \"\"\" a :RequestKey; :authorityName ; :junk "327462sjsdfjsakdhfkjsafd32164321" . """ a :test_string. #ends cwm-1.2.1/test/syntax/this-rules-ref2.n30000644015216600007660000000176310066677544017145 0ustar syosisyosi @prefix : <#> . @prefix daml: . @prefix log: . this log:forAll :a, :b, :p . :ancestor a daml:TransitiveProperty . :bill :ancestor :pa . :pa :ancestor :granpa . { :a :means :b . } log:implies {:a log:implies :b . :b log:implies :a . } . { :p a daml:TransitiveProperty . } :means {{ this log:forAll :x, :y, :z . { :x :p :y . :y :p :z . } log:implies {:x :p :z . } . } a log:Truth . } . { :a log:implies :b . :b log:implies :a . } log:implies {:a :means :b . } . cwm-1.2.1/test/syntax/djb1a.n30000644015216600007660000000013610006245352015142 0ustar syosisyosi@prefix : . @prefix a: . a:a a:b a:c. cwm-1.2.1/test/syntax/space-in-uri-rdf.rdf0000644015216600007660000000034710445041473017472 0ustar syosisyosi cwm-1.2.1/test/syntax/path1.n30000644015216600007660000000120407527433744015215 0ustar syosisyosi# Test the cwm builtins #@prefix rdf: . #@prefix s: . #@prefix daml: . @prefix fam: . #@prefix ex: . #@prefix log: . @prefix : . # Local stuff @prefix foo: . # Local stuff # Usage: See t10.n3 # # Output should conclude all test* a :success and no failures. # :albert!fam:mother fam:sister :auntieAnne . :albert^fam:father fam:sister :nieceBertha . #ends cwm-1.2.1/test/syntax/path2.n30000644015216600007660000000157210142267726015216 0ustar syosisyosi# Test the cwm path expressions #@prefix rdf: . @prefix s: . #@prefix daml: . @prefix fam: . @prefix lang: . @prefix log: . @prefix math: . #@prefix lang: . @prefix : . # Local stuff @prefix foo: . # Local stuff :albert!fam:mother :mentor!:inverse :auntieAnne . :albert :admires!:converse :grumpy. ("1" "2")!math:sum a :THREE. :x s:label "Help!"^lang:eng, "foo"^lang:fr . # "Au seccours!"^lang:fr. # Can one put paths inside lists? # yup. ( ! ^ ) <#relatedTo> ( !! ) . #ends cwm-1.2.1/test/syntax/no-last-nl.n30000644015216600007660000000001710066677544016165 0ustar syosisyosi . cwm-1.2.1/test/syntax/trailing-semicolon-ref.nt0000644015216600007660000000120410142251564020633 0ustar syosisyosi . _:L9C5 . _:L9C5 . _:L9C5 . cwm-1.2.1/test/syntax/colon-no-qname.n30000644015216600007660000000056610254356131017016 0ustar syosisyosi# QNames cannot have any colons other than the one separating the prefix from # the local name. Therefore, in dealing with , cwm should leave the # URI intact instead of trying to reduce it to a qname. # # Issue originally raised in the following bug: # http://lists.w3.org/Archives/Public/public-cwm-bugs/2004Nov/0011 @prefix a: . a:q . cwm-1.2.1/test/syntax/qvars1.n30000644015216600007660000000122707527433744015422 0ustar syosisyosi# Test the cwm quick variable expressions #@prefix rdf: . #@prefix s: . #@prefix daml: . #@prefix fam: . #@prefix lang: . #@prefix log: . #@prefix math: . #@prefix lang: . #@prefix : . # Local stuff #@prefix foo: . # Local stuff { ?a <#mother> ?b; <#sister> ?c } => { ?b <#aunt> ?c }. #ends cwm-1.2.1/test/syntax/base-ref.n30000644015216600007660000000051710671555637015672 0ustar syosisyosi @prefix : <#> . :b . :b2 . . cwm-1.2.1/test/syntax/detailed.tests0000644015216600007660000000432010713412510016552 0ustar syosisyosi# List of regression tests # # Syntax tests: details # # Note: Command lines must be for running in the directory above. # @prefix : <#>. @prefix x: <#>. @prefix test: . #:syn001 a test:ObsoleteCwmTest; # test:referenceOutput ; # test:description "Can still read the old 'this log:forSome' syntax. Removed 2007-07-07"; # test:arguments "syntax/this-quantifiers.n3". # #:syn002 a test:ObsoleteCwmTest; # test:referenceOutput ; # test:description "Can still read the old 'this log:forAll' syntax. Removed 2007-07-07"; # test:arguments "syntax/this-rules.n3". :syn000 a test:CwmTest; # 2007-09-11 test:referenceOutput ; test:description "The @base directive"; test:arguments "syntax/base.n3". :syn005 a test:CwmTest; test:referenceOutput ; test:description "Can still gen the old 'this log:forSome' syntax"; test:arguments "--n3=v includes/quantifiers.n3". :syn006 a test:CwmTest; test:referenceOutput ; test:description "Can still gen the old 'this log:forAll' syntax"; test:arguments "--n3=v rules13.n3". :syn007 a test:CwmTest; test:referenceOutput ; test:description "Propertylists can end in trailing semicolon."; test:arguments "--n3 syntax/trailing-semicolon.n3 --ntriples". :syn008 a test:CwmTest; test:referenceOutput ; test:description "Math datatypes are parsed and generated correctly"; test:arguments "--n3 syntax/decimal.n3". :syn009 a test:CwmTest; test:referenceOutput ; test:description "Adding true and false to n3"; test:arguments "--n3 syntax/boolean.n3". :syn010 a test:CwmTest; test:referenceOutput ; test:description "Canonicalize spaces in URIs (n3)"; test:arguments "--n3 --closure=n syntax/space-in-uri.n3". :syn011 a test:CwmTest; test:referenceOutput ; test:description "Canonicalize spaces in URIs (rdf/xml)"; test:arguments "--rdf --closure=n syntax/space-in-uri-rdf.rdf --n3". #ends cwm-1.2.1/test/syntax/keywords1.n30000644015216600007660000000044507740617245016133 0ustar syosisyosi # Test the cwm quick variable declarations @prefix : . # Local stuff @keywords . # Use no keywards @forAll :x, :y, :z. @forSome :a, :b, :c. b a c. # Should simply use a as a local symbol, NOT as rdf:type. #{ :x <#mother> :y. :y <#sister> :z } => { :x <#aunt> :z }. #ends cwm-1.2.1/test/syntax/keywords2.n30000644015216600007660000000050610653414735016126 0ustar syosisyosi # Test the cwm quick variable declarations @keywords. # Use no keywards @prefix : . # Local stuff @forAll x, y, z. @forSome a, b, c. b a c. # Should simply use a as a local symbol, NOT as rdf:type. # {x mother y. y sister z} => {x aunt z}. Comented out 7/7/7 - separate formula testing elsewhere #ends cwm-1.2.1/test/syntax/qvars2.n30000644015216600007660000000122607527433744015422 0ustar syosisyosi# Test the cwm quick variable expressions #@prefix rdf: . #@prefix s: . #@prefix daml: . #@prefix fam: . #@prefix lang: . #@prefix log: . #@prefix math: . #@prefix lang: . #@prefix : . # Local stuff #@prefix foo: . # Local stuff { ?b <#aunt> ?c } <= { [] <#parent> ?b; <#sister> ?c }. #ends cwm-1.2.1/test/syntax/trailing-semicolon.n30000644015216600007660000000032110142246131017751 0ustar syosisyosi# Test that you can have a final semicolon ';' in a propertylist # DJB pointed out that it is useful, # and it always was acceptable to the original n3 parser. @keywords. b c d;. e f [g h; i j;]. # ends cwm-1.2.1/test/syntax/boolean-ref.n30000644015216600007660000000032010365253630016353 0ustar syosisyosi @prefix : <#> . false a :FalseBoolean . true a :TrueBoolean . false a :FalseBoolean2 . true a :TrueBoolean2 . :true a :JustASymbol . cwm-1.2.1/test/syntax/numbers.n30000644015216600007660000000105510066677544015657 0ustar syosisyosi# Test number literals and some datatypes 2 <#is> "The integer 2". 00002 <#is> "The integer 2 expressed with leading zeroes". -2 <#is> "The integer -2". 0 <#is> "Zero". 2.0 <#is> "The number 2.0". 2.0000 <#is> "The number 2.0 expressed with extra trailing zeroes". # 2/3 <#is> "The raional number 2/3". 2.0e3 <#is> "The double precision floating point 2.0e3". "Le chat"@fr <#is> "The french phrase 'Le chat'". "800/600"^^ <#is> "800/600 with datatype http://example.com/types#rational". #ends cwm-1.2.1/test/syntax/dot-dash.n30000644015216600007660000000065607706054733015711 0ustar syosisyosi# test: make sure that the prefix isn't used when it can't be @prefix : . . . . #end cwm-1.2.1/test/dt/0000755015216600007660000000000010731073447013011 5ustar syosisyosicwm-1.2.1/test/dt/dtlit1.n30000644015216600007660000000023710222551064014445 0ustar syosisyosi@keywords is, of, a. @prefix : . @prefix log: . { ("2005-03-30T11:00:00" tz) log:dtlit ?X } => { ?X a Answer }. cwm-1.2.1/test/on-add/0000755015216600007660000000000010731073450013536 5ustar syosisyosicwm-1.2.1/test/on-add/smush.n30000644015216600007660000000134207726530230015143 0ustar syosisyosi# Smushing things which are = # @prefix : <#>. # Smush to labaleled nodes: :a :colour :Grey. :b a :Hatchback. :a = :b. # Two blank nodes: # A scholar and a gentleman. [ a :Scholar ] = [ a :Gentleman ] . :c :color :Gray. :color = :colour. :Grey = :Gray. # # Sush a blank node with labelled node = [ a :testFile ]. # Smush an existential _:bnode1 :called "Bnode1". _:bnode1 = :node1 . # Smush with Literals and Lists # vary order of declaration, type of thing :theTemperature = 34. :theTemperature :is :TooHot. :theHumidity :is :TooDamp. "86%" = :theHumidity. :vision :is :OkVision. :vision = ( 20 20 ). ( 1 2 3 ) = :firstThree . :firstThree :is :ListOfThreeNumbers. # :isa = rdf:type. #ends cwm-1.2.1/test/lists-simple.n30000644015216600007660000000154010022433415015255 0ustar syosisyosi# Test list syntax # # With no {} so it can be translated in DAML easily # @prefix t: . @prefix : . @prefix log: . # This is cheating a bit - in case output of # first and rest or equivalentTo is needed. @prefix dpo: . @prefix owl: . :a_threebrackets = ( ( ( :fff ) ) ) . [ :anonVerb12 :anonObj12 ] :verb12 :obj12. :threeItems = ( :b :c :d ) . :nested =( :first :second ( :left3 :right3 ) :fourth ) . :emptyList = ( ) . :listOf2Empties = (()()) . :twoAnons = ([a :mother][a :father]). () :verb0 :object0. ( "subj1" ) :verb1 :object1. ( "subj2a" "subj2b" ) :verb2 :object2. # Supressed: - see lists.n3 for version with this in # :twoFormulae = ({:a a :mother} {:b a :father}). #ENDS cwm-1.2.1/test/n3parser.tests0000644015216600007660000001421310653414734015225 0ustar syosisyosi@prefix : <#>. @prefix x: <#>. @prefix test: . @prefix dc: . # yuk - under protest - no hash @prefix n3test: . @prefix grammar: . :n3_10001 a n3test:PositiveParserTest; n3test:inputDocument ; n3test:outputDocument ; n3test:description "An N3 file with no final newline character" . :n3_10002 a n3test:PositiveParserTest; n3test:description "combinations of - and _ in identifiers"; n3test:outputDocument ; n3test:inputDocument . :n3_10003 a n3test:PositiveParserTest; n3test:description "@keywords in n3"; n3test:outputDocument ; n3test:inputDocument . :n3_10004 a n3test:PositiveParserTest; n3test:description "using no keywords in n3"; n3test:outputDocument ; n3test:inputDocument . :n3_10005 a n3test:PositiveParserTest; n3test:description "djb noticed a:b was parsed as rdf:type token"; n3test:outputDocument ; n3test:inputDocument . :n3_10006 a n3test:PositiveParserTest; n3test:description "we might as well be nice and self-referential"; n3test:outputDocument ; n3test:inputDocument <>. :n3_10007 a n3test:PositiveParserTest; n3test:description "Parse and generate simple contexts"; n3test:outputDocument ; n3test:inputDocument . :n3_10008 a n3test:PositiveParserTest; n3test:description "Parse and regen anonymous property"; n3test:outputDocument ; n3test:inputDocument . :n3_10009 a n3test:PositiveParserTest; n3test:description "N3 string quoting with escaping"; n3test:outputDocument ; n3test:inputDocument . :n3_10010 a n3test:PositiveParserTest; n3test:description "N3 string, qname and IRI with utf-8 non-ascii characters"; n3test:inputDocument . :n3_10011 a n3test:PositiveParserTest; n3test:description "Path syntax, simple"; n3test:outputDocument ; n3test:inputDocument . :n3_10012 a n3test:PositiveParserTest; n3test:description "Path syntax, more"; n3test:outputDocument ; n3test:inputDocument . :n3_10013 a n3test:PositiveParserTest; n3test:description "Number syntax"; n3test:outputDocument ; n3test:inputDocument . :n3_10014 a n3test:PositiveParserTest; n3test:description "Quick variable syntax, simple"; n3test:outputDocument ; n3test:inputDocument . :n3_10015 a n3test:PositiveParserTest; n3test:description "Quick variable syntax, more"; n3test:outputDocument ; n3test:inputDocument . :n3_10016 a n3test:PositiveParserTest; n3test:description "N3 string nested triple quoting"; n3test:outputDocument ; n3test:inputDocument . :n3_10017 a n3test:PositiveParserTest; n3test:description "parsing and generation of N3 list syntax"; n3test:outputDocument ; n3test:inputDocument . :n3_10018 a n3test:PositiveParserTest; n3test:description "Propertylists can end in trailing semicolon."; n3test:outputDocument ; n3test:inputDocument . :n3_10021 a n3test:PositiveParserTest; n3test:description "Are we exceeding a maximum recursion limit or two?"; n3test:inputDocument . :n3_10025 a n3test:PositiveParserTest; n3test:description "The = keyword"; # n3test:outputDocument ; n3test:inputDocument . :n3_10026 a n3test:PositiveParserTest; n3test:description "The = keyword"; # n3test:outputDocument ; n3test:inputDocument . :n3_10027 a n3test:PositiveParserTest; n3test:description "A statement that says nothing at all"; # n3test:outputDocument ; n3test:inputDocument . :n3_20028 a n3test:NegativeParserTest; n3test:description "A statement that says nothing at all"; # n3test:outputDocument ; n3test:inputDocument . :n3_20000 a n3test:NegativeParserTest; n3test:description "something that isn't n3"; n3test:inputDocument . :n3_20001 a n3test:NegativeParserTest; n3test:description "@keywords is not a valid predicate"; n3test:inputDocument . :n3_20002 a n3test:NegativeParserTest; n3test:description "single quoted strings are illegal"; n3test:inputDocument . :n3_20003 a n3test:NegativeParserTest; n3test:description "The `this' keyword is no longer legal "; n3test:inputDocument . :n3_20004 a n3test:NegativeParserTest; n3test:description "A predicate cannot be a literal, I hope"; n3test:inputDocument . :n3_20005 a n3test:NegativeParserTest; n3test:description "A predicate cannot be a formula, I hope"; n3test:inputDocument . :n3_10019 a n3test:NegativeParserTest; n3test:description "Can still read the old 'this log:forSome' syntax?"; n3test:outputDocument ; n3test:inputDocument . :n3_10020 a n3test:NegativeParserTest; n3test:description "Can still read the old 'this log:forAll' syntax"; n3test:outputDocument ; n3test:inputDocument . cwm-1.2.1/test/lists.n30000644015216600007660000000075207724163436014014 0ustar syosisyosi# Test list syntax # @prefix t: . @prefix : . @prefix ont: . :threeItems = ( :b :c :d ) . :nested =( :first :second ( :left3 :right3 ) :fourth ) . :emptyList = ( ) . :listOf2Empties = (()()) . :twoAnons = ([a :mother][a :father]). () :verb0 :object0. ( "subj1" ) :verb1 :object1. ( "subj2a" "subj2b" ) :verb2 :object2. # N3 only: ( 1 ) <#linksEqualLists> ( 1 ) . :twoFormulae = ({:a a :mother} {:b a :father}). #ENDS cwm-1.2.1/test/resolves-rdf.n30000644015216600007660000000053110066677543015266 0ustar syosisyosi@prefix : <#>. @prefix log: . @prefix u: . @forAll :x. #{ log:semantics [ log:includes { :x a u:Class } ]} # log:implies { :x a :ClassInrdfs_n3 }. { log:semantics [ log:includes { :x a u:Class } ]} log:implies { :x a :ClassInAnimal_rdf }. cwm-1.2.1/test/daml-ex.n30000644015216600007660000000571607302103577014202 0ustar syosisyosi#Processed by Id: cwm.py,v 1.44 2001/05/19 03:39:00 timbl Exp # using base file:/cygdrive/c/devel/WWW/2000/10/swap/test/daml-ex.rdf # Notation3 generation by # notation3.py,v 1.76 2001/05/19 03:39:00 timbl Exp # Base was: file:/cygdrive/c/devel/WWW/2000/10/swap/test/daml-ex.rdf @prefix rdf: . @prefix daml: . @prefix : <#> . @prefix ex: <#> . :Adam a daml:Person; daml:comment "Adam is a person."; daml:label "Adam" . :Animal a daml:Class; daml:comment """This class of animals is illustrative of a number of ontological idioms."""; daml:label "Animal" . :Car a daml:Class; daml:comment "no car is a person"; daml:subClassOf [ a daml:Class; daml:complementOf :Person ] . :Female a daml:Class; daml:disjointFrom :Male; daml:subClassOf :Animal . :Height a daml:Class; daml:oneOf ( :short :medium :tall ) . :Male a daml:Class; daml:subClassOf :Animal . :Man a daml:Class; daml:subClassOf :Male, :Person . :Person a daml:Class; daml:comment "every person is a man or a woman"; daml:disjointUnionOf ( :Man :Woman ); daml:restrictedBy [ a daml:Restriction; daml:onProperty :parent; daml:toClass :Person ]; daml:subClassOf :Animal . :TallMan a daml:Class; daml:intersectionOf ( :TallThing :Man ) . :TallThing a daml:Class; daml:restrictedBy [ a daml:Restriction; daml:onProperty :height; daml:toValue :tall ] . :Woman a daml:Class; daml:subClassOf :Female, :Person . :ancestor a daml:TransitiveProperty; daml:label "ancestor" . :child a daml:Property; daml:inverseOf :parent . :descendant a daml:TransitiveProperty . :father a daml:Property; daml:cardinality "1"; daml:range :Man; daml:subProperty :parent . :height a daml:Property; daml:domain :Person; daml:range :Height . :mom a daml:Property; = :mother . :mother a daml:UniqueProperty; daml:range :Woman; daml:subProperty :parent . :occupation a daml:Property; daml:maxCardinality "1" . :parent a daml:Property; daml:cardinality "2"; daml:domain :Animal . <> a daml:Ontology; daml:comment "An example ontology"; daml:imports ; daml:versionInfo "$Id: daml-ex.n3,v 1.5 2001/05/21 03:11:59 timbl Exp $" . #ENDS cwm-1.2.1/test/sets/0000755015216600007660000000000010731073450013352 5ustar syosisyosicwm-1.2.1/test/sets/set_ops.n30000644015216600007660000000132610174767530015304 0ustar syosisyosi@prefix set: . @prefix log: . {$ :a, :b $} a :Set . {$ 1, 2 $} a :Set . {$ :a, 1 $} a :Set . { ?x a :Set . ?y a :Set . ?x log:notEqualTo ?y . (?x ?y) set:union ?z . } => {?z a :Union; :unionOf (?x ?y)} . { ?x a :Set . ?y a :Set . ?x log:notEqualTo ?y . (?x ?y) set:symmetricDifference ?z . } => {?z a :SymmetricDifference; :symmetricDifferenceOf (?x ?y)} . { ?x a :Set . ?y a :Set . ?x log:notEqualTo ?y . (?x ?y) set:difference ?z . } => {?z a :Difference; :differenceOf (?x ?y)} . { ?x a :Set . ?y a :Set . ?x log:notEqualTo ?y . (?x ?y) set:intersection ?z . } => {?z a :intersection; :intersectionOf (?x ?y)} . cwm-1.2.1/test/sets/sets.n30000644015216600007660000000116010253053124014563 0ustar syosisyosi# Test Set syntax # @prefix t: . @prefix : . @prefix ont: . :threeItems = {$ :b, :c, :d $} . :theeDistinctItems = {$ :b, :c, :d, :c $}. :nested ={$ :first, :second, {$ :left3, :right3 $}, :fourth $} . :emptyList = {$ $} . :listOf2Empties = {${$$},{$$}$} . :twoAnons = {$[a :mother],[a :father]$}. {$$} :verb0 :object0. {$ "subj1" $} :verb1 :object1. {$ "subj2a", "subj2b" $} :verb2 :object2. # N3 only: {$ 1 $} <#linksEqualSets> {$ 1 $} . :twoFormulae = {$ {:a a :mother}, {:b a :father} $}. :setOfLists = {$ ( 1 2 ), (), ( 3 4 5 ) $}. #ENDS cwm-1.2.1/test/sets/sets-reified.n30000644015216600007660000000314510174772301016204 0ustar syosisyosi @prefix : . @prefix owl: . :emptyList = [ owl:oneOf () ] . :listOf2Empties = [ owl:oneOf ( [ owl:oneOf () ] ) ] . :nested = [ owl:oneOf ( :first :fourth :second [ owl:oneOf ( :left3 :right3 ) ] ) ] . :setOfLists = [ owl:oneOf ( () ( 1 2 ) ( 3 4 5 ) ) ] . :theeDistinctItems = [ owl:oneOf ( :b :c :d ) ] . :threeItems = [ owl:oneOf ( :b :c :d ) ] . :twoAnons = [ owl:oneOf ( [ a :mother ] [ a :father ] ) ] . :twoFormulae = [ owl:oneOf ( {:a a :mother . } {:b a :father . } ) ] . [ owl:oneOf (); :verb0 :object0 ]. [ owl:oneOf ( "subj1" ); :verb1 :object1 ]. [ owl:oneOf ( "subj2a" "subj2b" ); :verb2 :object2 ]. [ owl:oneOf ( 1 ); <#linksEqualSets> [ owl:oneOf ( 1 ) ] ]. cwm-1.2.1/test/sets/set-builtins.ref0000644015216600007660000001551610174772077016516 0ustar syosisyosi @prefix : <#> . @prefix owl: . [ owl:oneOf (); a :intersection; :intersectionOf ( [ owl:oneOf ( 1 2 ) ] [ owl:oneOf ( :a :b ) ] ), ( [ owl:oneOf ( :a :b ) ] [ owl:oneOf ( 1 2 ) ] ) ]. [ owl:oneOf ( 1 ); a :Difference, :intersection; :differenceOf ( [ owl:oneOf ( 1 :a ) ] [ owl:oneOf ( :a :b ) ] ); :intersectionOf ( [ owl:oneOf ( 1 2 ) ] [ owl:oneOf ( 1 :a ) ] ), ( [ owl:oneOf ( 1 :a ) ] [ owl:oneOf ( 1 2 ) ] ) ]. [ owl:oneOf ( 2 ); a :Difference; :differenceOf ( [ owl:oneOf ( 1 2 ) ] [ owl:oneOf ( 1 :a ) ] ) ]. [ owl:oneOf ( 1 2 ); a :Difference, :Set; :differenceOf ( [ owl:oneOf ( 1 2 ) ] [ owl:oneOf ( :a :b ) ] ) ]. [ owl:oneOf ( :a ); a :Difference, :intersection; :differenceOf ( [ owl:oneOf ( 1 :a ) ] [ owl:oneOf ( 1 2 ) ] ); :intersectionOf ( [ owl:oneOf ( 1 :a ) ] [ owl:oneOf ( :a :b ) ] ), ( [ owl:oneOf ( :a :b ) ] [ owl:oneOf ( 1 :a ) ] ) ]. [ owl:oneOf ( 1 :a ); a :Set ]. [ owl:oneOf ( 2 :a ); a :SymmetricDifference; :symmetricDifferenceOf ( [ owl:oneOf ( 1 2 ) ] [ owl:oneOf ( 1 :a ) ] ), ( [ owl:oneOf ( 1 :a ) ] [ owl:oneOf ( 1 2 ) ] ) ]. [ owl:oneOf ( 1 2 :a ); a :Union; :unionOf ( [ owl:oneOf ( 1 2 ) ] [ owl:oneOf ( 1 :a ) ] ), ( [ owl:oneOf ( 1 :a ) ] [ owl:oneOf ( 1 2 ) ] ) ]. [ owl:oneOf ( :b ); a :Difference; :differenceOf ( [ owl:oneOf ( :a :b ) ] [ owl:oneOf ( 1 :a ) ] ) ]. [ owl:oneOf ( 1 :b ); a :SymmetricDifference; :symmetricDifferenceOf ( [ owl:oneOf ( 1 :a ) ] [ owl:oneOf ( :a :b ) ] ), ( [ owl:oneOf ( :a :b ) ] [ owl:oneOf ( 1 :a ) ] ) ]. [ owl:oneOf ( :a :b ); a :Difference, :Set; :differenceOf ( [ owl:oneOf ( :a :b ) ] [ owl:oneOf ( 1 2 ) ] ) ]. [ owl:oneOf ( 1 :a :b ); a :Union; :unionOf ( [ owl:oneOf ( 1 :a ) ] [ owl:oneOf ( :a :b ) ] ), ( [ owl:oneOf ( :a :b ) ] [ owl:oneOf ( 1 :a ) ] ) ]. [ owl:oneOf ( 1 2 :a :b ); a :SymmetricDifference, :Union; :symmetricDifferenceOf ( [ owl:oneOf ( 1 2 ) ] [ owl:oneOf ( :a :b ) ] ), ( [ owl:oneOf ( :a :b ) ] [ owl:oneOf ( 1 2 ) ] ); :unionOf ( [ owl:oneOf ( 1 2 ) ] [ owl:oneOf ( :a :b ) ] ), ( [ owl:oneOf ( :a :b ) ] [ owl:oneOf ( 1 2 ) ] ) ]. cwm-1.2.1/test/sets/detailed.tests0000644015216600007660000000125010174772062016215 0ustar syosisyosi# List of regression tests # # - was in bash script retest.sh # @prefix : <#>. @prefix x: <#>. @prefix test: . :t1001 a test:CwmTest; test:referenceOutput ; test:description "parsing of N3 set syntax"; test:arguments """-n3 sets/sets.n3""". :t1002 a test:CwmTest; test:referenceOutput ; test:description "parsing of N3 set reified syntax"; test:arguments """ sets/sets-reified.n3""". :t1005 a test:CwmTest; test:referenceOutput ; test:description "cwm set builtins"; test:arguments """ sets/set_ops.n3 --think --data""". #ends cwm-1.2.1/test/retest.py0000755015216600007660000005515510717716425014304 0ustar syosisyosi#! /bin/python """Regression test harness for new versions of cwm python retrest.py Options: --testsFrom=uri -f uri Take test definitions from these files (in RDF/XML or N3 format) Or just by themselves at end of command line after options --normal -n Do normal tests, checking output NOW DEFAULT - NOT NEEDED --chatty -c Do tests with debug --chatty=100 (flag just check doesn't crash) --proof -p Do tests generating and cheking a proof (if a test:CwmProofTest) --start=13 -s 13 Skip the first 12 tests --verbose -v Print what you are doing as you go --ignoreErrors -i Print error message but plough on though more tests if errors found (Summary error still raised when all tests ahve been tried) --cwm=../cwm.py Cwm command is ../cwm --help -h Print this message and exit You must specify some test definitions, and normal or proofs or both, or nothing will happen. Example: python retest.py -n -f regression.n3 $Id: retest.py,v 1.45 2007/11/18 02:01:57 syosi Exp $ This is or was http://www.w3.org/2000/10/swap/test/retest.py W3C open source licence . """ from os import system, popen3 import os import sys import urllib # From PYTHONPATH equivalent to http://www.w3.org/2000/10 from swap import llyn from swap.myStore import load, loadMany, Namespace from swap.uripath import refTo, base from swap import diag from swap.diag import progress from swap.term import AnonymousNode rdf = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") test = Namespace("http://www.w3.org/2000/10/swap/test.n3#") n3test = Namespace("http://www.w3.org/2004/11/n3test#") rdft = Namespace("http://www.w3.org/2000/10/rdf-tests/rdfcore/testSchema#") triage = Namespace("http://www.w3.org/2000/10/swap/test/triage#") sparql_manifest = Namespace("http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#") sparql_query = Namespace("http://www.w3.org/2001/sw/DataAccess/tests/test-query#") dawg_test = Namespace("http://www.w3.org/2001/sw/DataAccess/tests/test-dawg#") import getopt import sys import re normal = 1 chatty = 0 proofs = 0 verbose = 0 no_action = 0 def localize(uri): """Get URI relative to where this lives""" from swap import uripath return uripath.refTo("http://www.w3.org/2000/10/swap/test/retest.py", uri) def problem(str): global ploughOn global problems sys.stderr.write(str + "\n") problems.append(str) if not ploughOn: sys.exit(-1) # raise RuntimeError(str) def usage(): print __doc__ from subprocess import Popen, call, PIPE def execute(cmd1, noStdErr=False): global verbose, no_action if verbose: print " "+cmd1 if no_action: return if noStdErr: stderr = file('/dev/null', 'w') else: stderr = None result = call(cmd1, shell=True, stderr=stderr) if result != 0: raise RuntimeError("Error %i executing %s" %(result, cmd1)) def diff(case, ref=None, prog="diff -Bbwu"): global verbose if ref == None: ref = "ref/%s" % case if diag.print_all_file_names: #for use in listing all files used in testing a = open('testfilelist','a') a.write(ref) a.write('\n') a.close() diffcmd = """%s %s ,temp/%s >,diffs/%s""" %(prog, ref, case, case) if verbose: print " ", diffcmd if no_action: result = 0 else: result = system(diffcmd) if result < 0: raise problem("Comparison fails: result %i executing %s" %(result, diffcmd)) if result > 0: print "Files differ, result=", result d = urllib.urlopen(",diffs/"+case) buf = d.read() if len(buf) > 0: if just_fix_it == 0: print "# If this is OK, cp ,temp/%s %s" %(case, ref) print "######### Differences from reference output:\n" + buf return 1 else: os.system("cp ,temp/%s %s" %(case, ref)) return 0 return result def rdfcompare3(case, ref=None): "Compare NTriples fieles using the cant.py" global verbose if ref == None: ref = "ref/%s" % case diffcmd = """python ../cant.py -d %s -f ,temp/%s >,diffs/%s""" %(ref, case, case) if verbose: print " ", diffcmd result = system(diffcmd) if result < 0: raise problem("Comparison fails: result %i executing %s" %(result, diffcmd)) if result > 0: print "Files differ, result=", result d = urllib.urlopen(",diffs/"+case) buf = d.read() if len(buf) > 0: # print "# If this is OK, cp ,temp/%s %s" %(case, ref) print "######### Differences from reference output:\n" + buf return 1 return result def rdfcompare2(case, ref1): """Comare ntriples files by canonicalizing and comparing text files""" cant = "python ../cant.py" ref = ",temp/%s.ref" % case execute("""cat %s | %s > %s""" % (ref1, cant, ref)) return diff(case, ref) def rdfcompare(case, ref=None): """ The jena.rdfcompare program writes its results to the standard output stream and sets its exit code to 0 if the models are equal, to 1 if they are not and to -1 if it encounters an error.

""" global verbose if ref == None: ref = "ref/%s" % case diffcmd = """java jena.rdfcompare %s ,temp/%s N-TRIPLE N-TRIPLE >,diffs/%s""" %(ref, case, case) if verbose: print " ", diffcmd result = system(diffcmd) if result != 0: raise problem("Comparison fails: result %s executing %s" %(result, diffcmd)) return result def main(): global verbose, proofs, chatty, normal, no_action start = 1 cwm_command='../cwm.py' python_command='python -tt' global ploughOn # even if error ploughOn = 0 global verbose verbose = 0 global just_fix_it just_fix_it = 0 if diag.print_all_file_names: a = file('testfilelist','w') a.write('') a.close() try: opts, testFiles = getopt.getopt(sys.argv[1:], "h?s:nNcipf:v", ["help", "start=", "testsFrom=", "no-action", "No-normal", "chatty", "ignoreErrors", "proofs", "verbose","overwrite","cwm="]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) output = None for o, a in opts: if o in ("-h", "-?", "--help"): usage() sys.exit() if o in ("-v", "--verbose"): verbose = 1 if o in ("-i", "--ignoreErrors"): ploughOn = 1 if o in ("-s", "--start"): start = int(a) if o in ("-f", "--testsFrom"): testFiles.append(a) if o in ("-n", "--no-action"): no_action = 1 if o in ("-N", "--No-normal"): normal = 0 if o in ("-c", "--chatty"): chatty = 1 if o in ("-p", "--proofs"): proofs = 1 if o in ("--overwrite",): just_fix_it = 1 if o in ("--cwm", "--the_end"): cwm_command=a assert system("mkdir -p ,temp") == 0 assert system("mkdir -p ,diffs") == 0 if proofs: assert system("mkdir -p ,proofs") == 0 tests=0 passes=0 global problems problems = [] REFWD="http://example.com/swap/test" WD = base()[:-1] #def basicTest(case, desc, args) if verbose: progress("Test files:", testFiles) kb = loadMany(testFiles, referer="") testData = [] RDFTestData = [] RDFNegativeTestData = [] perfData = [] n3PositiveTestData = [] n3NegativeTestData = [] sparqlTestData = [] # for fn in testFiles: # print "Loading tests from", fn # kb=load(fn) for t in kb.each(pred=rdf.type, obj=test.CwmTest): verboseDebug = kb.contains(subj=t, pred=rdf.type, obj=test.VerboseTest) u = t.uriref() ref = kb.the(t, test.referenceOutput) if ref == None: case = str(kb.the(t, test.shortFileName)) refFile = "ref/%s" % case else: refFile = refTo(base(), ref.uriref()) case = "" for ch in refFile: if ch in "/#": case += "_" else: case += ch # Make up test-unique temp filename description = str(kb.the(t, test.description)) arguments = str(kb.the(t, test.arguments)) environment = kb.the(t, test.environment) if environment == None: env="" else: env = str(environment) + " " testData.append((t, t.uriref(), case, refFile, description, env, arguments, verboseDebug)) for t in kb.each(pred=rdf.type, obj=rdft.PositiveParserTest): x = t.uriref() y = x.find("/rdf-tests/") x = x[y+11:] # rest for i in range(len(x)): if x[i]in"/#": x = x[:i]+"_"+x[i+1:] case = "rdft_" + x + ".nt" # Hack - temp file name description = str(kb.the(t, rdft.description)) # if description == None: description = case + " (no description)" inputDocument = kb.the(t, rdft.inputDocument).uriref() outputDocument = kb.the(t, rdft.outputDocument).uriref() status = kb.the(t, rdft.status).string good = 1 if status != "APPROVED": if verbose: print "\tNot approved: "+ inputDocument[-40:] good = 0 categories = kb.each(t, rdf.type) for cat in categories: if cat is triage.ReificationTest: if verbose: print "\tNot supported (reification): "+ inputDocument[-40:] good = 0 ## if cat is triage.ParseTypeLiteralTest: ## if verbose: print "\tNot supported (Parse type literal): "+ inputDocument[-40:] ## good = 0 if good: RDFTestData.append((t.uriref(), case, description, inputDocument, outputDocument)) for t in kb.each(pred=rdf.type, obj=rdft.NegativeParserTest): x = t.uriref() y = x.find("/rdf-tests/") x = x[y+11:] # rest for i in range(len(x)): if x[i]in"/#": x = x[:i]+"_"+x[i+1:] case = "rdft_" + x + ".nt" # Hack - temp file name description = str(kb.the(t, rdft.description)) # if description == None: description = case + " (no description)" inputDocument = kb.the(t, rdft.inputDocument).uriref() status = kb.the(t, rdft.status).string good = 1 if status != "APPROVED": if verbose: print "\tNot approved: "+ inputDocument[-40:] good = 0 categories = kb.each(t, rdf.type) for cat in categories: if cat is triage.knownError: if verbose: print "\tknown failure: "+ inputDocument[-40:] good = 0 if cat is triage.ReificationTest: if verbose: print "\tNot supported (reification): "+ inputDocument[-40:] good = 0 if good: RDFNegativeTestData.append((t.uriref(), case, description, inputDocument)) for t in kb.each(pred=rdf.type, obj=n3test.PositiveParserTest): u = t.uriref() hash = u.rfind("#") slash = u.rfind("/") assert hash >0 and slash > 0 case = u[slash+1:hash] + "_" + u[hash+1:] + ".out" # Make up temp filename description = str(kb.the(t, n3test.description)) # if description == None: description = case + " (no description)" inputDocument = kb.the(t, n3test.inputDocument).uriref() good = 1 categories = kb.each(t, rdf.type) for cat in categories: if cat is triage.knownError: if verbose: print "\tknown failure: "+ inputDocument[-40:] good = 0 if good: n3PositiveTestData.append((t.uriref(), case, description, inputDocument)) for t in kb.each(pred=rdf.type, obj=n3test.NegativeParserTest): u = t.uriref() hash = u.rfind("#") slash = u.rfind("/") assert hash >0 and slash > 0 case = u[slash+1:hash] + "_" + u[hash+1:] + ".out" # Make up temp filename description = str(kb.the(t, n3test.description)) # if description == None: description = case + " (no description)" inputDocument = kb.the(t, n3test.inputDocument).uriref() n3NegativeTestData.append((t.uriref(), case, description, inputDocument)) for tt in kb.each(pred=rdf.type, obj=sparql_manifest.Manifest): for t in kb.the(subj=tt, pred=sparql_manifest.entries): name = str(kb.the(subj=t, pred=sparql_manifest.name)) query_node = kb.the(subj=t, pred=sparql_manifest.action) if isinstance(query_node, AnonymousNode): data = '' for data_node in kb.each(subj=query_node, pred=sparql_query.data): data = data + ' ' + data_node.uriref() inputDocument = kb.the(subj=query_node, pred=sparql_query.query).uriref() else: data = '' inputDocument = query_node.uriref() j = inputDocument.rfind('/') case = inputDocument[j+1:] outputDocument = kb.the(subj=t, pred=sparql_manifest.result) if outputDocument: outputDocument = outputDocument.uriref() else: outputDocument = None good = 1 status = kb.the(subj=t, pred=dawg_test.approval) if status != dawg_test.Approved: print status, name if verbose: print "\tNot approved: "+ inputDocument[-40:] good = 0 if good: sparqlTestData.append((tt.uriref(), case, name, inputDocument, data, outputDocument)) for t in kb.each(pred=rdf.type, obj=test.PerformanceTest): x = t.uriref() theTime = kb.the(subj=t, pred=test.pyStones) description = str(kb.the(t, test.description)) arguments = str(kb.the(t, test.arguments)) environment = kb.the(t, test.environment) if environment == None: env="" else: env = str(environment) + " " perfData.append((x, theTime, description, env, arguments)) testData.sort() cwmTests = len(testData) if verbose: print "Cwm tests: %i" % cwmTests RDFTestData.sort() RDFNegativeTestData.sort() rdfTests = len(RDFTestData) rdfNegativeTests = len(RDFNegativeTestData) perfData.sort() perfTests = len(perfData) n3PositiveTestData.sort() n3PositiveTests = len(n3PositiveTestData) n3NegativeTestData.sort() n3NegativeTests = len(n3NegativeTestData) sparqlTestData.sort() sparqlTests = len(sparqlTestData) totalTests = cwmTests + rdfTests + rdfNegativeTests + sparqlTests \ + perfTests + n3PositiveTests + n3NegativeTests if verbose: print "RDF parser tests: %i" % rdfTests for t, u, case, refFile, description, env, arguments, verboseDebug in testData: tests = tests + 1 if tests < start: continue urel = refTo(base(), u) print "%3i/%i %-30s %s" %(tests, totalTests, urel, description) # print " %scwm %s giving %s" %(arguments, case) assert case and description and arguments cleanup = """sed -e 's/\$[I]d.*\$//g' -e "s;%s;%s;g" -e '/@prefix run/d' -e 's;%s;%s;g'""" % (WD, REFWD, cwm_command, '../cwm.py') if normal: execute("""CWM_RUN_NS="run#" %s %s %s --quiet %s | %s > ,temp/%s""" % (env, python_command, cwm_command, arguments, cleanup , case)) if diff(case, refFile): problem("######### from normal case %s: %scwm %s" %( case, env, arguments)) continue if chatty and not verboseDebug: execute("""%s %s %s --chatty=100 %s &> /dev/null""" % (env, python_command, cwm_command, arguments), noStdErr=True) if proofs and kb.contains(subj=t, pred=rdf.type, obj=test.CwmProofTest): execute("""%s %s %s --quiet %s --base=a --why > ,proofs/%s""" % (env, python_command, cwm_command, arguments, case)) execute("""%s ../check.py < ,proofs/%s | %s > ,temp/%s""" % (python_command, case, cleanup , case)) if diff(case, refFile): problem("######### from proof case %s: %scwm %s" %( case, env, arguments)) # else: # progress("No proof for "+`t`+ " "+`proofs`) # progress("@@ %s" %(kb.each(t,rdf.type))) passes = passes + 1 for u, case, name, inputDocument, data, outputDocument in sparqlTestData: tests += 1 if tests < start: continue urel = refTo(base(), u) print "%3i/%i %-30s %s" %(tests, totalTests, urel, name) inNtriples = case + '_1' outNtriples = case + '_2' try: execute("""%s %s %s --sparql=%s --filter=%s --filter=%s --ntriples > ',temp/%s'""" % (python_command, cwm_command, data, inputDocument, 'sparql/filter1.n3', 'sparql/filter2.n3', inNtriples)) except NotImplementedError: pass except: problem(str(sys.exc_info()[1])) if outputDocument: execute("""%s %s %s --ntriples > ',temp/%s'""" % (python_command, cwm_command, outputDocument, outNtriples)) if rdfcompare3(inNtriples, ',temp/' + outNtriples): problem('We have a problem with %s on %s' % (inputDocument, data)) passes += 1 for u, case, description, inputDocument, outputDocument in RDFTestData: tests = tests + 1 if tests < start: continue print "%3i/%i) %s %s" %(tests, totalTests, case, description) # print " %scwm %s giving %s" %(inputDocument, case) assert case and description and inputDocument and outputDocument # cleanup = """sed -e 's/\$[I]d.*\$//g' -e "s;%s;%s;g" -e '/@prefix run/d' -e '/^#/d' -e '/^ *$/d'""" % ( # WD, REFWD) execute("""%s %s --quiet --rdf=RT %s --ntriples > ,temp/%s""" % (python_command, cwm_command, inputDocument, case)) if rdfcompare3(case, localize(outputDocument)): problem(" from positive parser test %s running\n\tcwm %s\n" %( case, inputDocument)) passes = passes + 1 for u, case, description, inputDocument in RDFNegativeTestData: tests = tests + 1 if tests < start: continue print "%3i/%i) %s %s" %(tests, totalTests, case, description) # print " %scwm %s giving %s" %(inputDocument, case) assert case and description and inputDocument # cleanup = """sed -e 's/\$[I]d.*\$//g' -e "s;%s;%s;g" -e '/@prefix run/d' -e '/^#/d' -e '/^ *$/d'""" % ( # WD, REFWD) try: execute("""%s %s --quiet --rdf=RT %s --ntriples > ,temp/%s 2>/dev/null""" % (python_command, cwm_command, inputDocument, case)) except: pass else: problem("""I didn't get a parse error running python %s --quiet --rdf=RT %s --ntriples > ,temp/%s from test ^=%s I should have. """ % (cwm_command, inputDocument, case, u)) passes = passes + 1 for u, case, description, inputDocument in n3PositiveTestData: tests = tests + 1 if tests < start: continue print "%3i/%i) %s %s" %(tests, totalTests, case, description) # print " %scwm %s giving %s" %(inputDocument, case) assert case and description and inputDocument # cleanup = """sed -e 's/\$[I]d.*\$//g' -e "s;%s;%s;g" -e '/@prefix run/d' -e '/^#/d' -e '/^ *$/d'""" % ( # WD, REFWD) try: execute("""%s %s --grammar=../grammar/n3-selectors.n3 --as=http://www.w3.org/2000/10/swap/grammar/n3#document --parse=%s > ,temp/%s 2>/dev/null""" % (python_command, '../grammar/predictiveParser.py', inputDocument, case)) except RuntimeError: problem("""Error running ``python %s --grammar=../grammar/n3-selectors.n3 --as=http://www.w3.org/2000/10/swap/grammar/n3#document --parse=%s > ,temp/%s 2>/dev/null''""" % ('../grammar/predictiveParser.py', inputDocument, case)) passes = passes + 1 for u, case, description, inputDocument in n3NegativeTestData: tests = tests + 1 if tests < start: continue print "%3i/%i) %s %s" %(tests, totalTests, case, description) # print " %scwm %s giving %s" %(inputDocument, case) assert case and description and inputDocument # cleanup = """sed -e 's/\$[I]d.*\$//g' -e "s;%s;%s;g" -e '/@prefix run/d' -e '/^#/d' -e '/^ *$/d'""" % ( # WD, REFWD) try: execute("""%s %s ../grammar/n3-selectors.n3 http://www.w3.org/2000/10/swap/grammar/n3#document %s > ,temp/%s 2>/dev/null""" % (python_command, '../grammar/predictiveParser.py', inputDocument, case)) except: pass else: problem("""There was no error executing ``python %s --grammar=../grammar/n3-selectors.n3 --as=http://www.w3.org/2000/10/swap/grammar/n3#document --parse=%s > ,temp/%s'' There should have been one.""" % ('../grammar/predictiveParser.py', inputDocument, case)) passes = passes + 1 timeMatcher = re.compile(r'\t([0-9]+)m([0-9]+)\.([0-9]+)s') ## from test.pystone import pystones ## pyStoneTime = pystones()[1] for u, theTime, description, env, arguments in perfData: tests = tests + 1 if tests < start: continue urel = refTo(base(), u) print "%3i/%i %-30s %s" %(tests, totalTests, urel, description) tt = os.times()[-1] a = system("""%s %s %s --quiet %s >,time.out""" % (env, python_command, cwm_command, arguments)) userTime = os.times()[-1] - tt print """%spython %s --quiet %s 2>,time.out""" % \ (env, cwm_command, arguments) ## c = file(',time.out', 'r') ## timeOutput = c.read() ## c.close() ## timeList = [timeMatcher.search(b).groups() for b in timeOutput.split('\n') if timeMatcher.search(b) is not None] ## print timeList ## userTimeStr = timeList[1] ## userTime = int(userTimeStr[0])*60 + float(userTimeStr[1] + '.' + userTimeStr[2]) pyCount = pyStoneTime * userTime print pyCount if problems != []: sys.stderr.write("\nProblems:\n") for s in problems: sys.stderr.write(" " + s + "\n") raise RuntimeError("Total %i errors in %i tests." % (len(problems), tests)) if __name__ == "__main__": main() # ends cwm-1.2.1/test/forgetDups.n30000644015216600007660000000214010066677543014773 0ustar syosisyosi@prefix dc: . @prefix contact: . @prefix rcs: . <> dc:description """rules for forgetting things that are equal to other things. Usage: cwm ...data and rules... --think --apply=forgetDups.n3 --purge"""; rcs:id "$Id: forgetDups.n3,v 1.6 2004/06/25 01:26:59 timbl Exp $"; dc:creator [ contact:fullName "Dan Connolly"; contact:homePage ; contact:mailbox ]; dc:relation ; #@@ or is dc:relation a class of properties? # should I be using rdfs:seeAlso? dc:rights "copyright (c) 2001 W3C (MIT, Keio, INRIA)". @prefix log: . @prefix string: . @prefix : <#>. @forAll :x, :y, :z, :p, :q. @forAll :s1, :s2. { :x = :y. :x log:rawUri :s1. # Levelbreaker - cheats by looking at URI of bnode :y log:rawUri :s2. :s1 string:lessThan :s2. } log:implies { :y a log:Chaff. # :s2 :forgottenInFavorOf :s1 # diagnostic/audit info }. cwm-1.2.1/test/reluri-1.n30000644015216600007660000000055307315555707014317 0ustar syosisyosi@prefix p: . @prefix m: . p:GivenName "Fred"; p:hasEmail ; m:attending . m:homePage . cwm-1.2.1/test/log-filter.n30000644015216600007660000000061110453454063014704 0ustar syosisyosi@prefix log: . @prefix v: . @forAll :x, :y, :z . {(!log:semantics !log:semantics !log:semantics)!log:conjunction log:conclusion ?x . log:semantics ?y . (?x ?y) log:filter :z } => {:z a log:Truth} . { ?f a log:Truth . ?f log:includes {:x :y :z} . } => {:x :y :z} . cwm-1.2.1/test/equiv-syntax.n30000644015216600007660000000043007276256374015332 0ustar syosisyosi<#x> = <#y>. @prefix dc: . <> dc:description """testing = short-hand syntax in N3. I'm adding this test in particular to track changes regarding which DAML+OIL namespace we use. $Id: equiv-syntax.n3,v 1.1 2001/05/09 15:06:36 connolly Exp $ """. cwm-1.2.1/test/smush-examples.rdf0000644015216600007660000000216407326052173016054 0ustar syosisyosi MegaCorp Inc. MEGA Mr Mega 50 Ethical Business Shared Guidelines 1.1 cwm-1.2.1/test/daml-ont.n30000644015216600007660000002357507524227565014403 0ustar syosisyosi# Base URI of process is file:///dev/swap/test/ # Input from file:/dev/swap/test/daml-pref.n3 # Input from http://www.daml.org/2001/03/daml-ont # Notation3 generation by # $Id: daml-ont.n3,v 1.5 2002/08/07 14:32:21 timbl Exp $ @prefix : . @prefix ont: . @prefix rdfs: . @prefix rdf: . <> ont:versionInfo "$Id: daml-ont.n3,v 1.5 2002/08/07 14:32:21 timbl Exp $"; ont:imports ; a ont:Ontology . ont:first a ont:Property; ont:domain ont:List . ont:UniqueProperty a ont:Class; ont:label "UniqueProperty"; ont:comment """compare with maxCardinality=1; e.g. integer successor: if P is a UniqueProperty, then if P(x, y) and P(x, z) then y=z. aka functional. """; ont:subClassOf ont:Property . ont:subClassOf a ont:Property; ont:samePropertyAs . ont:unionOf a ont:Property; ont:label "unionOf"; ont:comment """ for unionOf(X, Y) read: X is the union of the classes in the list Y; i.e. if something is in any of the classes in Y, it's in X, and vice versa. cf OIL OR"""; ont:domain ont:Class; ont:range ont:List . ont:Disjoint a ont:Class; ont:label "Disjoint"; ont:subClassOf ont:List; ont:comment """for type(L, Disjoint) read: the classes in L are pairwise disjoint. i.e. if type(L, Disjoint), and C1 in L and C2 in L, then disjointWith(C1, C2). """ . ont:UnambiguousProperty a ont:Class; ont:label "UnambiguousProperty"; ont:comment """if P is an UnambiguousProperty, then if P(x, y) and P(z, y) then x=z. aka injective. e.g. if nameOfMonth(m, "Feb") and nameOfMonth(n, "Feb") then m and n are the same month. """; ont:subClassOf ont:Property . ont:intersectionOf a ont:Property; ont:comment """ for intersectionOf(X, Y) read: X is the intersection of the classes in the list Y; i.e. if something is in all the classes in Y, then it's in X, and vice versa. cf OIL AND"""; ont:domain ont:Class; ont:range ont:List . ont:restrictedBy a ont:Property; ont:label "restrictedBy"; ont:comment """for restrictedBy(C, R), read: C is restricted by R; i.e. the restriction R applies to c; if onProperty(R, P) and toValue(R, V) then for every i in C, we have P(i, V). if onProperty(R, P) and toClass(R, C2) then for every i in C and for all j, if P(i, j) then type(j, C2). """; ont:domain ont:Class; ont:range ont:Restriction . ont:minCardinality a ont:Property; ont:comment """for minCardinality(P, N) read: P has minimum cardinality N; i.e. everything x in the domain of P has at least N things y such that P(x, y). """; ont:domain ont:Property . ont:item a ont:Property; ont:comment """for item(L, I) read: I is an item in L; either first(L, I) or item(R, I) where rest(L, R)."""; ont:domain ont:List . ont:value a ont:Property; ont:samePropertyAs rdf:value . ont:cardinality a ont:Property; ont:label "cardinality"; ont:comment """for cardinality(P, N) read: P has cardinality N; i.e. everything x in the domain of P has N things y such that P(x, y). """; ont:domain ont:Property . ont:default a ont:Property; ont:label "default"; ont:comment """default(X, Y) suggests that Y be considered a/the default value for the X property. This can be considered documentation (ala label, comment) but we don't specify any logical impact. """ . ont:oneOf a ont:Property; ont:comment """for oneOf(C, L) read everything in C is one of the things in L; This lets us define classes by enumerating the members. """; ont:domain ont:Class; ont:range ont:List . ont:Restriction a ont:Class . ont:disjointWith a ont:Property; ont:label "disjointWith"; ont:comment """for disjointWith(X, Y) read: X and Y have no members in common. """; ont:domain ont:Class; ont:range ont:Class . ont:equivalentTo a ont:Property; ont:comment """for equivalentTo(X, Y), read X is an equivalent term to Y. """ . ont:TransitiveProperty a ont:Class . ont:Property a ont:Class; ont:sameClassAs rdf:Property . ont:Qualification a ont:Class . ont:sameClassAs a ont:Property; ont:subPropertyOf ont:equivalentTo, ont:subClassOf . ont:Thing a ont:Class; ont:label "Thing"; ont:comment "The most general class in DAML." . ont:List a ont:Class; ont:subClassOf rdf:Seq . ont:versionInfo a ont:Property; ont:label "versionInfo"; ont:comment """generally, a string giving information about this version; e.g. RCS/CVS keywords """ . ont:range a ont:Property; ont:samePropertyAs . ont:subPropertyOf a ont:Property; ont:samePropertyAs ; ont:subPropertyOf . ont:seeAlso a ont:Property; ont:samePropertyAs . ont:Class a ont:Class; ont:sameClassAs . ont:type a ont:Property; ont:samePropertyAs rdf:type . ont:Ontology a ont:Class; ont:label "Ontology"; ont:comment """An Ontology is a document that describes a vocabulary of terms for communication between (human and) automated agents. """ . ont:Nothing a ont:Class; ont:comment "the class with no things in it."; ont:complementOf ont:Thing . ont:maxCardinality a ont:Property; ont:label "maxCardinality"; ont:comment """for maxCardinality(P, N) read: P has maximum cardinality N; i.e. everything x in the domain of P has at most N things y such that P(x, y). """; ont:domain ont:Property . ont:label a ont:Property; ont:samePropertyAs . ont:onProperty a ont:Property; ont:comment """for onProperty(R, P), read: R is a restriction/qualification on P."""; ont:domain ont:Restriction, ont:Qualification; ont:range ont:Property . ont:hasValue a ont:Property; ont:label "hasValue"; ont:comment """for hasValue(Q, C), read: Q is a hasValue qualification to C."""; ont:domain ont:Qualification; ont:range ont:Class . ont:inverseOf a ont:Property; ont:comment """for inverseOf(R, S) read: R is the inverse of S; i.e. if R(x, y) then S(y, x) and vice versa."""; ont:domain ont:Property; ont:range ont:Property . ont:toValue a ont:Property; ont:comment "for toValue(R, V), read: R is a restriction to V."; ont:domain ont:Restriction; ont:range ont:Class . ont:Empty a ont:Class; ont:asClass ont:Nothing . ont:isDefinedBy a ont:Property; ont:samePropertyAs ; ont:subPropertyOf ont:seeAlso . ont:qualifiedBy a ont:Property; ont:label "qualifiedBy"; ont:comment """for qualifiedBy(C, Q), read: C is qualified by Q; i.e. the qualification Q applies to C; if onProperty(Q, P) and hasValue(Q, C2) then for every i in C, there is some V so that type(V, C2) and P(i, V). """; ont:domain ont:Class; ont:range ont:Qualification . ont:samePropertyAs a ont:Property; ont:subPropertyOf ont:equivalentTo, ont:subPropertyOf . ont:Literal a ont:Class; ont:sameClassAs . ont:rest a ont:Property; ont:domain ont:List; ont:range ont:List . ont:imports a ont:Property; ont:label "imports"; ont:comment """for imports(X, Y) read: X imports Y; i.e. X asserts the* contents of Y by reference; i.e. if imports(X, Y) and you believe X and Y says something, then you should believe it. Note: "the contents" is, in the general case, an il-formed definite description. Different interactions with a resource may expose contents that vary with time, data format, preferred language, requestor credentials, etc. So for "the contents", read "any contents". """ . ont:complementOf a ont:Property; ont:comment """ for complementOf(X, Y) read: X is the complement of Y; if something is in Y, then it's not in X, and vice versa. cf OIL NOT"""; ont:domain ont:Class; ont:range ont:Class . ont:toClass a ont:Property; ont:comment "for toClass(R, C), read: R is a restriction to C."; ont:domain ont:Restriction; ont:range ont:Class . ont:disjointUnionOf a ont:Property; ont:label "disjointUnionOf"; ont:domain ont:Class; ont:range ont:List; ont:comment """ for disjointUnionOf(X, Y) read: X is the disjoint union of the classes in the list Y: (a) for any c1 and c2 in Y, disjointWith(c1, c2), and (b) i.e. if something is in any of the classes in Y, it's in X, and vice versa. cf OIL disjoint-covered """ . ont:domain a ont:Property; ont:samePropertyAs . ont:comment a ont:Property; ont:samePropertyAs . cwm-1.2.1/test/includes/0000755015216600007660000000000010731073447014210 5ustar syosisyosicwm-1.2.1/test/includes/t4.n30000644015216600007660000000141210066677544015010 0ustar syosisyosi# Test the log:includes function @prefix rdf: . @prefix s: . @prefix daml: . @prefix dpo: . @prefix ex: . @prefix log: . @prefix : <#>. # Local stuff # Usage: cwm includes.n3 -think # # Output should conclude all test* a :success and no failures. # :thesis :is { <#theSky> <#is> <#blue> } . @forAll :x. #{ :thesis :is :x. :x log:includes {<#theSky> <#is> <#green>} } log:implies { :test4_bis a :FAILURE } . { :thesis :is :x. :x log:notIncludes {<#theSky> <#is> <#green>} } log:implies { :test4 a :success } . #ends cwm-1.2.1/test/includes/concat.n30000644015216600007660000000456310066677544015742 0ustar syosisyosi# Test the string:concatenation function # # The earlier tests were written with a historical string:concat which is the INVERSE!! # Please use string:concatenation -- or think of a better name for its inverse. #@prefix rdf: . #@prefix s: . #@prefix daml: . #@prefix dpo: . #@prefix ex: . @prefix log: . @prefix string: . @prefix : <#>. # Local stuff # Usage: cwm t13.n3 -think # # Output should conclude all test* a :success and no failures. # #@forAll :x. @forAll :x, :y, :z. { "" string:concat () } log:implies {:test13a a :success}. { :x string:concat () } log:implies {:emptyString :is :x}. { :emptyString :is "" } log:implies { :test13b a :success }. { :x string:concat ( "foo" ) } log:implies { :fooString :is :x }. { :fooString :is "foo" } log:implies { :test13c a :success }. { :x string:concat ("World" [string:concat ("W" "i" "d" "e")] "Web") } log:implies {:www :is :x}. { :www :is "WorldWideWeb" } log:implies { :test13d a :success }. { :x string:concat ("World" "Wide" "Web") } log:implies {:www2 :is :x}. { :www2 :is "WorldWideWeb" } log:implies { :test13e a :success }. { :x string:concat ("World" :y "Web"). :y string:concat ( "W" "I" "D""E"). } log:implies {:www3:is :x}. { :www3 :is "WorldWIDEWeb" } log:implies { :test13f a :success }. { "" log:equalTo [ string:concat () ] } log:implies {:test13g a :success}. { "one" log:equalTo [ string:concat () ] } log:implies {:test13a_bis a :FAILURE}. { "" log:equalTo [ string:concat ( "one" ) ].} log:implies {:test13b_bis a :FAILURE}. { "one" log:equalTo [ string:concat ( "World" "Wide" "Web" ) ]} log:implies {:test13c_bis a :FAILURE}. { :x is string:concatenation of ( "World" [is string:concatenation of ("W" "i" "d" "e")] "Web") } log:implies {:www5 :is :x}. { :www5 :is "WorldWideWeb" } log:implies { :test13h a :success }. { :test13a a :success. :test13b a :success. :test13c a :success. :test13d a :success. :test13e a :success. :test13f a :success. :test13g a :success. :test13h a :success. } log:implies { :TEST13 a :success }. log:implies a log:Chaff. # Purge will remove rules # ends cwm-1.2.1/test/includes/conclusion.n30000644015216600007660000000241510066677544016641 0ustar syosisyosi# Test the log:includes function @prefix rdf: . @prefix s: . @prefix daml: . @prefix dpo: . @prefix ex: . @prefix log: . @prefix foo: . # Local stuff @prefix : . # Local stuff @prefix local: . # Usage: cwm conclusion.n3 -think # # See also t10a.n3 foo.n3 # # Output should be (in "result" formula) the same as for the cwm command below. # @forAll :d, :x, :y, :F, :G. # Conjunction junction, what's your're function? - schoolhouse rock. # Conjunction of a list of formulae is the logical AND of them, ie # the set of statements which contains each of the statements in each of the # conjoined formulae. { ( [ is log:semantics of <../daml-ex.n3> ] [ is log:semantics of <../invalid-ex.n3> ] [ is log:semantics of <../schema-rules.n3> ] ) log:conjunction [ log:conclusion :G]} log:implies { :result :is :G }. # The above is a much more complicated way of writing the cwm # command line "cwm daml-ex.n3 invalid-ex.n3 schema-rules.n3 --think". # #ends cwm-1.2.1/test/includes/xsd.n30000644015216600007660000000063510174031724015245 0ustar syosisyosi@prefix log: . @prefix string: . @prefix math: . @prefix xsd: . @forAll :s, :x . {("CASH"^^xsd:string " IS "^^xsd:Name ("2"^^xsd:integer "3"^^xsd:unsignedShort)!math:product "\n") string:concatenation :s} => {"Here we go"^^xsd:string log:outputString :s} . cwm-1.2.1/test/includes/xsd.ref0000644015216600007660000000001210073304116015462 0ustar syosisyosiCASH IS 6 cwm-1.2.1/test/includes/uri-object-invalid.n30000644015216600007660000000032510073304116020126 0ustar syosisyosi @prefix : <#> . @prefix log: . @forAll :y . { :y log:uri <> . } log:implies {:y a :TEST_RESULT . } . cwm-1.2.1/test/includes/list-in-ref.n30000644015216600007660000000055210160717036016600 0ustar syosisyosi @prefix : <#> . 12 :a :Pythagorean . 13 :a :Pythagorean . 3 :a :Pythagorean, :RESULT1 . 4 :a :Pythagorean, :RESULT1 . 5 :a :Pythagorean, :RESULT1 . :amy a :Friend . :fred a :Friend . :joe a :Friend . cwm-1.2.1/test/includes/t10.n30000644015216600007660000000265110066677544015073 0ustar syosisyosi# Test the log:includes function @prefix rdf: . @prefix s: . @prefix daml: . @prefix dpo: . @prefix ex: . @prefix log: . @prefix foo: . # Local stuff @prefix : . # Local stuff @prefix local: . # Usage: cwm t10.n3 -think # # See also t10a.n3 foo.n3 # # Output should conclude all test* a :success and no failures. # @forAll :d, :x, :y, :F, :G. { log:semantics :F. :F log:includes { :theSky :is :blue} } log:implies { :test10a a :success } . { log:semantics :F. :F log:includes { :theSky :is :green} } log:implies { :test10-bis a :FAILURE } . { log:semantics :F. :F log:includes { :theSky :is :x} } log:implies { :fred local:favoriteColor :x } . { :fred local:favoriteColor :blue } log:implies { :test10b a :success}. #----------------------------------- # # This illustrates the inabilaty of cwm to do backward chaining # # #{ :d log:semantics :F . # :F log:includes :G } log:implies { :doc local:says :G }. # #{ local:says { :theSky :is :blue } } log:implies {:test_SURPRISE a :success}. # Not to mention: # { :d log:signedBy :k. :d local:says :F } log:means { :k log:guarantees :F }. #ends cwm-1.2.1/test/includes/t3.n30000644015216600007660000000133407303351263014775 0ustar syosisyosi# Test the log:includes function @prefix rdf: . @prefix s: . @prefix daml: . @prefix dpo: . @prefix ex: . @prefix log: . @prefix : <#>. # Local stuff # Usage: cwm i.n3 -think # # Output should conclude all test* a :success and no failures. # { { <#theSky> <#is> <#blue> } log:includes {<#theSky> <#is> <#blue>} } log:implies { :test3 a :success } . { { <#theSky> <#is> <#blue> } log:notIncludes {<#theSky> <#is> <#blue>} } log:implies { :test3_bis a :FAILURE } . #ends cwm-1.2.1/test/includes/t2.n30000644015216600007660000000163407352723227015006 0ustar syosisyosi# Test the log:includes function @prefix rdf: . @prefix s: . @prefix daml: . @prefix dpo: . @prefix ex: . @prefix log: . @prefix : <#>. # Local stuff # Usage: cwm includes.n3 -think # # Output should conclude all test* a :success and no failures. # log:includes a rdf:Property; s:comment """ The includes property indicates that one formula either is, or is a conjunction of several subformulae one of which is, the other forumla or its equivalent by the renaming of variables. It can be calculated if one knows the formulae involved. """. :a :b :c. # { :a :b :c } log:implies { :testa a :success } . { [ :b :c ] } log:implies { :test2 a :success } . #ends cwm-1.2.1/test/includes/genBnodeInNestedFormula.n30000644015216600007660000000021410453454066021151 0ustar syosisyosi@keywords a, is, of, this. @prefix : <#>. [ a Mother; name "Mary" ]. @forAll :x . { :x a Mother } => { :x says { You listenTo :x }}. cwm-1.2.1/test/includes/builtins.n30000644015216600007660000000171410365773311016306 0ustar syosisyosi@prefix log: . @prefix rdf: . { {} log:includes {:a log:equalTo :a} } => { :test1n a :Failure} . { {} log:includes {{:a :b :c} log:includes {}} } => { :test2n a :Failure} . { {} log:notIncludes {:a log:equalTo :a} } => { :test1 a :Success} . { { :foo :bar (1 2) } log:includes { :foo :bar [rdf:first []]} } => {:test2 a :Success} . { { :foo :bar (1 2) } log:notIncludes { :foo :bar [rdf:first []]} } => {:test2 a :FAILURE} . { {} log:notIncludes {:a log:equalTo :a} } => { :test3 a :Success} . # All lists exist and non-empty lists have firsts. # For cwm this shows up as the list (1 2) being a List datatype, # and the rdf:first builtin which extracts its first element. # rdf:first works even with a plain log:includes because the # rdf:first property is part of the RDF model of a list. { {} log:includes { (1 2) rdf:first [] } } => { :test4 a :Success }. # ends cwm-1.2.1/test/includes/t8.n30000644015216600007660000000253107351226425015006 0ustar syosisyosi# Test the string built-ins @prefix log: . @prefix string: . @prefix : <#>. # Local stuff # Usage: cwm includes.n3 -think # # Output should conclude all test* a :success and no failures. # { "abc" string:greaterThan "aaa" } log:implies { :testh1 a :success }. { "abc" string:greaterThan "abc" } log:implies { :testh_1 a :FAILURE }. { "aaa" string:greaterThan "abc" } log:implies { :testh_2 a :FAILURE }. { "abc" string:notGreaterThan "aaa" } log:implies { :testh_3 a :FAILURE }. { "abc" string:notGreaterThan "abc" } log:implies { :testh2 a :success }. { "aaa" string:notGreaterThan "abc" } log:implies { :testh3 a :success }. { "abc" string:lessThan "aaa" } log:implies { :testh_4 a :FAILURE }. { "abc" string:lessThan "abc" } log:implies { :testh_5 a :FAILURE }. { "aaa" string:lessThan "abc" } log:implies { :testh4 a :success }. { "abc" string:notLessThan "aaa" } log:implies { :testh5 a :success }. { "abc" string:notLessThan "abc" } log:implies { :testh6 a :success }. { "aaa" string:notLessThan "abc" } log:implies { :testh_6 a :FAILURE }. { "abc" string:startsWith "a" } log:implies { :testh7 a :success }. { "def" string:startsWith "def" } log:implies { :testh8 a :success }. { "a" string:startsWith "abc" } log:implies { :testh_7 a :FAILURE }. # ends cwm-1.2.1/test/includes/bnode-conclude-ref.n30000644015216600007660000000007110370500735020075 0ustar syosisyosi @prefix : <#> . [ a :Result ]. cwm-1.2.1/test/includes/detailed.tests0000644015216600007660000000122710371464447017055 0ustar syosisyosi# List of regression tests for this directory # # Includes tests: details # # Note: Command lines must be for running in the directory above. # @prefix : <#>. @prefix x: <#>. @prefix test: . :listin a test:CwmTest; test:referenceOutput ; test:description "Builtins for list membership, binding multiple values."; test:arguments "includes/list-in.n3 --think --data". :bnode a test:CwmTest; test:referenceOutput ; test:description "Binding a bnode from a log:includes."; test:arguments "includes/bnodeConclude.n3 --think --data". #ends cwm-1.2.1/test/includes/list-in.n30000644015216600007660000000037510160717036016031 0ustar syosisyosi@prefix li: . @keywords. { ?x li:in (3 4 5) } => { ?x a RESULT1 }. { ( joe fred amy ) li:member ?y } => { ?y @a Friend }. { ((3 4 5) (5 12 13))!li:member li:member ?z } => { ?z a Pythagorean }. # ends cwm-1.2.1/test/includes/quant-implies.n30000644015216600007660000000124307616041767017252 0ustar syosisyosi# Test of interactions of qualifiers with log:implies # # $Id: quant-implies.n3,v 1.1 2003/01/29 21:13:27 timbl Exp $ # # Usage: cwm quantifiers.n3 -think -purge # @prefix log: . @prefix : <#>. # # The machine should, under --think, be able to conclude that # the eplicitly named day is great, and that the unnamed day is # great, without getting in a muddle over when to generate new # bodes. When conclusing "there is a God", however, it has to generate # a new bnode. # <#today> a <#Sunnyday>. [] a <#Sunnyday>, <#Birthday>. { ?x a <#Sunnyday> } => { ?x a <#Greatday> }. { ?x a <#Sunnyday> } => { [] a <#God> }. # ENDS cwm-1.2.1/test/includes/conjunction.n30000644015216600007660000000336410066677544017022 0ustar syosisyosi# Test the log:includes function @prefix rdf: . @prefix s: . #@prefix daml: . #@prefix dpo: . #@prefix ex: . @prefix log: . #@prefix string: . @prefix foo: . # Local stuff @prefix : . # Local stuff @prefix local: . # Usage: cwm conclusion.n3 -think # # See also t10a.n3 foo.n3 # # Output should be (in "result" formula) the same as for the cwm command below. # @forAll :d, :x, :y, :F, :G. #{ "z" string:greaterThan "a" } log#:implies { :result :is :sanity }. { ( { :sky :color :blue } { :sky :color :green } ) log:conjunction :F } log:implies { :F a :result} . # "Conjunction junction, what's your're function?" - schoolhouse rock. # The conjunction of a list of formulae is the logical AND of them, ie # the set of statements which contains each of the statements in each of the # conjoined formulae. # #{ ( [ is log:semantics of <../daml-ex.n3> ] # [ is log:semantics of <../invalid-ex.n3> ] # [ is log:semantics of <../schema-rules.n3> ] ) # log:conjunction [ log:conclusion :G]} # log:implies { :result :is :G }. # # The above is a much more complicated way of writing the cwm # command line "cwm daml-ex.n3 invalid-ex.n3 schema-rules.n3 --think". # # (Maybe conjunction should automatically reference a resource with no "#" # so that the log:semantics becomes unnecesary. Maybe N3 should just assume # coersion from resource to formula where that is appropriate? :o/ ) #ends cwm-1.2.1/test/includes/bnodeConclude.n30000644015216600007660000000017710370500735017215 0ustar syosisyosi@prefix log: . @forAll :X . { {:a :b []} log:includes {:a :b :X} } => {:X a :Result} . cwm-1.2.1/test/includes/t1.n30000644015216600007660000000156507352723227015010 0ustar syosisyosi# Test the log:includes function @prefix rdf: . @prefix s: . @prefix daml: . @prefix dpo: . @prefix ex: . @prefix log: . @prefix : <#>. # Local stuff # Usage: cwm includes.n3 -think # # Output should conclude all test* a :success and no failures. # log:includes a rdf:Property; s:comment """ The includes property indicates that one formula either is, or is a conjunction of several subformulae one of which is, the other forumla or its equivalent by the renaming of variables. It can be calculated if one knows the formulae involved. """. {{ :a :b :c } log:includes { :a :b :c }} log:implies { :test1 a :success } . #ends cwm-1.2.1/test/includes/foo.n30000644015216600007660000000105707350026447015241 0ustar syosisyosi# Test whether a schema mentions the predicates used in this data # @prefix rdf: . @prefix s: . @prefix log: . @prefix : . # Local stuff @prefix foo: . # Local stuff # Usage: cwm t11.n3 -think # # Output should conclude all test* a :success and no failures. # foo:theSky s:isDefinedBy <> . foo:is a rdf:Property; s:isDefinedBy <> . foo:blue s:isDefinedBy <> . #foo:red s:isDefinedBy <> . # #ends cwm-1.2.1/test/includes/t11.n30000644015216600007660000001145610066677544015077 0ustar syosisyosi# Test whether a schema mentions the predicates used in this data # This involves searching in files for statements being present or absent. @prefix rdf: . @prefix s: . # @prefix daml: . # @prefix dpo: . # @prefix ex: . @prefix log: . @prefix : . # Local stuff # @prefix foo: . # Local stuff @prefix foo: . # Local stuff # Usage: cwm t11.n3 -think # # Output should conclude all test* a :success and no failures. # @forAll :d, :o, :p, :s, :S, :s1, :x, :y, :F, :G, :H. { log:semantics :F . :F log:includes { :blue a rdf:Property }} log:implies { :includesTest a :FAILURE}. { log:semantics :F . :F log:notIncludes { :blue a rdf:Property }} log:implies { :includesTest2 a :success}. { log:semantics :F . :F log:includes { :is a rdf:Property }} log:implies { :includesTest3 a :success}. { log:semantics :F . :F log:notIncludes { :is a rdf:Property }} log:implies { :includesTest4 a :FAILURE}. { log:semantics :F. :F log:includes { :s :p :o} } log:implies { :p a :UsedProperty } . # # Debug: #{ :blue log:semantics :F. } log:implies { :WE :FOUND :F }. # #{ :blue log:semantics :F. # :F log:includes { :x s:isDefinedBy :y }} log:implies { :x :DEFINEDIN_BLUE_NS :y }. # #{ :blue log:semantics :F. # :F log:includes { :x s:isDefinedBy :y }} log:implies { :x :DEFINEDIN_BLUE_NS :y }. # #{ :p a :UsedProperty . # :p log:semantics :F. # } log:implies { :p :USED_AND_RESOLVES_TO :F }. #{ :p :USED_AND_RESOLVES_TO :F. #:F log:includes { :x s:isDefinedBy :y } } log:implies { :p :USED_AND_SOMETHING_DEFINED_IN :F }. # # # The RDF and RDFS specs imply the following algorithm for the definitive schema corresponding # to a Property :p. (From Ralph Swick, whiteboard conversation) # { :p a :UsedProperty . :p log:semantics [log:includes { :p s:isDefinedBy :s }] } log:implies {:p :schema :s}. # We may need the schema as a formula too: { :p :schema [ log:semantics :F ] } log:implies { :p :schemaFormula :F }. # If there is no schema found, then we flag a problem { :p a :UsedProperty . :p log:semantics [log:notIncludes { :p s:isDefinedBy [] }] } log:implies {:p a :ERROR_CANT_GET_SCHEMA}. { :p a :UsedProperty . :p log:semantics :F. :F log:includes { :p s:isDefinedBy :s }. :s log:semantics :G } log:implies { :p :schemaFormula :G }. # FYI {:p :schemaFormula :F. :F log:includes { :p a rdf:Property }}log:implies { :p a :Property_declared } . # It is an error, we say, for something to be used as a Property but # not *explicitly* declared as such in the schema: {:p :schemaFormula :F. :F log:notIncludes { :p a rdf:Property }}log:implies { :p a :ERROR_PROPERTY_NOT_DECLARED } . #{ :p :schema :s. # :s log:semantics [log:notIncludes { :p a rdf:Property }]. #} log:implies { # :p a :ERROR_SPELLING_MISTAKE_MAYBE. # ;-) #}. # Now we can find the schema, we can check whether the property is indeed # mentioned in the schema. # Exactly what we require of a schema is a good question. # One answer is that # (a)when the schema is found and combined with well-known general rules # with inference that you can show that each of the predictes used is # indeed declared as a property. This gets rid of spelling errors etc. # (b)when the document is combined with the above, no condradiction # can be found from anything being (eg) member of disjoint sets. # #{ :p :schema :s. # :s log:semantics [log:includes { :p a rdf:Property }]. #} log:implies { # :p a :schema_defined_property4. # #}. # # #{ :p :schema :s. # :s log:semantics [log:notIncludes { :p a rdf:Property }]. #} log:implies { # :p a :ERROR_SPELLING_MISTAKE_MAYBE. # ;-) #}. # log:implies a log:Chaff. # Clear out rules on -purge ########################### Old stuff: #{ :p a :UsedProperty. # :p log:semantics :H. # } log:impliesXX {:H a :schemaFormula }. #{ foo:is log:semantics :H. # :H log:includes { foo:is a rdf:Property } #} log:implies { :H a :success1 }. #{ foo:is log:semantics :H. # :H log:includes { foo:is a rdf:Property } #} log:implies { foo:is a :defined_as_prop_in_schema }. #{ :p a :UsedProperty. # :p log:semantics :H. # :H log:includes { :p a rdf:Property } #} log:implies { :p a :defined_as_property_in_ns_doc1 }. #{ log:semantics :H. # :H log:includes { :p s:isDefinedBy :x }} log:impliesXX { :p a :defined_in_schema2 . # :p :is_defined_in2 :x. # :H :is :whatFooIsResolvedTo2 }. # { :p a :defined_in_schema. :p a :UsedProperty } log:implies { :p a :UsedAndDefined }. #ends cwm-1.2.1/test/includes/t10a.n30000644015216600007660000000134407352723227015224 0ustar syosisyosi# Test the cwm builtins #@prefix rdf: . #@prefix s: . #@prefix daml: . #@prefix dpo: . #@prefix ex: . #@prefix log: . @prefix : . # Local stuff @prefix foo: . # Local stuff # Usage: See t10.n3 # # Output should conclude all test* a :success and no failures. # :theSky :is :blue . # A valid statement. :theSky :blue :is . # Predicate defined by schema but not a Property. :theSky :test_undefined :blue . # Not a schema-valid Property #ends cwm-1.2.1/test/includes/quantifiers.n30000644015216600007660000001161310066677544017017 0ustar syosisyosi# Test of interactions of qualifiers with log:includes # # $Id: quantifiers.n3,v 1.3 2004/06/25 01:27:00 timbl Exp $ # # Usage: cwm quantifiers.n3 -think -purge # Should give 18 successes and no failures. # @prefix log: . @prefix : <#>. @prefix qu: <#>. # # Basically, forall x G(x) implies G(x) which implies forSome X G(x). # log:includes should allow the stronger statement to "include" the weaker one. # {{ :foo :bar :baz } log:includes { @forSome :foo. :foo :bar :baz }} log:implies { :testa2 a :success }. # Originally failed {{ @forSome :foo. :foo :bar :baz } log:includes {@forSome :foo. :foo :bar :baz }} log:implies { :testb2 a :success }. {{ @forAll :foo. :foo :bar :baz } log:includes {@forSome :foo. :foo :bar :baz }} log:implies { :testc2 a :success }. # Originally failed {{ :foo :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testa1 a :success }. {{ @forSome :foo. :foo :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testb1 a :FAILURE }. # Originally failed, STILL FAILS. {{ @forAll :foo. :foo :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testc1 a :success }. {{ :foo :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} log:implies { :testa3 a :FAILURE }. {{ @forSome :foo. :foo :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} log:implies { :testb3 a :FAILURE }. {{ @forAll :foo. :foo :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} log:implies { :testc3 a :success }. # Negative tests: {{ :foo :bar :baz } log:notIncludes { @forSome :foo. :foo :bar :baz }} log:implies { :testa2n a :FAILURE }.# Originally failed {{ @forSome :foo. :foo :bar :baz } log:notIncludes {@forSome :foo. :foo :bar :baz }} log:implies { :testb2n a :FAILURE }. {{ @forAll :foo. :foo :bar :baz } log:notIncludes {@forSome :foo. :foo :bar :baz }} log:implies { :testc2n a :FAILURE }. # Originally failed {{ :foo :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testa1n a :FAILURE }. {{ @forSome :foo. :foo :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testb1n a :success }. {{ @forAll :foo. :foo :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testc1n a :FAILURE }. {{ :foo :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} log:implies { :testa3n a :success }. {{ @forSome :foo. :foo :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} log:implies { :testb3n a :success }. {{ @forAll :foo. :foo :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} log:implies { :testc3n a :FAILURE }. ######################## Versions with different identifiers: {{ :fee :bar :baz } log:includes { @forSome :foo. :foo :bar :baz }} log:implies { :testa2d a :success }. # Originally failed {{ @forSome :fee. :fee :bar :baz } log:includes {@forSome :foo. :foo :bar :baz }} log:implies { :testb2d a :success }. {{ @forAll :fee. :fee :bar :baz } log:includes {@forSome :foo. :foo :bar :baz }} log:implies { :testc2d a :success }. # Originally failed {{ :fee :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testa1d a :FAILURE }. {{ @forSome :fee. :fee :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testb1d a :FAILURE }. # Originally failed {{ @forAll :fee. :fee :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testc1d a :success }. {{ :fee :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} log:implies { :testa3d a :FAILURE }. {{ @forSome :fee. :fee :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} log:implies { :testb3d a :FAILURE }. {{ @forAll :fee. :fee :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} log:implies { :testc3d a :success }. # Negative tests: {{ :fee :bar :baz } log:notIncludes { @forSome :foo. :foo :bar :baz }} log:implies { :testa2nd a :FAILURE }. # Originally failed {{ @forSome :fee. :fee :bar :baz } log:notIncludes {@forSome :foo. :foo :bar :baz }} log:implies { :testb2nd a :FAILURE }. {{ @forAll :fee. :fee :bar :baz } log:notIncludes {@forSome :foo. :foo :bar :baz }} log:implies { :testc2nd a :FAILURE }. # Originally failed {{ :fee :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testa1nd a :success }. {{ @forSome :fee. :fee :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testb1nd a :success }. {{ @forAll :fee. :fee :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testc1nd a :FAILURE }. # Originally failed, STILL FAILS {{ :fee :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} log:implies { :testa3nd a :success }. {{ @forSome :fee. :fee :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} log:implies { :testb3nd a :success }. {{ @forAll :fee. :fee :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} log:implies { :testc3nd a :FAILURE }. log:implies a log:Chaff. # Purge input rules # ENDS cwm-1.2.1/test/includes/t9br.n30000644015216600007660000000112410066677544015341 0ustar syosisyosi@prefix log: . @prefix string: . @prefix : <#>. # Test the interaction of builtins with variable binding. # fails as of cwm.py,v 1.47 2001/05/23 01:39:39 timbl # # Usage: cwm includes.n3 -think # # Output should conclude all test* a :success and no failures. :e1 :date "2001-09-27". @forAll :e, :d. # find events in september 2001 { :e :date :d. :d string:notLessThan "2001-09"; string:lessThan "2001-10" } log:implies { :e a :Sep2001Event }. { :e1 a :Sep2001Event } log:implies { :t1 a :Success. }. cwm-1.2.1/test/includes/t6.n30000644015216600007660000000204307346026311014776 0ustar syosisyosi# Test the log:includes function @prefix rdf: . @prefix s: . @prefix daml: . @prefix dpo: . @prefix ex: . @prefix log: . @prefix : <#>. # Local stuff # Usage: cwm includes.n3 -think # # Output should conclude all test* a :success and no failures. # # Test we can operate with anonymous nodes: # # Someone whose mother is audrey knows someone whose sister is Betsy # {{ :foo :bar [:baz :bam] } log:includes { :foo :bar [:baz :bam] }} log:implies { :TEST1 a :success }. #{{ [ :mother :Audrey ] :knows [ :sister :Betsy ]. :foo :bar :baz. } # log:includes {[:mother :Audrey]:knows[:sister :Betsy]}} # log:implies{:testf_1 a :success} . # { <#_formula> log:notIncludes {[:mother :Audrey]:knows[:sister :Betsy]}}log:implies{testf_2 a :FAILURE} . # log:includes a log:Chaff. #ends cwm-1.2.1/test/includes/uri-startswith.n30000644015216600007660000000374110066677544017501 0ustar syosisyosi@prefix log: . @prefix string: . @prefix c: . @prefix org: . @prefix w3c: . @prefix : . @prefix aacl: . @prefix v: <#>. [ c:mailbox [ = ; c:archive ] ]. @forAll v:doc. { v:doc log:uri [ string:startsWith "http://lists.w3.org/Archives/Public/" ] } log:implies { v:doc a :PubliclyReadable }. ########### # # Here's what I see when I try this test case: # # connolly@shoal:~/w3ccvs/WWW/2000/10/swap/test/includes$ python2 ../../cwm.py uri-startswith.n3 --think # #Processed by Id: cwm.py,v 1.54 2001/06/01 07:50:20 connolly Exp # # using base file:/home/connolly/w3ccvs/WWW/2000/10/swap/test/includes/uri-startswith.n3 # # @@@@@@@@@ State is 20, q length 1 # # @@ Current item: 20) _formula :: _g3? startsWith ttp://lists.w3.org/Archives/Public . consts=[1, 0, 3] vars=[2] short=1 # # 20) _formula :: doc? uri _g3? . consts=[1, 0] vars=[2, 3] short=1 # # Traceback (most recent call last): # File "../../cwm.py", line 2334, in ? # doCommand() # File "../../cwm.py", line 2284, in doCommand # step = _store.applyRules(workingContext, workingContext) # File "../../cwm.py", line 1160, in applyRules # found = self.tryRule(s, workingContext, targetContext, _variables) # File "../../cwm.py", line 1228, in tryRule # self.conclude, ( self, conclusions, targetContext, _outputVariables)) # File "../../cwm.py", line 1389, in match # return self.query(queue, variables, existentials, smartIn, action, param, bindings, newBindings, justOne) # File "../../cwm.py", line 1588, in query # raise internalError # We have something in an unknown state in the queue # NameError: There is no variable named 'internalError' cwm-1.2.1/test/includes/n3ExprFor.n30000644015216600007660000000033210066677544016307 0ustar syosisyosi@prefix log: . @prefix : <#>. @forAll :x. { """@prefix : . :x :y :z .""" log:n3ExprFor :x } log:implies { :Blargh_b :semantics :x } . # ends cwm-1.2.1/test/includes/quantifiers_limited.n30000644015216600007660000001176210066677544020533 0ustar syosisyosi# Test of interactions of qualifiers with log:includes # # 2003-07-28 stripped of anything having "forall" in obj of log:includes # # $Id: quantifiers_limited.n3,v 1.2 2004/06/25 01:27:00 timbl Exp $ # # Usage: cwm quantifiers_limited.n3 -think -purge-rules # Should give successes and no failures. # @prefix log: . @prefix : <#>. @prefix qu: <#>. # # Basically, forall x G(x) implies G(x) which implies forSome X G(x). # log:includes should allow the stronger statement to "include" the weaker one. # {{ :foo :bar :baz } log:includes { @forSome :foo. :foo :bar :baz }} log:implies { :testa2 a :success }. # Originally failed {{ @forSome :foo. :foo :bar :baz } log:includes {@forSome :foo. :foo :bar :baz }} log:implies { :testb2 a :success }. {{ @forAll :foo. :foo :bar :baz } log:includes {@forSome :foo. :foo :bar :baz }} log:implies { :testc2 a :success }. # Originally failed {{ :foo :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testa1 a :success }. {{ @forSome :foo. :foo :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testb1 a :FAILURE }. # Originally failed, STILL FAILS. {{ @forAll :foo. :foo :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testc1 a :success }. ##{{ :foo :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testa3 a :FAILURE }. ##{{ @forSome :foo. :foo :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testb3 a :FAILURE }. ##{{ @forAll :foo. :foo :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testc3 a :success }. # Negative tests: {{ :foo :bar :baz } log:notIncludes { @forSome :foo. :foo :bar :baz }} log:implies { :testa2n a :FAILURE }.# Originally failed {{ @forSome :foo. :foo :bar :baz } log:notIncludes {@forSome :foo. :foo :bar :baz }} log:implies { :testb2n a :FAILURE }. {{ @forAll :foo. :foo :bar :baz } log:notIncludes {@forSome :foo. :foo :bar :baz }} log:implies { :testc2n a :FAILURE }. # Originally failed {{ :foo :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testa1n a :FAILURE }. {{ @forSome :foo. :foo :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testb1n a :success }. {{ @forAll :foo. :foo :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testc1n a :FAILURE }. ##{{ :foo :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testa3n a :success }. ##{{ @forSome :foo. :foo :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testb3n a :success }. ##{{ @forAll :foo. :foo :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testc3n a :FAILURE }. ######################## Versions with different identifiers: {{ :fee :bar :baz } log:includes { @forSome :foo. :foo :bar :baz }} log:implies { :testa2d a :success }. # Originally failed {{ @forSome :fee. :fee :bar :baz } log:includes {@forSome :foo. :foo :bar :baz }} log:implies { :testb2d a :success }. {{ @forAll :fee. :fee :bar :baz } log:includes {@forSome :foo. :foo :bar :baz }} log:implies { :testc2d a :success }. # Originally failed {{ :fee :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testa1d a :FAILURE }. {{ @forSome :fee. :fee :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testb1d a :FAILURE }. # Originally failed {{ @forAll :fee. :fee :bar :baz } log:includes { :foo :bar :baz }} log:implies { :testc1d a :success }. ##{{ :fee :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testa3d a :FAILURE }. ## ##{{ @forSome :fee. :fee :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testb3d a :FAILURE }. ## ##{{ @forAll :fee. :fee :bar :baz } log:includes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testc3d a :success }. # Negative tests: {{ :fee :bar :baz } log:notIncludes { @forSome :foo. :foo :bar :baz }} log:implies { :testa2nd a :FAILURE }. # Originally failed {{ @forSome :fee. :fee :bar :baz } log:notIncludes {@forSome :foo. :foo :bar :baz }} log:implies { :testb2nd a :FAILURE }. {{ @forAll :fee. :fee :bar :baz } log:notIncludes {@forSome :foo. :foo :bar :baz }} log:implies { :testc2nd a :FAILURE }. # Originally failed {{ :fee :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testa1nd a :success }. {{ @forSome :fee. :fee :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testb1nd a :success }. {{ @forAll :fee. :fee :bar :baz } log:notIncludes { :foo :bar :baz }} log:implies { :testc1nd a :FAILURE }. # Originally failed, STILL FAILS ##{{ :fee :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testa3nd a :success }. ## ##{{ @forSome :fee. :fee :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testb3nd a :success }. ## ##{{ @forAll :fee. :fee :bar :baz } log:notIncludes {@forAll :foo. :foo :bar :baz }} ## log:implies { :testc3nd a :FAILURE }. # ENDS cwm-1.2.1/test/reason/0000755015216600007660000000000010731073450013663 5ustar syosisyosicwm-1.2.1/test/reason/t4.n30000644015216600007660000000007610303444701014453 0ustar syosisyosi@prefix : <#>. :a :b :c. {:a :b ?x} => { ?x :d :e }. # ends cwm-1.2.1/test/reason/t3.n30000644015216600007660000000010307604057623014456 0ustar syosisyosi@prefix : <#>. :a :b :c. {:a :b :c} => { :a2 :b2 :c2 }. # ends cwm-1.2.1/test/reason/t2.n30000644015216600007660000000004507574245427014471 0ustar syosisyosi
. . # ends cwm-1.2.1/test/reason/socrates.n30000644015216600007660000000016710642726425015764 0ustar syosisyosi@prefix : . @prefix vars: . :socrates a :Man. { ?who a :Man } => { ?who a :Mortal }. #ends cwm-1.2.1/test/reason/t5.n30000644015216600007660000000020507604057623014463 0ustar syosisyosi@prefix log: . @prefix foo: <#>. @prefix : <#>. :a :b :c. {:a ?y ?x} => { ?x ?y }. # ends cwm-1.2.1/test/reason/timbl.n30000644015216600007660000000052010453352555015240 0ustar syosisyosi@prefix log: . @prefix owl: . @prefix rdf: . @prefix rdfs: . @forAll :X . {} => {:Document owl:disjointWith rdf:Property} . owl:sameAs a owl:SymmetricProperty . cwm-1.2.1/test/reason/t8.n30000644015216600007660000000014007644572402014465 0ustar syosisyosi# Testing proof generation and checking. []. { ?x} => { ?x }. # ends cwm-1.2.1/test/reason/detailed.tests0000644015216600007660000001615610731063556016541 0ustar syosisyosi# List of regression tests for $SWAP/test/reason @prefix : <#>. @prefix x: <#>. @prefix test: . @prefix dc: . # yuk - under protest - no hash # Test proof generation -- see also the -p option of retest.py # Commented out the tests which are not checks, as proof format itself is not # so stable or guarantted yet and the proofs tend to serialize with unordered # bnodes :t01proof # a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t01proof.n3>; test:description "Proof for just loading a file"; test:arguments """reason/t1.n3 --think --base=foo --why""". :t01zcheck a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t01check.n3>; test:description "Proof for just loading a file"; test:arguments """reason/t1.n3 --think --base=foo --why | python ../check.py""". :t02proof # a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t02proof.n3>; test:description "Proof for just loading a file"; test:arguments """reason/t2.n3 --think --base=foo --why""". :t02zcheck a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t02check.n3>; test:description "Proof for just loading a file"; test:arguments """reason/t2.n3 --think --base=foo --why | python ../check.py""". :t03proof # a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t03proof.n3>; test:description "Proof for just loading a file"; test:arguments """reason/t3.n3 --think --base=foo --why""". :t03zcheck a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t03check.n3>; test:description "Proof for just loading a file"; test:arguments """reason/t3.n3 --think --base=foo --why | python ../check.py""". :t04proof # a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t04proof.n3>; test:description "Proof for just loading a file"; test:arguments """reason/t4.n3 --think --base=foo --why""". :t04zcheck a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t04check.n3>; test:description "Proof for just loading a file"; test:arguments """reason/t4.n3 --think --base=foo --why | python ../check.py""". :t05proof # a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t05proof.n3>; test:description "Proof for a little inference"; test:arguments """reason/t5.n3 --think --base=foo --why""". :t05zcheck a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t05check.n3>; test:description "Proof for a little inference"; test:arguments """reason/t5.n3 --think --base=foo --why | python ../check.py""". :t06proof # a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t06proof.n3>; test:description "Proof for a little inference"; test:arguments """reason/t6.n3 --think --base=foo --why""". :t06zcheck a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t06check.n3>; test:description "Proof for a little inference"; test:arguments """reason/t6.n3 --think --base=foo --why | python ../check.py""". # This is equiv of others but easier to explain with famous example :socrates a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/socrates.n3>; test:description "Proof with basic modus ponens"; test:arguments """reason/socrates.n3 --think --base=foo --why | python ../check.py""". :t07zcheck a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-single-gen.n3>; test:description "make sure a proof does not split anonymous nodes unnecessarily"; test:arguments """reason/single_gen.n3 --think --base=foo --why | python ../check.py""" . :t08proof # a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t08proof.n3>; test:description "Proof for inference, --n3=B to name BNodes"; test:arguments """--n3=B reason/t8.n3 --think --base=foo --why""". :t08zcheck a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t08check.n3>; test:description "Proof for inference, --n3=B to name BNodes (check proof)"; test:arguments """--n3=B reason/t8.n3 --think --base=foo --why | python ../check.py""". :t09proof # a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t09proof.n3>; test:description "Proof for a little inference - binding Bnode to symbol"; test:arguments """--n3=B reason/t9.n3 --think --base=foo --why""". :t09qcheck a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t09check.n3>; test:description "Proof for a little inference"; test:arguments """--n3=B reason/t9.n3 --think --base=foo --why | python ../check.py""". :t09wf # a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t09filter.n3>; test:description "Proof with filter - binding Bnode to symbol"; test:arguments """--n3=B reason/t9.n3 --think --filter=reason/f9.n3 --base=foo --why""". :t09zf a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t09filtercheck.n3>; test:description "Proof with filter (check)"; test:arguments """--n3=B reason/t9.n3 --think --filter=reason/f9.n3 --base=foo --why | python ../check.py""". :t10 a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-rename-loop.n3>; test:description "Renaming can lead to loops if not careful"; test:arguments """--n3=eiouB reason/rename-loop.n3 --think --base=foo --why | python ../check.py""". :t11 a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-poor-urop.n3>; test:description "Smushing of equal formulas can lead to proof issues"; test:arguments """--n3=eiouB reason/poor-urop.n3 --think --base=foo --why | python ../check.py""". :t12 #a test:CwmTest; # too unstable! test:workingDirectory <../>; test:referenceOutput <../ref/double-proof.n3>; test:description "Are we splitting bNodes in proofs with no good reason?"; test:arguments """--ntriples reason/double.n3 --think --base=foo --why --flatten | ../cant.py""". :t90check a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/reason-t90check.n3>; test:description "Proof bug: used to make cyclic proof. (long)"; test:arguments """--n3=B includes/conclusion.n3 --think --base=foo --why | python ../check.py""". #:t99 a test: # # http://www.w3.org/2000/10/swap/test/includes/conclusion.n3 #:t2060 a test:CwmTest; # test:workingDirectory <../>; # test:referenceOutput <../ref/reason-tretst.n3>; # test:description "Proof for one simple rule"; # test:arguments """reason/t5.n3 --think --base=foo --why""". # cwm-1.2.1/test/reason/poor-urop.n30000644015216600007660000000071210655653256016104 0ustar syosisyosi@prefix log: . @prefix owl: . @keywords prefix, of, is, has, a, keywords, forAll, forSome . ### Poor UROP doesn't know what is true. ### He figures that in the rare cases that timbl ## agrees with DanC ## It must be true! forAll S, P, O . forAll S2, P2, O2 . { !log:semantics log:supports {S P O} . !log:semantics log:supports {S P O} . } => {S P O} . cwm-1.2.1/test/reason/t9.n30000644015216600007660000000014610352331242014455 0ustar syosisyosi# Testing proof generation and checking. . { []} => { a }. # ends cwm-1.2.1/test/reason/t1.n30000644015216600007660000000001507573550674014467 0ustar syosisyosi . cwm-1.2.1/test/reason/single_gen.n30000644015216600007660000000010210655644305016240 0ustar syosisyosi:a :b "A noun", 3.14159265359 . {:a :b ?X} => { [ a :Thing ] } . cwm-1.2.1/test/reason/f9.n30000644015216600007660000000021210327211277014440 0ustar syosisyosi# Testing proof generation and checking. Filter for t9.n3 when testing filter { ?x a } => { ?x a }. # ends cwm-1.2.1/test/reason/rename-loop.n30000644015216600007660000000030610453454067016352 0ustar syosisyosi@prefix log: . @forAll :Y . {@forAll :A . :A :b :c} a :Thing . { ?Z a :Thing . ?Z log:conclusion ?X . ?X log:includes {_:a :b :Y} . } => {?X a :Thing2} . cwm-1.2.1/test/reason/danc.n30000644015216600007660000000054210453352555015042 0ustar syosisyosi@prefix log: . @prefix owl: . @prefix rdf: . @prefix rdfs: . @forAll :X . owl:sameAs a owl:SymmetricProperty . {:a [] :b} a log:Formula . {:X a :Man} => {:X a :Mortal} . [ a :Man ] . cwm-1.2.1/test/reason/t6.n30000644015216600007660000000071107604116430014456 0ustar syosisyosi@prefix log: . @prefix math: . @prefix foo: <#>. @prefix : <#>. :joe :friend :kev; :height "1.6". # Currently (2002/12) the checker can't compare things with bnodes # with different identifiers and find them equal :-( #{?x :friend :kev; :height [math:greaterThan "1.3"]} => { ?x a :player }. {?x :friend :kev; :height ?h. ?h math:greaterThan "1.3"} => { ?x a :player }. # ends cwm-1.2.1/test/math/0000755015216600007660000000000010731073447013333 5ustar syosisyosicwm-1.2.1/test/math/quotient_string.n30000644015216600007660000000017710137463464017042 0ustar syosisyosi@prefix math: . @prefix : <#>. { ("10" "2.3") math:quotient ?X } => { ?X a :Answer }. cwm-1.2.1/test/math/long.n30000644015216600007660000000012710073525027014527 0ustar syosisyosi @prefix : <#> . 1000000000000000000000000000000000 :is :happy . cwm-1.2.1/test/math/trigo.ref.n30000644015216600007660000000306310357372717015504 0ustar syosisyosi @prefix : <#> . -0.707 a :NonPiTestValue, :TestValue; :ACOS 2.35604349019e+00; :ASIN -0.785247163395e+00; :ATAN -0.615408517629e+00; :COS 0.760313961744e+00; :COSH 1.26050988668e+00; :SIN -0.649555755556e+00; :SINH -0.76738854201e+00; :TAN -0.854325697329e+00; :TANH -0.608792164283e+00 . 0.23 a :NonPiTestValue, :TestValue; :ACOS 1.33871864393e+00; :ASIN 0.232077682863e+00; :ATAN 0.226068387994e+00; :COS 0.973666395005e+00; :COSH 1.02656680622e+00; :SIN 0.227977523535e+00; :SINH 0.232033203713e+00; :TAN 0.234143362351e+00; :TANH 0.226028352279e+00 . 1.23 a :NonPiTestValue, :TestValue; :ATAN 0.888173774378e+00; :COS 0.334237727125e+00; :COSH 1.85676105699e+00; :SIN 0.942488801932e+00; :SINH 1.5644684793e+00; :TAN 2.81981573427e+00; :TANH 0.842579325659e+00 . 3.14159265358979323846 a :TestValue; :ATAN 1.26262725568e+00; :COS -1.0e+00; :COSH 11.5919532755e+00; :SINH 11.5487393573e+00; :TANH 0.996272076221e+00 . 0 a :NonPiTestValue, :TestValue; :ACOS 1.57079632679e+00; :ASIN 0.0e+00; :ATAN 0.0e+00; :COS 1.0e+00; :COSH 1.0e+00; :SIN 0.0e+00; :SINH 0.0e+00; :TAN 0.0e+00; :TANH 0.0e+00 . cwm-1.2.1/test/math/trigo-test.n30000644015216600007660000000306510066634033015675 0ustar syosisyosi# Author: karl # $Id: trigo-test.n3,v 1.7 2004/06/24 20:22:51 syosi Exp $ @prefix : <#> . @prefix log: . @prefix math: . @prefix string: . @keywords a, is, of. #cwm post 2003/08 # A math test to see if it works here: #{ ("3" "5") math:sum ?x } => { ?x :valueOf "3 + 5" } . # test sine, cosine, arcsine, arcosine 0 a TestValue, NonPiTestValue. 0.23 a TestValue, NonPiTestValue. -0.707 a TestValue, NonPiTestValue. 1.23 a TestValue, NonPiTestValue. 3.14159265358979323846 a TestValue. # test very simple { 0 math:asin ?x } => { ?x :valueOf "asin(0) = 0" } . { 1 math:acos ?x } => { ?x :valueOf "acos(1) = 0" } . { ?x a NonPiTestValue; math:sin ?y} => {?x SIN ?y}. { ?x a TestValue; is math:sin of ?y} => {?x ASIN ?y}. { ?x a TestValue; math:cos ?y} => {?x COS ?y}. { ?x a TestValue; is math:cos of ?y} => {?x ACOS ?y}. { ?x a NonPiTestValue; math:tan ?y} => {?x TAN ?y}. { ?x a TestValue; is math:tan of ?y} => {?x ATAN ?y}. { ?x a TestValue; math:sinh ?y} => {?x SINH ?y}. { ?x a TestValue; is math:sinh of ?y} => {?x ASINH ?y}. { ?x a TestValue; math:cosh ?y} => {?x COSH ?y}. { ?x a TestValue; is math:cosh of ?y} => {?x ACOSH ?y}. { ?x a TestValue; math:tanh ?y} => {?x TANH ?y}. { ?x a TestValue; is math:tanh of ?y} => {?x ATANH ?y}. #{ 0 math:acos ?x } => { ?x :valueOf "acos(0) = 1.57079632679" } . #{ 1 math:asin ?x } => { ?x :valueOf "asin(1) = 1.57079632679" } . #{ 3.14159265358979323846 math:cos ?x } => { ?x :valueOf "cos(Pi) = -1" } . cwm-1.2.1/test/math/detailed.tests0000644015216600007660000000233310137502652016166 0ustar syosisyosi# List of regression tests # # Math tests # # Note: Command lines must be for running in the directory above. # @prefix : <#>. @prefix x: <#>. @prefix test: . @prefix dc: . # yuk - under protest - no hash # Math: :t10393 a test:CwmTest; test:referenceOutput <../ref/math1.n3>; test:description "Various math builtins"; test:arguments """math/math-test.n3 --think --data""". :t10394 a test:CwmTest; test:referenceOutput <../math/trigo.ref.n3>; test:description "Various trig builtins"; test:arguments """math/trigo-test.n3 --think --data""". :t10395 a test:CwmTest; test:referenceOutput <../math/long.n3>; test:description "Various trig builtins"; test:arguments """math/long.n3""". :t10396 a test:CwmTest; test:referenceOutput <../ref/dec-div.ref.n3>; test:description "A bug was found in division with decimals"; test:arguments """datatypes/dec-div.n3 --think""". :t10398 a test:CwmTest; test:referenceOutput <../ref/quotient_string.ref.n3>; test:description "A bug was found in division with longs"; test:arguments """math/quotient_string.n3 --think""". #ends cwm-1.2.1/test/math/math-test.n30000644015216600007660000000746610453454066015521 0ustar syosisyosi# Author: sbp # $Id: math-test.n3,v 1.6 2006/07/07 03:30:52 syosi Exp $ @prefix : <#> . @prefix log: . @prefix math: . @prefix string: . @forAll :x , :y , :z . # Some simple rules # Obsolete - do not use: #{ :x math:sumOf ("3" "5") } => { :x :valueOf "3 + 5" } . #{ :x math:differenceOf ("8" "3") } => { :x :valueOf "8 - 3" } . #{ :x math:differenceOf ("8") } => { :x :valueOf "8 - (error?)" } . #{ :x math:factors ("5" "3" "2") } => { :x :valueOf "5 * 3 * 2" } . #{ :x math:quotientOf ("7" "2") } => { :x :valueOf "7 / 2" } . #{ :x math:remainderOf ("7" "2") } => { :x :valueOf "7 % 2" } . #{ :x math:negation "3" } => { :x :valueOf "3 negated" } . #{ "-3" math:negation :x } => { :x :valueOf "what -3's the - of" } . #{ :x math:exponentiationOf ("2" "10") } => { :x :valueOf "2^10" } . # Using strings: { ("3" "5") math:sum :x } => { :x :valueOf "3 + 5" } . { ("8" "3") math:difference :x} => { :x :valueOf "8 - 3" } . { ("8") math:difference :x } => { :x :valueOf "8 - (error?)" } . { ("5" "3" "2") math:product :x} => { :x :valueOf "5 * 3 * 2" } . { :x is math:quotient of ("7" "2") } => { :x :valueOf "7 / 2" } . { :x is math:remainder of ("7" "2") } => { :x :valueOf "7 % 2" } . { :x math:negation "3" } => { :x :valueOf "3 negated" } . { "-3" math:negation :x } => { :x :valueOf "what -3's the - of" } . { :x is math:exponentiation of ("2" "10") } => { :x :valueOf "2^10" } . # using numbers: { (3) math:sum :x } => { :x :valueOf "sum(3) = 3" } . { (3 5) math:sum :x } => { :x :valueOf "3 + 5 = 8" } . { (3 5 100) math:sum :x } => { :x :valueOf "3 + 5 + 100" } . { (8 3) math:difference :x} => { :x :valueOf "8 - 3" } . # { (8) math:difference :x } => { :x :valueOf "8 - (error?)" } . { (5 3 2) math:product :x} => { :x :valueOf "5 * 3 * 2" } . { :x is math:quotient of (7 2) } => { :x :valueOf "7 / 2" } . { :x is math:remainder of (7 2) } => { :x :valueOf "7 % 2" } . { :x math:negation 3 } => { :x :valueOf "3 negated" } . { -3 math:negation :x } => { :x :valueOf "what -3's the - of" } . { :x is math:exponentiation of (2 10) } => { :x :valueOf "2^10" } . # Corner cases: { () math:sum ?x } => { ?x :valuOf " () math:sum ?x --- should be 0" }. { () math:product ?x } => { ?x :valuOf " () math:product ?x --- should be 1" }. # Check that comparison is really numeric and not string comparison { "008" math:greaterThan "70" } => { :test10 a :FAILURE }. { "70" math:greaterThan "008" } => { :test10 a :success }. # A nested rule { :x is math:sum of (3 (8 3)!math:difference ) } => { :x :valueOf "3 + (8 - 3)" } . # Getting the amount of members in a list # List bug: See bug1.n3 # #{ :x a :List; math:memberCount :y } => { :x :memberCount :y } . #("x" "y" "z") a :List . # An example implementation: error flagging a list with too many members #{ :x a :TwoItemedList; math:memberCount [ math:notEqualTo "2" ] } # => { :x :hasAn :Error } . #("p" "q") a :TwoItemedList . #("p" "q" "r") a :TwoItemedList . # Big test { ( ("7" "2")!math:quotient (("7" "2")!math:remainder "10000000")!math:exponentiation ("a" "b" "c" "d" "e")!math:memberCount ) math:sum ?x } => { ?x :valueOf "(7 / 2) + ((7 % 2)^10000000) + 5 [should be 9.5]" } . # Combinatorial test "3.1415926" a :testValue. 3.1415926 a :testValue. "1729" a :testValue. 1729 a :testValue. "0" a :testValue. 0 a :testValue. "1.0e7" a :testValue. 1.0e7 a :testValue. { :x a :testValue. :y a :testValue. (:x [ is math:difference of (:y :x)]) math:sum :y } => {:x :worksWith :y}. { :x a :testValue. :y a :testValue. :z is math:sum of (:x (:y :x)!math:difference). :z math:notEqualTo :y } => {(:x :y) :SumDifferenceFAILS :z}. { :x a :testValue. :y a :testValue. (:x :y) math:sum :z. (:x " + " :y " = " :z ) string:concatenation ?s } => { ?s a :RESULT }. #ends cwm-1.2.1/test/daml-ont.rdf0000644015216600007660000002524307302103577014616 0ustar syosisyosi $Id: daml-ont.rdf,v 1.2 2001/05/21 03:11:59 timbl Exp $ The most general class in DAML. the class with no things in it. for disjointWith(X, Y) read: X and Y have no members in common. for type(L, Disjoint) read: the classes in L are pairwise disjoint. i.e. if type(L, Disjoint), and C1 in L and C2 in L, then disjointWith(C1, C2). for unionOf(X, Y) read: X is the union of the classes in the list Y; i.e. if something is in any of the classes in Y, it's in X, and vice versa. cf OIL OR for disjointUnionOf(X, Y) read: X is the disjoint union of the classes in the list Y: (a) for any c1 and c2 in Y, disjointWith(c1, c2), and (b) i.e. if something is in any of the classes in Y, it's in X, and vice versa. cf OIL disjoint-covered for intersectionOf(X, Y) read: X is the intersection of the classes in the list Y; i.e. if something is in all the classes in Y, then it's in X, and vice versa. cf OIL AND for complementOf(X, Y) read: X is the complement of Y; if something is in Y, then it's not in X, and vice versa. cf OIL NOT for oneOf(C, L) read everything in C is one of the things in L; This lets us define classes by enumerating the members. for item(L, I) read: I is an item in L; either first(L, I) or item(R, I) where rest(L, R). for cardinality(P, N) read: P has cardinality N; i.e. everything x in the domain of P has N things y such that P(x, y). for maxCardinality(P, N) read: P has maximum cardinality N; i.e. everything x in the domain of P has at most N things y such that P(x, y). for minCardinality(P, N) read: P has minimum cardinality N; i.e. everything x in the domain of P has at least N things y such that P(x, y). for inverseOf(R, S) read: R is the inverse of S; i.e. if R(x, y) then S(y, x) and vice versa. compare with maxCardinality=1; e.g. integer successor: if P is a UniqueProperty, then if P(x, y) and P(x, z) then y=z. aka functional. if P is an UnambiguousProperty, then if P(x, y) and P(z, y) then x=z. aka injective. e.g. if nameOfMonth(m, "Feb") and nameOfMonth(n, "Feb") then m and n are the same month. for restrictedBy(C, R), read: C is restricted by R; i.e. the restriction R applies to c; if onProperty(R, P) and toValue(R, V) then for every i in C, we have P(i, V). if onProperty(R, P) and toClass(R, C2) then for every i in C and for all j, if P(i, j) then type(j, C2). for onProperty(R, P), read: R is a restriction/qualification on P. for toValue(R, V), read: R is a restriction to V. for toClass(R, C), read: R is a restriction to C. for qualifiedBy(C, Q), read: C is qualified by Q; i.e. the qualification Q applies to C; if onProperty(Q, P) and hasValue(Q, C2) then for every i in C, there is some V so that type(V, C2) and P(i, V). for hasValue(Q, C), read: Q is a hasValue qualification to C. An Ontology is a document that describes a vocabulary of terms for communication between (human and) automated agents. generally, a string giving information about this version; e.g. RCS/CVS keywords for imports(X, Y) read: X imports Y; i.e. X asserts the* contents of Y by reference; i.e. if imports(X, Y) and you believe X and Y says something, then you should believe it. Note: "the contents" is, in the general case, an il-formed definite description. Different interactions with a resource may expose contents that vary with time, data format, preferred language, requestor credentials, etc. So for "the contents", read "any contents". for equivalentTo(X, Y), read X is an equivalent term to Y. default(X, Y) suggests that Y be considered a/the default value for the X property. This can be considered documentation (ala label, comment) but we don't specify any logical impact. cwm-1.2.1/test/rules12.n30000644015216600007660000000115210453454063014136 0ustar syosisyosi# Test filter in N3 # Use # cwm rules12.n3 -think -filter=filter12.n3 # should conclude that granpa is ancestor of bill # @prefix log: . @prefix daml: . @prefix : <#> . @prefix rules: <#> . # SimplifiedDanC challenge - simplied version of rules13.n3 @forAll <#p> . { <#p> a daml:TransitiveProperty . } log:implies { @forAll <#x> , <#y> , <#z>. { <#x> <#p> <#y>. <#y> <#p> <#z>. } log:implies { <#x> <#p> <#z>. }. } . <#ancestor> a daml:TransitiveProperty . <#granpa> <#ancestor> <#pa> . <#pa> <#ancestor> <#bill> . cwm-1.2.1/test/i18n/0000755015216600007660000000000010731073447013161 5ustar syosisyosicwm-1.2.1/test/i18n/n3string.n30000644015216600007660000000015510247137543015173 0ustar syosisyosi@prefix log: . {{:㐭 :b :c} log:n3String ?x} => {?x a :interesting}. cwm-1.2.1/test/smush-query.n30000644015216600007660000000134210066677543015156 0ustar syosisyosi# http://rdfweb.org/2001/01/design/smush.html # (Q1) What are the technology interests of persons who own companies that have an ethical # policy committment to the policy stated in the document # http://dotherightthing.example.org/policy.xhtml @prefix agg: . @prefix : . @prefix v: . @prefix log: . @forAll :interest, :person, :company. { :interest is agg:technologyInterest of :person. :person is agg:owner of :company. :company agg:ethicalPolicy . } => { :interest a agg:Q1Answer }. cwm-1.2.1/test/time/0000755015216600007660000000000010731073450013332 5ustar syosisyosicwm-1.2.1/test/time/t1s.n30000644015216600007660000000257710066677544014335 0ustar syosisyosi# test cwm time built-ins # # usage: cwm --think # # The repeatable ones are tested. Ones that depend # on the actual time are in now.n3 # @prefix log: . @prefix time: . @prefix v: <#>. @prefix TEST: . @prefix : <#>. @forAll :f, :t, :x, :y, :z. "2002-06-22T22:09:32-05:00" a :TestDate. "2002-06-22T12:34Z" a :TestDate. "2002-06-22" a :TestDate. "2002-06" a :TestDate. "2002" a :TestDate. "2000-01-01T00:00:00Z" a :TestDate. "1999-12-31T23:59:59.99Z" a :TestDate. "year %Y month %M day %d date: %D" a :TestFormat. "" a :TestFormat. { :y a :TestDate; time:inSeconds :x } log:implies { :y TEST:inSeconds :x }. { :t time:inSeconds "1000000000"} log:implies { :t TEST:inSeconds "1000000000"}. { :y a :TestDate; time:year :x } log:implies { :y TEST:year :x }. { :y a :TestDate; time:month :x } log:implies { :y TEST:month :x }. { :y a :TestDate; time:day :x } log:implies { :y TEST:day :x }. { :y a :TestDate; time:hour :x } log:implies { :y TEST:hour :x }. { :y a :TestDate; time:minute :x } log:implies { :y TEST:minute :x }. { :y a :TestDate; time:second :x } log:implies { :y TEST:second :x }. { :y a :TestDate; time:dayOfWeek :x } log:implies { :y TEST:dayOfWeek :x }. { :y a :TestDate; time:timeZone :x } log:implies { :y TEST:timeZone :x }. log:implies a log:Chaff. # purge rules #ends cwm-1.2.1/test/time/t1.n30000644015216600007660000000257610066677544014151 0ustar syosisyosi# test cwm time built-ins # # usage: cwm --think # # The repeatable ones are tested. Ones that depend # on the actual time are in now.n3 # @prefix log: . @prefix time: . @prefix v: <#>. @prefix TEST: . @prefix : <#>. @forAll :f, :t, :x, :y, :z. "2002-06-22T22:09:32-05:00" a :TestDate. "2002-06-22T12:34Z" a :TestDate. "2002-06-22" a :TestDate. "2002-06" a :TestDate. "2002" a :TestDate. "2000-01-01T00:00:00Z" a :TestDate. "1999-12-31T23:59:59.99Z" a :TestDate. "year %Y month %M day %d date: %D" a :TestFormat. "" a :TestFormat. { :y a :TestDate; time:inSeconds :x } log:implies { :y TEST:inSeconds :x }. { :t time:inSeconds "1000000000"} log:implies { :t TEST:inSeconds "1000000000"}. { :y a :TestDate; time:year :x } log:implies { :y TEST:year :x }. { :y a :TestDate; time:month :x } log:implies { :y TEST:month :x }. { :y a :TestDate; time:day :x } log:implies { :y TEST:day :x }. { :y a :TestDate; time:hour :x } log:implies { :y TEST:hour :x }. { :y a :TestDate; time:minute :x } log:implies { :y TEST:minute :x }. { :y a :TestDate; time:second :x } log:implies { :y TEST:second :x }. { :y a :TestDate; time:dayOfWeek :x } log:implies { :y TEST:dayOfWeek :x }. { :y a :TestDate; time:timeZone :x } log:implies { :y TEST:timeZone :x }. log:implies a log:Chaff. # purge rules #ends cwm-1.2.1/test/ntriples/0000755015216600007660000000000010731073450014234 5ustar syosisyosicwm-1.2.1/test/ntriples/t1.ref.ntriples0000644015216600007660000000020210007205224017077 0ustar syosisyosi "Some data on\ntwo lines" . cwm-1.2.1/test/ntriples/detailed.tests0000644015216600007660000000076410007205224017072 0ustar syosisyosi# List of regression tests # # Internationalization tests # # Note: Command lines must be for running in the directory above. # @prefix : <#>. @prefix x: <#>. @prefix test: . :t001 a test:CwmTest; test:originalRequest ; test:referenceOutput ; test:description "No newline in NTriples"; test:arguments "ntriples/t1.n3 --ntriples". #ends cwm-1.2.1/test/ntriples/t1.n30000644015216600007660000000025410007205224015013 0ustar syosisyosi# See http://lists.w3.org/Archives/Public/www-archive/2001Oct/0022.html # @prefix : . :a :b """Some data on two lines""" . #ends cwm-1.2.1/test/nodeID/0000755015216600007660000000000010731073447013544 5ustar syosisyosicwm-1.2.1/test/nodeID/classes.n30000644015216600007660000000020710074532624015437 0ustar syosisyosi@prefix log: . @forSome :_x . :yosi :likes :_x; :eats :_x . :_x a :Thing; :color :red . cwm-1.2.1/test/nodeID/classes.ref.rdf0000644015216600007660000000053410137460165016450 0ustar syosisyosi cwm-1.2.1/test/nodeID/ex1.rdf0000644015216600007660000000105007635662762014747 0ustar syosisyosi cwm-1.2.1/test/paw/0000755015216600007660000000000010731073447013171 5ustar syosisyosicwm-1.2.1/test/paw/detailed.tests0000644015216600007660000000207110466115352016025 0ustar syosisyosi# List of regression tests for $SWAP/test/reason @prefix : <#>. @prefix x: <#>. @prefix test: . @prefix dc: . # yuk - under protest - no hash # Tests for PAW -- see also the -p option of retest.py :t01check a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/paw-t01check.n3>; test:description "main paw example"; test:arguments """--closure=e --rdf http://dig.csail.mit.edu/2005/09/rein/examples/judy-req.rdf --n3 http://dig.csail.mit.edu/2005/09/rein/engine.n3 --think --filter="http://dig.csail.mit.edu/2005/09/rein/filter.n3" --why | python ../check.py""". :t02check a test:CwmTest; test:workingDirectory <../>; test:referenceOutput <../ref/paw-t02check.n3>; test:description "main paw lean example"; test:arguments """--closure=e --n3=Bir paw/alice-req2.n3 http://dig.csail.mit.edu/2006/06/rein/src/lean-engine.n3 --think --filter="http://dig.csail.mit.edu/2006/06/rein/src/lean-filter.n3" --why | python ../check.py """. cwm-1.2.1/test/invalid-ex.n30000644015216600007660000000072107302103577014702 0ustar syosisyosi# Example using daml-ex ontology # but with invalid things @prefix ex: . @prefix daml: . @prefix rdfs: . @prefix rdf: . <> daml:imports . <#disjointTest> a ex:Man; a ex:Woman. # Can't be both. <#joe> is ex:father of <#alex>; is ex:mother of <#bill>. # Same, but less direct. #ENDS cwm-1.2.1/test/smush-schema.n30000644015216600007660000000136510066677543015256 0ustar syosisyosi# from http://rdfweb.org/2001/01/design/smush.html # see also: #rdfig 20 Jul 2001. @prefix : . @prefix v: . @prefix agg: . @prefix log: . # :UniquelyIdentifyingProperty has since # been called daml+oil:UnambiguousProperty. # but let's not mix DAML into this... @forAll :p, :x, :y, :z. { :p a agg:UniquelyIdentifyingProperty. } log:implies { { :x :p :z. :y :p :z. } log:implies { :x = :y } }. agg:personalMailbox a agg:UniquelyIdentifyingProperty. agg:personalHomepage a agg:UniquelyIdentifyingProperty. agg:corporateHomepage a agg:UniquelyIdentifyingProperty. cwm-1.2.1/test/anonymous_loop.n30000644015216600007660000000003210161625402015707 0ustar syosisyosi_:a :z _:b . _:b :y _:a . cwm-1.2.1/test/ql/0000755015216600007660000000000010731073450013010 5ustar syosisyosicwm-1.2.1/test/ql/t00.n30000644015216600007660000000042410070622465013657 0ustar syosisyosi@prefix : . @prefix q: . @prefix ex: . @prefix math: . @keywords a. [] select { result is (?x ?y) }; where { ?x a ex:Librarian; ex:hairColor ?y }. cwm-1.2.1/test/ql/kb1.n30000644015216600007660000000101510070622465013726 0ustar syosisyosi# example knowledge base @prefix q: . @prefix ex: . @prefix : . @prefix math: . @keywords a. [] a Reading; temp 26; ex:place London. [] a Reading; temp 21; ex:place Helsinki. [] a Reading; temp -10; ex:place Boston. [] a Reading; temp 31; ex:place Barcelona. Joe a Librarian; hairColor "black"; phone "+1 234 555 6789". Mary a Librarian; hairColor "red". Phil a FilmStar; hairColor "green". #endscwm-1.2.1/test/ql/t00-ref.n30000644015216600007660000000033010070622754014426 0ustar syosisyosi @prefix : . @prefix q: . q:result q:is ( :Joe "black" ), ( :Mary "red" ) . cwm-1.2.1/test/ql/detailed.tests0000644015216600007660000000106210070622754015651 0ustar syosisyosi# List of regression tests # # N3QL tests: details # # Note: Command lines must be for running in the directory above. # @prefix : <#>. @prefix x: <#>. @prefix test: . :QL_00 a test:CwmTest; test:referenceOutput ; test:description "Basic query"; test:arguments "ql/kb1.n3 --query=ql/t00.n3". :QL_01 a test:CwmTest; test:referenceOutput ; test:description "Basic query plus an arithmetic constraint"; test:arguments "ql/kb1.n3 --query=ql/t01.n3". #ends cwm-1.2.1/test/ql/t01.n30000644015216600007660000000062310070622465013661 0ustar syosisyosi@prefix : . @prefix q: . @prefix ex: . @prefix math: . @keywords a. <> select { ?p ex:had ?t }; where { [ a ex:Reading; ex:temp ?t; ex:place ?p]. ?t math:greaterThan 25 }. #___________________________________________ #ex:London ex:had 26. #ex:Barcelona had 31. cwm-1.2.1/test/ql/t01-ref.n30000644015216600007660000000016510070622754014435 0ustar syosisyosi @prefix : . :Barcelona :had 31 . :London :had 26 . cwm-1.2.1/test/reify/0000755015216600007660000000000010731073447013520 5ustar syosisyosicwm-1.2.1/test/reify/detailed.tests0000644015216600007660000000724210155654420016360 0ustar syosisyosi# List of regression tests # # - was in bash script retest.sh # @prefix : <#>. @prefix x: <#>. @prefix test: . # test:shortFileName "lists-simple.n3"; :t1001 a test:CwmTest; test:referenceOutput ; test:description "reify never. If this test fails, all the next are meaningless"; test:arguments """-n3 rules13.n3""". :t1002 a test:CwmTest; test:referenceOutput ; test:description "simple reifying"; test:arguments """-n3 reify/reify0.n3 --reify""". :t1003 a test:CwmTest; test:referenceOutput ; test:description "reify a document with quantifiers"; test:arguments """-n3 includes/quantifiers_limited.n3 --reify """. :t1004 a test:CwmTest, test:VerboseTest; # Don't run with debug output on test:referenceOutput ; test:description "reify twice"; test:arguments """-n3 reify/reify0.n3 --reify --reify""". :t1005 a test:CwmTest; test:referenceOutput ; test:description "reify, then dereify"; test:arguments """-n3 reify/reify0.n3 --reify --dereify""". :t1007 a test:CwmTest; test:referenceOutput ; test:description "reify twice, then dereify twice"; test:arguments """-n3 reify/reify0.n3 --reify --reify --dereify --dereify""". :t1009 a test:CwmTest; test:referenceOutput ; test:description "reify thrice, then dereify thrice"; test:arguments """-n3 reify/reify0.n3 --reify --reify --reify --dereify --dereify --dereify""". :t1010 a test:CwmTest; test:referenceOutput ; test:description "dereifying test 1"; test:arguments """-n3 reify/reify1.n3 --dereify""". :t1012 a test:CwmTest; test:referenceOutput ; test:description "dereifying twice"; test:arguments """-n3 reify/reify2.n3 --dereify --dereify""". :t1014 a test:CwmTest; test:referenceOutput ; test:description "dereifying thrice"; test:arguments """-n3 reify/reify3.n3 --dereify --dereify --dereify""". :t1016 a test:CwmTest; test:referenceOutput ; test:description "dereifying test 2"; test:arguments """-n3 reify/reify2.n3 --dereify""". :t1100 a test:CwmTest; test:referenceOutput ; test:description "flatten test 1"; test:arguments """-n3 reify/reify0.n3 --flatten""". #:t1102 a test:CwmTest; # test:referenceOutput ; # test:description "flatten a flattened file"; # test:arguments """-n3 reify/flatten1.n3 --flatten""". :t1101 a test:CwmTest; test:referenceOutput ; test:description "flatten twice -- the second should do nothing"; test:arguments """-n3 reify/reify0.n3 --flatten --flatten""". :t1103 a test:CwmTest; test:referenceOutput ; test:description "unflatten a flattened file"; test:arguments """-n3 reify/flatten1.n3 --unflatten""". #:t1018 a test:CwmTest; # test:referenceOutput ; # test:description "dereifying test 3"; # test:arguments """-n3 reify/reify3.n3 --dereify""". #:t1020 a test:CwmTest; # test:referenceOutput ; # test:description "sanity check on serializing 1"; # test:arguments """-n3 reify/reify1.n3 --reify""". #:t1025 a test:CwmTest; # test:referenceOutput ; # test:description "sanity check on serializing 2"; # test:arguments """-n3 reify/reify2.n3 --reify""". #:t1027 a test:CwmTest; # test:referenceOutput ; # test:description "reify thrice"; # test:arguments """-n3 reify/reify0.n3 --reify --reify --reify""". #ends cwm-1.2.1/cwm_os.html0000644015216600007660000012621710642726420013606 0ustar syosisyosi Python: module cwm_os
 
 
cwm_os
index
/Users/yosi/CVSROOT/WWW/2000/10/swap/cwm_os.py

 
Modules
       
os
uripath

 
Classes
       
term.Function(term.BuiltIn)
BI_argv(term.LightBuiltIn, term.Function)
BI_baseAbsolute(term.LightBuiltIn, term.Function)
BI_baseRelative(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_environ(term.LightBuiltIn, term.Function)
term.LightBuiltIn(term.GenericBuiltIn)
BI_argv(term.LightBuiltIn, term.Function)
BI_baseAbsolute(term.LightBuiltIn, term.Function)
BI_baseRelative(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_environ(term.LightBuiltIn, term.Function)
term.ReverseFunction(term.BuiltIn)
BI_baseRelative(term.LightBuiltIn, term.Function, term.ReverseFunction)

 
class BI_argv(term.LightBuiltIn, term.Function)
    # Command line argument: read-only
#  The command lines are passed though cwm using "--with" and into the RDFStore when init'ed.
# Not fatal if not defined
 
 
Method resolution order:
BI_argv
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_baseAbsolute(term.LightBuiltIn, term.Function)
    The baseAbsolute function generates an absolute URIref from a string,
interpreting the string as a a relative URIref relative to the current
process base URI (typically, current working directory).
It is not a reverse function, because sereral different relativisations
exist for the same absolute URI. See uripath.py.
 
 
Method resolution order:
BI_baseAbsolute
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_baseRelative(term.LightBuiltIn, term.Function, term.ReverseFunction)
    The baseRelative of a URI is its expression relation to the process base URI.
It is 1:1, being an arbitrary cannonical form.
It is a reverse function too, as you can always work the other way.
 
 
Method resolution order:
BI_baseRelative
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
evaluateSubject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Methods inherited from term.ReverseFunction:
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_environ(term.LightBuiltIn, term.Function)
    # Read Operating sytem environment lookup - read-only
#
# Not fatal if not defined
 
 
Method resolution order:
BI_environ
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
Functions
       
isString(x)
register(store)

 
Data
        OS_NS_URI = 'http://www.w3.org/2000/10/swap/os#'
cwm-1.2.1/thing.html0000644015216600007660000024243110642726424013431 0ustar syosisyosi Python: module thing
 
 
thing
index
/Users/yosi/CVSROOT/WWW/2000/10/swap/thing.py

$Id: thing.html,v 1.23 2007/06/27 17:58:39 syosi Exp $
 
OBSOLETE
 This module was too much of a mixture. See
 
 - myStore.py to import to set up a default store for your program, and Namespace.
 - term.py to define the class of Term and some subclasses.
 
Was: Interning of URIs and strings for storage in SWAP store
 
Includes:
 - template classes for builtins

 
Modules
       
binascii
md5
string
sys
uripath
urllib

 
Classes
       
__builtin__.object
Namespace
Term
CompoundTerm
List
EmptyList
FragmentNil(EmptyList, Fragment)
NonEmptyList
Fragment
Anonymous
BuiltIn
Function
HeavyBuiltIn
LightBuiltIn
ReverseFunction
Literal
Integer
Symbol

 
class Anonymous(Fragment)
    
Method resolution order:
Anonymous
Fragment
Term

Methods defined here:
__init__(self, resource, fragid)
asPair(self)
generated(self)

Methods inherited from Fragment:
reification(self, sink, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/#whatever"]
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
occurringIn(self, vars)
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
value(self)
As a python value - by default, none exists, use self

 
class BuiltIn(Fragment)
    This class is a supercalss to any builtin predicate in cwm.
 
A binary operator can calculate truth value given 2 arguments
 
 
Method resolution order:
BuiltIn
Fragment
Term

Methods defined here:
__init__(self, resource, fragid)
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use evaluate, subject, etc.

Methods inherited from Fragment:
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
reification(self, sink, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/#whatever"]
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
occurringIn(self, vars)
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
value(self)
As a python value - by default, none exists, use self

 
class CompoundTerm(Term)
    A compound term has occurrences of terms within it.
Examples: List, Formula
 
  Methods inherited from Term:
__init__(self, store=None)
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
representation(self, base=None)
The string represnting this in N3
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
value(self)
As a python value - by default, none exists, use self

 
class EmptyList(List)
    
Method resolution order:
EmptyList
List
CompoundTerm
Term

Methods defined here:
__repr__(self)
newList(self, value)
occurringIn(self, vars)
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
uriref(self)
value(self)

Methods inherited from List:
__init__(self, store, first, rest)
__iter__(self)
The internal method which allows one to iterate over the statements
as though a formula were a sequence.
asSequence(self)
Convert to a python sequence - NOT recursive
precededBy(self, first)

Methods inherited from Term:
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
representation(self, base=None)
The string represnting this in N3

 
class Fragment(Term)
    Term which DOES have a fragment id in its URI
 
  Methods defined here:
__init__(self, resource, fragid)
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
reification(self, sink, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/#whatever"]
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
occurringIn(self, vars)
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
value(self)
As a python value - by default, none exists, use self

 
class FragmentNil(EmptyList, Fragment)
    This is unique in being both a symbol and a list
 
 
Method resolution order:
FragmentNil
EmptyList
List
CompoundTerm
Term
Fragment

Methods defined here:
__init__(self, resource, fragid)

Methods inherited from EmptyList:
__repr__(self)
newList(self, value)
occurringIn(self, vars)
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
uriref(self)
value(self)

Methods inherited from List:
__iter__(self)
The internal method which allows one to iterate over the statements
as though a formula were a sequence.
asSequence(self)
Convert to a python sequence - NOT recursive
precededBy(self, first)

Methods inherited from Term:
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
representation(self, base=None)
The string represnting this in N3

Methods inherited from Fragment:
reification(self, sink, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/#whatever"]
uriref2(self, base)

 
class Function(BuiltIn)
    A function is a builtin which can calculate its object given its subject.
 
To get cwm to invoke it this way, your built-in must be a subclass of Function.
I may make changes to clean up the parameters of these methods below some day. -tbl
 
 
Method resolution order:
Function
BuiltIn
Fragment
Term

Methods defined here:
__init__(self)
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Methods inherited from Fragment:
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
reification(self, sink, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/#whatever"]
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
occurringIn(self, vars)
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
value(self)
As a python value - by default, none exists, use self

 
class HeavyBuiltIn(BuiltIn)
    A heavy built-in is fast and is calculated late, after searching the store
to see if the answer is already in it.
 
Make your built-in a subclass of either this or LightBultIn to tell cwm when to
run it.  Going out onto the web or net counts as Heavy.
 
 
Method resolution order:
HeavyBuiltIn
BuiltIn
Fragment
Term

Methods inherited from BuiltIn:
__init__(self, resource, fragid)
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use evaluate, subject, etc.

Methods inherited from Fragment:
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
reification(self, sink, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/#whatever"]
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
occurringIn(self, vars)
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
value(self)
As a python value - by default, none exists, use self

 
class Integer(Literal)
    
Method resolution order:
Integer
Literal
Term

Methods defined here:
__init__(self, store, str)
__int__(self)
__repr__(self)
__str__(self)
representation(self, base=None)
value(self)

Methods inherited from Literal:
asHashURI(self)
return a md5: URI for this literal.
Hmm... encoding... assuming utf8? @@test this.
Hmm... for a class of literals including this one,
strictly speaking.
asPair(self)
occurringIn(self, vars)
reification(self, sink, why=None)
Describe myself in RDF to the given context
 
[ reify:value "un expression quelconque"@fr ]
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
uriref(self)

Methods inherited from Term:
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).

 
class LightBuiltIn(BuiltIn)
    A light built-in is fast and is calculated immediately before searching the store.
 
Make your built-in a subclass of either this or HeavyBultIn to tell cwm when to
run it.  Going out onto the web or net counts as heavy.
 
 
Method resolution order:
LightBuiltIn
BuiltIn
Fragment
Term

Methods inherited from BuiltIn:
__init__(self, resource, fragid)
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use evaluate, subject, etc.

Methods inherited from Fragment:
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
reification(self, sink, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/#whatever"]
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
occurringIn(self, vars)
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
value(self)
As a python value - by default, none exists, use self

 
class List(CompoundTerm)
    
Method resolution order:
List
CompoundTerm
Term

Methods defined here:
__init__(self, store, first, rest)
__iter__(self)
The internal method which allows one to iterate over the statements
as though a formula were a sequence.
asSequence(self)
Convert to a python sequence - NOT recursive
occurringIn(self, vars)
Which variables in the list occur in this list?
precededBy(self, first)
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
uriref(self)
value(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
representation(self, base=None)
The string represnting this in N3
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match

 
class Literal(Term)
    Literal is a representation of an RDF literal
 
really, data:text/rdf+n3;%22hello%22 == "hello" but who
wants to store it that way?  Maybe we do... at least in theory and maybe
practice but, for now, we keep them in separate subclases of Term.
An RDF literal has a value - by default a string, and a datattype, and a language
 
  Methods defined here:
__init__(self, store, string, dt=None, lang=None)
__int__(self)
__repr__(self)
__str__(self)
asHashURI(self)
return a md5: URI for this literal.
Hmm... encoding... assuming utf8? @@test this.
Hmm... for a class of literals including this one,
strictly speaking.
asPair(self)
occurringIn(self, vars)
reification(self, sink, why=None)
Describe myself in RDF to the given context
 
[ reify:value "un expression quelconque"@fr ]
representation(self, base=None)
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
uriref(self)
value(self)

Methods inherited from Term:
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).

 
class Namespace(__builtin__.object)
    A shortcut for getting a symbols as interned by the default store
 
>>> RDF = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
>>> RDF.type
'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
>>> RDF.type is RDF.type
1
 
  Methods defined here:
__getattr__(self, lname)
get the lname Symbol in this namespace.
 
lname -- an XML name (limited to URI characters)
I hope this is only called *after* the ones defines above have been checked
__init__(self, name)
sym(self, lname)
For getting a symbol for an expression, rather than a constant.
For, and from, pim/toIcal.py

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Namespace' objects>
list of weak references to the object (if defined)

 
class NonEmptyList(List)
    
Method resolution order:
NonEmptyList
List
CompoundTerm
Term

Methods defined here:
__repr__(self)
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match

Methods inherited from List:
__init__(self, store, first, rest)
__iter__(self)
The internal method which allows one to iterate over the statements
as though a formula were a sequence.
asSequence(self)
Convert to a python sequence - NOT recursive
occurringIn(self, vars)
Which variables in the list occur in this list?
precededBy(self, first)
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
uriref(self)
value(self)

Methods inherited from Term:
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
representation(self, base=None)
The string represnting this in N3

 
class ReverseFunction(BuiltIn)
    A reverse function is a builtin which can calculate its subject given its object.
 
To get cwm to invoke it this way, your built-in must be a subclass of ReverseFunction.
If a function (like log:uri for example) is a two-way  (1:1) builtin, it should be declared
a subclass of Function and ReverseFunction. Then, cwm will call it either way as needed
in trying to resolve a query.
 
 
Method resolution order:
ReverseFunction
BuiltIn
Fragment
Term

Methods defined here:
__init__(self)
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Methods inherited from Fragment:
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
reification(self, sink, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/#whatever"]
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
occurringIn(self, vars)
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
value(self)
As a python value - by default, none exists, use self

 
class Symbol(Term)
    Term which has no fragment
 
  Methods defined here:
__init__(self, uri, store=None)
internAnonymous(r, fragid)
internFrag(self, fragid, thetype)
reification(self, sink, why=None)
Describe myself in RDF to the given context
 
[ reify:uri "http://example.org/whatever"]
uriref(self)
uriref2(self, base)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
representation(self, base=None)
The string represnting this in N3
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
value(self)
As a python value - by default, none exists, use self

 
class Term
    The Term object represents an RDF term.
 
It is interned for speed of processing by the store.
 
  Methods defined here:
__init__(self, store=None)
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
qname(self)
Output XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This should be beefed up to guarantee unambiguity (see __repr__ documentation).
representation(self, base=None)
The string represnting this in N3
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
Return [(var1, val1), (var2,val2)...] if match
value(self)
As a python value - by default, none exists, use self

 
Functions
       
bNode(str, context)
Create or reuse, in the default store, a new unnamed node within the given
formula as context, and return it for future use
existential(str, context, uri)
Create or reuse, in the default store, a new named variable
existentially qualified within the given
formula as context, and return it for future use
formula()
Create or reuse, in the default store, a new empty formula (triple people think: triple store)
and return it for future use
literal(str, dt=None, lang=None)
Create or reuse, in the default store, an interned version of the given literal string
and return it for future use
load(uri=None, contentType=None, formulaURI=None, remember=1)
Get and parse document.  Guesses format if necessary.
 
uri:      if None, load from standard input.
remember: if 1, store as metadata the relationship between this URI and this formula.
 
Returns:  top-level formula of the parsed document.
Raises:   IOError, SyntaxError, DocumentError
loadMany(uris)
Load a number of resources into the same formula
 
Returns:  top-level formula of the parsed information.
Raises:   IOError, SyntaxError, DocumentError
merge(a, b)
Merge sorted sequences
 
The fact that the sequences are sorted makes this faster
setStore(s)
Set the process-global default store to be used when an explicit store is not
setStoreClass(c)
Set the process-global class to be used to generate a new store if needed
symbol(uri)
Create or reuse, in the default store, an interned version of the given symbol
and return it for future use
universal(str, context, uri)
Create or reuse, in the default store, a named variable
universally qualified within the given
formula as context, and return it for future use
uri_encode(str)
untested - this must be in a standard library somewhere

 
Data
        ALL4 = (0, 1, 2, 3)
ANONYMOUS = 3
BOUNDLISTS = 4
CONSTS = 2
CONTEXT = 0
FORMULA = 1
INFINITY = 1000000000
LITERAL = 2
LITERAL_URI_prefix = 'data:text/rdf+n3;'
List_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
Logic_NS = 'http://www.w3.org/2000/10/swap/log#'
OBJ = 3
PARTS = (1, 2, 3)
PRED = 1
QUAD = 5
SHORT = 1
STATE = 0
SUBJ = 2
SYMBOL = 0
VARS = 3
generators = _Feature((2, 2, 0, 'alpha', 1), (2, 3, 0, 'final', 0), 4096)
reify = <thing.Namespace object>
store = None
storeClass = None
subcontext_cache_context = None
subcontext_cache_subcontexts = None
cwm-1.2.1/cwm_times.html0000644015216600007660000046321510642726422014312 0ustar syosisyosi Python: module cwm_times
 
 
cwm_times (version 0.3)
index
/Users/yosi/CVSROOT/WWW/2000/10/swap/cwm_times.py

The time built-ins concern dates and times expressed in a specific
version of ISO date-time format.  These functions allow the various
parts of the date and time to be compared, and converted
into interger second GMT era format for arithmetic.
 
Be aware that ISo times carry timezone offset information:  they cannot be
converted to integer second times without a valid timezone offset, such as "Z".

 
Modules
       
calendar
isodate
notation3
re
time

 
Classes
       
term.Function(term.BuiltIn)
BI_date(term.LightBuiltIn, term.Function)
BI_day(term.LightBuiltIn, term.Function)
BI_dayOfWeek(term.LightBuiltIn, term.Function)
BI_format(term.LightBuiltIn, term.Function)
BI_formatSeconds(term.LightBuiltIn, term.Function)
BI_gmTime(term.LightBuiltIn, term.Function)
BI_hour(term.LightBuiltIn, term.Function)
BI_inSeconds(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_localTime(term.LightBuiltIn, term.Function)
BI_minute(term.LightBuiltIn, term.Function)
BI_month(term.LightBuiltIn, term.Function)
BI_parseToSeconds(term.LightBuiltIn, term.Function)
BI_second(term.LightBuiltIn, term.Function)
BI_timeZone(term.LightBuiltIn, term.Function)
BI_year(term.LightBuiltIn, term.Function)
term.LightBuiltIn(term.GenericBuiltIn)
BI_date(term.LightBuiltIn, term.Function)
BI_day(term.LightBuiltIn, term.Function)
BI_dayOfWeek(term.LightBuiltIn, term.Function)
BI_equalTo
BI_format(term.LightBuiltIn, term.Function)
BI_formatSeconds(term.LightBuiltIn, term.Function)
BI_gmTime(term.LightBuiltIn, term.Function)
BI_hour(term.LightBuiltIn, term.Function)
BI_inSeconds(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_localTime(term.LightBuiltIn, term.Function)
BI_minute(term.LightBuiltIn, term.Function)
BI_month(term.LightBuiltIn, term.Function)
BI_parseToSeconds(term.LightBuiltIn, term.Function)
BI_second(term.LightBuiltIn, term.Function)
BI_timeZone(term.LightBuiltIn, term.Function)
BI_year(term.LightBuiltIn, term.Function)
term.ReverseFunction(term.BuiltIn)
BI_inSeconds(term.LightBuiltIn, term.Function, term.ReverseFunction)

 
class BI_date(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_date
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_day(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_day
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_dayOfWeek(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_dayOfWeek
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_equalTo(term.LightBuiltIn)
    
Method resolution order:
BI_equalTo
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluate(self, subj_py, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_format(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_format
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
params are ISO time string, format string. Returns reformatted. Ignores TZ@@

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_formatSeconds(term.LightBuiltIn, term.Function)
    #  original things from mNot's cwm_time.py:
#
#  these ise Integer time in seconds from epoch.
 
 
Method resolution order:
BI_formatSeconds
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
params are epoch-seconds time string, format string. Returns reformatted

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_gmTime(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_gmTime
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
Subject is  (empty string for standard formatting or) format string.
Returns formatted.

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_hour(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_hour
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_inSeconds(term.LightBuiltIn, term.Function, term.ReverseFunction)
    For a time string, the number of seconds from the era start as an integer-representing string.
 
 
Method resolution order:
BI_inSeconds
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Methods inherited from term.ReverseFunction:
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_localTime(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_localTime
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
Subject is format string or empty string for std formatting.
Returns reformatted. @@@@ Ignores TZ

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_minute(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_minute
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_month(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_month
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_parseToSeconds(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_parseToSeconds
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_second(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_second
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_timeZone(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_timeZone
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_year(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_year
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
Functions
       
register(store)
#  Register the string built-ins with the store

 
Data
        DAY = 86400
TIMES_NS_URI = 'http://www.w3.org/2000/10/swap/times#'
__version__ = '0.3'
tzone = <_sre.SRE_Pattern object>
cwm-1.2.1/cwm0000755015216600007660000007447610731063551012154 0ustar syosisyosi#!/usr/bin/python """ $Id: cwm.py,v 1.197 2007/12/13 15:38:39 syosi Exp $ Closed World Machine (also, in Wales, a valley - topologiclly a partially closed world perhaps?) This is an application which knows a certian amount of stuff and can manipulate it. It uses llyn, a (forward chaining) query engine, not an (backward chaining) inference engine: that is, it will apply all rules it can but won't figure out which ones to apply to prove something. License ------- Cwm: http://www.w3.org/2000/10/swap/doc/cwm.html Copyright (c) 2000-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 """ #the following lines should be removed. They will NOT work with any distribution #----------------- from os import chdir, getcwd from sys import path qqq = getcwd() chdir(path[0]) chdir('..') path.append(getcwd()) chdir(qqq) #import swap #print dir(swap) #----------------- #end lines should be removed import string, sys # From http://www.w3.org/2000/10/swap/ from swap import diag from swap.why import explainFormula, newTopLevelFormula from swap.diag import verbosity, setVerbosity, progress, tracking, setTracking from swap.uripath import join, splitFrag from swap.webAccess import urlopenForRDF, load, sandBoxed from swap import notation3 # N3 parsers and generators from swap import toXML # RDF generator from swap.why import BecauseOfCommandLine from swap.query import think, applyRules, applyQueries, applySparqlQueries, testIncludes from swap.update import patch from swap import uripath from swap import llyn from swap import RDFSink cvsRevision = "$Revision: 1.197 $" ################################################# Command line def doCommand(): """Command line RDF/N3 tool [--with ] options: --pipe Don't store, just pipe out * steps, in order left to right: --rdf Input & Output ** in RDF/XML insead of n3 from now on --n3 Input & Output in N3 from now on. (Default) --rdf=flags Input & Output ** in RDF and set given RDF flags --n3=flags Input & Output in N3 and set N3 flags --ntriples Input & Output in NTriples (equiv --n3=usbpartane -bySubject -quiet) --language=x Input & Output in "x" (rdf, n3, etc) --rdf same as: --language=rdf --languageOptions=y --n3=sp same as: --language=n3 --languageOptions=sp --ugly Store input and regurgitate, data only, fastest * --bySubject Store input and regurgitate in subject order * --no No output * (default is to store and pretty print with anonymous nodes) * --base= Set the base URI. Input or output is done as though theis were the document URI. --closure=flags Control automatic lookup of identifiers (see below) Load document. URI may be relative to current directory. --apply=foo Read rules from foo, apply to store, adding conclusions to store --patch=foo Read patches from foo, applying insertions and deletions to store --filter=foo Read rules from foo, apply to store, REPLACING store with conclusions --query=foo Read a N3QL query from foo, apply it to the store, and replace the store with its conclusions --sparql=foo Read a SPARQL query from foo, apply it to the store, and replace the store with its conclusions --rules Apply rules in store to store, adding conclusions to store --think as -rules but continue until no more rule matches (or forever!) --engine=otter use otter (in your $PATH) instead of llyn for linking, etc --why Replace the store with an explanation of its contents --why=u proof tries to be shorter --mode=flags Set modus operandi for inference (see below) --reify Replace the statements in the store with statements describing them. --dereify Undo the effects of --reify --flatten Reify only nested subexpressions (not top level) so that no {} remain. --unflatten Undo the effects of --flatten --think=foo as -apply=foo but continue until no more rule matches (or forever!) --purge Remove from store any triple involving anything in class log:Chaff --data Remove all except plain RDF triples (formulae, forAll, etc) --strings Dump :s to stdout ordered by :k whereever { :k log:outputString :s } --crypto Enable processing of crypto builtin functions. Requires python crypto. --help print this message --revision print CVS revision numbers of major modules --chatty=50 Verbose debugging output of questionable use, range 0-99 --sparqlServer instead of outputting, start a SPARQL server on port 8000 of the store --sparqlResults After sparql query, print in sparqlResults format instead of rdf finally: --with Pass any further arguments to the N3 store as os:argv values * mutually exclusive ** doesn't work for complex cases :-/ Examples: cwm --rdf foo.rdf --n3 --pipe Convert from rdf/xml to rdf/n3 cwm foo.n3 bar.n3 --think Combine data and find all deductions cwm foo.n3 --flat --n3=spart Mode flags affect inference extedning to the web: r Needed to enable any remote stuff. a When reading schema, also load rules pointed to by schema (requires r, s) E Errors loading schemas of definitive documents are ignored m Schemas and definitive documents laoded are merged into the meta knowledge (otherwise they are consulted independently) s Read the schema for any predicate in a query. u Generate unique ids using a run-specific Closure flags are set to cause the working formula to be automatically exapnded to the closure under the operation of looking up: s the subject of a statement added p the predicate of a statement added o the object of a statement added t the object of an rdf:type statement added i any owl:imports documents r any doc:rules documents E errors are ignored --- This is independant of --mode=E n Normalize IRIs to URIs e Smush together any nodes which are = (owl:sameAs) See http://www.w3.org/2000/10/swap/doc/cwm for more documentation. Setting the environment variable CWM_RDFLIB to 1 maked Cwm use rdflib to parse rdf/xml files. Note that this requires rdflib. """ import time import sys from swap import myStore # These would just be attributes if this were an object global _store global workingContext option_need_rdf_sometime = 0 # If we don't need it, don't import it # (to save errors where parsers don't exist) option_pipe = 0 # Don't store, just pipe though option_inputs = [] option_reify = 0 # Flag: reify on output (process?) option_flat = 0 # Flag: reify on output (process?) option_crypto = 0 # Flag: make cryptographic algorithms available setTracking(0) option_outURI = None option_outputStyle = "-best" _gotInput = 0 # Do we not need to take input from stdin? option_meta = 0 option_normalize_iri = 0 option_flags = { "rdf":"l", "n3":"", "think":"", "sparql":""} # RDF/XML serializer can't do list ("collection") syntax. option_quiet = 0 option_with = None # Command line arguments made available to N3 processing option_engine = "llyn" option_why = "" _step = 0 # Step number used for metadata _genid = 0 hostname = "localhost" # @@@@@@@@@@@ Get real one # The base URI for this process - the Web equiv of cwd _baseURI = uripath.base() option_format = "n3" # set the default format option_first_format = None _outURI = _baseURI option_baseURI = _baseURI # To start with - then tracks running base # First pass on command line - - - - - - - P A S S 1 for argnum in range(1,len(sys.argv)): # options after script name arg = sys.argv[argnum] if arg.startswith("--"): arg = arg[1:] # Chop posix-style -- to - # _equals = string.find(arg, "=") _lhs = "" _rhs = "" try: [_lhs,_rhs]=arg.split('=',1) try: _uri = join(option_baseURI, _rhs) except ValueError: _uri = _rhs except ValueError: pass if arg == "-ugly": option_outputStyle = arg elif _lhs == "-base": option_baseURI = _uri elif arg == "-rdf": option_format = "rdf" if option_first_format == None: option_first_format = option_format option_need_rdf_sometime = 1 elif _lhs == "-rdf": option_format = "rdf" if option_first_format == None: option_first_format = option_format option_flags["rdf"] = _rhs option_need_rdf_sometime = 1 elif arg == "-n3": option_format = "n3" if option_first_format == None: option_first_format = option_format elif _lhs == "-n3": option_format = "n3" if option_first_format == None: option_first_format = option_format option_flags["n3"] = _rhs elif _lhs == "-mode": option_flags["think"] = _rhs elif _lhs == "-closure": if "n" in _rhs: option_normalize_iri = 1 #elif _lhs == "-solve": # sys.argv[argnum+1:argnum+1] = ['-think', '-filter=' + _rhs] elif _lhs == "-language": option_format = _rhs if option_first_format == None: option_first_format = option_format elif _lhs == "-languageOptions": option_flags[option_format] = _rhs elif arg == "-quiet": option_quiet = 1 elif arg == "-pipe": option_pipe = 1 elif arg == "-crypto": option_crypto = 1 elif _lhs == "-why": diag.tracking=1 diag.setTracking(1) option_why = _rhs elif arg == "-why": diag.tracking=1 diag.setTracking(1) option_why = "" elif arg == "-track": diag.tracking=1 diag.setTracking(1) elif arg == "-bySubject": option_outputStyle = arg elif arg == "-no": option_outputStyle = "-no" elif arg == "-debugString": option_outputStyle = "-debugString" elif arg == "-strings": option_outputStyle = "-no" elif arg == "-sparqlResults": option_outputStyle = "-no" elif arg == "-triples" or arg == "-ntriples": option_format = "n3" option_flags["n3"] = "bravestpun" option_outputStyle = "-bySubject" option_quiet = 1 elif _lhs == "-outURI": option_outURI = _uri elif _lhs == "-chatty": setVerbosity(int(_rhs)) elif arg[:7] == "-apply=": pass elif arg[:7] == "-patch=": pass elif arg == "-reify": option_reify = 1 elif arg == "-flat": option_flat = 1 elif arg == "-help": print doCommand.__doc__ print notation3.ToN3.flagDocumentation print toXML.ToRDF.flagDocumentation try: from swap import sax2rdf # RDF1.0 syntax parser to N3 RDF stream print sax2rdf.RDFXMLParser.flagDocumentation except: pass return elif arg == "-revision": progress( "cwm=",cvsRevision, "llyn=", llyn.cvsRevision) return elif arg == "-with": option_with = sys.argv[argnum+1:] # The rest of the args are passed to n3 break elif arg[0] == "-": pass # Other option else : option_inputs.append(join(option_baseURI, arg)) _gotInput = _gotInput + 1 # input filename # Between passes, prepare for processing setVerbosity(0) if not option_normalize_iri: llyn.canonical = lambda x: x # Base defauts if option_baseURI == _baseURI: # Base not specified explicitly - special case if _outURI == _baseURI: # Output name not specified either if _gotInput == 1: # But input file *is*, _outURI = option_inputs[0] # Just output to same URI option_baseURI = _outURI # using that as base. if diag.tracking: _outURI = RDFSink.runNamespace()[:-1] option_baseURI = _outURI option_baseURI = splitFrag(option_baseURI)[0] # Fix the output sink if option_format == "rdf": _outSink = toXML.ToRDF(sys.stdout, _outURI, base=option_baseURI, flags=option_flags["rdf"]) elif option_format == "n3" or option_format == "sparql": _outSink = notation3.ToN3(sys.stdout.write, base=option_baseURI, quiet=option_quiet, flags=option_flags["n3"]) elif option_format == "trace": _outSink = RDFSink.TracingRDFSink(_outURI, base=option_baseURI, flags=option_flags.get("trace","")) if option_pipe: # this is really what a parser wants to dump to _outSink.backing = llyn.RDFStore( _outURI+"#_g", argv=option_with, crypto=option_crypto) else: # this is really what a store wants to dump to _outSink.backing = notation3.ToN3(sys.stdout.write, base=option_baseURI, quiet=option_quiet, flags=option_flags["n3"]) # hm. why does TimBL use sys.stdout.write, above? performance at the else: raise NotImplementedError version = "$Id: cwm.py,v 1.197 2007/12/13 15:38:39 syosi Exp $" if not option_quiet and option_outputStyle != "-no": _outSink.makeComment("Processed by " + version[1:-1]) # Strip $ to disarm _outSink.makeComment(" using base " + option_baseURI) if option_flat: _outSink = notation3.Reifier(_outSink, _outURI+ "#_formula", flat=1) if diag.tracking: myReason = BecauseOfCommandLine(`sys.argv`) # @@ add user, host, pid, pwd, date time? Privacy! else: myReason = None if option_pipe: _store = _outSink workingContext = _outSink #.newFormula() else: if "u" in option_flags["think"]: _store = llyn.RDFStore(argv=option_with, crypto=option_crypto) else: _store = llyn.RDFStore( _outURI+"#_g", argv=option_with, crypto=option_crypto) myStore.setStore(_store) if _gotInput: workingContext = _store.newFormula(option_inputs [0]+"#_work") newTopLevelFormula(workingContext) else: # default input if option_first_format is None: option_first_format = option_format ContentType={ "rdf": "application/xml+rdf", "n3": "text/rdf+n3", "sparql": "x-application/sparql"}[option_first_format] workingContext = _store.load( # asIfFrom = join(_baseURI, ".stdin"), asIfFrom = _baseURI, contentType = ContentType, flags = option_flags[option_first_format], remember = 0, referer = "", why = myReason, topLevel=True) workingContext.reopen() workingContext.stayOpen = 1 # Never canonicalize this. Never share it. # ____________________________________________________________________ # Take commands from command line:- - - - - P A S S 2 option_format = "n3" # Use RDF/n3 rather than RDF/XML option_flags = { "rdf":"l", "n3":"", "think": "", "sparql":"" } option_quiet = 0 _outURI = _baseURI option_baseURI = _baseURI # To start with def filterize(): """implementation of --filter for the --filter command, so we don't have it printed twice """ global workingContext global r workingContext = workingContext.canonicalize() _store._formulaeOfLength = {} filterContext = _store.newFormula() newTopLevelFormula(filterContext) _store.load(_uri, openFormula=filterContext, why=myReason, referer="") _newContext = _store.newFormula() newTopLevelFormula(_newContext) applyRules(workingContext, filterContext, _newContext) workingContext.close() workingContext = _newContext sparql_query_formula = None for arg in sys.argv[1:]: # Command line options after script name if verbosity()>5: progress("Processing %s." % (arg)) if arg.startswith("--"): arg = arg[1:] # Chop posix-style -- to - _equals = string.find(arg, "=") _lhs = "" _rhs = "" if _equals >=0: _lhs = arg[:_equals] _rhs = arg[_equals+1:] try: _uri = join(option_baseURI, _rhs) except ValueError: _uri =_rhs if arg[0] != "-": _inputURI = join(option_baseURI, splitFrag(arg)[0]) assert ':' in _inputURI ContentType={ "rdf": "application/xml+rdf", "n3": "text/rdf+n3", "sparql": "x-application/sparql"}[option_format] if not option_pipe: workingContext.reopen() try: load(_store, _inputURI, openFormula=workingContext, contentType =ContentType, flags=option_flags[option_format], referer="", why=myReason) except: progress(_inputURI) raise _gotInput = 1 elif arg == "-help": pass # shouldn't happen elif arg == "-revision": pass elif _lhs == "-base": option_baseURI = _uri if verbosity() > 10: progress("Base now "+option_baseURI) elif arg == "-ugly": option_outputStyle = arg elif arg == "-crypto": pass elif arg == "-pipe": pass elif _lhs == "-outURI": option_outURI = _uri elif arg == "-rdf": option_format = "rdf" elif _lhs == "-rdf": option_format = "rdf" option_flags["rdf"] = _rhs elif _lhs == "-mode": option_flags["think"] = _rhs elif _lhs == "-closure": workingContext.setClosureMode(_rhs) elif arg == "-n3": option_format = "n3" elif _lhs == "-n3": option_format = "n3" option_flags["n3"] = _rhs elif _lhs == "-language": option_format = _rhs if option_first_format == None: option_first_format = option_format elif _lhs == "-languageOptions": option_flags[option_format] = _lhs elif arg == "-quiet" : option_quiet = 1 elif _lhs == "-chatty": setVerbosity(int(_rhs)) elif arg[:7] == "-track=": diag.tracking = int(_rhs) elif option_pipe: ############## End of pipable options print "# Command line error: %s illegal option with -pipe", arg break elif arg == "-triples" or arg == "-ntriples": option_format = "n3" option_flags["n3"] = "spartan" option_outputStyle = "-bySubject" option_quiet = 1 elif arg == "-bySubject": option_outputStyle = arg elif arg == "-debugString": option_outputStyle = arg elif arg[:7] == "-apply=": workingContext = workingContext.canonicalize() filterContext = _store.load(_uri, flags=option_flags[option_format], referer="", why=myReason, topLevel=True) workingContext.reopen() applyRules(workingContext, filterContext); elif arg[:7] == "-apply=": workingContext = workingContext.canonicalize() filterContext = _store.load(_uri, flags=option_flags[option_format], referer="", why=myReason, topLevel=True) workingContext.reopen() applyRules(workingContext, filterContext); elif arg[:7] == "-patch=": workingContext = workingContext.canonicalize() filterContext = _store.load(_uri, flags=option_flags[option_format], referer="", why=myReason, topLevel=True) workingContext.reopen() patch(workingContext, filterContext); elif _lhs == "-filter": filterize() elif _lhs == "-query": workingContext = workingContext.canonicalize() filterContext = _store.load(_uri, flags=option_flags[option_format], referer="", why=myReason, topLevel=True) _newContext = _store.newFormula() applyQueries(workingContext, filterContext, _newContext) workingContext.close() workingContext = _newContext elif _lhs == "-sparql": workingContext.stayOpen = False workingContext = workingContext.canonicalize() filterContext = _store.load(_uri, why=myReason, referer="", contentType="x-application/sparql") _newContext = _store.newFormula() _newContext.stayOpen = True sparql_query_formula = filterContext applySparqlQueries(workingContext, filterContext, _newContext) # workingContext.close() workingContext = _newContext elif _lhs == "-why" or arg == "-why": workingContext.stayOpen = False workingContext = workingContext.close() workingContext = explainFormula(workingContext, option_why) # Can't prove proofs diag.tracking=0 diag.setTracking(0) elif arg == "-dump": workingContext = workingContext.canonicalize() progress("\nDump of working formula:\n" + workingContext.debugString()) elif arg == "-purge": workingContext.reopen() _store.purge(workingContext) elif arg == "-purge-rules" or arg == "-data": workingContext.reopen() _store.purgeExceptData(workingContext) elif arg == "-rules": workingContext.reopen() applyRules(workingContext, workingContext) elif arg[:7] == "-think=": filterContext = _store.load(_uri, referer="", why=myReason, topLevel=True) if verbosity() > 4: progress( "Input rules to --think from " + _uri) workingContext.reopen() think(workingContext, filterContext, mode=option_flags["think"]) elif arg[:7] == "-solve=": # --solve is a combination of --think and --filter. think(workingContext, mode=option_flags["think"]) filterize() elif _lhs == "-engine": option_engine = _rhs elif arg == "-think": workingContext.isWorkingContext = True think(workingContext, mode=option_flags["think"]) elif arg == '-rete': from swap import pycwmko pythink = pycwmko.directPychinkoQuery(workingContext) #return #pythink() """ from pychinko import interpreter from swap.set_importer import Set, ImmutableSet pyf = pycwmko.N3Loader.N3Loader() conv = pycwmko.ToPyStore(pyf) conv.statements(workingContext) interp = interpreter.Interpreter(pyf.rules[:]) interp.addFacts(Set(pyf.facts), initialSet=True) interp.run() pyf.facts = interp.totalFacts workingContext = workingContext.store.newFormula() reconv = pycwmko.FromPyStore(workingContext, pyf) reconv.run() """ elif arg == '-sparqlServer': from swap.sparql import webserver from swap import cwm_sparql sandBoxed(True) workingContext.stayOpen = False workingContext = workingContext.canonicalize() def _handler(s): return cwm_sparql.sparql_queryString(workingContext, s) webserver.sparql_handler = _handler webserver.run() elif arg == "-lxkbdump": # just for debugging raise NotImplementedError elif arg == "-lxfdump": # just for debugging raise NotImplementedError elif _lhs == "-prove": # code copied from -filter without really being understood -sdh _tmpstore = llyn.RDFStore( _outURI+"#_g", metaURI=_metaURI, argv=option_with, crypto=option_crypto) tmpContext = _tmpstore.newFormula(_uri+ "#_formula") _newURI = join(_baseURI, "_w_"+`_genid`) # Intermediate _genid = _genid + 1 _newContext = _tmpstore.newFormula(_newURI+ "#_formula") _tmpstore.loadURI(_uri) print targetkb elif arg == "-flatten": #raise NotImplementedError from swap import reify workingContext = reify.flatten(workingContext) elif arg == "-unflatten": from swap import reify workingContext = reify.unflatten(workingContext) #raise NotImplementedError elif arg == "-reify": from swap import reify workingContext = reify.reify(workingContext) elif arg == "-dereify": from swap import reify workingContext = reify.dereify(workingContext) elif arg == "-size": progress("Size: %i statements in store, %i in working formula." %(_store.size, workingContext.size())) elif arg == "-strings": # suppress output workingContext.outputStrings() option_outputStyle = "-no" elif arg == '-sparqlResults': from cwm_sparql import outputString, SPARQL_NS ns = _store.newSymbol(SPARQL_NS) if not sparql_query_formula: raise ValueError('No query') else: sys.stdout.write(outputString(sparql_query_formula, workingContext)[0].encode('utf_8')) option_outputStyle = "-no" elif arg == "-no": # suppress output option_outputStyle = arg elif arg[:8] == "-outURI=": pass elif arg == "-with": break else: progress( "cwm: Unknown option: " + arg) sys.exit(-1) # Squirt it out if not piped workingContext.stayOpen = 0 # End its use as an always-open knoweldge base if option_pipe: workingContext.endDoc() else: if hasattr(_outSink, "serializeKB"): raise NotImplementedError else: if verbosity()>5: progress("Begining output.") workingContext = workingContext.close() assert workingContext.canonical != None if option_outputStyle == "-ugly": _store.dumpChronological(workingContext, _outSink) elif option_outputStyle == "-bySubject": _store.dumpBySubject(workingContext, _outSink) elif option_outputStyle == "-no": pass elif option_outputStyle == "-debugString": print workingContext.debugString() else: # "-best" _store.dumpNested(workingContext, _outSink, flags=option_flags[option_format]) ############################################################ Main program if __name__ == '__main__': import os doCommand() cwm-1.2.1/pretty.html0000644015216600007660000002256010717716424013650 0ustar syosisyosi Python: module pretty
 
 
pretty
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/pretty.py

$Id: pretty.html,v 1.18 2007/11/18 02:01:56 syosi Exp $
 
Printing of N3 and RDF formulae
 
20003-8-20 split offf from llyn.py
 
This is or was http://www.w3.org/2000/10/swap/pretty.py

 
Modules
       
diag
string
types

 
Classes
       
exceptions.Exception
TooMuchRecursion
Serializer

 
class Serializer
    A serializer to serialize the formula F into the given
abstract syntax sink
 
  Methods defined here:
__init__(self, F, sink, flags='', sorting=0)
dumpBySubject(self, sorting=1)
Dump one formula only by order of subject except
forSome's first for n3=a mode
dumpChronological(self)
Fast as possible. Only dumps data. No formulae or universals.
dumpFormulaContents(self, context, sink, sorting, equals=0)
Iterates over statements in formula, bunching them up into a set
for each subject.
dumpLists(self)
Dump lists out as first and rest. Not used in pretty.
dumpNested(self)
Iterates over all URIs ever seen looking for statements
dumpPrefixes(self)
dumpStatement(self, sink, triple, sorting)
Dump one statement, including structure within object
dumpVariables(self, context, sink, sorting=1, pretty=0, dataOnly=0)
Dump the forAlls and the forSomes at the top of a formula
selectDefaultPrefix(self, printFunction)
Symbol whose fragments have the most occurrences.
we suppress the RDF namespace itself because the XML syntax
has problems with it being default as it is used for attributes.
 
This also outputs the prefixes.
tmDumpNested(self)

 
class TooMuchRecursion(exceptions.Exception)
     Methods inherited from exceptions.Exception:
__getitem__(...)
__init__(...)
__str__(...)

 
Functions
       
auPair(x)
Encode as object-free form for unparser interface
auxPairs(t)
canItbeABNode(formula, symbol)

 
Data
        ALL4 = (0, 1, 2, 3)
ANONYMOUS = 3
BNodePossibles = None
CONTEXT = 0
DAML_sameAs_URI = 'http://www.w3.org/2002/07/owl#sameAs'
FLOAT_DATATYPE = 'http://www.w3.org/2001/XMLSchema#double'
INTEGER_DATATYPE = 'http://www.w3.org/2001/XMLSchema#integer'
LITERAL = 2
LITERAL_DT = 21
LITERAL_LANG = 22
List_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
Logic_NS = 'http://www.w3.org/2000/10/swap/log#'
META_NS_URI = 'http://www.w3.org/2000/10/swap/meta#'
N3_Empty = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#Empty')
N3_List = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#List')
N3_first = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first')
N3_nil = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil')
N3_rest = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest')
OBJ = 3
OWL_NS = 'http://www.w3.org/2002/07/owl#'
PARTS = (1, 2, 3)
PRED = 1
RDF_NS_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
RDF_type_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
STRING_NS_URI = 'http://www.w3.org/2000/10/swap/string#'
SUBJ = 2
SYMBOL = 0
XMLLITERAL = 25
cvsRevision = '$Revision: 1.18 $'
forAllSym = 'http://www.w3.org/2000/10/swap/log#forAll'
forSomeSym = 'http://www.w3.org/2000/10/swap/log#forSome'
prefixchars = 'abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
tracking = 0
cwm-1.2.1/cwm_maths.html0000644015216600007660000064214510277134340014302 0ustar syosisyosi Python: module cwm_maths
 
 
cwm_maths (version 1.11)
index
/home/syosi/CVS-local/WWW/2000/10/swap/cwm_maths.py

Matematical Built-Ins for CWM/Llyn using Strings
 
Allows CWM to do addition, multiplication, subtraction, division, 
remainders, negation, exponentiation, count the members in a DAML 
list, and do the normal truth checking functions, only sub classed 
for numeric values.
 
All values are represented by string types (untyped literals in RDF).
See math (no s) for versions using numeric types.
 
cf. http://www.w3.org/2000/10/swap/cwm.py and 
http://ilrt.org/discovery/chatlogs/rdfig/2001-12-01.txt from 
"01:20:58" onwards.

 
Modules
       
re
string
sys
urllib

 
Classes
       
term.Function(term.BuiltIn)
BI_absoluteValue(term.LightBuiltIn, term.Function)
BI_difference(term.LightBuiltIn, term.Function)
BI_exponentiation(term.LightBuiltIn, term.Function)
BI_integerQuotient(term.LightBuiltIn, term.Function)
BI_memberCount(term.LightBuiltIn, term.Function)
BI_negation(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_product(term.LightBuiltIn, term.Function)
BI_quotient(term.LightBuiltIn, term.Function)
BI_remainder(term.LightBuiltIn, term.Function)
BI_rounded(term.LightBuiltIn, term.Function)
BI_sum(term.LightBuiltIn, term.Function)
term.LightBuiltIn(term.GenericBuiltIn)
BI_absoluteValue(term.LightBuiltIn, term.Function)
BI_difference(term.LightBuiltIn, term.Function)
BI_differenceOf(term.LightBuiltIn, term.ReverseFunction)
BI_equalTo
BI_exponentiation(term.LightBuiltIn, term.Function)
BI_exponentiationOf(term.LightBuiltIn, term.ReverseFunction)
BI_factors(term.LightBuiltIn, term.ReverseFunction)
BI_greaterThan
BI_integerQuotient(term.LightBuiltIn, term.Function)
BI_lessThan
BI_memberCount(term.LightBuiltIn, term.Function)
BI_negation(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_notEqualTo
BI_notGreaterThan
BI_notLessThan
BI_product(term.LightBuiltIn, term.Function)
BI_quotient(term.LightBuiltIn, term.Function)
BI_quotientOf(term.LightBuiltIn, term.ReverseFunction)
BI_remainder(term.LightBuiltIn, term.Function)
BI_remainderOf(term.LightBuiltIn, term.ReverseFunction)
BI_rounded(term.LightBuiltIn, term.Function)
BI_sum(term.LightBuiltIn, term.Function)
BI_sumOf(term.LightBuiltIn, term.ReverseFunction)
term.ReverseFunction(term.BuiltIn)
BI_differenceOf(term.LightBuiltIn, term.ReverseFunction)
BI_exponentiationOf(term.LightBuiltIn, term.ReverseFunction)
BI_factors(term.LightBuiltIn, term.ReverseFunction)
BI_negation(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_quotientOf(term.LightBuiltIn, term.ReverseFunction)
BI_remainderOf(term.LightBuiltIn, term.ReverseFunction)
BI_sumOf(term.LightBuiltIn, term.ReverseFunction)

 
class BI_absoluteValue(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_absoluteValue
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, x)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_difference(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_difference
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_differenceOf(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_differenceOf
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_equalTo(term.LightBuiltIn)
    
Method resolution order:
BI_equalTo
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_exponentiation(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_exponentiation
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_exponentiationOf(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_exponentiationOf
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_factors(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_factors
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_greaterThan(term.LightBuiltIn)
    
Method resolution order:
BI_greaterThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_integerQuotient(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_integerQuotient
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_lessThan(term.LightBuiltIn)
    
Method resolution order:
BI_lessThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_memberCount(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_memberCount
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_negation(term.LightBuiltIn, term.Function, term.ReverseFunction)
    
Method resolution order:
BI_negation
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalaluateObject(self, subject)
evalaluateSubject(self, object)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Methods inherited from term.ReverseFunction:
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notEqualTo(term.LightBuiltIn)
    
Method resolution order:
BI_notEqualTo
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notGreaterThan(term.LightBuiltIn)
    
Method resolution order:
BI_notGreaterThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notLessThan(term.LightBuiltIn)
    
Method resolution order:
BI_notLessThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_product(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_product
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_quotient(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_quotient
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_quotientOf(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_quotientOf
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_remainder(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_remainder
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_remainderOf(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_remainderOf
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_rounded(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_rounded
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, x)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_sum(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_sum
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_sumOf(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_sumOf
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
Functions
       
isString(x)
register(store)
tidy(x)

 
Data
        MATHS_NS_URI = 'http://www.w3.org/2000/10/swap/maths#'
__author__ = 'Sean B. Palmer'
__cvsid__ = '$Id: cwm_maths.html,v 1.11 2005/08/10 15:05:38 syosi Exp $'
__version__ = '$Revision: 1.11 $'

 
Author
        Sean B. Palmer
cwm-1.2.1/notation3.html0000644015216600007660000010245310731070067014227 0ustar syosisyosi Python: module notation3
 
 
notation3
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/notation3.py

$Id: notation3.py,v 1.200 2007/12/11 21:18:08 syosi Exp $
 
 
This module implements a Nptation3 parser, and the final
part of a notation3 serializer.
 
See also:
 
Notation 3
http://www.w3.org/DesignIssues/Notation3
 
Closed World Machine - and RDF Processor
http://www.w3.org/2000/10/swap/cwm
 
To DO: See also "@@" in comments
 
- Clean up interfaces
______________________________________________
 
Module originally by Dan Connolly, includeing notation3
parser and RDF generator. TimBL added RDF stream model
and N3 generation, replaced stream model with use
of common store/formula API.  Yosi Scharf developped
the module, including tests and test harness.

 
Modules
       
RDFSink
codecs
diag
re
string
sys
triple_maker
types
uripath
urllib

 
Classes
       
RDFSink.RDFSink
ToN3
tmToN3
exceptions.SyntaxError(exceptions.StandardError)
BadSyntax
SinkParser

 
class BadSyntax(exceptions.SyntaxError)
    
Method resolution order:
BadSyntax
exceptions.SyntaxError
exceptions.StandardError
exceptions.Exception

Methods defined here:
__init__(self, uri, lines, str, i, why)
__str__(self)

Data and other attributes inherited from exceptions.SyntaxError:
filename = None
lineno = None
msg = ''
offset = None
print_file_and_line = None
text = None

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class SinkParser
     Methods defined here:
UEscape(self, str, i, startline)
__init__(self, store, openFormula=None, thisDoc='', baseURI=None, genPrefix='', metaURI=None, flags='', why=None)
note: namespace names should *not* end in #;
the # will get added during qname processing
anonymousNode(self, ln)
Remember or generate a term for one of these _: anonymous nodes
bareWord(self, str, i, res)
abc -> :abc
bind(self, qn, uri)
blankNode(self, uri=None)
checkDot(self, str, i)
commaSeparatedList(self, str, j, res, what)
return value: -1 bad syntax; >1 new position in str
res has things found appended
directive(self, str, i)
directiveOrStatement(self, str, h)
endDoc(self)
Signal end of document and stop parsing. returns formula
feed(self, octets)
Feed an octet stream tothe parser
 
if BadSyntax is raised, the string
passed in the exception object is the
remainder after any statements have been parsed.
So if there is more data to feed to the
parser, it should be straightforward to recover.
formula(self)
here(self, i)
String generated from position in file
 
This is for repeatability when refering people to bnodes in a document.
This has diagnostic uses less formally, as it should point one to which 
bnode the arbitrary identifier actually is. It gives the
line and character number of the '[' charcacter or path character
which introduced the blank node. The first blank node is boringly _L1C1.
It used to be used only for tracking, but for tests in general
it makes the canonical ordering of bnodes repeatable.
item(self, str, i, res)
loadBuf(self, buf)
Parses a buffer and returns its top level formula
loadStream(self, stream)
makeStatement(self, quadruple)
node(self, str, i, res, subjectAlready=None)
Parse the <node> production.
Space is now skipped once at the beginning
instead of in multipe calls to skipSpace().
nodeOrLiteral(self, str, i, res)
object(self, str, i, res)
objectList(self, str, i, res)
path(self, str, i, res)
Parse the path production.
prop(self, str, i, res)
property_list(self, str, i, subj)
Parse property list
Leaves the terminating punctuation in the buffer
qname(self, str, i, res)
xyz:def -> ('xyz', 'def')
If not in keywords and keywordsSet: def -> ('', 'def')
:def -> ('', 'def')
setKeywords(self, k)
Takes a list of strings
skipSpace(self, str, i)
Skip white space, newlines and comments.
return -1 if EOF, else position of first non-ws character
startDoc(self)
statement(self, str, i)
strconst(self, str, i, delim)
parse an N3 string constant delimited by delim.
return index, val
subject(self, str, i, res)
tok(self, tok, str, i)
Check for keyword.  Space must have been stripped on entry and
we must not be at end of file.
uEscape(self, str, i, startline)
uriOf(self, sym)
uri_ref2(self, str, i, res)
Generate uri from n3 representation.
 
Note that the RDF convention of directly concatenating
NS and local name is now used though I prefer inserting a '#'
to make the namesapces look more like what XML folks expect.
variable(self, str, i, res)
?abc -> variable(:abc)
verb(self, str, i, res)
has _prop_
is _prop_ of
a
=
_prop_
>- prop ->
<- prop -<
_operator_

 
class ToN3(RDFSink.RDFSink)
    Serializer output sink for N3
 
keeps track of most recent subject and predicate reuses them.
Adapted from Dan's ToRDFParser(Parser);
 
  Methods defined here:
__init__(self, write, base=None, genPrefix=None, noLists=0, quiet=0, flags='')
bind(self, prefixString, uri)
Just accepting a convention here
dummyClone(self)
retun a version of myself which will only count occurrences
endAnonymous(self, subject, verb)
endAnonymousNode(self, subj=None)
endDoc(self, rootFormulaPair=None)
endFormulaObject(self, pred, subj)
endFormulaSubject(self, subj)
endListObject(self, subject, verb)
endListSubject(self, subj=None)
makeComment(self, str)
makeStatement(self, triple, why=None, aIsPossible=1)
representationOf(self, context, pair)
Representation of a thing in the output stream
 
Regenerates genids if required.
Uses prefix dictionary to use qname syntax if possible.
setDefaultNamespace(self, uri)
startAnonymous(self, triple)
startAnonymousNode(self, subj)
startDoc(self)
startFormulaObject(self, triple)
startFormulaSubject(self, context)
startListObject(self, triple)
startListSubject(self, subj)
writeEncoded(self, str)
Write a possibly unicode string out to the output

Data and other attributes defined here:
flagDocumentation = 'Flags for N3 output are as follows:-\n \na ...a existentially qualified explicitly named node.\n'

Methods inherited from RDFSink.RDFSink:
checkNewId(self, uri)
The store can override this to raise an exception if the
id is not in fact new. This is useful because it is usfeul
to generate IDs with useful diagnostic ways but this lays them
open to possibly clashing in pathalogical cases.
countNamespace(self, namesp)
On output, count how many times each namespace is used
genId(self)
intern(self, something)
namespaceCounts(self)
newBlankNode(self, context, uri=None, why=None)
newExistential(self, context, uri=None, why=None)
newFormula(self, uri=None)
newList(self, l, context)
newLiteral(self, str, dt=None, lang=None)
newSymbol(self, uri)
newUniversal(self, context, uri=None, why=None)
newXMLLiteral(self, doc)
reopen(self)
Un-End a document
 
If you have added stuff to a document, thought you were done, and
then want to add more, call this to get back into the sate that makeSatement
is again acceptable. Remember to end the document again when done.
setGenPrefix(self, genPrefix)

 
class tmToN3(RDFSink.RDFSink)
     Methods defined here:
IsOf(self)
__init__(self, write, base=None, genPrefix=None, noLists=0, quiet=0, flags='')
addAnonymous(self, Id)
If an anonymous shows up more than once, this is the
function to call
addLiteral(self, lit, dt=None, lang=None)
addNode(self, node)
addQuestionMarkedSymbol(self, sym)
addSymbol(self, sym)
backwardPath(self)
beginAnonymous(self)
beginFormula(self)
beginList(self)
bind(self, prefixString, uri)
Just accepting a convention here
checkIsOf(self)
declareExistential(self, sym)
declareUniversal(self, sym)
end(self)
endAnonymous(self)
endFormula(self)
endList(self)
endStatement(self)
forewardPath(self)
setDefaultNamespace(self, uri)
start(self)
symbolString(self, value)
writeEncoded(self, str)
Write a possibly unicode string out to the output

Methods inherited from RDFSink.RDFSink:
checkNewId(self, uri)
The store can override this to raise an exception if the
id is not in fact new. This is useful because it is usfeul
to generate IDs with useful diagnostic ways but this lays them
open to possibly clashing in pathalogical cases.
countNamespace(self, namesp)
On output, count how many times each namespace is used
endDoc(self, rootFormulaPair)
End a document
 
Call this once only at the end of parsing so that the receiver can wrap
things up, oprimize, intern, index and so on.  The pair given is the (type, value)
identifier of the root formula of the thing parsed.
genId(self)
intern(self, something)
makeComment(self, str)
This passes on a comment line which of course has no semantics.
 
This is only useful in direct piping of parsers to output, to preserve
comments in the original file.
makeStatement(self, tuple, why=None)
add a statement to a stream/store.
 
raises URISyntaxError on bad URIs
tuple is a quad (context, predicate, subject, object) of things generated by calls to newLiteral etc
why is reason for the statement.
namespaceCounts(self)
newBlankNode(self, context, uri=None, why=None)
newExistential(self, context, uri=None, why=None)
newFormula(self, uri=None)
newList(self, l, context)
newLiteral(self, str, dt=None, lang=None)
newSymbol(self, uri)
newUniversal(self, context, uri=None, why=None)
newXMLLiteral(self, doc)
reopen(self)
Un-End a document
 
If you have added stuff to a document, thought you were done, and
then want to add more, call this to get back into the sate that makeSatement
is again acceptable. Remember to end the document again when done.
setGenPrefix(self, genPrefix)
startDoc(self)

 
Functions
       
backslashUify(ustr)
Use URL encoding to return an ASCII string corresponding
to the given unicode
dummy()
dummyWrite(x)
hexify(ustr)
Use URL encoding to return an ASCII string
corresponding to the given UTF8 string
 
>>> hexify("http://example/a b")
'http://example/a%20b'
nothing()
stringToN3(str, singleLine=0, flags='')
#"
stripCR(str)
toBool(s)

 
Data
        ADDED_HASH = '#'
ALL4 = (0, 1, 2, 3)
ANONYMOUS = 3
BOOLEAN_DATATYPE = 'http://www.w3.org/2001/XMLSchema#boolean'
CONTEXT = 0
DAML_sameAs = (0, 'http://www.w3.org/2002/07/owl#sameAs')
DAML_sameAs_URI = 'http://www.w3.org/2002/07/owl#sameAs'
DECIMAL_DATATYPE = 'http://www.w3.org/2001/XMLSchema#decimal'
Escapes = {'"': '"', r'\': r'\', 'a': '\x07', 'b': '\x08', 'f': '\x0c', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\x0b'}
FLOAT_DATATYPE = 'http://www.w3.org/2001/XMLSchema#double'
INTEGER_DATATYPE = 'http://www.w3.org/2001/XMLSchema#integer'
LIST = 10000
LITERAL = 2
LITERAL_DT = 21
LITERAL_LANG = 22
LOG_implies_URI = 'http://www.w3.org/2000/10/swap/log#implies'
List_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
Logic_NS = 'http://www.w3.org/2000/10/swap/log#'
N3CommentCharacter = '#'
N3_Empty = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#Empty')
N3_List = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#List')
N3_first = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first')
N3_forAll_URI = 'http://www.w3.org/2000/10/swap/log#forAll'
N3_forSome_URI = 'http://www.w3.org/2000/10/swap/log#forSome'
N3_li = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#li')
N3_nil = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil')
N3_rest = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest')
OBJ = 3
PARTS = (1, 2, 3)
PRED = 1
QUESTION = 10001
RDF_NS_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
RDF_spec = 'http://www.w3.org/TR/REC-rdf-syntax/'
RDF_type = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type')
RDF_type_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
SUBJ = 2
SYMBOL = 0
XMLLITERAL = 25
becauseSubexpression = <why.BecauseSubexpression instance>
digitstring = <_sre.SRE_Pattern object>
eof = <_sre.SRE_Pattern object>
eol = <_sre.SRE_Pattern object>
forbidden1 = <_sre.SRE_Pattern object>
forbidden2 = <_sre.SRE_Pattern object>
interesting = <_sre.SRE_Pattern object>
langcode = <_sre.SRE_Pattern object>
number_syntax = <_sre.SRE_Pattern object>
option_noregen = 0
parsesTo_URI = 'http://www.w3.org/2000/10/swap/log#parsesTo'
signed_integer = <_sre.SRE_Pattern object>
wide_build = True
ws = <_sre.SRE_Pattern object>
cwm-1.2.1/diag.html0000644015216600007660000000714110642726422013217 0ustar syosisyosi Python: module diag
 
 
diag
index
/Users/yosi/CVSROOT/WWW/2000/10/swap/diag.py

Use this with diagnostics so that it can be changed as necessary
For example, sometimes want on stdout maybe or in a scroll window....
 
Let's replace this with pythong logging stuff.
at least get it to the point where "make quick" in swap/test works.
 
There is some wierd stuff here because TimBL and I couldn't
figure out how to share the chatty global across modules.
Surely Daniel K and DanC should be able figure that out.

 
Modules
       
os
sys
traceback

 
Functions
       
printState(prefix='#trace# ')
Output the (caller's) function name and local variables
progress(*args)
##lineCount = [0]
setTracking(x)
setVerbosity(x)
utf_8_encode(...)
verbosity()

 
Data
        chatty_flag = 0
file_list = []
print_all_file_names = 0
tracking = 0
cwm-1.2.1/check.html0000644015216600007660000006145310642726415013400 0ustar syosisyosi Python: module check
 
 
check (version Id: check.py,v 1.59 2007/06/26 02:36:15 syosi Exp )
index
/Users/yosi/CVSROOT/WWW/2000/10/swap/check.py

Check a proof
 
This is a simple proof checker.  It hasn't itself been proved,
and there are probably lots of ways to fool it especially as a deliberate
malicious attack. That is because there are simple things I may have forgotten
to check.
 
Command line options for debug:
 -v50   Set verbosity to 50 (range is 0 -100)
 -c50   Set verbosity for inference done by cwm code to 50
 -p50   Set verobsity when parsing top 50    
 
@@for more command line options, see main() in source

 
Modules
       
swap.diag
swap
sys

 
Classes
       
__builtin__.object
FormulaCache
Checker
Policy
AllPremises
Assumption
ParsingOK
exceptions.Exception
InvalidProof
LogicalFallacy
PolicyViolation

 
class AllPremises(Policy)
    A useful testing policy is to accept all premises and no sources.
 
 
Method resolution order:
AllPremises
Policy
__builtin__.object

Methods defined here:
__init__(self)
assumes(self, f)
documentOK(self, f)

Data and other attributes inherited from Policy:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Policy' objects>
list of weak references to the object (if defined)

 
class Assumption(Policy)
    
Method resolution order:
Assumption
Policy
__builtin__.object

Methods defined here:
__init__(self, premise)
assumes(self, f)
documentOK(self, u)

Data and other attributes inherited from Policy:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Policy' objects>
list of weak references to the object (if defined)

 
class Checker(FormulaCache)
    
Method resolution order:
Checker
FormulaCache
__builtin__.object

Methods defined here:
__init__(self, proof)
proof   is the formula which contains the proof
checkParsing(self, r, f, policy, level)
conjecture(self)
return the formula that is claimed to be proved and
the main justification step.
report(self, out, f=None, step=None)
result(self, r, policy, level=0)
Get the result of a proof step.
 
r       is the step to be checked; in the case of the root reason,
        proof.the(pred=rdf.type, obj=reason.Proof),
        as from `proofStep()`
 
level   is just the nesting level for diagnostic output
 
Returns the formula proved
raises InvalidProof (perhaps IOError, others)

Methods inherited from FormulaCache:
get(self, uri)

Data and other attributes inherited from FormulaCache:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'FormulaCache' objects>
list of weak references to the object (if defined)

 
class FormulaCache(__builtin__.object)
     Methods defined here:
__init__(self)
get(self, uri)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'FormulaCache' objects>
list of weak references to the object (if defined)

 
class InvalidProof(exceptions.Exception)
     Methods defined here:
__init__(self, s, level=0)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class LogicalFallacy(InvalidProof)
    
Method resolution order:
LogicalFallacy
InvalidProof
exceptions.Exception

Methods inherited from InvalidProof:
__init__(self, s, level=0)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class ParsingOK(Policy)
    When run from the command-line, the policy is that
all Parsing's are OK.
 
Hmm... shouldn't it be only those that are mentioned
in the CommandLine step?
 
 
Method resolution order:
ParsingOK
Policy
__builtin__.object

Methods defined here:
assumes(self, f)
documentOK(self, u)

Data and other attributes inherited from Policy:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Policy' objects>
list of weak references to the object (if defined)

 
class Policy(__builtin__.object)
    a proof-checking policy
 
  Methods defined here:
assumes(self, f)
Check whether a formula is an axiom.
 
Hmm... move checkBuiltin here?
documentOK(self, u)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Policy' objects>
list of weak references to the object (if defined)

 
class PolicyViolation(InvalidProof)
    
Method resolution order:
PolicyViolation
InvalidProof
exceptions.Exception

Methods inherited from InvalidProof:
__init__(self, s, level=0)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
Functions
       
atomicFormulaTerms(f)
Check that a formula is atomic and return the p, s, o terms.
 
>>> atomicFormulaTerms(_s2f("<#sky> <#color> <#blue>.",
...                         "http://example/stuff"))
(color, sky, blue)
checkBuiltin(r, f, checker, policy, level=0)
Check a built-in step.
@@hmm... integrate with Policy more?
 
>>> soc = Namespace("http://example/socrates#")
>>> pf = _s2f(_TestBuiltinStep % '"a" list:in ("b" "a" "c")',
...           "http://example/socrates")
>>> f = checkBuiltin(soc.step1,
...                 pf.the(subj=soc.step1, pred=reason.gives),
...                 Checker(pf), AllPremises())
>>> len(f)
1
 
>>> pf = _s2f(_TestBuiltinStep % '"abc" str:startsWith "a"',
...           "http://example/socrates")
>>> f = checkBuiltin(soc.step1,
...                 pf.the(subj=soc.step1, pred=reason.gives),
...                 Checker(pf), AllPremises())
>>> len(f)
1
 
 
>>> pf = _s2f(_TestBuiltinStep % '"abc" str:startsWith "b"',
...           "http://example/socrates")
>>> f = checkBuiltin(soc.step1,
...                 pf.the(subj=soc.step1, pred=reason.gives),
...                 Checker(pf), AllPremises())
Traceback (most recent call last):
    ...
LogicalFallacy: Built-in fact does not give correct results: predicate: abc subject: str:startsWith object: b result: None
checkConjunction(r, f, checker, policy, level)
checkExtraction(r, f, checker, policy, level=0)
check an Extraction step.
 
>>> soc = Namespace("http://example/socrates#")
>>> pf = _s2f(_TestCEstep, "http://example/socrates")
>>> checkExtraction(soc.step1,
...                 pf.the(subj=soc.step1, pred=reason.gives),
...                 Checker(pf), AllPremises())
{soc:socrates type soc:Man}
checkGMP(r, f, checker, policy, level=0)
check a generalized modus ponens step.
 
>>> soc = Namespace("http://example/socrates#")
>>> pf = _s2f(_TestGMPStep, "http://example/socrates")
>>> f = checkGMP(soc.step1, None, Checker(pf), AllPremises())
>>> f.n3String().strip()
u'@prefix : <http://example/socrates#> .\n    \n    :socrates     a :Mortal .'
checkSupports(r, f, checker, policy, level)
fyi(str, level=0, thresh=50)
getSymbol(proof, x)
De-reify a symbol: get the informatuion identifying it from the proof
getTerm(proof, x)
De-reify a term: get the informatuion about it from the proof
main(argv)
n3Entails(f, g, skipIncludes=0, level=0)
Does f N3-entail g?
 
First try indexed graph match algorithm, and if that fails,
unification.
topLevelLoad(uri=None, flags='')
usage()

 
Data
        OBJ = 3
PRED = 1
SUBJ = 2
__version__ = 'Id: check.py,v 1.59 2007/06/26 02:36:15 syosi Exp '
chatty = 0
debugLevelForInference = 0
debugLevelForParsing = 0
knownReasons = set([Premise, Parsing, Inference, Conjunction, Fact, Extraction, ...])
log = <swap.myStore.Namespace object>
nameBlankNodes = 0
proofSteps = 0
rdf = <swap.myStore.Namespace object>
reason = <swap.myStore.Namespace object>
rei = <swap.myStore.Namespace object>
cwm-1.2.1/uripath.html0000644015216600007660000006060610642726424013776 0ustar syosisyosi Python: module uripath
 
 
uripath (version $Id: uripath.html,v 1.13 2007/06/27 17:58:39 syosi Exp $)
index
/Users/yosi/CVSROOT/WWW/2000/10/swap/uripath.py

Uniform Resource Identifier (URI) path manipulation,
above the access layer
 
The name of this module and the functions are somewhat
arbitrary; they hark to other parts of the python
library; e.g. uripath.join() is somewhat like os.path.join().
 
REFERENCES
 
  Uniform Resource Identifiers (URI): Generic Syntax
  http://www.ietf.org/rfc/rfc2396.txt
 
  The Web Model: Information hiding and URI syntax (Jan 98)
  http://www.w3.org/DesignIssues/Model.html
 
  URI API design [was: URI Test Suite] Dan Connolly (Sun, Aug 12 2001)
  http://lists.w3.org/Archives/Public/uri/2001Aug/0021.html

 
Modules
       
os
re
string
unittest

 
Classes
       
unittest.TestCase(__builtin__.object)
Tests

 
class Tests(unittest.TestCase)
    
Method resolution order:
Tests
unittest.TestCase
__builtin__.object

Methods defined here:
testPaths(self)
testRFCCases(self)
testSplit(self)

Methods inherited from unittest.TestCase:
__call__(self, *args, **kwds)
__init__(self, methodName='runTest')
Create an instance of the class that will use the named test
method when executed. Raises a ValueError if the instance does
not have a method with the specified name.
__repr__(self)
__str__(self)
assertAlmostEqual = failUnlessAlmostEqual(self, first, second, places=7, msg=None)
Fail if the two objects are unequal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero.
 
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most signficant digit).
assertAlmostEquals = failUnlessAlmostEqual(self, first, second, places=7, msg=None)
Fail if the two objects are unequal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero.
 
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most signficant digit).
assertEqual = failUnlessEqual(self, first, second, msg=None)
Fail if the two objects are unequal as determined by the '=='
operator.
assertEquals = failUnlessEqual(self, first, second, msg=None)
Fail if the two objects are unequal as determined by the '=='
operator.
assertFalse = failIf(self, expr, msg=None)
Fail the test if the expression is true.
assertNotAlmostEqual = failIfAlmostEqual(self, first, second, places=7, msg=None)
Fail if the two objects are equal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero.
 
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most signficant digit).
assertNotAlmostEquals = failIfAlmostEqual(self, first, second, places=7, msg=None)
Fail if the two objects are equal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero.
 
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most signficant digit).
assertNotEqual = failIfEqual(self, first, second, msg=None)
Fail if the two objects are equal as determined by the '=='
operator.
assertNotEquals = failIfEqual(self, first, second, msg=None)
Fail if the two objects are equal as determined by the '=='
operator.
assertRaises = failUnlessRaises(self, excClass, callableObj, *args, **kwargs)
Fail unless an exception of class excClass is thrown
by callableObj when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
assertTrue = failUnless(self, expr, msg=None)
Fail the test unless the expression is true.
assert_ = failUnless(self, expr, msg=None)
Fail the test unless the expression is true.
countTestCases(self)
debug(self)
Run the test without collecting errors in a TestResult
defaultTestResult(self)
fail(self, msg=None)
Fail immediately, with the given message.
failIf(self, expr, msg=None)
Fail the test if the expression is true.
failIfAlmostEqual(self, first, second, places=7, msg=None)
Fail if the two objects are equal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero.
 
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most signficant digit).
failIfEqual(self, first, second, msg=None)
Fail if the two objects are equal as determined by the '=='
operator.
failUnless(self, expr, msg=None)
Fail the test unless the expression is true.
failUnlessAlmostEqual(self, first, second, places=7, msg=None)
Fail if the two objects are unequal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero.
 
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most signficant digit).
failUnlessEqual(self, first, second, msg=None)
Fail if the two objects are unequal as determined by the '=='
operator.
failUnlessRaises(self, excClass, callableObj, *args, **kwargs)
Fail unless an exception of class excClass is thrown
by callableObj when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
id(self)
run(self, result=None)
setUp(self)
Hook method for setting up the test fixture before exercising it.
shortDescription(self)
Returns a one-line description of the test, or None if no
description has been provided.
 
The default implementation of this method returns the first line of
the specified test method's docstring.
tearDown(self)
Hook method for deconstructing the test fixture after testing it.

Data and other attributes inherited from unittest.TestCase:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'TestCase' objects>
list of weak references to the object (if defined)
failureException = <class exceptions.AssertionError>
Assertion failed.

 
Functions
       
base()
The base URI for this process - the Web equiv of cwd
 
Relative or abolute unix-standard filenames parsed relative to
this yeild the URI of the file.
If we had a reliable way of getting a computer name,
we should put it in the hostname just to prevent ambiguity
canonical(str_in)
Convert equivalent URIs (or parts) to the same string
 
There are many differenet levels of URI canonicalization
which are possible.  See http://www.ietf.org/rfc/rfc3986.txt
Done:
- Converfting unicode IRI to utf-8
- Escaping all non-ASCII
- De-escaping, if escaped, ALPHA (%41-%5A and %61-%7A), DIGIT (%30-%39),
  hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) (Sect 2.4) 
- Making all escapes uppercase hexadecimal
Not done:
- Making URI scheme lowercase
- changing /./ or  /foo/../ to / with care not to change host part
 
 
>>> canonical("foo bar")
'foo%20bar'
 
>>> canonical(u'http:')
'http:'
 
>>> canonical('fran%c3%83%c2%a7ois')
'fran%C3%83%C2%A7ois'
 
>>> canonical('a')
'a'
 
>>> canonical('%4e')
'N'
 
>>> canonical('%9d')
'%9D'
 
>>> canonical('%2f')
'%2F'
 
>>> canonical('%2F')
'%2F'
join(here, there)
join an absolute URI and URI reference
(non-ascii characters are supported/doctested;
haven't checked the details of the IRI spec though)
 
here is assumed to be absolute.
there is URI reference.
 
>>> join('http://example/x/y/z', '../abc')
'http://example/x/abc'
 
Raise ValueError if there uses relative path
syntax but here has no hierarchical path.
 
>>> join('mid:foo@example', '../foo')
Traceback (most recent call last):
    raise ValueError, here
ValueError: Base <mid:foo@example> has no slash after colon - with relative '../foo'.
 
>>> join('http://example/x/y/z', '')
'http://example/x/y/z'
 
>>> join('mid:foo@example', '#foo')
'mid:foo@example#foo'
 
We grok IRIs
 
>>> len(u'Andr\xe9')
5
 
>>> join('http://example.org/', u'#Andr\xe9')
u'http://example.org/#Andr\xe9'
refTo(base, uri)
figure out a relative URI reference from base to uri
 
>>> refTo('http://example/x/y/z', 'http://example/x/abc')
'../abc'
 
>>> refTo('file:/ex/x/y', 'file:/ex/x/q/r#s')
'q/r#s'
 
>>> refTo(None, 'http://ex/x/y')
'http://ex/x/y'
 
>>> refTo('http://ex/x/y', 'http://ex/x/y')
''
 
Note the relationship between refTo and join:
join(x, refTo(x, y)) == y
which points out certain strings which cannot be URIs. e.g.
>>> x='http://ex/x/y';y='http://ex/x/q:r';join(xrefTo(x, y)) == y
0
 
So 'http://ex/x/q:r' is not a URI. Use 'http://ex/x/q%3ar' instead:
>>> x='http://ex/x/y';y='http://ex/x/q%3ar';join(xrefTo(x, y)) == y
1
 
This one checks that it uses a root-realtive one where that is
all they share.  Now uses root-relative where no path is shared.
This is a matter of taste but tends to give more resilience IMHO
-- and shorter paths
 
Note that base may be None, meaning no base.  In some situations, there
just ain't a base. Slife. In these cases, relTo returns the absolute value.
The axiom abs(,rel(b,x))=x still holds.
This saves people having to set the base to "bogus:".
 
>>> refTo('http://ex/x/y/z', 'http://ex/r')
'/r'
splitFrag(uriref)
split a URI reference between the fragment and the rest.
 
Punctuation is thrown away.
 
e.g.
 
>>> splitFrag("abc#def")
('abc', 'def')
 
>>> splitFrag("abcdef")
('abcdef', None)
splitFragP(uriref, punct=0)
split a URI reference before the fragment
 
Punctuation is kept.
 
e.g.
 
>>> splitFragP("abc#def")
('abc', '#def')
 
>>> splitFragP("abcdef")
('abcdef', '')

 
Data
        URI_unreserved = 'ABCDEFGHIJJLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'
__version__ = '$Id: uripath.html,v 1.13 2007/06/27 17:58:39 syosi Exp $'
commonHost = <_sre.SRE_Pattern object>
cwm-1.2.1/query.html0000644015216600007660000020351010717717524013464 0ustar syosisyosi Python: module query
 
 
query
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/query.py

Query for cwm architecture
 
2003-09-07 split off from llyn.py

 
Modules
       
diag
sys
types

 
Classes
       
__builtin__.list(__builtin__.object)
Queue
__builtin__.object
BecauseBuiltInWill
BecauseSupportsWill
BetterNone
Chain_Step
exceptions.Exception
BuiltInFailed
formula.Formula(term.AnonymousNode, term.CompoundTerm)
Query
formula.StoredStatement
QueryItem
CyclicSetOfRules
InferenceTask
Rule

 
class BecauseBuiltInWill(__builtin__.object)
     Methods defined here:
__init__(self, *args)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'BecauseBuiltInWill' objects>
list of weak references to the object (if defined)

 
class BecauseSupportsWill(__builtin__.object)
     Methods defined here:
__init__(self, *args)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'BecauseSupportsWill' objects>
list of weak references to the object (if defined)

 
class BetterNone(__builtin__.object)
     Methods defined here:
__eq__(self, other)
__geq__ = __eq__(self, other)
__gt__ = __eq__(self, other)
__hash__(self)
__leq__ = __eq__(self, other)
__lt__ = __eq__(self, other)
__neq__ = __eq__(self, other)
__str__(self)

Static methods defined here:
__new__(cls)

Data and other attributes defined here:
__slots__ = []
__val__ = <query.BetterNone object>

 
class BuiltInFailed(exceptions.Exception)
     Methods defined here:
__init__(self, info, item, pred)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class Chain_Step(__builtin__.object)
     Methods defined here:
__cmp__(self, other)
__init__(self, vars, existentials, queue, env, parent=None, evidence=[])
__repr__(self)
copy(self)
done(self)
popBest(self)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Chain_Step' objects>
list of weak references to the object (if defined)

 
class CyclicSetOfRules
    A set of rules which are connected
 
  Methods defined here:
__getitem__(self, i)
__init__(self, rules)
__repr__(self)
run(self)
Run a cyclic subset of the rules

 
class InferenceTask
    A task of applying rules or filters to information
 
  Methods defined here:
__init__(self, workingContext, ruleFormula=None, targetContext=None, universals=set([]), mode='', why=None, repeat=0)
Apply rules in one context to the same or another
 
A rule here is defined by log:implies, which associates the template
(aka premise, precondidtion, antecedent, body) to the conclusion
(aka postcondition, head).
gatherQueries(self, ruleFormula)
Find a set of rules in N3QL
gatherRules(self, ruleFormula)
gatherSparqlQueries(self, ruleFormula)
Find the rules in SPARQL
run(self)
Perform task.
Return number of  new facts
runLaborious(self)
Perform task.
Return number of  new facts.
Start again if new rule mayhave been generated.
runSmart(self)
Run the rules by mapping rule interactions first

 
class Query(formula.Formula)
    A query holds a hypothesis/antecedent/template which is being matched aginst (unified with)
the knowledge base.
 
 
Method resolution order:
Query
formula.Formula
term.AnonymousNode
term.Node
term.CompoundTerm
term.Term
__builtin__.object

Methods defined here:
__init__(self, store, unmatched=[], template=None, variables=set([]), existentials=set([]), workingContext=None, conclusion=None, targetContext=None, already=None, rule=None, interpretBuiltins=0, justOne=0, justReturn=0, mode='', meta=None)
checkRedirectsInAlready(self)
Kludge
conclude(self, bindings, evidence=[], extraBNodes=set([]), allBindings=None)
When a match found in a query, add conclusions to target formula.
 
Returns the number of statements added.
matchFormula(query, queue, variables, existentials, env=Env({}))
matchFormula2(query, queue, variables, existentials, bindings=Env({}), newBindings=Env({}), evidence=[])
Iterate on the remaining query items
bindings      collected matches already found
newBindings  matches found and not yet applied - used in recursion
 
You probably really need the state diagram to understand this
http://www.w3.org/2000/10/swap/doc/states.svg
even if it is a bit out of date.
redirect(self, redirections)
remoteQuery(query, items)
Perform remote query as client on remote store
Currently  this only goes to an SQL store, but should later use SPARQL etc
in remote HTTP/SOAP call.
resolve(self)

Methods inherited from formula.Formula:
__iter__(self)
The internal method which allows one to iterate over the statements
as though a formula were a sequence.
__len__(self)
How many statements?
__repr__(self)
add(self, subj, pred, obj, why=None)
Add a triple to the formula.
 
The formula must be open.
subj, pred and obj must be objects as for example generated 
by Formula.newSymbol() and newLiteral(), or else literal
values which can be interned.
why     may be a reason for use when a proof will be required.
any(self, subj=None, pred=None, obj=None)
Return None or the value filing the blank in the called parameters.
 
Specifiy exactly two of the arguments.
color = f.any(pred=pantoneColor, subj=myCar)
somethingRed = f.any(pred=pantoneColor, obj=red)
 
Note difference from the old store.any!!
Note SPO order not PSO.
To aboid confusion, use named parameters.
asPair(self)
Return an old representation. Obsolete
bind(self, prefix, uri)
Give a prefix and associated URI as a hint for output
 
The store does not use prefixes internally, but keeping track
of those usedd in the input data makes for more human-readable output.
canonicalize(F)
If this formula already exists, return the master version.
If not, record this one and return it.
Call this when the formula is in its final form, with all its statements.
Make sure no one else has a copy of the pointer to the smushed one.
 
LIMITATION: The basic Formula class does NOT canonicalize. So
it won't spot idenical formulae. The IndexedFormula will.
classOrder(self)
close(self)
No more to add. Please return interned value.
NOTE You must now use the interned one, not the original!
compareTerm(self, other)
Assume is also a Formula - see function compareTerm below
contains(self, pred=None, subj=None, obj=None)
Return boolean true iff formula contains statement(s) matching the parts given
 
For example:
if f.contains(pred=pantoneColor):
    print "We've got one statement about something being some color"
declareExistential(self, v)
declareUniversal(self, v, key=None)
doesNodeAppear(self, symbol)
Does that particular node appear anywhere in this formula
 
This function is necessarily recursive, and is useful for the pretty printer
It will also be useful for the flattener, when we write it.
each(self, subj=None, pred=None, obj=None)
Return a list of values value filing the blank in the called parameters
 
Examples:
colors = f.each(pred=pantoneColor, subj=myCar)
 
for redthing in f.each(pred=pantoneColor, obj=red): ...
existentials(self)
Return a list of existential variables with this formula as scope.
 
Implementation:
we may move to an internal storage rather than these pseudo-statements
freeVariables(self)
generated(self)
Yes, any identifier you see for this is arbitrary.
intern(self, value)
loadFormulaWithSubstitution(self, old, bindings={}, why=None, cannon=False)
Load information from another formula, subsituting as we go
returns number of statements added (roughly)
n3EntailedBy(pattern, kb, vars=set([]), existentials=set([]), bindings={})
See Term.unify() and term.matchSet()
 
KB is a stronger statement han other.
Bindings map variables in pattern onto kb.
Self n3-entails other.
Criteria:  Subset of self statements must match other statements.
  Self's exisetntials must be subset of other's
  Self's universals must be superset.
n3String(self, base=None, flags='')
Dump the formula to an absolute string in N3
newBlankNode(self, uri=None, why=None)
Create a new unnamed node with this formula as context.
 
The URI is typically omitted, and the system will make up an internal idnetifier.
If given is used as the (arbitrary) internal identifier of the node.
newExistential(self, uri=None, why=None)
Create a named variable existentially qualified within this formula
 
See also: existentials()  and newBlankNode().
newFormula(self, uri=None)
Create a new open, empty, formula in the same store as this one.
 
The URI is typically omitted, and the system will make up an internal idnetifier.
If given is used as the (arbitrary) internal identifier of the formula.
newList(self, list)
newLiteral(self, str, dt=None, lang=None)
Create or reuse the internal representation of the RDF literal whose string is given
 
The literal is created in the same store as the formula.
newSymbol(self, uri)
Create or reuse the internal representation of the RDF node whose uri is given
 
The symbol is created in the same store as the formula.
newUniversal(self, uri=None, why=None)
Create a named variable universally qualified within this formula
 
See also: universals()
newXMLLiteral(self, doc)
Create or reuse the internal representation of the RDF literal whose string is given
 
The literal is created in the same store as the formula.
ntString(self, base=None, flags='bravestpun')
Dump the formula to an absolute string in N3
objects(self, pred=None, subj=None)
Obsolete - use each(subj=..., pred=...)
occurringIn(self, vars)
Which variables in the list occur in this?
outputStrings(self, channel=None, relation=None)
Fetch output strings from store, sort and output
 
To output a string, associate (using the given relation) with a key
such that the order of the keys is the order in which you want the corresponding
strings output.
 
@@ what is this doing here??
predicates(self, subj=None, obj=None)
Obsolete - use each(subj=..., obj=...)
rdfString(self, base=None, flags='')
Dump the formula to an absolute string in RDF/XML
removeStatement(self, s)
Removes a statement The formula must be open.
 
This implementation is alas slow, as removal of items from tha hash is slow.
renameVars(self)
reopen(self)
Make a formula which was once closed oopen for input again.
 
NOT Recommended.  Dangers: this formula will be, because of interning,
the same objet as a formula used elsewhere which happens to have the same content.
You mess with this one, you mess with that one.
Much better to keep teh formula open until you don't needed it open any more.
The trouble is, the parsers close it at the moment automatically. To be fixed.
searchable(self, subj=None, pred=None, obj=None)
A pair of the difficulty of searching and a statement iterator of found statements
 
The difficulty is a store-portable measure of how long the store
thinks (in arbitrary units) it will take to search.
This will only be used for choisng which part of the query to search first.
If it is 0 there is no solution to the query, we know now.
 
In this implementation, we use the length of the sequence to be searched.
size(self)
Return the number statements.
Obsolete: use len(F).
statementsMatching(self, pred=None, subj=None, obj=None)
Return a READ-ONLY list of StoredStatement objects matching the parts given
 
For example:
for s in f.statementsMatching(pred=pantoneColor):
    print "We've got one which is ", `s[OBJ]`
    
If none, returns []
subSet(self, statements, why=None)
subjects(self, pred=None, obj=None)
Obsolete - use each(pred=..., obj=...)
substituteEquals(self, bindings, newBindings)
Return this or a version of me with subsitution made
 
Subsitution of = for = does NOT happen inside a formula,
as the formula is a form of quotation.
substitution(self, bindings, why=None, cannon=False, keepOpen=False)
Return this or a version of me with subsitution made
the(self, subj=None, pred=None, obj=None)
Return None or the value filing the blank in the called parameters
 
This is just like any() except it checks that there is only
one answer in the store. It wise to use this when you expect only one.
 
color = f.the(pred=pantoneColor, subj=myCar)
redCar = f.the(pred=pantoneColor, obj=red)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source)
universals(self)
Return a set of variables universally quantified with this formula as scope.
 
Implementation:
We may move to an internal storage rather than these statements.
variables(self)
Return a set of all variables quantified within this scope.

Static methods inherited from formula.Formula:
resetRenames(reset=True)

Methods inherited from term.AnonymousNode:
uriref(self)

Methods inherited from term.Term:
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
representation(self, base=None)
The string represnting this in N3
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class QueryItem(formula.StoredStatement)
    One line in a query being resolved.
 
To a large extent, each line can keep track of its own state.
When a remote query is done, query lines to the same server have to be coordinated again.
 
  Methods defined here:
__init__(self, query, quad)
__repr__(self)
Diagnostic string only
bindNew(self, newBindings)
Take into account new bindings from query processing to date
 
The search may get easier, and builtins may become ready to run.
Lists may either be matched against store by searching,
and/or may turn out to be bound and therefore ready to run.
 
Return:
    0           No way can this item ever complete.
    None        Binding done, see item.state
canRun(self)
Is this built-in ready to run?
clone(self)
Take a copy when for iterating on a query
doIncludes(item, queue, existentials, variables, bindings)
Implement log:includes by adding all the statements on the LHS
to the query items.  The plan is that this should
doSupports(item, queue, existentials, variables, bindings)
Real implementation of log:supports. Have fun.
searchDone(self)
Search has been done: figure out next state.
setup(self, allvars, unmatched, interpretBuiltins=[], mode='')
Check how many variables in this term,
and how long it would take to search
 
Returns, true normally or false if there is no way this query will work.
Only called on virgin query item.
The mode is a set of character flags about how we think.
tryBuiltin(self, queue, bindings, evidence)
Check for  built-in functions to see whether it will resolve.
Return codes:  0 - give up; 
        [] - success, no new bindings, (action has been called)
        [...] list of binding lists, each a pair of bindings and reason.
tryDeepSearch(self, queue, oldBindings=Env({}))
Search the store, unifying nested compound structures
 
Returns lists of list of bindings, attempting if necessary to unify
any nested compound terms. Added 20030810, not sure whether it is worth the
execution time in practice. It could be left to a special magic built-in like "matches"
or something if it is only occasionnaly used.
 
Used in state S_NEED_DEEP
updateMyIndex(self, formula)

Methods inherited from formula.StoredStatement:
__cmp__(self, other)
Just compare SUBJ, Pred and OBJ, others the same
Avoid loops by spotting reference to containing formula
__getitem__(self, i)
__hash__(self)
__len__(self)
asFormula(self, why=None)
The formula which contains only a statement like this.
 
When we split the statement up, we lose information in any existentials which are
shared with other statements. So we introduce a skolem constant to tie the
statements together.  We don't have access to any enclosing formula 
so we can't express its quantification.  This @@ not ideal.
 
This extends the StoredStatement class with functionality we only need with "why" module.
comparePredObj(self, other)
Just compare P and OBJ, others the same
context(self)
Return the context of the statement
existentials(self)
object(self)
Return the object of the statement
occurringIn(self, vars)
Which variables in the list occur in this?
predicate(self)
Return the predicate of the statement
spo(self)
statements(self)
subject(self)
Return the subject of the statement
unify(self, other, env1, env2, vars, universals, existentials, n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source)
universals(self)

 
class Queue(__builtin__.list)
    
Method resolution order:
Queue
__builtin__.list
__builtin__.object

Methods defined here:
__init__(self, other=[], metaSource=None)
__repr__(self)
popBest(self)

Data and other attributes defined here:
__slots__ = ['statements', 'bNodes']
bNodes = <member 'bNodes' of 'Queue' objects>
list = <type 'list'>
list() -> new list
list(sequence) -> new list initialized from sequence's items
statements = <member 'statements' of 'Queue' objects>

Methods inherited from __builtin__.list:
__add__(...)
x.__add__(y) <==> x+y
__contains__(...)
x.__contains__(y) <==> y in x
__delitem__(...)
x.__delitem__(y) <==> del x[y]
__delslice__(...)
x.__delslice__(i, j) <==> del x[i:j]
 
Use of negative indices is not supported.
__eq__(...)
x.__eq__(y) <==> x==y
__ge__(...)
x.__ge__(y) <==> x>=y
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__gt__(...)
x.__gt__(y) <==> x>y
__hash__(...)
x.__hash__() <==> hash(x)
__iadd__(...)
x.__iadd__(y) <==> x+=y
__imul__(...)
x.__imul__(y) <==> x*=y
__iter__(...)
x.__iter__() <==> iter(x)
__le__(...)
x.__le__(y) <==> x<=y
__len__(...)
x.__len__() <==> len(x)
__lt__(...)
x.__lt__(y) <==> x<y
__mul__(...)
x.__mul__(n) <==> x*n
__ne__(...)
x.__ne__(y) <==> x!=y
__reversed__(...)
L.__reversed__() -- return a reverse iterator over the list
__rmul__(...)
x.__rmul__(n) <==> n*x
__setitem__(...)
x.__setitem__(i, y) <==> x[i]=y
__setslice__(...)
x.__setslice__(i, j, y) <==> x[i:j]=y
 
Use  of negative indices is not supported.
append(...)
L.append(object) -- append object to end
count(...)
L.count(value) -> integer -- return number of occurrences of value
extend(...)
L.extend(iterable) -- extend list by appending elements from the iterable
index(...)
L.index(value, [start, [stop]]) -> integer -- return first index of value
insert(...)
L.insert(index, object) -- insert object before index
pop(...)
L.pop([index]) -> item -- remove and return item at index (default last)
remove(...)
L.remove(value) -- remove first occurrence of value
reverse(...)
L.reverse() -- reverse *IN PLACE*
sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1

Data and other attributes inherited from __builtin__.list:
__new__ = <built-in method __new__ of type object>
T.__new__(S, ...) -> a new object with type S, a subtype of T

 
class Rule
     Methods defined here:
__init__(self, task, antecedent, consequent, statement, variables)
Try a rule
 
Beware lists are corrupted. Already list is updated if present.
The idea is that, for a rule which may be tried many times, the constant 
processing is done in this rather than in Query().
 
The already dictionary is used to track bindings.
This less useful when not repeating (as in --filter), but as in fact
there may be several ways in which one cane get the same bindings,
even without a repeat.
__repr__(self)
compareByAffects(other)
once(self)
traceForward(self, r1)

 
Functions
       
applyQueries(workingContext, ruleFormula=None, targetContext=None)
Once, nothing recusive, for a N3QL query
applyRules(workingContext, ruleFormula=None, targetContext=None)
Once
applySparqlQueries(workingContext, ruleFormula=None, targetContext=None)
Once, nothing recusive, for a N3QL query
bindingsToString(bindings)
buildPattern(workingContext, template)
Make a list of unmatched statements including special
builtins to check something is universally quantified
buildStrictPattern(workingContext, template)
compareCyclics(self, other)
Note the set indirectly affected is the same for any
member of a cyclic subsystem
hasFormula(l)
lookupQuad(bindings, q)
Return a subsituted quad
lookupQuadRecursive(bindings, q, why=None)
n3Equivalent(g, f, env1, env2, vars=set([]), universals=set([]), existentials=set([]), n1Source=42, n2Source=42)
Return whether or nor f contains a top-level formula equvalent to g.
Just a test: no bindings returned.
partialOrdered(cy1, pool)
Return sequence conforming to the partially order in a set of cyclic subsystems
 
Basially, we find the dependencies of a node and remove them from the pool.
Then, any node in the pool can be done earlier, because has no depndency from those done.
quadToString(q, neededToRun=[[], [], [], []], pattern=[1, 1, 1, 1])
queueToString(queue)
#   DIAGNOSTIC STRING OUTPUT
returnWrapper(f)
seqToString(set)
setToString(set)
smarterSubstitution(f, bindings, source, why=None, exception=[])
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
testIncludes(f, g, _variables=set([]), bindings={}, interpretBuiltins=0)
Return whether or nor f contains a top-level formula equvalent to g.
Just a test: no bindings returned.
think(knowledgeBase, ruleFormula=None, mode='', why=None)
Forward-chaining inference
 
In the case in which rules are added back into the
store. The store is used for read (normally canonical) and write
(normally open) at the samne time.  It in fact has to be open.

 
Data
        ALL4 = (0, 1, 2, 3)
BNone = <query.BetterNone object>
BuiltinFeedError = (<class term.ArgumentNotLiteral>, <class term.UnknownType>)
CONTEXT = 0
INFINITY = 1000000000
List_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
Logic_NS = 'http://www.w3.org/2000/10/swap/log#'
N3_Empty = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#Empty')
N3_List = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#List')
N3_first = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first')
N3_nil = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil')
N3_rest = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest')
OBJ = 3
OWL_NS = 'http://www.w3.org/2002/07/owl#'
PARTS = (1, 2, 3)
PRED = 1
QL_NS = 'http://www.w3.org/2004/ql#'
RDF_NS_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
SPARQL_NS = 'http://www.w3.org/2000/10/swap/sparqlCwm'
SUBJ = 2
S_DONE = 80
S_HEAVY_READY = 40
S_HEAVY_WAIT = 20
S_LIGHT_EARLY = 50
S_LIGHT_GO = 65
S_LIGHT_UNS_READY = 70
S_LIGHT_WAIT = 30
S_NEED_DEEP = 45
S_NOT_LIGHT = 60
S_REMOTE = 10
S_UNKNOWN = 99
becauseSubexpression = <why.BecauseSubexpression instance>
chatty_flag = 0
forAllSym = 'http://www.w3.org/2000/10/swap/log#forAll'
forSomeSym = 'http://www.w3.org/2000/10/swap/log#forSome'
nextRule = 0
stateName = {10: 'Remote', 20: 'HvWait', 30: 'LtWait', 40: 'HvGo', 45: 'Deep', 50: 'LtEarly', 60: 'NotLt', 65: 'LtGo', 70: 'LtUsGo', 80: 'DONE', ...}
tracking = 0
cwm-1.2.1/cwm.html0000644015216600007660000003561110731070066013077 0ustar syosisyosi Python: module cwm
 
 
cwm
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/cwm.py

$Id: cwm.py,v 1.197 2007/12/13 15:38:39 syosi Exp $
 
Closed World Machine
 
(also, in Wales, a valley  - topologiclly a partially closed world perhaps?)
 
This is an application which knows a certian amount of stuff and can manipulate
it. It uses llyn, a (forward chaining) query engine, not an (backward chaining)
inference engine: that is, it will apply all rules it can but won't figure out
which ones to apply to prove something. 
 
 
License
-------
Cwm: http://www.w3.org/2000/10/swap/doc/cwm.html
 
Copyright (c) 2000-2004 World Wide Web Consortium, (Massachusetts 
Institute of Technology, European Research Consortium for Informatics 
and Mathematics, Keio University). All Rights Reserved. This work is 
distributed under the W3C Software License [1] in the hope that it 
will be useful, but WITHOUT ANY WARRANTY; without even the implied 
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
[1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231

 
Modules
       
swap.RDFSink
swap.diag
swap.llyn
swap.notation3
string
sys
swap.toXML
swap.uripath

 
Functions
       
chdir(...)
chdir(path)
 
Change the current working directory to the specified path.
doCommand()
Command line RDF/N3 tool
        
 <command> <options> <steps> [--with <more args> ]
 
options:
 
--pipe        Don't store, just pipe out *
 
steps, in order left to right:
 
--rdf         Input & Output ** in RDF/XML insead of n3 from now on
--n3          Input & Output in N3 from now on. (Default)
--rdf=flags   Input & Output ** in RDF and set given RDF flags
--n3=flags    Input & Output in N3 and set N3 flags
--ntriples    Input & Output in NTriples (equiv --n3=usbpartane -bySubject -quiet)
--language=x  Input & Output in "x" (rdf, n3, etc)  --rdf same as: --language=rdf
--languageOptions=y     --n3=sp same as:  --language=n3 --languageOptions=sp
--ugly        Store input and regurgitate, data only, fastest *
--bySubject   Store input and regurgitate in subject order *
--no          No output *
              (default is to store and pretty print with anonymous nodes) *
--base=<uri>  Set the base URI. Input or output is done as though theis were the document URI.
--closure=flags  Control automatic lookup of identifiers (see below)
<uri>         Load document. URI may be relative to current directory.
 
--apply=foo   Read rules from foo, apply to store, adding conclusions to store
--patch=foo   Read patches from foo, applying insertions and deletions to store
--filter=foo  Read rules from foo, apply to store, REPLACING store with conclusions
--query=foo   Read a N3QL query from foo, apply it to the store, and replace the store with its conclusions
--sparql=foo   Read a SPARQL query from foo, apply it to the store, and replace the store with its conclusions
--rules       Apply rules in store to store, adding conclusions to store
--think       as -rules but continue until no more rule matches (or forever!)
--engine=otter use otter (in your $PATH) instead of llyn for linking, etc
--why         Replace the store with an explanation of its contents
--why=u       proof tries to be shorter
--mode=flags  Set modus operandi for inference (see below)
--reify       Replace the statements in the store with statements describing them.
--dereify     Undo the effects of --reify
--flatten     Reify only nested subexpressions (not top level) so that no {} remain.
--unflatten   Undo the effects of --flatten
--think=foo   as -apply=foo but continue until no more rule matches (or forever!)
--purge       Remove from store any triple involving anything in class log:Chaff
--data              Remove all except plain RDF triples (formulae, forAll, etc)
--strings     Dump :s to stdout ordered by :k whereever { :k log:outputString :s }
--crypto      Enable processing of crypto builtin functions. Requires python crypto.
--help        print this message
--revision    print CVS revision numbers of major modules
--chatty=50   Verbose debugging output of questionable use, range 0-99
--sparqlServer instead of outputting, start a SPARQL server on port 8000 of the store
--sparqlResults        After sparql query, print in sparqlResults format instead of rdf
 
finally:
 
--with        Pass any further arguments to the N3 store as os:argv values
 
 
            * mutually exclusive
            ** doesn't work for complex cases :-/
Examples:
  cwm --rdf foo.rdf --n3 --pipe     Convert from rdf/xml to rdf/n3
  cwm foo.n3 bar.n3 --think         Combine data and find all deductions
  cwm foo.n3 --flat --n3=spart
 
Mode flags affect inference extedning to the web:
 r   Needed to enable any remote stuff.
 a   When reading schema, also load rules pointed to by schema (requires r, s)
 E   Errors loading schemas of definitive documents are ignored
 m   Schemas and definitive documents laoded are merged into the meta knowledge
     (otherwise they are consulted independently)
 s   Read the schema for any predicate in a query.
 u   Generate unique ids using a run-specific
 
Closure flags are set to cause the working formula to be automatically exapnded to
the closure under the operation of looking up:
 
 s   the subject of a statement added
 p   the predicate of a statement added
 o   the object of a statement added
 t   the object of an rdf:type statement added
 i   any owl:imports documents
 r   any doc:rules documents
 E   errors are ignored --- This is independant of --mode=E
 
 n   Normalize IRIs to URIs
 e   Smush together any nodes which are = (owl:sameAs)
 
See http://www.w3.org/2000/10/swap/doc/cwm  for more documentation.
 
Setting the environment variable CWM_RDFLIB to 1 maked Cwm use rdflib to parse
rdf/xml files. Note that this requires rdflib.
getcwd(...)
getcwd() -> path
 
Return a string representing the current working directory.

 
Data
        cvsRevision = '$Revision: 1.197 $'
path = ['.', '/usr/lib/python2.4/site-packages/Cheesecake-0.6-py2.4.egg', '/usr/lib/python2.4/site-packages/setuptools-0.6c6-py2.4.egg', '/usr/lib/python2.4/site-packages/FuXi-0.85b.dev_r107-py2.4.egg', '/usr/lib/python2.4/site-packages/rdflib-2.4.0-py2.4-linux-i686.egg', '/usr/lib/python2.4/site-packages/storm-0.10-py2.4.egg', '/home/syosi/cvs-trunk/WWW/2000/10/swap', '/home/syosi/cvs-trunk/WWW/2000/10', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/HTMLgen', '/usr/lib/python2.4/site-packages/Numeric', '/usr/lib/python2.4/site-packages/PIL', '/usr/lib/python2.4/site-packages/cairo', '/usr/lib/python2.4/site-packages/gnuradio', ...]
qqq = '/home/syosi/cvs-trunk/WWW/2000/10/swap'
tracking = 0
cwm-1.2.1/setup.py0000755015216600007660000000324010766341520013135 0ustar syosisyosi#!/usr/bin/env python # borrowing liberally from Eikeon's setup.py for rdflib # an attempt at a setup.py installer for Cwm/SWAP # version: $Id: setup.py,v 1.23 2007/12/16 00:22:59 syosi Exp $ # by Dan Brickley # # STATUS: this file now works # much of what danbri typed I honestly do not know what it is trying to do. I suspect the answer is # ``not much'' # # DO NOT run this file directly! Use make dist_tarball instead. # # notes: # http://esw.w3.org/t/view/ESW/CwmTips from distutils.sysconfig import get_python_lib from os import rename from os.path import join, exists from time import time lib_dir = get_python_lib() swap_dir = join(lib_dir, "swap") print "swap dir: "+swap_dir ##if exists(swap_dir): ## backup = "%s-%s" % (swap_dir, int(time())) ## print "Renaming previously installed swap to: \n %s" % backup ## rename(swap_dir, backup) # Install SWAP from distutils.core import setup #from swap import __version__ __version__='1.2.1' setup( name = 'cwm', version = __version__, description = "Semantic Web Area for Play", author = "TimBL, Dan Connolly and contributors", author_email = "timbl@w3.org", maintainer = "Tim Berners-Lee", maintainer_email = "timbl@w3.org", url = "http://www.w3.org/2000/10/swap/", package_dir = {'swap': 'swap'}, packages = ['swap'], # py_modules = ['cwm', 'delta', 'cant'], scripts = ['cwm', 'delta', 'cant.py'], ) # todo, figure out which other modules are in public APIs # --danbri #,'swap.cwm','swap.RDFSink','swap.llyn'], # 'swap.RDFSink', # 'swap.llyn'], # packages = ['swap.cwm', # 'swap.RDFSink', # 'swap.llyn'], # package_dir = {'': 'swap'}, cwm-1.2.1/cwm_crypto.html0000644015216600007660000021502510277134335014503 0ustar syosisyosi Python: module cwm_crypto
 
 
cwm_crypto (version 1.11)
index
/home/syosi/CVS-local/WWW/2000/10/swap/cwm_crypto.py

Cryptographic Built-Ins for CWM/Llyn
 
The continuing story of cryptographic builtins.
 
cf. http://www.w3.org/2000/10/swap/cwm.py
http://www.amk.ca/python/writing/pycrypt/node16.html

 
Modules
       
Crypto.PublicKey.RSA
base64
binascii
md5
quopri
Crypto.Util.randpool
sha

 
Classes
       
term.Function(term.BuiltIn)
BI_keyLength(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_md5(term.LightBuiltIn, term.Function)
BI_publicKey(term.LightBuiltIn, term.Function)
BI_sha(term.LightBuiltIn, term.Function)
BI_sign(term.LightBuiltIn, term.Function)
BI_verifyBoolean(term.LightBuiltIn, term.Function)
term.LightBuiltIn(term.GenericBuiltIn)
BI_keyLength(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_md5(term.LightBuiltIn, term.Function)
BI_publicKey(term.LightBuiltIn, term.Function)
BI_sha(term.LightBuiltIn, term.Function)
BI_sign(term.LightBuiltIn, term.Function)
BI_verify
BI_verifyBoolean(term.LightBuiltIn, term.Function)
term.ReverseFunction(term.BuiltIn)
BI_keyLength(term.LightBuiltIn, term.Function, term.ReverseFunction)

 
class BI_keyLength(term.LightBuiltIn, term.Function, term.ReverseFunction)
    
Method resolution order:
BI_keyLength
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
__init__(self, resource, fragid)
evaluateObject(self, subj_py)
evaluateSubject(self, obj_py)
Generates an RSA keypair, and spews it out as plain text.
Has the limitation that it will *only* ever let you generate 
one key pair (per iteration), in order to work around a bug.

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Methods inherited from term.ReverseFunction:
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_md5(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_md5
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_publicKey(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_publicKey
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
Generate a quopri public key from a keypair.

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_sha(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_sha
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_sign(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_sign
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
Sign a hash with a key, and get a signature back.

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_verify(term.LightBuiltIn)
    
Method resolution order:
BI_verify
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluate(self, subj_py, obj_py)
Verify a hash/signature.

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use evaluate, subject, etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_verifyBoolean(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_verifyBoolean
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
Verify a hash/signature.

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols, string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already)
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None)
Return this or a version of me with subsitution made
unify(self, other, vars, existentials, bindings)
Unify this which may contain variables with the other,
which may contain existentials but not variables.
Return 0 if impossible.
return [({}, reason] if no new bindings
Return [( {var1: val1, var2: val2,...}, reason), ...] if match
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
Functions
       
baseDecode(s)
baseEncode(s)
decToBin(i)
formatObject(obj)
Print the various bits found within a key (works on any object).
keyToQuo(key, joi='\n\n')
Returns a quoted printable version of a key - ee then m.
Leading and trailing whitespace is allowed; stripped by quoToKey.
newKey(e, n, d=None, p=None, q=None)
Create a new key.
quoToKey(strkey, spl='\n\n')
Returns a key from quopri (ee then m) version of a key.
register(store)

 
Data
        CRYPTO_NS_URI = 'http://www.w3.org/2000/10/swap/crypto#'
USE_PKC = 1
__author__ = 'Sean B. Palmer'
__cvsid__ = '$Id: cwm_crypto.html,v 1.7 2005/08/10 15:05:38 syosi Exp $'
__version__ = '$Revision: 1.7 $'

 
Author
        Sean B. Palmer
cwm-1.2.1/LICENSE0000644015216600007660000000407110073554235012430 0ustar syosisyosiW3C® SOFTWARE NOTICE AND LICENSE http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 This work (and included software, documentation such as READMEs, or other related items) is being provided by the copyright holders under the following license. By obtaining, using and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions. Permission to copy, modify, and distribute this software and its documentation, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the software and documentation or portions thereof, including modifications: 1. The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. 2. Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software Short Notice should be included (hypertext is preferred, text is permitted) within the body of any redistributed or derivative code. 3. Notice of any changes or modifications to the files, including the date changes were made. (We recommend you provide URIs to the location from which the code is derived.) THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENTATION. The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the software without specific, written prior permission. Title to copyright in this software and any associated documentation will at all times remain with copyright holders. cwm-1.2.1/LICENSE.rdf0000644015216600007660000000147207506364667013223 0ustar syosisyosi Share and Enjoy. Open Source license: Copyright (c) 2000,1,2 W3C (MIT, INRIA, Keio) Copyright other contributers mentioned in individual files. http://www.w3.org/Consortium/Legal/copyright-software-19980720 cwm-1.2.1/cwm_string.html0000644015216600007660000077545710642726421014514 0ustar syosisyosi Python: module cwm_string
 
 
cwm_string
index
/Users/yosi/CVSROOT/WWW/2000/10/swap/cwm_string.py

$Id: cwm_string.html,v 1.18 2007/06/27 17:58:39 syosi Exp $
 
String built-ins for cwm
This started as http://www.w3.org/2000/10/swap/string.py
 
See cwm.py

 
Modules
       
binascii
md5
re
string
urllib

 
Classes
       
term.Function(term.BuiltIn)
BI_concatenation(term.LightBuiltIn, term.Function)
BI_encodeForFragID(term.LightBuiltIn, term.Function)
BI_encodeForURI(term.LightBuiltIn, term.Function)
BI_format(term.LightBuiltIn, term.Function)
BI_normalize_space(term.LightBuiltIn, term.Function)
BI_resolve_uri(term.LightBuiltIn, term.Function)
BI_scrape(term.LightBuiltIn, term.Function)
BI_search(term.LightBuiltIn, term.Function)
BI_split(term.LightBuiltIn, term.Function)
BI_stringToList(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_tokenize(term.LightBuiltIn, term.Function)
BI_xmlEscapeAttribute(term.LightBuiltIn, term.Function)
BI_xmlEscapeData(term.LightBuiltIn, term.Function)
term.LightBuiltIn(term.GenericBuiltIn)
BI_Contains
BI_ContainsIgnoringCase
BI_ContainsRoughly
BI_DoesNotContain
BI_EndsWith
BI_GreaterThan
BI_LessThan
BI_NotGreaterThan
BI_NotLessThan
BI_StartsWith
BI_concat(term.LightBuiltIn, term.ReverseFunction)
BI_concatenation(term.LightBuiltIn, term.Function)
BI_encodeForFragID(term.LightBuiltIn, term.Function)
BI_encodeForURI(term.LightBuiltIn, term.Function)
BI_equalIgnoringCase
BI_format(term.LightBuiltIn, term.Function)
BI_matches
BI_normalize_space(term.LightBuiltIn, term.Function)
BI_notEqualIgnoringCase
BI_notMatches
BI_resolve_uri(term.LightBuiltIn, term.Function)
BI_scrape(term.LightBuiltIn, term.Function)
BI_search(term.LightBuiltIn, term.Function)
BI_split(term.LightBuiltIn, term.Function)
BI_stringToList(term.LightBuiltIn, term.Function, term.ReverseFunction)
BI_tokenize(term.LightBuiltIn, term.Function)
BI_xmlEscapeAttribute(term.LightBuiltIn, term.Function)
BI_xmlEscapeData(term.LightBuiltIn, term.Function)
term.ReverseFunction(term.BuiltIn)
BI_concat(term.LightBuiltIn, term.ReverseFunction)
BI_stringToList(term.LightBuiltIn, term.Function, term.ReverseFunction)

 
class BI_Contains(term.LightBuiltIn)
    
Method resolution order:
BI_Contains
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_ContainsIgnoringCase(term.LightBuiltIn)
    
Method resolution order:
BI_ContainsIgnoringCase
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_ContainsRoughly(term.LightBuiltIn)
    
Method resolution order:
BI_ContainsRoughly
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_DoesNotContain(term.LightBuiltIn)
    
Method resolution order:
BI_DoesNotContain
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_EndsWith(term.LightBuiltIn)
    
Method resolution order:
BI_EndsWith
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_GreaterThan(term.LightBuiltIn)
    
Method resolution order:
BI_GreaterThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_LessThan(term.LightBuiltIn)
    
Method resolution order:
BI_LessThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_NotGreaterThan(term.LightBuiltIn)
    
Method resolution order:
BI_NotGreaterThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_NotLessThan(term.LightBuiltIn)
    
Method resolution order:
BI_NotLessThan
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_StartsWith(term.LightBuiltIn)
    
Method resolution order:
BI_StartsWith
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_concat(term.LightBuiltIn, term.ReverseFunction)
    
Method resolution order:
BI_concat
term.LightBuiltIn
term.GenericBuiltIn
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.ReverseFunction:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_concatenation(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_concatenation
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_encodeForFragID(term.LightBuiltIn, term.Function)
    Take a unicode string and return it encoded so as to pass in
a URI grament identifier.
 
 
Method resolution order:
BI_encodeForFragID
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_encodeForURI(term.LightBuiltIn, term.Function)
    Take a unicode string and return it encoded so as to pass in an
URI path segment. See
http://www.w3.org/TR/2005/CR-xpath-functions-20051103/#func-encode-for-uri
 
 
Method resolution order:
BI_encodeForURI
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_equalIgnoringCase(term.LightBuiltIn)
    
Method resolution order:
BI_equalIgnoringCase
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_format(term.LightBuiltIn, term.Function)
    a built-in for string formatting,
ala python % or C's sprintf or common-lisp's format
takes a list; the first item is the format string, and the rest are args.
see also: test/@@
 
 
Method resolution order:
BI_format
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_matches(term.LightBuiltIn)
    
Method resolution order:
BI_matches
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_normalize_space(term.LightBuiltIn, term.Function)
    Returns the value of $arg with whitespace normalized by
stripping leading and trailing whitespace and replacing sequences
of one or more than one whitespace character with a single space,
#x20 -- http://www.w3.org/2006/xpath-functions#normalize-space
 
 
Method resolution order:
BI_normalize_space
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notEqualIgnoringCase(term.LightBuiltIn)
    
Method resolution order:
BI_notEqualIgnoringCase
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notMatches(term.LightBuiltIn)
    
Method resolution order:
BI_notMatches
term.LightBuiltIn
term.GenericBuiltIn
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_resolve_uri(term.LightBuiltIn, term.Function)
    see http://www.w3.org/2006/xpath-functions#resolve-uri
 
 
Method resolution order:
BI_resolve_uri
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_scrape(term.LightBuiltIn, term.Function)
    a built-in for scraping using regexps.
takes a list of 2 strings; the first is the
input data, and the second is a regex with one () group.
Returns the data matched by the () group.
 
see also: test/includes/scrape1.n3
Hmm... negative tests don't seem to work.
 
 
Method resolution order:
BI_scrape
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_search(term.LightBuiltIn, term.Function)
    a more powerful built-in for scraping using regexps.
takes a list of 2 strings; the first is the
input data, and the second is a regex with one or more () group.
Returns the list of data matched by the () groups.
 
see also: test/includes/search.n3
 
 
Method resolution order:
BI_search
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_split(term.LightBuiltIn, term.Function)
    split a string into a list of strings
takes a list of 2 strings and an integer; the first is the
input data, and the second is a regex
see re.split in http://docs.python.org/lib/node46.html
 
 
Method resolution order:
BI_split
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_stringToList(term.LightBuiltIn, term.Function, term.ReverseFunction)
    You need nothing else. Makes a string a list of characters, and visa versa.
 
 
Method resolution order:
BI_stringToList
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)
evaluateSubject(self, obj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Methods inherited from term.ReverseFunction:
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_tokenize(term.LightBuiltIn, term.Function)
    like split without the max arg
 
 
Method resolution order:
BI_tokenize
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_xmlEscapeAttribute(term.LightBuiltIn, term.Function)
    Take a unicode string and return it encoded so as to pass in an XML data
You may need stg different for attributes, escaping quotes.
 
 
Method resolution order:
BI_xmlEscapeAttribute
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_xmlEscapeData(term.LightBuiltIn, term.Function)
    Take a unicode string and return it encoded so as to pass in an XML data
You will need the BI_xmlEscapeAttribute on for attributes, escaping quotes.
 
 
Method resolution order:
BI_xmlEscapeData
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj_py)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
Functions
       
isString(x)
normalizeWhitespace(s)
Normalize whitespace sequences in a string to single spaces
register(store)
xmlEscape(subj_py, markupChars)
Escape a string given a regex of the markup chars to be escaped
from toXML.py

 
Data
        LITERAL_URI_prefix = 'data:text/rdf+n3;'
STRING_NS_URI = 'http://www.w3.org/2000/10/swap/string#'
attrEsc = <_sre.SRE_Pattern object>
dataEsc = <_sre.SRE_Pattern object>
cwm-1.2.1/sparql2cwm.html0000644015216600007660000023627410717172614014422 0ustar syosisyosi Python: module sparql2cwm
 
 
sparql2cwm
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/sparql2cwm.py

sparql2cwm
 
This is meant to be used with a sparql.n3 based SPARQL parser, to add the query to cwm
 
$Id: sparql2cwm.py,v 1.24 2007/08/06 16:13:56 syosi Exp $

 
Modules
       
diag
uripath

 
Classes
       
__builtin__.dict(__builtin__.object)
multimap
__builtin__.object
AST
Coerce
NotNot
RulesMaker
productionHandler
FilterExpr
FromSparql
__builtin__.tuple(__builtin__.object)
TripleHolder
andExtra
__builtin__.unicode(__builtin__.basestring)
typedThing

 
class AST(__builtin__.object)
     Methods defined here:
__init__(self, ast, sink=None)
abbr(self, prodURI)
onFinish(self)
onStart(self, prod)
onToken(self, prod, tok)
prod(self, thing)
run(self)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'AST' objects>
list of weak references to the object (if defined)

 
class Coerce(__builtin__.object)
     Methods defined here:
__call__(self, expr, coerce=True)
__init__(self)
atom(self, p, coerce)
on_And(self, p, coerce)
on_BoolVal(self, p, coerce)
on_Boolean(self, p, coerce)
on_Bound(self, p, coerce)
on_Not(self, p, coerce)
on_Or(self, p, coerce)
on_Regex(self, p, coerce)
on_function(self, p, coerce)
on_isBlank(self, p, coerce)
on_isLiteral(self, p, coerce)
on_isURI(self, p, coerce)
on_math(self, p, coerce)
on_pred(self, p, coerce)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Coerce' objects>
list of weak references to the object (if defined)

 
class FilterExpr(productionHandler)
    
Method resolution order:
FilterExpr
productionHandler
__builtin__.object

Methods defined here:
__init__(self, store, parent)
arithmetic(self, p, op)
compare(self, p, op)
on_And(self, p)
on_BoolVal(self, p)
on_Boolean(self, p)
on_Bound(self, var)
on_Literal(self, p)
on_Not(self, p)
on_Number(self, p)
on_Or(self, p)
on_Regex(self, p)
on_String(self, p)
on_Var(self, p)
on_add(self, p)
on_datatype(self, p)
on_divide(self, p)
on_equal(self, p)
on_funcName(self, p)
on_function(self, p)
on_greater(self, p)
on_isNotURI(self, p)
on_isURI(self, p)
on_lang(self, p)
on_less(self, p)
on_multiply(self, p)
on_notBound(self, var)
on_notEqual(self, p)
on_notGreater(self, p)
on_notLess(self, p)
on_subtract(self, p)
on_symbol(self, p)
typeConvert(self, keepGoing, uri, val)

Methods inherited from productionHandler:
prod(self, production)

Data and other attributes inherited from productionHandler:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'productionHandler' objects>
list of weak references to the object (if defined)

 
class FromSparql(productionHandler)
    
Method resolution order:
FromSparql
productionHandler
__builtin__.object

Methods defined here:
__init__(self, store, formula=None, ve=0, why=None)
absolutize(self, uri)
anonymize(self, formula, uri=None)
makePatterns(self, f, node, patterns)
new_bnode(self)
on_AdditiveExpression(self, p)
on_ArgList(self, p)
on_AskQuery(self, p)
on_BaseDecl(self, p)
on_BlankNode(self, p)
on_BlankNodePropertyList(self, p)
on_BooleanLiteral(self, p)
on_BrackettedExpression(self, p)
on_BuiltinCallExpression(self, p)
on_CallExpression(self, p)
on_Collection(self, p)
on_ConditionalAndExpression(self, p)
on_ConditionalOrExpression(self, p)
on_Constraint(self, p)
on_ConstructQuery(self, p)
on_ConstructTemplate(self, p)
on_DatasetClause(self, p)
on_DefaultGraphClause(self, p)
on_DescribeQuery(self, p)
on_Expression(self, p)
on_FunctionCall(self, p)
on_GraphGraphPattern(self, p)
on_GraphNode(self, p)
on_GraphPatternList(self, p)
on_GraphPatternListTail(self, p)
on_GraphPatternNotTriples(self, p)
on_GraphPatternNotTriplesList(self, p)
on_GraphPatternNotTriplesTail(self, p)
on_GraphTerm(self, p)
on_GroupGraphPattern(self, p, fromFilter=False)
on_GroupOrUnionGraphPattern(self, p)
on_IRIref(self, p)
on_IRIrefOrFunc(self, p)
on_LimitClause(self, p)
on_MultiplicativeExpression(self, p)
on_NamedGraphClause(self, p)
on_NamelessBlank(self, p)
on_NumericExpression(self, p)
on_NumericLiteral(self, p)
on_Object(self, p)
on_ObjectList(self, p)
on_OffsetClause(self, p)
on_OptionalGraphPattern(self, p)
on_OrderClause(self, p)
on_OrderCondition(self, p)
on_PrefixDecl(self, p)
on_PrimaryExpression(self, p)
on_Prolog(self, p)
on_PropertyList(self, p)
on_PropertyListNotEmpty(self, p)
on_QName(self, p)
on_Query(self, p)
on_RDFLiteral(self, p)
on_RDFTerm(self, p)
on_RDFTermOrFunc(self, p)
on_RegexExpression(self, p)
on_RelationalExpression(self, p)
on_SelectQuery(self, p)
on_SolutionModifier(self, p)
on_SourceSelector(self, p)
on_String(self, p)
on_Triples(self, p)
on_Triples1(self, p)
on_Triples2(self, p)
on_Triples3(self, p)
on_TriplesNode(self, p)
on_UnaryExpression(self, p)
on_ValueLogical(self, p)
on_Var(self, p)
on_VarOrBlankNodeOrIRIref(self, p)
on_VarOrIRIref(self, p)
on_VarOrTerm(self, p)
on_Verb(self, p)
on_WhereClause(self, p)
on__O_QAND_E____QValueLogical_E__C(self, p)
on__O_QASC_E__Or__QDESC_E__C(self, p)
on__O_QASC_E__Or__QDESC_E____QBrackettedExpression_E__C(self, p)
on__O_QBrackettedExpression_E__Or__QCallExpression_E__C(self, p)
see normalize for an explanation of what we are doing
on__O_QCOMMA_E____QExpression_E__C(self, p)
on__O_QCOMMA_E____QObjectList_E__C(self, p)
on__O_QDTYPE_E____QIRIref_E__C(self, p)
on__O_QDefaultGraphClause_E__Or__QNamedGraphClause_E__C(self, p)
on__O_QDot_E_Opt___QGraphPatternList_E__C(self, p)
on__O_QDot_E____QGraphPatternList_E__C(self, p)
on__O_QDot_E____QTriples_E_Opt_C(self, p)
on__O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C(self, p)
on__O_QExpression_E____QCOMMA_E____QExpression_E_Star_C(self, p)
on__O_QFunctionCall_E__Or__QVar_E__Or__QBrackettedExpression_E__C(self, p)
on__O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C(self, p)
on__O_QOR_E____QConditionalAndExpression_E__C(self, p)
on__O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C(self, p)
on__O_QSEMI_E____QPropertyList_E__C(self, p)
on__O_QSelectQuery_E__Or__QConstructQuery_E__Or__QDescribeQuery_E__Or__QAskQuery_E__C(self, p)
on__O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C(self, p)
on__O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C(self, p)
on__O_QUNION_E____QGroupGraphPattern_E__C(self, p)
on__O_QVarOrIRIref_E_Plus_Or__QTIMES_E__C(self, p)
on__O_QVar_E_Plus_Or__QTIMES_E__C(self, p)
on__QArgList_E_Opt(self, p)
on__QBaseDecl_E_Opt(self, p)
on__QDISTINCT_E_Opt(self, p)
on__QDatasetClause_E_Star(self, p)
on__QDot_E_Opt(self, p)
on__QGraphNode_E_Plus(self, p)
on__QGraphNode_E_Star(self, p)
on__QLimitClause_E_Opt(self, p)
on__QOffsetClause_E_Opt(self, p)
on__QOrderClause_E_Opt(self, p)
on__QOrderCondition_E_Plus(self, p)
on__QPrefixDecl_E_Star(self, p)
on__QPropertyListNotEmpty_E_Opt(self, p)
on__QTriples_E_Opt(self, p)
on__QVarOrIRIref_E_Plus(self, p)
on__QVar_E_Plus(self, p)
on__QWHERE_E_Opt(self, p)
on__QWhereClause_E_Opt(self, p)
on__Q_O_QAND_E____QValueLogical_E__C_E_Star(self, p)
on__Q_O_QCOMMA_E____QExpression_E__C_E_Opt(self, p)
on__Q_O_QCOMMA_E____QExpression_E__C_E_Star(self, p)
on__Q_O_QCOMMA_E____QObjectList_E__C_E_Opt(self, p)
on__Q_O_QDot_E____QGraphPatternList_E__C_E_Opt(self, p)
on__Q_O_QDot_E____QTriples_E_Opt_C_E_Opt(self, p)
on__Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt(self, p)
on__Q_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C_E_Opt(self, p)
on__Q_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C_E_Opt(self, p)
on__Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star(self, p)
on__Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star(self, p)
on__Q_O_QSEMI_E____QPropertyList_E__C_E_Opt(self, p)
on__Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star(self, p)
on__Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt(self, p)
on__Q_O_QUNION_E____QGroupGraphPattern_E__C_E_Star(self, p)

Methods inherited from productionHandler:
prod(self, production)

Data and other attributes inherited from productionHandler:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'productionHandler' objects>
list of weak references to the object (if defined)

 
class NotNot(__builtin__.object)
    This class is used to figure out the inverses of all SPARQL boolean tests, and invert all functions
 
  Methods defined here:
__call__(self, expr, inv=False, Ored=False)
__init__(self)
atom(self, p, inv, ored)
expr(self, p, inv, ored)
on_And(self, p, inv, ored)
on_BoolVal(self, p, inv, ored)
on_Not(self, p, inv, ored)
on_Or(self, p, inv, ored)
on_Regex(self, p, inv, ored)
on_notMatches(self, p, inv)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'NotNot' objects>
list of weak references to the object (if defined)
inverse_operators = {'Bound': 'notBound', 'equal': 'notEqual', 'greater': 'notGreater', 'isBlank': 'isNotBlank', 'isLiteral': 'isNotLiteral', 'isNotBlank': 'isBlank', 'isNotLiteral': 'isLiteral', 'isNotURI': 'isURI', 'isURI': 'isNotURI', 'less': 'notLess', ...}

 
class RulesMaker(__builtin__.object)
     Methods defined here:
__init__(self, ns)
find_vars(self, vars, f)
implications(self, query, formula, totalResult)
matching_subformula(self, retF, illegals, F)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'RulesMaker' objects>
list of weak references to the object (if defined)

 
class TripleHolder(__builtin__.tuple)
    
Method resolution order:
TripleHolder
__builtin__.tuple
__builtin__.object

Static methods defined here:
__new__(cls, *args, **keywords)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)

Methods inherited from __builtin__.tuple:
__add__(...)
x.__add__(y) <==> x+y
__contains__(...)
x.__contains__(y) <==> y in x
__eq__(...)
x.__eq__(y) <==> x==y
__ge__(...)
x.__ge__(y) <==> x>=y
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getnewargs__(...)
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__gt__(...)
x.__gt__(y) <==> x>y
__hash__(...)
x.__hash__() <==> hash(x)
__iter__(...)
x.__iter__() <==> iter(x)
__le__(...)
x.__le__(y) <==> x<=y
__len__(...)
x.__len__() <==> len(x)
__lt__(...)
x.__lt__(y) <==> x<y
__mul__(...)
x.__mul__(n) <==> x*n
__ne__(...)
x.__ne__(y) <==> x!=y
__repr__(...)
x.__repr__() <==> repr(x)
__rmul__(...)
x.__rmul__(n) <==> n*x

 
class andExtra(__builtin__.tuple)
    
Method resolution order:
andExtra
__builtin__.tuple
__builtin__.object

Methods defined here:
__repr__(self)

Static methods defined here:
__new__(cls, val, extra)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)

Methods inherited from __builtin__.tuple:
__add__(...)
x.__add__(y) <==> x+y
__contains__(...)
x.__contains__(y) <==> y in x
__eq__(...)
x.__eq__(y) <==> x==y
__ge__(...)
x.__ge__(y) <==> x>=y
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getnewargs__(...)
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__gt__(...)
x.__gt__(y) <==> x>y
__hash__(...)
x.__hash__() <==> hash(x)
__iter__(...)
x.__iter__() <==> iter(x)
__le__(...)
x.__le__(y) <==> x<=y
__len__(...)
x.__len__() <==> len(x)
__lt__(...)
x.__lt__(y) <==> x<y
__mul__(...)
x.__mul__(n) <==> x*n
__ne__(...)
x.__ne__(y) <==> x!=y
__rmul__(...)
x.__rmul__(n) <==> n*x

 
class multimap(__builtin__.dict)
    A class to handle where each element maps to a set of elements
 
It would perhaps be simpler to have used dict.setdefault(), but this has the
advantage of merging instead of nesting sets
 
 
Method resolution order:
multimap
__builtin__.dict
__builtin__.object

Methods defined here:
__add__(self, other)
__init__(self, olddict={}, **values)
__setitem__(self, key, value)
translate(self, fromkey, tokey)
update(self, other={}, **values)

Class methods defined here:
fromTuples = _fromTuples(cls, iterator) from __builtin__.type

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'multimap' objects>
list of weak references to the object (if defined)
innerSet = <class 'sparql2cwm.innerSet'>

Methods inherited from __builtin__.dict:
__cmp__(...)
x.__cmp__(y) <==> cmp(x,y)
__contains__(...)
D.__contains__(k) -> True if D has a key k, else False
__delitem__(...)
x.__delitem__(y) <==> del x[y]
__eq__(...)
x.__eq__(y) <==> x==y
__ge__(...)
x.__ge__(y) <==> x>=y
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__gt__(...)
x.__gt__(y) <==> x>y
__hash__(...)
x.__hash__() <==> hash(x)
__iter__(...)
x.__iter__() <==> iter(x)
__le__(...)
x.__le__(y) <==> x<=y
__len__(...)
x.__len__() <==> len(x)
__lt__(...)
x.__lt__(y) <==> x<y
__ne__(...)
x.__ne__(y) <==> x!=y
__repr__(...)
x.__repr__() <==> repr(x)
clear(...)
D.clear() -> None.  Remove all items from D.
copy(...)
D.copy() -> a shallow copy of D
get(...)
D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
has_key(...)
D.has_key(k) -> True if D has a key k, else False
items(...)
D.items() -> list of D's (key, value) pairs, as 2-tuples
iteritems(...)
D.iteritems() -> an iterator over the (key, value) items of D
iterkeys(...)
D.iterkeys() -> an iterator over the keys of D
itervalues(...)
D.itervalues() -> an iterator over the values of D
keys(...)
D.keys() -> list of D's keys
pop(...)
D.pop(k[,d]) -> v, remove specified key and return the corresponding value
If key is not found, d is returned if given, otherwise KeyError is raised
popitem(...)
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty
setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
values(...)
D.values() -> list of D's values

Data and other attributes inherited from __builtin__.dict:
__new__ = <built-in method __new__ of type object>
T.__new__(S, ...) -> a new object with type S, a subtype of T
fromkeys = <built-in method fromkeys of type object>
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.

 
class productionHandler(__builtin__.object)
     Methods defined here:
prod(self, production)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'productionHandler' objects>
list of weak references to the object (if defined)

 
class typedThing(__builtin__.unicode)
    
Method resolution order:
typedThing
__builtin__.unicode
__builtin__.basestring
__builtin__.object

Methods defined here:
__call__(self)

Static methods defined here:
__new__(cls, val, retType=None, ArgTypes=[], trueOnError=False)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'typedThing' objects>
list of weak references to the object (if defined)

Methods inherited from __builtin__.unicode:
__add__(...)
x.__add__(y) <==> x+y
__cmp__(...)
x.__cmp__(y) <==> cmp(x,y)
__contains__(...)
x.__contains__(y) <==> y in x
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__getitem__(...)
x.__getitem__(y) <==> x[y]
__getnewargs__(...)
__getslice__(...)
x.__getslice__(i, j) <==> x[i:j]
 
Use of negative indices is not supported.
__hash__(...)
x.__hash__() <==> hash(x)
__len__(...)
x.__len__() <==> len(x)
__mod__(...)
x.__mod__(y) <==> x%y
__mul__(...)
x.__mul__(n) <==> x*n
__repr__(...)
x.__repr__() <==> repr(x)
__rmod__(...)
x.__rmod__(y) <==> y%x
__rmul__(...)
x.__rmul__(n) <==> n*x
__str__(...)
x.__str__() <==> str(x)
capitalize(...)
S.capitalize() -> unicode
 
Return a capitalized version of S, i.e. make the first character
have upper case.
center(...)
S.center(width[, fillchar]) -> unicode
 
Return S centered in a Unicode string of length width. Padding is
done using the specified fill character (default is a space)
count(...)
S.count(sub[, start[, end]]) -> int
 
Return the number of occurrences of substring sub in Unicode string
S[start:end].  Optional arguments start and end are
interpreted as in slice notation.
decode(...)
S.decode([encoding[,errors]]) -> string or unicode
 
Decodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registerd with codecs.register_error that is
able to handle UnicodeDecodeErrors.
encode(...)
S.encode([encoding[,errors]]) -> string or unicode
 
Encodes S using the codec registered for encoding. encoding defaults
to the default encoding. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
endswith(...)
S.endswith(suffix[, start[, end]]) -> bool
 
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
expandtabs(...)
S.expandtabs([tabsize]) -> unicode
 
Return a copy of S where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
find(...)
S.find(sub [,start [,end]]) -> int
 
Return the lowest index in S where substring sub is found,
such that sub is contained within s[start,end].  Optional
arguments start and end are interpreted as in slice notation.
 
Return -1 on failure.
index(...)
S.index(sub [,start [,end]]) -> int
 
Like S.find() but raise ValueError when the substring is not found.
isalnum(...)
S.isalnum() -> bool
 
Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
isalpha(...)
S.isalpha() -> bool
 
Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
isdecimal(...)
S.isdecimal() -> bool
 
Return True if there are only decimal characters in S,
False otherwise.
isdigit(...)
S.isdigit() -> bool
 
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
islower(...)
S.islower() -> bool
 
Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
isnumeric(...)
S.isnumeric() -> bool
 
Return True if there are only numeric characters in S,
False otherwise.
isspace(...)
S.isspace() -> bool
 
Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.
istitle(...)
S.istitle() -> bool
 
Return True if S is a titlecased string and there is at least one
character in S, i.e. upper- and titlecase characters may only
follow uncased characters and lowercase characters only cased ones.
Return False otherwise.
isupper(...)
S.isupper() -> bool
 
Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
join(...)
S.join(sequence) -> unicode
 
Return a string which is the concatenation of the strings in the
sequence.  The separator between elements is S.
ljust(...)
S.ljust(width[, fillchar]) -> int
 
Return S left justified in a Unicode string of length width. Padding is
done using the specified fill character (default is a space).
lower(...)
S.lower() -> unicode
 
Return a copy of the string S converted to lowercase.
lstrip(...)
S.lstrip([chars]) -> unicode
 
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is a str, it will be converted to unicode before stripping
replace(...)
S.replace (old, new[, maxsplit]) -> unicode
 
Return a copy of S with all occurrences of substring
old replaced by new.  If the optional argument maxsplit is
given, only the first maxsplit occurrences are replaced.
rfind(...)
S.rfind(sub [,start [,end]]) -> int
 
Return the highest index in S where substring sub is found,
such that sub is contained within s[start,end].  Optional
arguments start and end are interpreted as in slice notation.
 
Return -1 on failure.
rindex(...)
S.rindex(sub [,start [,end]]) -> int
 
Like S.rfind() but raise ValueError when the substring is not found.
rjust(...)
S.rjust(width[, fillchar]) -> unicode
 
Return S right justified in a Unicode string of length width. Padding is
done using the specified fill character (default is a space).
rsplit(...)
S.rsplit([sep [,maxsplit]]) -> list of strings
 
Return a list of the words in S, using sep as the
delimiter string, starting at the end of the string and
working to the front.  If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any whitespace string
is a separator.
rstrip(...)
S.rstrip([chars]) -> unicode
 
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is a str, it will be converted to unicode before stripping
split(...)
S.split([sep [,maxsplit]]) -> list of strings
 
Return a list of the words in S, using sep as the
delimiter string.  If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None,
any whitespace string is a separator.
splitlines(...)
S.splitlines([keepends]]) -> list of strings
 
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
startswith(...)
S.startswith(prefix[, start[, end]]) -> bool
 
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
strip(...)
S.strip([chars]) -> unicode
 
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is a str, it will be converted to unicode before stripping
swapcase(...)
S.swapcase() -> unicode
 
Return a copy of S with uppercase characters converted to lowercase
and vice versa.
title(...)
S.title() -> unicode
 
Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.
translate(...)
S.translate(table) -> unicode
 
Return a copy of the string S, where all characters have been mapped
through the given translation table, which must be a mapping of
Unicode ordinals to Unicode ordinals, Unicode strings or None.
Unmapped characters are left untouched. Characters mapped to None
are deleted.
upper(...)
S.upper() -> unicode
 
Return a copy of S converted to uppercase.
zfill(...)
S.zfill(width) -> unicode
 
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.

 
Functions
       
abbr(prodURI)
getExtra(ex)
getTrueOnError(ex)
getType(ex)
intConvert(self, keepGoing, val)
makeSafeVal(val, (subj, pred, obj), safeVersion=False)
makeTriple(subj, pred, obj, safeVersion=False)
makeTripleObjList(subj, pred, obj)
normalize(expr)
The mapping from SPARQL syntax to n3 is decidedly nontrivial
at this point, we have done the first step, building an AST that is (relatively) independant of all of the oddities that
you get from the grammar
 
Normalize does a couple of top down transforms on the tree. The first is a type determiner; it determines what
needs to be coerced to a boolean. The second does boolean logic and pushes ``not''s all the way in.
 
After normalize, the last bottom up step to generate the n3 can be done.
on_Boolean_Gen(true, false)
reason2 = value(self, newVal=None) method of __builtin__.list instance
sparqlLookup(uri, server, property)
unEscape(string)
value(self, newVal=None)
verbose = value(self, newVal=None) method of __builtin__.list instance

 
Data
        AND = u'And'
NOT = u'Not'
OR = u'Or'
ORED_AND = u'And'
ORED_NOT = u'Not'
SPARQL_NS = 'http://www.w3.org/2000/10/swap/sparqlCwm'
knownFunctions = {'http://www.w3.org/2001/XMLSchema#integer': <function intConvert>}
cwm-1.2.1/myStore.html0000644015216600007660000003474310717716424013771 0ustar syosisyosi Python: module myStore
 
 
myStore
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/myStore.py

$Id: myStore.html,v 1.13 2007/11/18 02:01:56 syosi Exp $
 
Process-global store
 
Global variables are often a bad idea. However, the majority of cwm
applications involve just one RDF store. One store can contain many
formulae.  The main thing which these formulae of the same store share
is the index with which names and strings are interned.  Within a
store, you can compare things by comparing memory addresses rather
than the whole tring, uri or list.
 
Therefore, it is normal to just use one store.  When you do this, the
store paremeter to most methods beceomes unnecessary, and you get a
simpler API.  That is what this module does. If you import it, you
will get a global store. This will not stop you using other stores.
 
You also get the Namespace() class which allows you to generate
symbols easily.
 
History:
    Spilt off from  thing.py 2003-08-19
 
$Log: myStore.html,v $ Revision 1.13 2007/11/18 02:01:56 syosi closer to getting release process to run only problem in tests now is double-proof.n3
Revision 1.14  2007/08/06 16:13:56  syosi
A month of changes
 
Revision 1.13  2007/06/26 02:36:15  syosi
fix tabs
 
Revision 1.12  2005/10/24 16:58:38  timbl
--n3=B flag introduced. --why improved but not perfect.
 
Revision 1.11  2004/08/08 01:44:49  syosi
undo what I did last thing Friday. Those changes are nowhere near ready for the trunk
 
Revision 1.9  2004/07/29 16:16:11  syosi
rdflib tests in the default test suite
 
Revision 1.8  2004/04/19 13:32:22  connolly
trap __special_names__ in Namespace.__getattr__ so
that pychecker can work
 
Revision 1.7  2004/03/21 04:24:35  timbl
(See doc/changes.html)
on xml output, nodeID was incorrectly spelled.
update.py provides cwm's --patch option.
diff.py as independent progrem generates patch files for cwm --patch
 
Revision 1.6  2004/03/09 23:55:50  connolly
updated load to track change in llyn
 
Revision 1.5  2004/03/06 20:39:38  timbl
See http://www.w3.org/2000/10/swap/doc/changes.html for details
- Regresssion test incorporates the RDF Core Positive Parser Tests except XMLLiteral & reification
- xml:base support was added in the parser.
- Use the --rdf=R flag to allow RDF to be parsed even when there is no enveloping <rdf:RDF> tag
- nodeid generated on RDF output
- Automatically generated terms with no URIs sort after anything which has a URI.
Namespace prefix smarts on output - default ns used for that most frequently used.
- suppresses namespace prefix declarations which are not actually needed in the output.
- Cwm will also make up prefixes when it needs them for a namespace, and none of the input data uses one.-
- Will not use namespace names for URIs which do not have a "#". Including a "/" in the flags overrides.
 
Revision 1.4  2004/01/29 21:10:39  timbl
ooops - ref to SYMBOL
 
Revision 1.3  2004/01/28 23:03:00  connolly
- added unit tests to confirm that symbol functions take ustrings
- wrapped some comments at 79 chars
  per http://www.python.org/doc/essays/styleguide.html

 
Modules
       
uripath

 
Classes
       
__builtin__.object
Namespace

 
class Namespace(__builtin__.object)
    A shortcut for getting a symbols as interned by the default store
 
>>> RDF = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
>>> x = RDF.type
>>> y = RDF.type
>>> x is y
1
 
  Methods defined here:
__getattr__(self, lname)
get the lname Symbol in this namespace.
 
lname -- an XML name (limited to URI characters)
I hope this is only called *after* the ones defines above have been checked
__getitem__ = sym(self, lname)
__init__(self, name, store=None)
sym(self, lname)
For getting a symbol for an expression, rather than a constant.
For, and from, pim/toIcal.py

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Namespace' objects>
list of weak references to the object (if defined)

 
Functions
       
bind(prefix, uri)
existential(str, context, uri)
Create or reuse, in the default store, a new named variable
existentially qualified within the given
formula as context, and return it for future use
formula()
Create or reuse, in the default store, a new empty formula (triple people think: triple store)
and return it for future use
intern(v)
literal(str, dt=None, lang=None)
Create or reuse, in the default store, an interned version of
the given literal string and return it for future use
 
>>> x = literal("#Andr\xe9")
>>> y = literal("#Andr\xe9")
>>> x is y
1
load(uri=None, openFormula=None, contentType=None, remember=1, flags='')
Get and parse document.  Guesses format if necessary.
 
uri:      if None, load from standard input.
remember: if 1, store as metadata the relationship between this URI and this formula.
 
Returns:  top-level formula of the parsed document.
Raises:   IOError, SyntaxError, DocumentError
loadMany(uris, openFormula=None, referer=None)
Load a number of resources into the same formula
 
Returns:  top-level formula of the parsed information.
Raises:   IOError, SyntaxError, DocumentError
setStore(s)
Set the process-global default store to be used when an explicit store is not
setStoreClass(c)
Set the process-global class to be used to generate a new store if needed
symbol(uri)
Create or reuse an interned version of the given symbol
in the default store. and return it for future use
 
>>> x = symbol(u'http://example.org/#Andr\xe9')
>>> y = symbol(u'http://example.org/#Andr\xe9')
>>> x is y
1
universal(str, context, uri)
Create or reuse, in the default store, a named variable
universally qualified within the given
formula as context, and return it for future use

 
Data
        store = None
storeClass = None
cwm-1.2.1/rdflib2rdf.html0000644015216600007660000002047310070600433014322 0ustar syosisyosi Python: module rdflib2rdf
 
 
rdflib2rdf
index
/home/syosi/CVS-local/WWW/2000/10/swap/rdflib2rdf.py

This rdflib2rdf module provides code for glueing rdflib's rdf/xml
parser to cwm.
 
STATUS:
 
First pass, partially working, some questions.
 
 
QUESTIONS:
 
Does the context need to change per bag? I have assumed for the moment
not, as it breaks (or complicates) the interface between the parser
and the store.
 
Is there already or is there any interest in a ContextSink interface
to simplify the interface between the parser and the store? If
desired, I would be happy to help with any refactors that would be
needed. To better describe what I am thinking, I have implemented a
ContextSink enough to serve the purpose needed for this module.
 
Is urlparse.urljoin from the Python standard library buggy? RDFLib
uses urlparse.urljoin and I noticed that the differences between it
and uriparse.join are causing the test cases to fail (export
PYTHONPATH=..;python2.3 retest.py -n -f regression.n3). For example:
    file:/devel/WWW/2000/10/swap/test/animal.rdf#
    vs.
    file:///devel/WWW/2000/10/swap/test/animal.rdf#
 
Not really a question but... RDFLib's RDF/XML parser at the moment
does not make it easy to get to the namespace binding information. And
the way sax2rdf currently calls bind it looks like there will be
issues if a prefix gets redefined. Here is a question re:
this... should passing the namespace information to the store be a
[mandatory] part of the interface? or does it cause to much grief in
practice not too?
 
 
TO RUN: (cwm with rdflib's rdf/xml parser)
 
Double check that you have rdflib-1.2.x installed :)
  * Download from http://rdflib.net/stable/
  * extract
  * cd root of distribution
  * python2.2 setup.py install
 
Change the following line in cwm.py from:
    return sax2rdf.RDFXMLParser(...
to:
    return rdflib2rdf.RDFXMLParser(...
 
--eikeon, http://eikeon.com/

 
Modules
       
diag
uripath

 
Classes
       
RDFXMLParser
__builtin__.object
ContextSink

 
class ContextSink(__builtin__.object)
     Methods defined here:
__init__(self, sink, openFormula, thisDoc=None, flags='', why=None)
makeStatement(self, (predicate, subject, object))
newBlankNode(self)
newLiteral(self, s)
newSymbol(self, uri)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'ContextSink' objects>
list of weak references to the object (if defined)

 
class RDFXMLParser
     Methods defined here:
__init__(self, sink, formulaURI, thisDoc, flags='', why=None)
add(self, (s, p, o))
Add triple to the sink (rdflib.syntax.parser.Parser calls
this method).
feed(self, buffer)
load(self, uri, baseURI='')

 
Data
        FORMULA = 1
cwm-1.2.1/toXML.html0000644015216600007660000006612310717716425013330 0ustar syosisyosi Python: module toXML
 
 
toXML
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/toXML.py

$Id: toXML.html,v 1.26 2007/11/18 02:01:57 syosi Exp $
 
 
This module implements basic sources and sinks for RDF data.
It defines a stream interface for such data.
It has a command line interface, can work as a web query engine,
and has built in test(), all of which demosntrate how it is used.
 
To make a new RDF processor, subclass RDFSink.
 
See also:
 
Notation 3
http://www.w3.org/DesignIssues/Notation3
 
Closed World Machine - and RDF Processor
http;//www.w3.org/2000/10/swap/cwm
 
To DO: See also "@@" in comments
 
Internationlization:
- Decode incoming N3 file as unicode
- Encode outgoing file
- unicode \u  (??) escapes in parse
- unicode \u  (??) escapes in string output
 
Note currently unicode strings work in this code
but fail when they are output into the python debugger
interactive window.
 
______________________________________________
 
Module originally by Dan Connolly.
TimBL added RDF stream model.

 
Modules
       
RDFSink
codecs
re
string
sys
triple_maker
triple_maker
urllib
urlparse

 
Classes
       
RDFSink.RDFStructuredOutput(RDFSink.RDFSink)
ToRDF
tmToRDF
XMLWriter

 
class ToRDF(RDFSink.RDFStructuredOutput)
    keeps track of most recent subject, reuses it
 
 
Method resolution order:
ToRDF
RDFSink.RDFStructuredOutput
RDFSink.RDFSink

Methods defined here:
__init__(self, outFp, thisURI=None, base=None, flags='')
#@ Not actually complete, and can encode anyway
bind(self, prefix, namespace)
dummyClone(self)
retun a version of myself which will only count occurrences
endAnonymous(self, subject, verb)
endAnonymousNode(self, subj=None)
endDoc(self, rootFormulaPair=None)
endFormulaObject(self, pred, subj)
endFormulaSubject(self, subj)
endListObject(self, subject, verb)
endListSubject(self, subj)
flushStart(self)
makeComment(self, str)
makeStatement(self, tuple, why=None, aIsPossible=0)
referenceTo(self, uri)
Conditional relative URI
startAnonymous(self, tuple)
startAnonymousNode(self, subj, isList=0)
startDoc(self)
startFormulaObject(self, tuple)
startFormulaSubject(self, context)
startListObject(self, tuple, isList=0)
startListSubject(self, subj)
startWithParseType(self, parseType, tuple)

Data and other attributes defined here:
flagDocumentation = '\nFlags to control RDF/XML output (after --rdf=) ...e URIs.\nz - Allow relative URIs for namespaces\n\n'

Methods inherited from RDFSink.RDFSink:
checkNewId(self, uri)
The store can override this to raise an exception if the
id is not in fact new. This is useful because it is usfeul
to generate IDs with useful diagnostic ways but this lays them
open to possibly clashing in pathalogical cases.
countNamespace(self, namesp)
On output, count how many times each namespace is used
genId(self)
intern(self, something)
namespaceCounts(self)
newBlankNode(self, context, uri=None, why=None)
newExistential(self, context, uri=None, why=None)
newFormula(self, uri=None)
newList(self, l, context)
newLiteral(self, str, dt=None, lang=None)
newSymbol(self, uri)
newUniversal(self, context, uri=None, why=None)
newXMLLiteral(self, doc)
reopen(self)
Un-End a document
 
If you have added stuff to a document, thought you were done, and
then want to add more, call this to get back into the sate that makeSatement
is again acceptable. Remember to end the document again when done.
setDefaultNamespace(self, uri)
Pass on a binding hint for later use in output
 
This really is just a hint. The parser calls this to pass on
the default namespace which it came across, as this is a
useful hint for a human readable prefix for output of the same
namespace. Otherwise, output processors will have to invent or
avoid useing namespaces, which will look ugly.
setGenPrefix(self, genPrefix)

 
class XMLWriter
    taken from
Id: tsv2xml.py,v 1.1 2000/10/02 19:41:02 connolly Exp connolly
 
Takes as argument a writer which does the (eg utf-8) encoding
 
  Methods defined here:
__init__(self, encodingWriter, counter, squeaky=0, version='1.0')
closeTag(self)
data(self, str)
emptyElement(self, n, attrs=[], prefixes={})
endDocument(self)
endElement(self)
figurePrefix(self, uriref, rawAttrs, prefixes)
flushClose(self)
indent(self, extra=0)
makeComment(self, str)
makePI(self, str)
newline(self, howmany=1)
passXML(self, st)
startElement(self, n, attrs=[], prefixes={})

Data and other attributes defined here:
attrEsc = <_sre.SRE_Pattern object>
dataEsc = <_sre.SRE_Pattern object>

 
class tmToRDF(RDFSink.RDFStructuredOutput)
    Trying to do the same as above, using the TripleMaker interface
 
 
Method resolution order:
tmToRDF
RDFSink.RDFStructuredOutput
RDFSink.RDFSink

Methods defined here:
IsOf(self)
__init__(self, outFp, thisURI=None, base=None, flags='')
addAnonymous(self, Id)
addLiteral(self, lit, dt=None, lang=None)
addNode(self, node, nameLess=0)
addQuestionMarkedSymbol(self, sym)
addSymbol(self, sym)
backwardPath(self)
beginAnonymous(self)
beginFormula(self)
beginList(self)
checkIsOf(self)
declareExistential(self, sym)
declareUniversal(self, sym)
end(self)
endAnonymous(self)
endFormula(self)
endList(self)
endStatement(self)
forewardPath(self)
nodeIDize(self, argument)
referenceTo(self, uri)
Conditional relative URI
start(self)

Methods inherited from RDFSink.RDFStructuredOutput:
endAnonymousNode(self, endAnonymousNode)
endFormulaObject(self, pred, subj)
endFormulaSubject(self, subj)
startAnonymous(self, triple, isList=0)
startAnonymousNode(self, subj)
startFormulaObject(self, triple)
startFormulaSubject(self, context)

Methods inherited from RDFSink.RDFSink:
bind(self, prefix, uri)
Pass on a binding hint for later use in output
 
This really is just a hint. The parser calls bind to pass on
the prefix which it came across, as this is a useful hint for
a human readable prefix for output of the same
namespace. Otherwise, output processors will have to invent or
avoid useing namespaces, which will look ugly
checkNewId(self, uri)
The store can override this to raise an exception if the
id is not in fact new. This is useful because it is usfeul
to generate IDs with useful diagnostic ways but this lays them
open to possibly clashing in pathalogical cases.
countNamespace(self, namesp)
On output, count how many times each namespace is used
endDoc(self, rootFormulaPair)
End a document
 
Call this once only at the end of parsing so that the receiver can wrap
things up, oprimize, intern, index and so on.  The pair given is the (type, value)
identifier of the root formula of the thing parsed.
genId(self)
intern(self, something)
makeComment(self, str)
This passes on a comment line which of course has no semantics.
 
This is only useful in direct piping of parsers to output, to preserve
comments in the original file.
makeStatement(self, tuple, why=None)
add a statement to a stream/store.
 
raises URISyntaxError on bad URIs
tuple is a quad (context, predicate, subject, object) of things generated by calls to newLiteral etc
why is reason for the statement.
namespaceCounts(self)
newBlankNode(self, context, uri=None, why=None)
newExistential(self, context, uri=None, why=None)
newFormula(self, uri=None)
newList(self, l, context)
newLiteral(self, str, dt=None, lang=None)
newSymbol(self, uri)
newUniversal(self, context, uri=None, why=None)
newXMLLiteral(self, doc)
reopen(self)
Un-End a document
 
If you have added stuff to a document, thought you were done, and
then want to add more, call this to get back into the sate that makeSatement
is again acceptable. Remember to end the document again when done.
setDefaultNamespace(self, uri)
Pass on a binding hint for later use in output
 
This really is just a hint. The parser calls this to pass on
the default namespace which it came across, as this is a
useful hint for a human readable prefix for output of the same
namespace. Otherwise, output processors will have to invent or
avoid useing namespaces, which will look ugly.
setGenPrefix(self, genPrefix)
startDoc(self)

 
Functions
       
bNodePredicate()
dummyWrite(x)
findLegal(dict, str)
swap(List, a, b)
xmldata(write, str, markupChars)

 
Data
        ADDED_HASH = '#'
ALL4 = (0, 1, 2, 3)
ANONYMOUS = 3
CONTEXT = 0
DAML_LISTS = 1
DAML_NS = 'http://www.daml.org/2001/03/daml+oil#'
DAML_sameAs = (0, 'http://www.daml.org/2001/03/daml+oil#sameAs')
DAML_sameAs_URI = 'http://www.daml.org/2001/03/daml+oil#sameAs'
DPO_NS = 'http://www.daml.org/2001/03/daml+oil#'
FORMULA = 1
LITERAL = 2
LITERAL_DT = 21
LITERAL_LANG = 22
List_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
Logic_NS = 'http://www.w3.org/2000/10/swap/log#'
N3_Empty = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#Empty')
N3_List = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#List')
N3_first = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first')
N3_forAll_URI = 'http://www.w3.org/2000/10/swap/log#forAll'
N3_forSome_URI = 'http://www.w3.org/2000/10/swap/log#forSome'
N3_nil = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil')
N3_rest = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest')
NCNameChar = 0
NCNameStartChar = 1
NODE_MERGE_URI = 'http://www.w3.org/2000/10/swap/log#is'
OBJ = 3
PARTS = (1, 2, 3)
PRED = 1
RDF_NS_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
RDF_li = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#li')
RDF_spec = 'http://www.w3.org/TR/REC-rdf-syntax/'
RDF_type = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type')
RDF_type_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
SUBJ = 2
SYMBOL = 0
XMLLITERAL = 25
XML_NS_URI = 'http://www.w3.org/XML/1998/namespace'
option_noregen = 0
parsesTo_URI = 'http://www.w3.org/2000/10/swap/log#parsesTo'
cwm-1.2.1/swap/0000755015216600007660000000000010731073447012375 5ustar syosisyosicwm-1.2.1/swap/mixin.py0000644015216600007660000000311610265042211014057 0ustar syosisyosi"""mixin.py $ID: $ We want to be able to mixin query functions These include: substitution(self, bindings, why=None): substituteEquals(self, bindings, newRedirections): occurringIn(self, vars): unify(self, other, vars, existentials, bindings): we want the interface to be convenient. Here is how to use it: Let us say, in one file, you have a class foo class foo(object): def something(self): ... and you want to add a other() method to it. Create another file, and do as follows ------ from mixin import Mixin class betterFoo(Mixin, foo): def other(self): .... ---- and import that file where you need to use betterFoo, even AFTER the objects are created! """ ##try: ## Set = set ##except NameError: ## from sets import Set ## ##operations = {} class mixinClass(object): """ """ def __new__(metacls, name, bases, dict): for base in bases: #print base if base.__class__ is not mixinClass: for func in dict: #print func if func[0:1] != '_': ## if func not in operations: ## operations[func] = {} ## operations[func][base] = dict[func] if func in base.__dict__: raise ValueError('''I can't let you override an existing method. Use real inheritance: %s.%s''' % (`base`, func)) setattr(base, func, dict[func]) return object.__new__(metacls) class Mixin: __metaclass__ = mixinClass cwm-1.2.1/swap/isodate.py0000644015216600007660000000741010640064121014365 0ustar syosisyosi#!/usr/bin/env python """ isodate.py Copyright 2002 Mark Nottingham, THIS SOFTWARE IS SUPPLIED WITHOUT WARRANTY OF ANY KIND, AND MAY BE COPIED, MODIFIED OR DISTRIBUTED IN ANY WAY, AS LONG AS THIS NOTICE AND ACKNOWLEDGEMENT OF AUTHORSHIP REMAIN. Functions for manipulating a subset of ISO8601 date, as specified by Exposes: - parse(s) s being a conforming (regular or unicode) string. Raises ValueError for invalid strings. Returns a float (representing seconds from the epoch; see the time module). - asString(i) i being an integer or float. Returns a conforming string. TODO: - Precision? it would be nice to have an interface that tells us how precise a datestring is, so that we don't make assumptions about it; e.g., 2001 != 2001-01-01T00:00:00Z. 2002-06-22 added bad string to error message -- timbl@w3.org """ import sys, time, re, operator import calendar # timegm - from python from types import StringType, UnicodeType, IntType, LongType, FloatType __version__ = "0.6" date_parser = re.compile(r"""^ (?P\d{4,4}) (?: - (?P\d{1,2}) (?: - (?P\d{1,2}) (?: T (?P\d{1,2}) : (?P\d{1,2}) (?: : (?P\d{1,2}) (?: \. (?P\d+)? )? )? (?: Z | (?: (?P[+-]) (?P\d{1,2}) : (?P\d{2,2}) ) ) )? )? )? $""", re.VERBOSE) def parse(s): """ parse a string and return seconds since the epoch. """ assert type(s) in [StringType, UnicodeType] r = date_parser.search(s) try: a = r.groupdict('0') except: raise ValueError, 'invalid date string format:'+s y = int(a['year']) if y < 1970: raise ValueError, 'Sorry, date must be in Unix era (1970 or after):'+s d = calendar.timegm(( int(a['year']), int(a['month']) or 1, int(a['day']) or 1, int(a['hour']), int(a['minute']), int(a['second']), 0, 0, 0 )) return d - int("%s%s" % ( a.get('tz_sign', '+'), ( int(a.get('tz_hour', 0)) * 60 * 60 ) - \ ( int(a.get('tz_min', 0)) * 60 )) ) def fullString(i): """ given seconds since the epoch, return a full dateTime string in Z timezone. """ assert type(i) in [IntType, FloatType, LongType], "Wrong type: "+ `type(i)` +`i` year, month, day, hour, minute, second, wday, jday, dst = time.gmtime(i) return str(year) + '-%2.2d-%2.2dT%2.2d:%2.2d:%2.2dZ' % (month, day, hour, minute, second) def asString(i): """ given seconds since the epoch, return a dateTime string. """ assert type(i) in [IntType, FloatType] year, month, day, hour, minute, second, wday, jday, dst = time.gmtime(i) o = str(year) if (month, day, hour, minute, second) == (1, 1, 0, 0, 0): return o o = o + '-%2.2d' % month if (day, hour, minute, second) == (1, 0, 0, 0): return o o = o + '-%2.2d' % day if (hour, minute, second) == (0, 0, 0): return o o = o + 'T%2.2d:%2.2d' % (hour, minute) if second != 0: o = o + ':%2.2d' % second o = o + 'Z' return o cwm-1.2.1/swap/n3p/0000755015216600007660000000000010731073447013075 5ustar syosisyosicwm-1.2.1/swap/n3p/n3meta.py0000755015216600007660000015721510174057442014652 0ustar syosisyosi#!/usr/bin/env python """n3meta - For use with n3p.py.""" # Automatically generated by n3mp.py import re branches = {u'_:MMkYqbGW16': {u',': [u',', 'http://www.w3.org/2000/10/swap/grammar/n3#symbol', '_:MMkYqbGW16'], u'.': [], u'}': []}, u'_:MMkYqbGW20': {u',': [u',', 'http://www.w3.org/2000/10/swap/grammar/n3#symbol', '_:MMkYqbGW20'], u'.': [], u'}': []}, u'_:MMkYqbGW33': {u'.': [], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol', '_:MMkYqbGW16'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol', '_:MMkYqbGW16'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol', '_:MMkYqbGW16'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol', '_:MMkYqbGW16'], u'}': []}, u'_:MMkYqbGW36': {u'.': [], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol', '_:MMkYqbGW20'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol', '_:MMkYqbGW20'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol', '_:MMkYqbGW20'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol', '_:MMkYqbGW20'], u'}': []}, u'_:MMkYqbGW44': {u'.': [], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#barename', '_:MMkYqbGW9'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#barename', '_:MMkYqbGW9'], u'}': []}, u'_:MMkYqbGW9': {u',': [u',', 'http://www.w3.org/2000/10/swap/grammar/n3#barename', '_:MMkYqbGW9'], u'.': [], u'}': []}, u'http://www.w3.org/2000/10/swap/grammar/n3#declaration': {u'@keywords': [u'@keywords', '_:MMkYqbGW44'], u'@prefix': [u'@prefix', 'http://www.w3.org/2000/10/swap/grammar/n3#qname', 'http://www.w3.org/2000/10/swap/grammar/n3#explicituri']}, u'http://www.w3.org/2000/10/swap/grammar/n3#document': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'@EOFDUMMY': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'@forAll': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'@forSome': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'@keywords': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'@prefix': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#statements_optional', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof']}, u'http://www.w3.org/2000/10/swap/grammar/n3#dtlang': {u'!': [], u'"': [], u'(': [], u')': [], u'+': [], u',': [], u'-': [], u'.': [], u'0': [], u':': [], u';': [], u'<': [], u'<=': [], u'=': [], u'=>': [], u'?': [], u'@': [u'@', 'http://www.w3.org/2000/10/swap/grammar/n3#langcode'], u'@a': [], u'@has': [], u'@is': [], u'@of': [], u'@this': [], u'[': [], u']': [], u'^': [], u'^^': [u'^^', 'http://www.w3.org/2000/10/swap/grammar/n3#symbol'], u'_': [], u'a': [], u'{': [], u'}': []}, u'http://www.w3.org/2000/10/swap/grammar/n3#existential': {u'@forSome': [u'@forSome', '_:MMkYqbGW36']}, u'http://www.w3.org/2000/10/swap/grammar/n3#formulacontent': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'@forAll': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'@forSome': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'@keywords': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'@prefix': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'}': []}, u'http://www.w3.org/2000/10/swap/grammar/n3#literal': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#string', 'http://www.w3.org/2000/10/swap/grammar/n3#dtlang']}, u'http://www.w3.org/2000/10/swap/grammar/n3#node': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#literal'], u'(': [u'(', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist', u')'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#numericliteral'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#numericliteral'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#numericliteral'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#variable'], u'@this': [u'@this'], u'[': [u'[', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist', u']'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#symbol'], u'{': [u'{', 'http://www.w3.org/2000/10/swap/grammar/n3#formulacontent', u'}']}, u'http://www.w3.org/2000/10/swap/grammar/n3#object': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#path']}, u'http://www.w3.org/2000/10/swap/grammar/n3#objecttail': {u',': [u',', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail'], u'.': [], u';': [], u']': [], u'}': []}, u'http://www.w3.org/2000/10/swap/grammar/n3#path': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#node', 'http://www.w3.org/2000/10/swap/grammar/n3#pathtail']}, u'http://www.w3.org/2000/10/swap/grammar/n3#pathlist': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u')': [], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#path', 'http://www.w3.org/2000/10/swap/grammar/n3#pathlist']}, u'http://www.w3.org/2000/10/swap/grammar/n3#pathtail': {u'!': [u'!', 'http://www.w3.org/2000/10/swap/grammar/n3#path'], u'"': [], u'(': [], u')': [], u'+': [], u',': [], u'-': [], u'.': [], u'0': [], u':': [], u';': [], u'<': [], u'<=': [], u'=': [], u'=>': [], u'?': [], u'@a': [], u'@has': [], u'@is': [], u'@of': [], u'@this': [], u'[': [], u']': [], u'^': [u'^', 'http://www.w3.org/2000/10/swap/grammar/n3#path'], u'_': [], u'a': [], u'{': [], u'}': []}, u'http://www.w3.org/2000/10/swap/grammar/n3#propertylist': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'.': [], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'<=': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'=': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'=>': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'@a': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'@has': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'@is': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u']': [], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#verb', 'http://www.w3.org/2000/10/swap/grammar/n3#object', 'http://www.w3.org/2000/10/swap/grammar/n3#objecttail', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail'], u'}': []}, u'http://www.w3.org/2000/10/swap/grammar/n3#propertylisttail': {u'.': [], u';': [u';', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u']': [], u'}': []}, u'http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#subject', 'http://www.w3.org/2000/10/swap/grammar/n3#propertylist']}, u'http://www.w3.org/2000/10/swap/grammar/n3#statement': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u'@forAll': ['http://www.w3.org/2000/10/swap/grammar/n3#universal'], u'@forSome': ['http://www.w3.org/2000/10/swap/grammar/n3#existential'], u'@keywords': ['http://www.w3.org/2000/10/swap/grammar/n3#declaration'], u'@prefix': ['http://www.w3.org/2000/10/swap/grammar/n3#declaration'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#simpleStatement']}, u'http://www.w3.org/2000/10/swap/grammar/n3#statementlist': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'@forAll': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'@forSome': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'@keywords': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'@prefix': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', 'http://www.w3.org/2000/10/swap/grammar/n3#statementtail'], u'}': []}, u'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'@EOFDUMMY': [], u'@forAll': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'@forSome': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'@keywords': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'@prefix': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#statement', u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statements_optional']}, u'http://www.w3.org/2000/10/swap/grammar/n3#statementtail': {u'.': [u'.', 'http://www.w3.org/2000/10/swap/grammar/n3#statementlist'], u'}': []}, u'http://www.w3.org/2000/10/swap/grammar/n3#subject': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#path']}, u'http://www.w3.org/2000/10/swap/grammar/n3#symbol': {u':': ['http://www.w3.org/2000/10/swap/grammar/n3#qname'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#explicituri'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#qname'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#qname']}, u'http://www.w3.org/2000/10/swap/grammar/n3#universal': {u'@forAll': [u'@forAll', '_:MMkYqbGW33']}, u'http://www.w3.org/2000/10/swap/grammar/n3#verb': {u'"': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'(': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'+': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'-': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'0': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u':': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'<': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'<=': [u'<='], u'=': [u'='], u'=>': [u'=>'], u'?': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'@a': [u'@a'], u'@has': [u'@has', 'http://www.w3.org/2000/10/swap/grammar/n3#path'], u'@is': [u'@is', 'http://www.w3.org/2000/10/swap/grammar/n3#path', u'@of'], u'@this': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'[': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'_': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'a': ['http://www.w3.org/2000/10/swap/grammar/n3#path'], u'{': ['http://www.w3.org/2000/10/swap/grammar/n3#path']}} regexps = { u'http://www.w3.org/2000/10/swap/grammar/n3#barename': re.compile(u'[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf8ff-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][\\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf8ff-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*'), u'http://www.w3.org/2000/10/swap/grammar/n3#variable': re.compile(u'\\?[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf8ff-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][\\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf8ff-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*'), u'http://www.w3.org/2000/10/swap/grammar/n3#qname': re.compile(u'(([A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf8ff-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][\\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf8ff-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*)?:)?([A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf8ff-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][\\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf8ff-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*)?'), u'http://www.w3.org/2000/10/swap/grammar/n3#string': re.compile(u'("""[^"\\\\]*(?:(?:\\\\.|"(?!""))[^"\\\\]*)*""")|("[^"\\\\]*(?:\\\\.[^"\\\\]*)*")'), u'http://www.w3.org/2000/10/swap/grammar/n3#explicituri': re.compile(u'<[^>]*>'), u'http://www.w3.org/2000/10/swap/grammar/n3#langcode': re.compile(u'[a-z]+(-[a-z0-9]+)*'), u'http://www.w3.org/2000/10/swap/grammar/n3#numericliteral': re.compile(u'[-+]?[0-9]+(\\.[0-9]+)?(e[-+]?[0-9]+)?'), } if __name__=="__main__": print __doc__ cwm-1.2.1/swap/n3p/__init__.py0000644015216600007660000000000010173560143015166 0ustar syosisyosicwm-1.2.1/swap/n3p/n3p.py0000644015216600007660000001351610174060655014153 0ustar syosisyosi#!/usr/bin/env python """ N3P - An N3 Parser using n3.n3 Author: Sean B. Palmer, inamidst.com Licence: GPL 2; share and enjoy! Documentation: http://inamidst.com/n3p/ Derived from: http://www.w3.org/2000/10/swap/grammar/predictiveParser.py - predictiveParser.py, Tim Berners-Lee, 2004 Issues: http://lists.w3.org/Archives/Public/public-cwm-bugs/2005Jan/0006 http://lists.w3.org/Archives/Public/public-cwm-talk/2005JanMar/0015 """ import sys, os, re, urllib import cPickle as pickle try: set() except NameError: from sets import Set as set try: import n3meta branches = n3meta.branches regexps = n3meta.regexps except ImportError: for path in sys.path: fn = os.path.join(path, 'n3meta.pkl') if os.path.isfile(fn): f = open(fn, 'rb') n3meta = pickle.load(f) f.close() branches = n3meta['branches'] regexps = n3meta['regexps'] break start = 'http://www.w3.org/2000/10/swap/grammar/n3#document' r_whitespace = re.compile(r'[ \t\r\n]*(?:(?:#[^\n]*)?\r?(?:$|\n))?') singleCharacterSelectors = "\t\r\n !\"#$%&'()*.,+/;<=>?[\\]^`{|}~" r_qname = re.compile(r'([A-Za-z0-9_:]*)') r_name = re.compile(r'([A-Za-z0-9_]*)') notQNameChars = singleCharacterSelectors + "@" notNameChars = notQNameChars + ":" def abbr(prodURI): return prodURI.split('#').pop() class N3Parser(object): def __init__(self, uri, branches, regexps): if uri == 'nowhere': pass else: if (uri != 'file:///dev/stdin'): u = urllib.urlopen(uri) self.data = u.read() u.close() else: self.data = sys.stdin.read() self.pos = 0 self.branches = branches self.regexps = regexps self.keywordMode = False self.keywords = set(("a", "is", "of", "this", "has")) self.productions = [] self.memo = {} def parse(self, prod): todo_stack = [[prod, None]] while todo_stack: #print todo_stack #prod = todo_stack.pop() if todo_stack[-1][1] is None: todo_stack[-1][1] = [] tok = self.token() # Got an opened production self.onStart(abbr(todo_stack[-1][0])) if not tok: return tok # EOF prodBranch = self.branches[todo_stack[-1][0]] sequence = prodBranch.get(tok, None) if sequence is None: print >> sys.stderr, 'prodBranch', prodBranch raise Exception("Found %s when expecting a %s . todo_stack=%s" % (tok, todo_stack[-1][0], `todo_stack`)) for term in sequence: todo_stack[-1][1].append(term) while todo_stack[-1][1]: term = todo_stack[-1][1].pop(0) if isinstance(term, unicode): j = self.pos + len(term) word = self.data[self.pos:j] if word == term: self.onToken(term, word) self.pos = j elif '@' + word[:-1] == term: self.onToken(term, word[:-1]) self.pos = j - 1 else: raise Exception("Found %s; %s expected" % \ (self.data[self.pos:self.pos+10], term)) elif not self.regexps.has_key(term): todo_stack.append([term, None]) continue else: regexp = self.regexps[term] m = regexp.match(self.data, self.pos) if not m: raise Exception("Token: %r should match %s" % \ (self.data[self.pos:self.pos+10], regexp.pattern)) end = m.end() self.onToken(abbr(term), self.data[self.pos:end]) self.pos = end self.token() while todo_stack[-1][1] == []: todo_stack.pop() self.onFinish() def token(self): """Memoizer for getToken.""" if self.memo.has_key(self.pos): return self.memo[self.pos] result = self.getToken() pos = self.pos self.memo[pos] = result return result def getToken(self): self.whitespace() if self.pos == len(self.data): return '' # EOF! ch2 = self.data[self.pos:self.pos+2] for double in ('=>', '<=', '^^'): if ch2 == double: return double ch = self.data[self.pos] if ch == '.' and self.keywordMode: self.keywordMode = False if ch in singleCharacterSelectors + '"': return ch elif ch in '+-0123456789': return '0' if ch == '@': if self.pos and (self.data[self.pos-1] == '"'): return '@' name = r_name.match(self.data, self.pos + 1).group(1) if name == 'keywords': self.keywords = set() self.keywordMode = True return '@' + name word = r_qname.match(self.data, self.pos).group(1) if self.keywordMode: self.keywords.add(word) elif word in self.keywords: if word == 'keywords': self.keywords = set() self.keywordMode = True return '@' + word # implicit keyword return 'a' def whitespace(self): while True: end = r_whitespace.match(self.data, self.pos).end() if end <= self.pos: break self.pos = end def onStart(self, prod): print (' ' * len(self.productions)) + prod self.productions.append(prod) def onFinish(self): prod = self.productions.pop() print (' ' * len(self.productions)) + '/' + prod def onToken(self, prod, tok): print (' ' * len(self.productions)) + prod, tok def main(argv=None): if argv is None: argv = sys.argv if len(argv) == 2: p = N3Parser(argv[1], branches, regexps) p.parse(start) if __name__=="__main__": main() cwm-1.2.1/swap/rdflib2rdf.py0000644015216600007660000001233010640065473014765 0ustar syosisyosi""" This rdflib2rdf module provides code for glueing rdflib's rdf/xml parser to cwm. STATUS: First pass, partially working, some questions. QUESTIONS: Does the context need to change per bag? I have assumed for the moment not, as it breaks (or complicates) the interface between the parser and the store. Is there already or is there any interest in a ContextSink interface to simplify the interface between the parser and the store? If desired, I would be happy to help with any refactors that would be needed. To better describe what I am thinking, I have implemented a ContextSink enough to serve the purpose needed for this module. Is urlparse.urljoin from the Python standard library buggy? RDFLib uses urlparse.urljoin and I noticed that the differences between it and uriparse.join are causing the test cases to fail (export PYTHONPATH=..;python2.3 retest.py -n -f regression.n3). For example: file:/devel/WWW/2000/10/swap/test/animal.rdf# vs. file:///devel/WWW/2000/10/swap/test/animal.rdf# Not really a question but... RDFLib's RDF/XML parser at the moment does not make it easy to get to the namespace binding information. And the way sax2rdf currently calls bind it looks like there will be issues if a prefix gets redefined. Here is a question re: this... should passing the namespace information to the store be a [mandatory] part of the interface? or does it cause to much grief in practice not too? TO RUN: (cwm with rdflib's rdf/xml parser) Double check that you have rdflib-1.2.x installed :) * Download from http://rdflib.net/stable/ * extract * cd root of distribution * python2.2 setup.py install Change the following line in cwm.py from: return sax2rdf.RDFXMLParser(... to: return rdflib2rdf.RDFXMLParser(... --eikeon, http://eikeon.com/ """ from RDFSink import FORMULA import diag from diag import progress class ContextSink(object): def __init__(self, sink, openFormula, thisDoc=None, flags="", why=None): self.sink = sink assert thisDoc != None, "Need document URI at the moment, sorry" self.thisDoc = thisDoc self.formulaURI = formulaURI self._context = openFormula self._reason = why # Why the parser w self._reason2 = None # Why these triples if diag.tracking: self._reason2 = BecauseOfData(sink.newSymbol(thisDoc), because=self._reason) def newSymbol(self, uri): return self.sink.newSymbol(uri) def newLiteral(self, s): return self.sink.newLiteral(s) def newXMLLiteral(self, s): return self.sink.newXMLLiteral(s) def newBlankNode(self): return self.sink.newBlankNode(self._context) def makeStatement(self, (predicate, subject, object)): self.sink.makeStatement((self._context, predicate, subject, object), why=self._reason2) import uripath from rdflib.syntax.parser import ParserDispatcher from rdflib.URIRef import URIRef from rdflib.Literal import Literal from rdflib.BNode import BNode from rdflib.URLInputSource import URLInputSource class RDFXMLParser: def __init__(self, sink, formulaURI, thisDoc, flags="", why=None): self.__sink = ContextSink(sink,formulaURI, thisDoc, flags, why) self.__bnodes = {} def __convert(self, t): """Convert from rdflib to cwm style term.""" # For now, I have decided not to try and add factory arguments # or some other such mechanism to rdflib's parser... but # rather convert the resulting rdflib term objects to the # desired types. # It may just be the cleanest interface moving forward as # well... as it removes the need to have to worry about the # details of the information needing to be passed to the # various constructors... for example, does the literal # constructor take a value and a language... and what happens # to the interface when datatype gets added. So in effect it # seems just to be a higher level interface. if isinstance(t, URIRef): return self.__sink.newSymbol(str(t)) elif isinstance(t, Literal): # return self.__sink.newLiteral(str(t)) return self.__sink.newLiteral(t) # t is subclass of unicode elif isinstance(t, BNode): bnodes = self.__bnodes if t in bnodes: return bnodes[t] else: bnode = self.__sink.newBlankNode() bnodes[t] = bnode return bnode else: raise Exception("Unexpected type") def add(self, (s, p, o)): """Add triple to the sink (rdflib.syntax.parser.Parser calls this method).""" subject = self.__convert(s) predicate = self.__convert(p) object = self.__convert(o) self.__sink.makeStatement((predicate, subject, object)) def feed(self, buffer): self.parser(StringInputSource(buffer)) def load(self, uri, baseURI=""): if uri: uri = uripath.join(baseURI, uri) # Make abs from relative source = URLInputSource(uri) self.parse(source) #ends cwm-1.2.1/swap/uripath.py0000644015216600007660000004205310640075640014423 0ustar syosisyosi#!/bin/env python """ Uniform Resource Identifier (URI) path manipulation, above the access layer The name of this module and the functions are somewhat arbitrary; they hark to other parts of the python library; e.g. uripath.join() is somewhat like os.path.join(). REFERENCES Uniform Resource Identifiers (URI): Generic Syntax http://www.ietf.org/rfc/rfc2396.txt The Web Model: Information hiding and URI syntax (Jan 98) http://www.w3.org/DesignIssues/Model.html URI API design [was: URI Test Suite] Dan Connolly (Sun, Aug 12 2001) http://lists.w3.org/Archives/Public/uri/2001Aug/0021.html """ __version__ = "$Id: uripath.py,v 1.21 2007/06/26 02:36:16 syosi Exp $" from string import find, rfind, index def splitFrag(uriref): """split a URI reference between the fragment and the rest. Punctuation is thrown away. e.g. >>> splitFrag("abc#def") ('abc', 'def') >>> splitFrag("abcdef") ('abcdef', None) """ i = rfind(uriref, "#") if i>= 0: return uriref[:i], uriref[i+1:] else: return uriref, None def splitFragP(uriref, punct=0): """split a URI reference before the fragment Punctuation is kept. e.g. >>> splitFragP("abc#def") ('abc', '#def') >>> splitFragP("abcdef") ('abcdef', '') """ i = rfind(uriref, "#") if i>= 0: return uriref[:i], uriref[i:] else: return uriref, '' def join(here, there): """join an absolute URI and URI reference (non-ascii characters are supported/doctested; haven't checked the details of the IRI spec though) here is assumed to be absolute. there is URI reference. >>> join('http://example/x/y/z', '../abc') 'http://example/x/abc' Raise ValueError if there uses relative path syntax but here has no hierarchical path. >>> join('mid:foo@example', '../foo') Traceback (most recent call last): raise ValueError, here ValueError: Base has no slash after colon - with relative '../foo'. >>> join('http://example/x/y/z', '') 'http://example/x/y/z' >>> join('mid:foo@example', '#foo') 'mid:foo@example#foo' We grok IRIs >>> len(u'Andr\\xe9') 5 >>> join('http://example.org/', u'#Andr\\xe9') u'http://example.org/#Andr\\xe9' """ assert(find(here, "#") < 0), "Base may not contain hash: '%s'"% here # caller must splitFrag (why?) slashl = find(there, '/') colonl = find(there, ':') # join(base, 'foo:/') -- absolute if colonl >= 0 and (slashl < 0 or colonl < slashl): return there bcolonl = find(here, ':') assert(bcolonl >= 0), "Base uri '%s' is not absolute" % here # else it's not absolute path, frag = splitFragP(there) if not path: return here + frag # join('mid:foo@example', '../foo') bzzt if here[bcolonl+1:bcolonl+2] <> '/': raise ValueError ("Base <%s> has no slash after colon - with relative '%s'." %(here, there)) if here[bcolonl+1:bcolonl+3] == '//': bpath = find(here, '/', bcolonl+3) else: bpath = bcolonl+1 # join('http://xyz', 'foo') if bpath < 0: bpath = len(here) here = here + '/' # join('http://xyz/', '//abc') => 'http://abc' if there[:2] == '//': return here[:bcolonl+1] + there # join('http://xyz/', '/abc') => 'http://xyz/abc' if there[:1] == '/': return here[:bpath] + there slashr = rfind(here, '/') while 1: if path[:2] == './': path = path[2:] if path == '.': path = '' elif path[:3] == '../' or path == '..': path = path[3:] i = rfind(here, '/', bpath, slashr) if i >= 0: here = here[:i+1] slashr = i else: break return here[:slashr+1] + path + frag import re import string commonHost = re.compile(r'^[-_a-zA-Z0-9.]+:(//[^/]*)?/[^/]*$') def refTo(base, uri): """figure out a relative URI reference from base to uri >>> refTo('http://example/x/y/z', 'http://example/x/abc') '../abc' >>> refTo('file:/ex/x/y', 'file:/ex/x/q/r#s') 'q/r#s' >>> refTo(None, 'http://ex/x/y') 'http://ex/x/y' >>> refTo('http://ex/x/y', 'http://ex/x/y') '' Note the relationship between refTo and join: join(x, refTo(x, y)) == y which points out certain strings which cannot be URIs. e.g. >>> x='http://ex/x/y';y='http://ex/x/q:r';join(x, refTo(x, y)) == y 0 So 'http://ex/x/q:r' is not a URI. Use 'http://ex/x/q%3ar' instead: >>> x='http://ex/x/y';y='http://ex/x/q%3ar';join(x, refTo(x, y)) == y 1 This one checks that it uses a root-realtive one where that is all they share. Now uses root-relative where no path is shared. This is a matter of taste but tends to give more resilience IMHO -- and shorter paths Note that base may be None, meaning no base. In some situations, there just ain't a base. Slife. In these cases, relTo returns the absolute value. The axiom abs(,rel(b,x))=x still holds. This saves people having to set the base to "bogus:". >>> refTo('http://ex/x/y/z', 'http://ex/r') '/r' """ # assert base # don't mask bugs -danc # not a bug. -tim if not base: return uri if base == uri: return "" # Find how many path segments in common i=0 while i0 and uri[i-1] != '/' : i=i-1 # scan for slash if i < 3: return uri # No way. if string.find(base, "//", i-2)>0 \ or string.find(uri, "//", i-2)>0: return uri # An unshared "//" if string.find(base, ":", i)>0: return uri # An unshared ":" n = string.count(base, "/", i) if n == 0 and i>> canonical("foo bar") 'foo%20bar' >>> canonical(u'http:') 'http:' >>> canonical('fran%c3%83%c2%a7ois') 'fran%C3%83%C2%A7ois' >>> canonical('a') 'a' >>> canonical('%4e') 'N' >>> canonical('%9d') '%9D' >>> canonical('%2f') '%2F' >>> canonical('%2F') '%2F' """ if type(str_in) == type(u''): s8 = str_in.encode('utf-8') else: s8 = str_in s = '' i = 0 while i < len(s8): ch = s8[i]; n = ord(ch) if (n > 126) or (n < 33) : # %-encode controls, SP, DEL, and utf-8 s += "%%%02X" % ord(ch) elif ch == '%' and i+2 < len(s8): ch2 = s8[i+1:i+3].decode('hex') if ch2 in URI_unreserved: s += ch2 else: s += "%%%02X" % ord(ch2) i = i+3 continue else: s += ch i = i +1 return s import unittest class Tests(unittest.TestCase): def testPaths(self): cases = (("foo:xyz", "bar:abc", "bar:abc"), ('http://example/x/y/z', 'http://example/x/abc', '../abc'), ('http://example2/x/y/z', 'http://example/x/abc', 'http://example/x/abc'), ('http://ex/x/y/z', 'http://ex/x/r', '../r'), # ('http://ex/x/y/z', 'http://ex/r', '../../r'), # DanC had this. ('http://ex/x/y', 'http://ex/x/q/r', 'q/r'), ('http://ex/x/y', 'http://ex/x/q/r#s', 'q/r#s'), ('http://ex/x/y', 'http://ex/x/q/r#s/t', 'q/r#s/t'), ('http://ex/x/y', 'ftp://ex/x/q/r', 'ftp://ex/x/q/r'), ('http://ex/x/y', 'http://ex/x/y', ''), ('http://ex/x/y/', 'http://ex/x/y/', ''), ('http://ex/x/y/pdq', 'http://ex/x/y/pdq', ''), ('http://ex/x/y/', 'http://ex/x/y/z/', 'z/'), ('file:/swap/test/animal.rdf', 'file:/swap/test/animal.rdf#Animal', '#Animal'), ('file:/e/x/y/z', 'file:/e/x/abc', '../abc'), ('file:/example2/x/y/z', 'file:/example/x/abc', '/example/x/abc'), # TBL ('file:/ex/x/y/z', 'file:/ex/x/r', '../r'), ('file:/ex/x/y/z', 'file:/r', '/r'), # I prefer this. - tbl ('file:/ex/x/y', 'file:/ex/x/q/r', 'q/r'), ('file:/ex/x/y', 'file:/ex/x/q/r#s', 'q/r#s'), ('file:/ex/x/y', 'file:/ex/x/q/r#', 'q/r#'), ('file:/ex/x/y', 'file:/ex/x/q/r#s/t', 'q/r#s/t'), ('file:/ex/x/y', 'ftp://ex/x/q/r', 'ftp://ex/x/q/r'), ('file:/ex/x/y', 'file:/ex/x/y', ''), ('file:/ex/x/y/', 'file:/ex/x/y/', ''), ('file:/ex/x/y/pdq', 'file:/ex/x/y/pdq', ''), ('file:/ex/x/y/', 'file:/ex/x/y/z/', 'z/'), ('file:/devel/WWW/2000/10/swap/test/reluri-1.n3', 'file://meetings.example.com/cal#m1', 'file://meetings.example.com/cal#m1'), ('file:/home/connolly/w3ccvs/WWW/2000/10/swap/test/reluri-1.n3', 'file://meetings.example.com/cal#m1', 'file://meetings.example.com/cal#m1'), ('file:/some/dir/foo', 'file:/some/dir/#blort', './#blort'), ('file:/some/dir/foo', 'file:/some/dir/#', './#'), # From Graham Klyne Thu, 20 Feb 2003 18:08:17 +0000 ("http://example/x/y%2Fz", "http://example/x/abc", "abc"), ("http://example/x/y/z", "http://example/x%2Fabc", "/x%2Fabc"), ("http://example/x/y%2Fz", "http://example/x%2Fabc", "/x%2Fabc"), ("http://example/x%2Fy/z", "http://example/x%2Fy/abc", "abc"), # Ryan Lee ("http://example/x/abc.efg", "http://example/x/", "./") ) for inp1, inp2, exp in cases: self.assertEquals(refTo(inp1, inp2), exp) self.assertEquals(join(inp1, exp), inp2) def testSplit(self): cases = ( ("abc#def", "abc", "def"), ("abc", "abc", None), ("#def", "", "def"), ("", "", None), ("abc#de:f", "abc", "de:f"), ("abc#de?f", "abc", "de?f"), ("abc#de/f", "abc", "de/f"), ) for inp, exp1, exp2 in cases: self.assertEquals(splitFrag(inp), (exp1, exp2)) def testRFCCases(self): base = 'http://a/b/c/d;p?q' # C.1. Normal Examples normalExamples = ( (base, 'g:h', 'g:h'), (base, 'g', 'http://a/b/c/g'), (base, './g', 'http://a/b/c/g'), (base, 'g/', 'http://a/b/c/g/'), (base, '/g', 'http://a/g'), (base, '//g', 'http://g'), (base, '?y', 'http://a/b/c/?y'), #@@wow... really? (base, 'g?y', 'http://a/b/c/g?y'), (base, '#s', 'http://a/b/c/d;p?q#s'), #@@ was: (current document)#s (base, 'g#s', 'http://a/b/c/g#s'), (base, 'g?y#s', 'http://a/b/c/g?y#s'), (base, ';x', 'http://a/b/c/;x'), (base, 'g;x', 'http://a/b/c/g;x'), (base, 'g;x?y#s', 'http://a/b/c/g;x?y#s'), (base, '.', 'http://a/b/c/'), (base, './', 'http://a/b/c/'), (base, '..', 'http://a/b/'), (base, '../', 'http://a/b/'), (base, '../g', 'http://a/b/g'), (base, '../..', 'http://a/'), (base, '../../', 'http://a/'), (base, '../../g', 'http://a/g') ) otherExamples = ( (base, '', base), (base, '../../../g', 'http://a/g'), #@@disagree with RFC2396 (base, '../../../../g', 'http://a/g'), #@@disagree with RFC2396 (base, '/./g', 'http://a/./g'), (base, '/../g', 'http://a/../g'), (base, 'g.', 'http://a/b/c/g.'), (base, '.g', 'http://a/b/c/.g'), (base, 'g..', 'http://a/b/c/g..'), (base, '..g', 'http://a/b/c/..g'), (base, './../g', 'http://a/b/g'), (base, './g/.', 'http://a/b/c/g/.'), #@@hmmm... (base, 'g/./h', 'http://a/b/c/g/./h'), #@@hmm... (base, 'g/../h', 'http://a/b/c/g/../h'), (base, 'g;x=1/./y', 'http://a/b/c/g;x=1/./y'), #@@hmmm... (base, 'g;x=1/../y', 'http://a/b/c/g;x=1/../y'), #@@hmmm... (base, 'g?y/./x', 'http://a/b/c/g?y/./x'), (base, 'g?y/../x', 'http://a/b/c/g?y/../x'), (base, 'g#s/./x', 'http://a/b/c/g#s/./x'), (base, 'g#s/../x', 'http://a/b/c/g#s/../x') ) for b, inp, exp in normalExamples + otherExamples: if exp is None: self.assertRaises(ValueError, join, b, inp) else: self.assertEquals(join(b, inp), exp) def _test(): import doctest, uripath doctest.testmod(uripath) unittest.main() if __name__ == '__main__': _test() # $Log: uripath.py,v $ # Revision 1.21 2007/06/26 02:36:16 syosi # fix tabs # # Revision 1.20 2007/01/25 20:26:50 timbl # @@@ BEWARE UNTESTED PARTIAL VERSION -- Introducing XML Literals as DOM objects # # Revision 1.19 2006/11/09 22:44:12 connolly # start base with file:// rather than just file:/ # for interop with xsltproc # # Revision 1.18 2006/07/07 22:06:50 connolly # fix bug with joining mid:abc with #foo # # Revision 1.17 2006/06/17 19:27:27 timbl # Add canonical() with unit tests # # Revision 1.16 2004/03/21 04:24:35 timbl # (See doc/changes.html) # on xml output, nodeID was incorrectly spelled. # update.py provides cwm's --patch option. # diff.py as independent progrem generates patch files for cwm --patch # # Revision 1.15 2004/01/28 22:22:10 connolly # tested that IRIs work in uripath.join() # # Revision 1.14 2003/10/20 17:31:55 timbl # Added @keyword support. # (eventually got python+expat to wrok on fink, with patch) # Trig functions are in, thanks to Karl, with some changes, but NOT in regeression.n3 # see test/math/test-trigo.n3 for now. # # Revision 1.13 2003/07/03 21:04:39 timbl # New string function to compare strings normalizing case and whitespace string:containsRoughly # # Revision 1.12 2003/04/03 22:35:12 ryanlee # fixed previous fix, added test case # # Revision 1.11 2003/04/03 22:06:54 ryanlee # small fix in if, line 217 # # Revision 1.10 2003/02/24 15:06:38 connolly # some more tests from Graham # # Revision 1.9 2002/12/25 20:01:32 timbl # some --flatten tests fail. --why fails. Formulae must be closed to be referenced in a add() # # Revision 1.8 2002/11/24 03:12:02 timbl # base can be None in uripath:refTo # # Revision 1.7 2002/09/04 05:03:07 connolly # convertet unittests to use python doctest and unittest modules; cleaned up docstrings a bit # # Revision 1.6 2002/09/04 04:07:50 connolly # fixed uripath.refTo # # Revision 1.5 2002/08/23 04:36:15 connolly # fixed refTo case: file:/some/dir/foo -> file:/some/dir/#blort # # Revision 1.4 2002/08/07 14:32:21 timbl # uripath changes. passes 51 general tests and 25 loopback tests # # Revision 1.3 2002/08/06 01:36:09 connolly # cleanup: diagnostic interface, relative/absolute uri handling # # Revision 1.2 2002/03/15 23:53:02 connolly # handle no-auth case # # Revision 1.1 2002/02/19 22:52:42 connolly # renamed uritools.py to uripath.py # # Revision 1.2 2002/02/18 07:33:51 connolly # pathTo seems to work # cwm-1.2.1/swap/cwm.py0000755015216600007660000000000010731063551015454 1cwm-1.2.1/cwmustar syosisyosicwm-1.2.1/swap/n3p_tm.py0000644015216600007660000002321110174261270014140 0ustar syosisyosi"""Why?? $$ """ from n3p import n3p import os from uripath import join class absolutizer(unicode): def __getitem__(self, other): return join(self, other) Logic_NS = "http://www.w3.org/2000/10/swap/log#" RDF_type_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" RDF_NS_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" # DAML_NS=DPO_NS = "http://www.daml.org/2001/03/daml+oil#" # DAML plus oil OWL_NS = "http://www.w3.org/2002/07/owl#" DAML_sameAs_URI = OWL_NS+"sameAs" parsesTo_URI = Logic_NS + "parsesTo" RDF_spec = "http://www.w3.org/TR/REC-rdf-syntax/" #List_NS = DPO_NS # We have to pick just one all the time List_NS = RDF_NS_URI # From 20030808 LOG_implies_URI = "http://www.w3.org/2000/10/swap/log#implies" INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer" FLOAT_DATATYPE = "http://www.w3.org/2001/XMLSchema#double" DECIMAL_DATATYPE = "http://www.w3.org/2001/XMLSchema#decimal" NORMAL = 1 PREFIX = 2 FORSOME = 4 FORALL = 5 NEED_PERIOD = 8 LITERAL = 9 KEYWORDS = 10 class n3p_tm(n3p.N3Parser): def __init__(self, uri, tm, baseURI=False): n3p.N3Parser.__init__(self, 'nowhere', n3p.branches, n3p.regexps) self.tm = tm self.productions = [] if baseURI: self._baseURI = baseURI + '#' else: self._baseURI = uri + '#' self.prefixes = {'':self._baseURI} self.abs = absolutizer(self._baseURI[:-1]) def parse(self, start=n3p.start): n3p.N3Parser.parse(self, start) def startDoc(self): self.tm.start() def endDoc(self): return self.tm.end() def feed(self, data): self.data = data.decode('utf_8') self._mode = NORMAL self.parse() def onStart(self, prod): self.productions.append(prod) if prod == 'literal': self._mode = LITERAL #print 'begin' + prod def onFinish(self): prod = self.productions.pop() if prod == 'literal': self.tm.addLiteral(self.literal['string'], self.literal['type'], self.literal['lang']) self._mode = NORMAL #print 'end' + prod def onToken(self, prod, tok): tm = self.tm if 1: if self._mode == NORMAL: if prod == '.': try: tm.endStatement() except ValueError: tm.forewardPath() elif prod == ';': tm.endStatement() tm.addNode(None) elif prod == ',': tm.endStatement() tm.addNode(None) tm.addNode(None) elif prod == '=>': tm.addSymbol(LOG_implies_URI) elif prod == '<=': tm.IsOf() tm.addSymbol(LOG_implies_URI) elif prod == '=': tm.addSymbol(DAML_sameAs_URI) elif prod == '@forAll': self._mode = FORALL elif prod == '@forSome': self._mode = FORSOME elif prod == '@a': tm.addSymbol(RDF_type_URI) elif prod == '@is': tm.IsOf() elif prod == '@of': assert tm.checkIsOf() elif prod == '{': tm.beginFormula() elif prod == '}': tm.endFormula() elif prod == '[': tm.beginAnonymous() elif prod == ']': tm.endAnonymous() elif prod == '(': tm.beginList() elif prod == ')': tm.endList() elif prod == '@has': pass elif prod == '@this': tm.addNode('@this') elif prod == '^': tm.backwardPath() elif prod == '!': tm.forewardPath() elif prod == '@prefix': self._mode = PREFIX elif prod == 'qname': ret = self.decodeQName(tok, True) if type(ret) is tuple: tm.addAnonymous(ret[0]) else: tm.addSymbol(ret) elif prod == 'explicituri': tm.addSymbol(self.abs[tok[1:-1]]) elif prod == 'numericliteral': if '.' in tok or 'e' in tok: tm.addLiteral(float(tok)) else: tm.addLiteral(int(tok)) elif prod == 'variable': tm.addQuestionMarkedSymbol(self._baseURI+tok[1:]) elif prod == '@keywords': self._mode = KEYWORDS elif self._mode == LITERAL: if prod == 'string': self.literal = {'string': unEscape(tok), 'type':None, 'lang':None} elif prod == 'qname': self.literal['type'] = self.decodeQName(tok, False) elif prod == 'explicituri': self.literal['type'] = self.abs[tok[1:-1]] elif prod == 'langcode': self.literal['lang'] = tok else: pass elif self._mode == PREFIX: if prod == 'qname': n = tok.find(':') self._newPrefix = tok[:n] elif prod == 'explicituri': tm.bind(self._newPrefix, self.abs[tok[1:-1]]) self.prefixes[self._newPrefix] = self.abs[tok[1:-1]] elif prod == '.': self._mode = NORMAL elif self._mode == FORALL: if prod == 'qname': uri = self.decodeQName(tok, False) tm.declareUniversal(uri) elif prod == 'explicituri': tm.declareUniversal(self.abs[tok[1:-1]]) elif prod == ',': pass elif prod == '.': self._mode = NORMAL elif self._mode == FORSOME: if prod == 'qname': uri = self.decodeQName(tok, False) tm.declareExistential(uri) elif prod == 'explicituri': tm.declareExistential(self.abs[tok[1:-1]]) elif prod == ',': pass elif prod == '.': self._mode = NORMAL if prod == '.': self._mode = NORMAL parent = self.productions[-1] #print 'mode=', self._mode, '. prod=', prod, '. tok =', tok def decodeQName(self, qName, bNode): n = qName.find(':') if n < 0: pfx = '' frag = qName else: pfx = qName[:n] frag = qName[n+1:] try: self.prefixes[pfx] except KeyError: if pfx == '_': if bNode: return (frag,) else: return qName raise return self.prefixes[pfx]+frag def unEscape(string): if string[:3] == '"""': real_str = string[3:-3] triple = True else: real_str = string[1:-1] triple = False ret = u'' n = 0 while n < len(real_str): ch = real_str[n] if ch == '\r': pass elif ch == '\\': a = real_str[n+1:n+2] if a == '': raise RuntimeError k = 'abfrtvn\\"'.find(a) if k >= 0: ret += '\a\b\f\r\t\v\n\\"'[k] n += 1 elif a == 'u': m = real_str[n+2:n+6] assert len(m) == 4 ret += unichr(int(m, 16)) n += 5 elif a == 'U': m = real_str[n+2:n+10] assert len(m) == 8 ret += unichr(int(m, 16)) n += 9 else: raise ValueError('Bad Escape') else: ret += ch n += 1 return ret def parse(uri, options): baseURI = options.baseURI sink = object() if options.root: sink.quantify = lambda *args: True sink.flatten = lambda *args: True if ':' not in uri: uri = 'file://' + os.path.join(os.getcwd(), uri) if baseURI and (':' not in baseURI): baseURI = 'file://' + os.path.join(os.getcwd(), baseURI) p = n3p_tm(uri, sink, baseURI=baseURI) p.parse() def main(argv=None): import optparse class MyHelpFormatter(optparse.HelpFormatter): def __init__(self): kargs = {'indent_increment': 2, 'short_first': 1, 'max_help_position': 25, 'width': None} optparse.HelpFormatter.__init__(self, **kargs) def format_usage(self, usage): return optparse._("%s") % usage.lstrip() def format_heading(self, heading): return "%*s%s:\n" % (self.current_indent, "", heading) formatter = MyHelpFormatter() parser = optparse.OptionParser(usage=__doc__, formatter=formatter) parser.add_option("-b", "--baseURI", dest="baseURI", default=False, help="set the baseURI", metavar="URI") parser.add_option("-r", "--root", dest="root", action="store_true", default=False, help="print triples in the root formula only") options, args = parser.parse_args(argv) if len(args) == 1: parse(args[0], options) else: parser.print_help() if __name__=="__main__": main() cwm-1.2.1/swap/cwm_set.py0000644015216600007660000001342010640075637014412 0ustar syosisyosi#! /usr/bin/env python """ $Id: cwm_set.py,v 1.4 2007/06/26 02:36:15 syosi Exp $ set built-ins for cwm http://www.w3.org/2000/10/swap/cwm_list.py See cwm.py and the os module in python """ from term import LightBuiltIn, Function, ReverseFunction, MultipleFunction,\ MultipleReverseFunction, \ CompoundTerm, N3Set, List, EmptyList, NonEmptyList from set_importer import Set from diag import verbosity, progress import uripath from RDFSink import List_NS, Logic_NS SetOperationsNamespace = "http://www.w3.org/2000/10/swap/set#" ############################################################################################### # # List handling B U I L T - I N s # # # Light Built-in classes class BI_in(LightBuiltIn, MultipleReverseFunction): """Is the subject in the object? Returnes a sequence of values.""" def eval(self, subj, obj, queue, bindings, proof, query): if not isinstance(obj, CompoundTerm): return None return subj in obj def evalSubj(self, obj, queue, bindings, proof, query): if not isinstance(obj, NonEmptyList) and not isinstance(obj, N3Set): return None rea = None return [x or x in obj] # [({subj:x}, rea) for x in obj] class BI_member(LightBuiltIn, MultipleFunction): """Is the subject in the object? Returnes a sequence of values.""" def eval(self, subj, obj, queue, bindings, proof, query): if not isinstance(subj, CompoundTerm): return None return obj in subj def evalObj(self,subj, queue, bindings, proof, query): if not isinstance(subj, NonEmptyList) and not isinstance(subj, N3Set): return None rea = None return subj # [({obj:x}, rea) for x in subj] class BI_union(LightBuiltIn, Function): """Takes a set or list of sets, and finds the union """ def evaluateObject(self, subj): ret = Set() for m in subj: ret.update(m) return ret class BI_intersection(LightBuiltIn, Function): """Takes a set or list of sets, and finds the intersection """ def evaluateObject(self, subj): ret = None for m in subj: if ret is None: ret = Set(m) else: ret.intersection_update(m) if ret is None: return Set() return ret class BI_symmetricDifference(LightBuiltIn, Function): """Takes a set or list of two sets, and finds the symmetric difference """ def evaluateObject(self, subj): if len(subj) != 2: raise ValueError('A symmetric difference of more than two things makes no sense') ret = Set() for m in subj: ret.symmetric_difference_update(m) return ret class BI_difference(LightBuiltIn, Function): """Takes a list of two sets, and finds the difference """ def evaluateObject(self, subj): if len(subj) != 2: raise ValueError('A symmetric difference of more than two things makes no sense') difference = N3Set.difference return difference(subj[0], subj[1]) class BI_oneOf(LightBuiltIn, ReverseFunction): """ Make a set from a list """ def evaluateSubject(self, obj): return Set(obj) ##################################### ## ## Sets and Formulae --- set:in is the inverse of most of these ## class BI_subjects(LightBuiltIn, Function): """Return the set of subjects used in a formula """ def evalObj(self, subj, queue, bindings, proof, query): if not isinstance(subj, Formula): raise ValueError('Only a formula has statements') return N3Set([x.subject() for x in subj]) class BI_predicates(LightBuiltIn, Function): """Return the set of subjects used in a formula """ def evalObj(self, subj, queue, bindings, proof, query): if not isinstance(subj, Formula): raise ValueError('Only a formula has statements') return N3Set([x.predicate() for x in subj]) class BI_objects(LightBuiltIn, Function): """Return the set of subjects used in a formula """ def evalObj(self, subj, queue, bindings, proof, query): if not isinstance(subj, Formula): raise ValueError('Only a formula has statements') return N3Set([x.object() for x in subj]) class BI_triples(LightBuiltIn, Function): """Return the set of triple used in a formula """ def evalObj(self, subj, queue, bindings, proof, query): if not isinstance(subj, Formula): raise ValueError('Only a formula has statements') return N3Set([x.asFormula() for x in subj]) ##class BI_existentials(LightBuiltIn, Function): ## """Return the set of subjects used in a formula ## ## """ ## def evalObj(self, subj, queue, bindings, proof, query): ## if not isinstance(subj, Formula): ## raise ValueError('Only a formula has statements') ## return N3Set(subj.existentials()) ## ##class BI_universals(LightBuiltIn, Function): ## """Return the set of subjects used in a formula ## ## """ ## def evalObj(self, subj, queue, bindings, proof, query): ## if not isinstance(subj, Formula): ## raise ValueError('Only a formula has statements') ## return N3Set(subj.universals()) # Register the string built-ins with the store def register(store): # Done explicitly in llyn # list = store.internURI(List_NS[:-1]) # list.internFrag("first", BI_first) # list.internFrag("rest", BI_rest) ns = store.symbol(SetOperationsNamespace[:-1]) ns.internFrag("in", BI_in) ns.internFrag("member", BI_member) ns.internFrag("union", BI_union) ns.internFrag("intersection", BI_intersection) ns.internFrag("symmetricDifference", BI_symmetricDifference) ns.internFrag("difference", BI_difference) ns.internFrag("oneOf", BI_oneOf) # ends cwm-1.2.1/swap/delta.py0000755015216600007660000004734710640075637014064 0ustar syosisyosi#! /usr/bin/python """ Find differences between two RDF graphs, using functional and inverse functional properties to identify bnodes in the patch file. --from=uri -f uri from-file --to=uri -t uri file against which to check for differences --meta=uri -m uri file with metadata to be assumed (in addition to schemas) --help -h print this help message --verbose= -v 1 verbose mode (can be 0 to 10, 0 is default) --granularity= -g 0 g=0 - lots of little diffs. g=1, fewer diffs (default) If from-file but not to-file is given, from-file is smushed and output Uris are relative to present working directory. For motivation and explanation, see $Id: delta.py,v 1.11 2007/06/26 02:36:15 syosi Exp $ http://www.w3.org/2000/10/swap/diff.py """ import string, getopt try: Set = set # Python2.4 and on except NameError: from sets import Set # Python2.3 and on import string import sys # http://www.w3.org/2000/10/swap/ try: from swap import llyn, diag from swap.myStore import loadMany from swap.diag import verbosity, setVerbosity, progress from swap import notation3 # N3 parsers and generators from swap.RDFSink import FORMULA, LITERAL, ANONYMOUS, Logic_NS from swap import uripath from swap.uripath import base from swap.myStore import Namespace from swap import myStore from swap.notation3 import RDF_NS_URI from swap.llyn import Formula, CONTEXT, PRED, SUBJ, OBJ except ImportError: import llyn, diag from myStore import loadMany from diag import verbosity, setVerbosity, progress import notation3 # N3 parsers and generators from RDFSink import FORMULA, LITERAL, ANONYMOUS, Logic_NS import uripath from uripath import base from myStore import Namespace import myStore from notation3 import RDF_NS_URI from llyn import Formula, CONTEXT, PRED, SUBJ, OBJ #daml = Namespace("http://www.daml.org/2001/03/daml+oil#") OWL = Namespace("http://www.w3.org/2002/07/owl#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") LOG = Namespace("http://www.w3.org/2000/10/swap/log#") DELTA = Namespace("http://www.w3.org/2004/delta#") def debugBnode(n, f): progress("For node %s" % `n`) for s in f.statementsMatching(subj=n): progress(" %s %s; # could be ifp?" %(`s.predicate()`, `s.object()`)) for s in f.statementsMatching(obj=n): progress(" is %s of %s; # could be fp?" %(`s.predicate()`, `s.subject()`)) def lookUp(predicates, assumptions=Set()): """Look up all the schemas for the predicates given""" global verbose schemas = assumptions for pred in predicates: if verbose > 3: progress("Predicate: %s" % `pred`) u = pred.uriref() hash = u.find("#") if hash <0: if verbose > 1: progress("Warning: Predicate <%s> looks like web resource not Property" % u) else: schemas.add(u[:hash]) if verbose > 2: for r in schemas: progress("Metadata to be loaded: ", r) if schemas: return loadMany([(x) for x in schemas]) return myStore.store.newFormula() # Empty formula def nailFormula(f, assumptions=Set()): """Smush the formula. Build a dictionary of nodes which are indirectly identified by [inverse] functonal properties.""" global verbose cc, predicates, ss, oo = getParts(f) nodes = ss | oo sofar = {} bnodes = Set() for node in nodes: if node.generated() or node in f.existentials(): bnodes.add(node) if verbose >=5: progress("Blank node: %s" % `node`) else: if verbose >=5: progress("Fixed node: %s" % `node`) sofar[node] = [] meta = lookUp(predicates, assumptions) ifps = predicates & Set(meta.each(pred=RDF.type, obj=OWL.InverseFunctionalProperty)) fps = predicates & Set(meta.each(pred=RDF.type, obj=OWL.FunctionalProperty)) if verbose > 1: for p in fps: progress("Functional Property:", p) for p in ifps: progress("Inverse Functional: ", p) definitions = [] if len(bnodes) == 0: if verbose > 0: progress("No bnodes in graph") return bnodes, definitions a = float(len(bnodes))/len(nodes) if verbose > 1: progress("Proportion of bodes which are blank: %f" % a) # if a == 0: return bnodes, definitions loose = bnodes.copy() equivs = Set() # Note possible optmization: First pass only like this, # future passes work from newNodes. while loose: newNailed = Set() for preds, inverse, char in ((fps, 0, "!"), (ifps, 1, "^")): for pred in preds: if verbose > 3: progress("Predicate", pred) ss = f.statementsMatching(pred=pred) for s in ss: if inverse: y, x = s.object(), s.subject() else: x, y = s.object(), s.subject() if not x.generated(): continue # Only anchor bnodes if y not in loose: # y is the possible anchor defi = (x, inverse, pred, y) if x in loose: # this node if verbose > 4: progress(" Nailed %s as %s%s%s" % (`x`, `y`, `char`, `pred`)) loose.discard(x) newNailed.add(x) else: if verbose >=6 : progress( " (ignored %s as %s%s%s)" % (`x`, `y`, `char`, `pred`)) definitions.append(defi) # if verbose > 9: progress(" Definition[x] is now", definition[x]) if inverse: equivalentSet = Set(f.each(obj=y, pred=pred)) else: equivalentSet = Set(f.each(subj=y, pred=pred)) if len(equivalentSet) > 1: equivs.add(equivalentSet) if not newNailed: if verbose > 1: progress("Failed to nail nodes:", loose) if verbose > 3: for n in loose: debugBnode(n, f) break # At this point if we still have loose nodes, we have failed with ifps and fps. # Diff may not be strong. (It might still be: the diffs might not involve weak definitions) weak = loose.copy() # Remember if verbose > 0: progress("\nFailed to directly nail everything, looking for weak nailings.") # sys.exit(-1) #@@@ while loose: newNailed = Set() if verbose>2: progress() progress("Pass: loose = %s" % loose) for x in loose.copy(): if verbose>3: progress("Checking weakly node %s" % x) for s in f.statementsMatching(obj=x): pred, y = s.predicate(), s.subject() if y in loose: if verbose > 4: progress("Can't nail to loose %s" % y) continue # Can't nail to something loose others = f.each(subj=y, pred=pred) # @@ Should ignore redirected equivalent nodes in others if len(others) != 1: if verbose>4: progress("Can't nail: %s all are %s of %s." % (others, pred, y)) continue # Defn would be ambiguous in this graph defi = (x, 0, pred, y) if verbose >4: progress(" Weakly-nailed %s as %s%s%s" % (x, y, "!", pred)) loose.discard(x) newNailed.add(x) definitions.append(defi) break # progress else: for s in f.statementsMatching(subj=x): pred, obj = s.predicate(), s.object() if obj in loose: if verbose >4: progress("Can't nail to loose %s" % obj) continue # Can't nail to something loose others = f.each(obj=obj, pred=pred) # @@ Should ignore redirected equivalent nodes in others if len(others) != 1: if verbose >4: progress( "Can't nail: %s all have %s of %s." % (others, pred, obj)) continue # Defn would be ambiguous in this graph defi = (x, 1, pred, obj) if verbose>2: progress(" Weakly-nailed %s as %s%s%s" % (`x`, `obj`, "^", `pred`)) loose.discard(x) newNailed.add(x) definitions.append(defi) break # progress if not newNailed: if verbose>0: progress("Failed to even weakly nail nodes:", loose) for n in loose: progress("For node %s" % n) for s in f.statementsMatching(subj=n): progress(" %s %s; # could be ifp?" %(`s.predicate()`, `s.object()`)) for s in f.statementsMatching(obj=n): progress(" is %s of %s; # could be fp?" %(s.predicate(), s.subject())) raise ValueError("Graph insufficiently labelled for nodes: %s" % loose) if verbose>0 and not weak: progress("Graph is solid.") if verbose>0 and weak: progress("Graph is NOT solid.") f.reopen() for es in equivs: if verbose>3: progress("Equivalent: ", es) prev = None for x in es: if prev: f.add(x, OWL.sameAs, prev) prev = x return bnodes, definitions def removeCommon(f, g, match): """Find common statements from f and g match gives the dictionary mapping bnodes in f to bnodes in g""" only_f, common_g = Set(), Set() for st in f.statements[:]: s, p, o = st.spo() assert s not in f._redirections assert o not in f._redirections if s.generated(): sg = match.get(s, None) else: sg = s if o.generated(): og = match.get(o, None) else: og = o if og != None and sg != None: gsts = g.statementsMatching(subj=sg, pred=p, obj=og) if len(gsts) == 1: if verbose>4: progress("Statement in both", st) common_g.add(gsts[0]) continue only_f.add(st) return only_f, Set(g.statements)-common_g def patches(delta, f, only_f, originalBnodes, definitions, deleting=0): """Generate patches in patch formula, for the remaining statements in f given the bnodes and definitions for f.""" todo = only_f.copy() if deleting: patchVerb = DELTA.deletion else: patchVerb = DELTA.insertion if verbose>2: progress("*********** PATCHES: %s, with %i to do" %(patchVerb, len(todo))) while todo: # find a contiguous subgraph defined in the given graph bnodesToDo = Set() bnodes = Set() rhs = delta.newFormula() lhs = delta.newFormula() # left hand side of patch newStatements = Set() for seed in todo: break # pick one #@2 fn? statementsToDo = Set([seed]) if verbose>3: progress("Seed:", seed) subgraph = statementsToDo while statementsToDo or bnodesToDo: for st in statementsToDo: s, p, o = st.spo() for x in s, p, o: if x.generated() and x not in bnodes: # and x not in commonBnodes: if verbose>4: progress(" Bnode ", x) bnodesToDo.add(x) bnodes.add(x) rhs.add(s, p, o) statementsToDo = Set() for x in bnodesToDo: bnodes.add(x) ss = (f.statementsMatching(subj=x) + f.statementsMatching(pred=x) + f.statementsMatching(obj=x)) for z in ss: if z in only_f: newStatements.add(z) if verbose>3: progress(" New statements from %s: %s" % (x, newStatements)) statementsToDo = statementsToDo | newStatements subgraph = subgraph |newStatements bnodesToDo = Set() if verbose>3: progress("Subgraph of %i statements (%i left):\n\t%s\n" %(len(subgraph), len(todo), subgraph)) todo = todo - subgraph undefined = bnodes.copy() for x, inverse, pred, y in definitions: if x in undefined: if inverse: s, p, o = x, pred, y else: s, p, o = y, pred, x if verbose > 4: progress("Declaring variable %s" % x.uriref()) if deleting: delta.declareUniversal(x) lhs.add(subj=s, pred=p, obj=o) else: # inserting if x in originalBnodes: delta.declareUniversal(x) lhs.add(subj=s, pred=p, obj=o) else: rhs.declareExistential(x) if y.generated(): undefined.add(y) undefined.discard(x) if undefined: progress("Still haven't defined bnodes %s" % undefined) for n in undefined: debugBnode(n, f) raise RuntimeError("BNodes still undefined", undefined) lhs = lhs.close() rhs = rhs.close() delta.add(subj=lhs, pred=patchVerb, obj=rhs) if verbose >1: progress("PATCH: %s %s %s\n" %(lhs.n3String(), `patchVerb`, rhs.n3String())) return def consolidate(delta, patchVerb): """Consolidate patches Where the same left hand side applies to more than 1 RHS formula, roll those RHS formulae into one, to make the dif file more readable and faster to execute in some implementations """ agenda = {} if verbose >3: progress("Consolidating %s" % patchVerb) for s in delta.statementsMatching(pred=patchVerb): list = agenda.get(s.subject(), None) if list == None: list = [] agenda[s.subject()] = list list.append(s) for lhs, list in agenda.items(): if verbose >3: progress("Patches lhs= %s: %s" %(lhs, list)) if len(list) > 1: rhs = delta.newFormula() for s in list: delta.store.copyFormula(s.object(), rhs) delta.removeStatement(s) delta.add(subj=lhs, pred=patchVerb, obj=rhs.close()) def differences(f, g, assumptions): """Smush the formulae. Compare them, generating patch instructions.""" global lumped # Cross-map nodes: g_bnodes, g_definitions = nailFormula(g, assumptions) bnodes, definitions = nailFormula(f, assumptions) if verbose > 1: progress("\n Done nailing") definitions.reverse() # go back down list @@@ reverse the g list too? @@@ g_definitions.reverse() # @@ needed for the patch generation unmatched = bnodes.copy() match = {} # Mapping of nodes in f to nodes in g for x, inverse, pred, y in definitions: if x in match: continue # done already if x in f._redirections: if verbose > 3: progress("Redirected %s to %s. Ignoring" % (`x`, `f._redirections[x]`)) unmatched.discard(x) continue if verbose > 3: progress("Definition of %s = %s%s%s"% (`x`, `y` , ".!^"[inverse], `pred`)) if y.generated(): while y in f._redirections: y = f._redirections[y] if verbose>4: progress(" redirected to %s = %s%s%s"% (`x`, `y`, "!^"[inverse], `pred`)) yg = match.get(y, None) if yg == None: if verbose>4: progress(" Had definition for %s in terms of %s which is not matched"%(`x`,`y`)) continue else: yg = y if inverse: # Inverse functional property like ssn matches = Set(g.each(obj=yg, pred=pred)) else: matches = Set(g.each(subj=yg, pred=pred)) if len(matches) == 0: continue # This is normal - the node does not exist in the other graph # raise RuntimeError("Can't match %s" % x) if len(matches) > 1: raise RuntimeError("""Rats. Wheras in the first graph %s%s%s uniquely selects %s, in the other graph there are more than 1 matches: %s""" % (`y`, "!^"[inverse], `pred`, `x`, `matches`)) for q in matches: # pick only one @@ python function? z = q break if verbose > 2: progress("Found match for %s in %s " % (`x`,`z`)) match[x] = z unmatched.discard(x) if len(unmatched) > 0: if verbose >1: progress("Failed to match all nodes:", unmatched) for n in unmatched: debugBnode(n, f) # Find common parts only_f, only_g = removeCommon(f,g, match) delta = f.newFormula() if len(only_f) == 0 and len(only_g) == 0: return delta f = f.close() # We are not going to mess with them any more g = g.close() common = Set([match[x] for x in match]) if verbose>2: progress("Common bnodes (as named in g)", common) patches(delta, f, only_f, Set(), definitions, deleting=1) patches(delta, g, only_g, common, g_definitions, deleting=0) if lumped: consolidate(delta, delta.store.insertion) consolidate(delta, delta.store.deletion) return delta def getParts(f, meta=None): """Make lists of all node IDs and arc types """ values = [Set([]),Set([]),Set([]),Set([])] for s in f.statements: for p in SUBJ, PRED, OBJ: x = s[p] values[p].add(x) return values def loadFiles(files): graph = myStore.formula() graph.setClosureMode("e") # Implement sameAs by smushing if verbose>0: progress("Loading %s..." % files) graph = myStore.loadMany(files, openFormula=graph) if verbose>0: progress("Loaded", graph) return graph def usage(): sys.stderr.write(__doc__) def main(): testFiles = [] diffFiles = [] assumptions = Set() global ploughOn # even if error ploughOn = 0 global verbose global lumped verbose = 0 lumped = 1 try: opts, args = getopt.getopt(sys.argv[1:], "hf:t:m:v:g:", ["help", "from=", "to=", "meta=", "verbose=", "granularity="]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) output = None for o, a in opts: if o in ("-h", "--help"): usage() sys.exit(2) if o in ("-v", "--verbose"): try: verbose = int(a) except ValueError: verbose = 10 if o in ("-g", "--granularity"): try: lumped = int(a) except ValueError: lumped = 0 if o in ("-f", "--from"): testFiles.append(a) if o in ("-t", "--to"): diffFiles.append(a) if o in ("-m", "--meta"): assumptions.add(a) # if testFiles == []: testFiles = [ "/dev/stdin" ] if testFiles == []: usage() sys.exit(2) graph = loadFiles(testFiles) version = "$Id: delta.py,v 1.11 2007/06/26 02:36:15 syosi Exp $"[1:-1] if diffFiles == []: nailFormula(graph, assumptions) if verbose > 1: print "# Smush generated by " + version print graph.close().n3String(base=base(), flags="a") sys.exit(0) graph2 = loadFiles(diffFiles) delta = differences(graph, graph2, assumptions) if verbose >1: print "# Differences by " + version print delta.close().n3String(base=base()) # sys.exit(len(delta)) # sys.exit(0) # didn't crash if delta.contains(): # Any statements in delta at all? sys.exit(1) else: sys.exit(0) if __name__ == "__main__": main() cwm-1.2.1/swap/pretty.py0000755015216600007660000007563410713412505014310 0ustar syosisyosi#! /usr/bin/python """ $Id: pretty.py,v 1.41 2007/09/09 22:51:42 timbl Exp $ Printing of N3 and RDF formulae 20003-8-20 split offf from llyn.py This is or was http://www.w3.org/2000/10/swap/pretty.py """ import types import string import diag from diag import progress, verbosity, tracking from term import Literal, XMLLiteral, Symbol, Fragment, AnonymousNode, \ AnonymousVariable, FragmentNil, AnonymousUniversal, \ Term, CompoundTerm, List, EmptyList, NonEmptyList, N3Set from formula import Formula, StoredStatement from RDFSink import Logic_NS, RDFSink, forSomeSym, forAllSym from RDFSink import CONTEXT, PRED, SUBJ, OBJ, PARTS, ALL4, \ ANONYMOUS, SYMBOL, LITERAL, LITERAL_DT, LITERAL_LANG, XMLLITERAL from RDFSink import N3_nil, N3_first, N3_rest, OWL_NS, N3_Empty, N3_List, \ List_NS from RDFSink import RDF_NS_URI from RDFSink import RDF_type_URI cvsRevision = "$Revision: 1.41 $" # Magic resources we know about from RDFSink import RDF_type_URI, DAML_sameAs_URI STRING_NS_URI = "http://www.w3.org/2000/10/swap/string#" META_NS_URI = "http://www.w3.org/2000/10/swap/meta#" INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer" FLOAT_DATATYPE = "http://www.w3.org/2001/XMLSchema#double" prefixchars = "abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" # Utility functions for the object-free abstract notation interface def auPair(x): """Encode as object-free form for unparser interface""" if isinstance(x, XMLLiteral): return (XMLLITERAL, x.dom) if isinstance(x, Literal): if x.datatype: return LITERAL_DT, (str(x), x.datatype.uriref()) # could be XMLLit if x.lang: return LITERAL_LANG, (x.string, x.lang) return (LITERAL, x.string) if isinstance(x, AnonymousUniversal): if x.uri: return (SYMBOL, x.uriref()) if isinstance(x, AnonymousNode): return (ANONYMOUS, x.uriref()) else: return (SYMBOL, x.uriref()) def auxPairs(t): return(auPair(t[CONTEXT]), auPair(t[PRED]), auPair(t[SUBJ]), auPair(t[OBJ]), ) class TooMuchRecursion(Exception): pass class Serializer: """A serializer to serialize the formula F into the given abstract syntax sink """ def __init__(self, F, sink, flags="", sorting=0): self.context = F # assert F.canonical is not None, "Formula printed must be canonical" self.store = F.store self.sink = sink self.defaultNamespace = None self.flags = flags self.sorting = sorting self._inContext ={} self._loopCheck = {} self._inLoop = {} self._tooDeep = {} self._occurringAs = [{}, {}, {}, {}] self._topology_returns = {} def selectDefaultPrefix(self, printFunction): """ Symbol whose fragments have the most occurrences. we suppress the RDF namespace itself because the XML syntax has problems with it being default as it is used for attributes. This also outputs the prefixes.""" if "d" in self.flags: self.defaultNamespace = None self.dumpPrefixes() return dummySink = self.sink.dummyClone() dummySerializer = Serializer(self.context, sink=dummySink, flags=self.flags+"d", sorting=self.sorting) printFunction(dummySerializer) best = 0 mp = None counts = dummySink.namespaceCounts() for r, count in counts.items(): if verbosity() > 25: progress(" Count is %3i for %s" %(count, r)) if (r != RDF_NS_URI and count > 0 and (count > best or (count == best and mp > r))) : # Must be repeatable for retests best = count mp = r if verbosity() > 20: progress("# Most popular Namespace is %s with %i" % ( mp, best)) self.defaultNamespace = mp # Make up prefixes for things which don't have them: for r, count in counts.items(): if count > 1 and r != mp: if self.store.prefixes.get(r, None) is None: p = r if p[-1] in "/#": p = p[:-1] slash = p.rfind("/") if slash >= 0: p = p[slash+1:] i = 0 while i < len(p): if p[i] in prefixchars: i = i + 1 else: break p = p[:i] if len(p) <6 and self.store.namespaces.get(p, None)is None: # and p[:3]!='xml': pref = p else: p = p[:5] for l in (3, 2, 4, 1, 5): if self.store.namespaces.get(p[:l], None) is None: # and p[:l][:3]!='xml': pref = p[:l] break else: n = 2 while 1: pref = p[:3]+`n` if self.store.namespaces.get(pref, None) is None: break n = n + 1 self.store.bind(pref, r) if verbosity() > 50: progress("Generated @prefix %s: <%s>." % (pref, r)) if self.defaultNamespace is not None: self.sink.setDefaultNamespace(self.defaultNamespace) # progress("&&&& Counts: ", counts) prefixes = self.store.namespaces.keys() # bind in same way as input did FYI prefixes.sort() # For repeatability of test results for pfx in prefixes: r = self.store.namespaces[pfx] try: count = counts[r] if count > 0: self.sink.bind(pfx, r) except KeyError: pass return def dumpPrefixes(self): if self.defaultNamespace is not None: sink.setDefaultNamespace(self.defaultNamespace) prefixes = self.store.namespaces.keys() # bind in same way as input did FYI prefixes.sort() for pfx in prefixes: uri = self.store.namespaces[pfx] self.sink.bind(pfx, uri) def _listsWithinLists(self, L, lists): if L not in lists: lists.append(L) for i in L: if isinstance(i, NonEmptyList) or isinstance(i, N3Set): self._listsWithinLists(i, lists) def dumpLists(self): "Dump lists out as first and rest. Not used in pretty." listList = {} context = self.context sink = self.sink lists = [] for s in context.statements: for x in s.predicate(), s.subject(), s.object(): if isinstance(x, NonEmptyList) or isinstance(x, N3Set): self._listsWithinLists(x, lists) for l in lists: if isinstance(l, N3Set): a = context.newBlankNode() ll = [mm for mm in l] #I hate sorting things ll.sort(Term.compareAnyTerm) list = self.store.newList(ll) self._outputStatement(sink, (context, self.store.forSome, context, a)) l._list = list l._node = a else: list = l while not isinstance(list, EmptyList): if list not in listList: self._outputStatement(sink, (context, self.store.forSome, context, list)) listList[list] = 1 list = list.rest listList = {} for l in lists: list = l if isinstance(l, N3Set): list = l._list self._outputStatement(sink, (context, self.store.owlOneOf, l._node, list)) while (not isinstance(list, EmptyList)) and list not in listList: if isinstance(list.first, N3Set): self._outputStatement(sink, (context, self.store.first, list, list.first._node)) else: self._outputStatement(sink, (context, self.store.first, list, list.first)) self._outputStatement(sink, (context, self.store.rest, list, list.rest)) listList[list] = 1 list = list.rest def dumpChronological(self): "Fast as possible. Only dumps data. No formulae or universals." context = self.context sink = self.sink sink.startDoc() self.dumpPrefixes() self.dumpVariables(context, sink, sorting=0, dataOnly=1) uu = context.universals() self.dumpLists() def fixSet(x): try: return x._node except AttributeError: return x for s in context.statements: for p in SUBJ, PRED, OBJ: x = s[p] if isinstance(x, Formula) or x in uu: break else: self._outputStatement(sink, [fixSet(x) for x in s.quad]) sink.endDoc() def _outputStatement(self, sink, quad, aWorks = 1): if isinstance(quad[1], Literal): raise ValueError("Cannot have a literal as a predicate. This makes no sense, %s" % `quad[1]`) if isinstance(quad[1], Formula): raise ValueError("Cannot have a formula as a predicate. This makes no sense") sink.makeStatement(auxPairs(quad), aIsPossible=aWorks) def dumpVariables(self, context, sink, sorting=1, pretty=0, dataOnly=0): """Dump the forAlls and the forSomes at the top of a formula""" uv = list(context.universals()) ev = list(context.existentials()) if sorting: uv.sort(Term.compareAnyTerm) ev.sort(Term.compareAnyTerm) if not dataOnly: for v in uv: self._outputStatement(sink, (context, self.store.forAll, context, v)) for v in ev: aWorks = 0 if pretty: _anon, _incoming = self._topology(v, context) if not _anon: self._outputStatement(sink, (context, self.store.forSome, context, v), \ canItbeABNode(context, v)) else: # not pretty, no formulae, can always use _:a form self._outputStatement(sink, (context, self.store.forSome, context, v), 1) def dumpBySubject(self, sorting=1): """ Dump one formula only by order of subject except forSome's first for n3=a mode""" context = self.context uu = context.universals().copy() sink = self.sink self._scan(context) sink.startDoc() self.selectDefaultPrefix(Serializer.dumpBySubject) self.dumpVariables(context, sink, sorting) self.dumpLists() ss = context.statements[:] ss.sort() def fixSet(x): try: return x._node except AttributeError: return x for s in ss: for p in SUBJ, PRED, OBJ: x = s[p] if isinstance(x, Formula) or x in uu: break else: self._outputStatement(sink, [fixSet(x) for x in s.quad]) if 0: # Doesn't work as ther ei snow no list of bnodes rs = self.store.resources.values() if sorting: rs.sort(Term.compareAnyTerm) for r in rs : # First the bare resource statements = context.statementsMatching(subj=r) if sorting: statements.sort(StoredStatement.comparePredObj) for s in statements : self._outputStatement(sink, s.quad) if not isinstance(r, Literal): fs = r.fragments.values() if sorting: fs.sort for f in fs : # then anything in its namespace statements = context.statementsMatching(subj=f) if sorting: statements.sort(StoredStatement.comparePredObj) for s in statements: self._outputStatement(sink, s.quad) sink.endDoc() # # Pretty printing # # An intersting alternative is to use the reverse syntax to the max, which # makes the DLG an undirected labelled graph. s and o above merge. The only think which # then prevents us from dumping the graph without new bnode ids is the presence of cycles. # # Blank nodes can be represented using the implicit syntax [] or rdf/xml equivalent # instead of a dummy identifier iff # - they are blank nodes, ie are existentials whose id has been generated, and # - the node only occurs directly in one formula in the whole thing to be printed, and # - the node occurs at most once as a object or list element within that formula # We used to work this out on the fly, but it is faster to build an index of the # whole formula to be printed first. # # Note when we scan a list we do it in the context of the formula in which we found # it. It may occcur in many formulae. def _scanObj(self, context, x): "Does this appear in just one context, and if so counts how many times as object" z = self._inContext.get(x, None) if z == "many": return # forget it if z is None: self._inContext[x] = context elif z is not context: self._inContext[x] = "many" return if isinstance(x, NonEmptyList) or isinstance(x, N3Set): for y in x: self._scanObj(context, y) if isinstance(x, AnonymousVariable) or (isinstance(x, Fragment) and x.generated()): y = self._occurringAs[OBJ].get(x, 0) + 1 self._occurringAs[OBJ][x] = y if verbosity() > 98: progress( "scan: %s, a %s, now has %i occurrences as %s" %(x, x.__class__,y,"CPSOqqqqq"[y])) # else: # if x is None: raise RuntimeError("Weird - None in a statement?") # progress("&&&&&&&&& %s has class %s " %(`z`, `z.__class__`)) def _scan(self, x, context=None): # progress("Scanning ", x, " &&&&&&&&") # assert self.context._redirections.get(x, None) is None, "Should not be redirected: "+`x` if verbosity() > 98: progress("scanning %s a %s in context %s" %(`x`, `x.__class__`,`context`), x.generated(), self._inContext.get(x, "--")) if isinstance(x, NonEmptyList) or isinstance(x, N3Set): for y in x: self._scanObj(context, y) if isinstance(x, Formula): for s in x.statements: for p in PRED, SUBJ, OBJ: y = s[p] if (isinstance(y, AnonymousVariable) or (isinstance(y, Fragment) and y.generated())): z = self._inContext.get(y, None) if z == "many": continue # forget it if z is None: self._inContext[y] = x elif z is not x: self._inContext[y] = "many" continue z = self._occurringAs[p].get(y, 0) self._occurringAs[p][y] = z + 1 # progress("&&&&&&&&& %s now occurs %i times as %s" %(`y`, z+1, "CPSO"[p])) # else: # progress("&&&&&&&&& yyyy %s has class %s " %(`y`, `y.__class__`)) if x is not y: self._scan(y, x) self._breakloops(x) def _breakloops(self, context): _done = {} _todo = list(self._occurringAs[SUBJ]) _todo.sort(Term.compareAnyTerm) for x in _todo: if x in _done: continue if not (isinstance(x, AnonymousVariable) and not ((isinstance(x, Fragment) and x.generated()))): _done[x] = True continue _done[x] = x a = True y = x while a is not None: a = context._index.get((None, None, y), None) if a is None or len(a) == 0: a = None if a is not None: #print a y = a[0][SUBJ] beenHere = _done.get(y, None) if beenHere is x: self._inLoop[y] = 1 a = None elif beenHere is not None: a = None elif not (isinstance(y, AnonymousVariable) and not ((isinstance(y, Fragment) and y.generated()))): _done[y] = True a = None else: _done[y] = x def _topology(self, x, context): """ Can be output as an anonymous node in N3. Also counts incoming links. Output tuple parts: 1. True iff can be represented as anonymous node in N3, [] or {} 2. Number of incoming links: >0 means occurs as object or pred, 0 means as only as subject. 1 means just occurs once >1 means occurs too many times to be anon Returns number of incoming links (1 or 2) including forSome link or zero if self can NOT be represented as an anonymous node. Paired with this is whether this is a subexpression. """ # This function takes way too long. My attempts to speed it up using a try / except # loop were clearly misguided, because this function does very little as is. # why does this take .08 seconds per function call to do next to nothing? ## try: ## return self._topology_returns[x] ## except KeyError: ## pass # progress("&&&&&&&&& ", `self`, self._occurringAs) _isExistential = x in context.existentials() # _isExistential = context.existentialDict.get(x,0) # return (0, 2) _loop = context.any(subj=x, obj=x) # does'nt count as incomming _asPred = self._occurringAs[PRED].get(x, 0) _asObj = self._occurringAs[OBJ].get(x, 0) _inLoop = self._inLoop.get(x, 0) _tooDeep = self._tooDeep.get(x, 0) if isinstance(x, Literal): _anon = 0 # Never anonymous, always just use the string elif isinstance(x, Formula): _anon = 2 # always anonymous, represented as itself elif isinstance(x, List): if isinstance(x, EmptyList): _anon = 0 # Never anonymous, always just use the string else: _anon = 2 # always anonymous, represented as itself _isExistential = 1 elif isinstance(x, N3Set): _anon = 2 _isExistential = 1 elif not x.generated(): _anon = 0 # Got a name, not anonymous else: # bnode ctx = self._inContext.get(x, "weird") _anon = ctx == "weird" or (ctx is context and _asObj < 2 and _asPred == 0 and _inLoop == 0 and _tooDeep == 0 and (not _loop) and _isExistential) if verbosity() > 97: progress( "Topology %s in %s is: ctx=%s,anon=%i obj=%i, pred=%i loop=%s ex=%i "%( `x`, `context`, `ctx`, _anon, _asObj, _asPred, _loop, _isExistential)) return ( _anon, _asObj+_asPred ) if verbosity() > 98: progress( "Topology %s in %s is: anon=%i obj=%i, pred=%i loop=%s ex=%i "%( `x`, `context`, _anon, _asObj, _asPred, _loop, _isExistential)) ## self._topology_returns[x] = ( _anon, _asObj+_asPred ) return ( _anon, _asObj+_asPred ) def dumpNested(self): """ Iterates over all URIs ever seen looking for statements """ context = self.context # assert context.canonical is not None self._scan(context) self.sink.startDoc() self.selectDefaultPrefix(Serializer.dumpNested) self.dumpFormulaContents(context, self.sink, sorting=1, equals=1) self.sink.endDoc() def tmDumpNested(self): """ """ context = self.context assert context.canonical is not None self._scan(context) self.tm.start() self._dumpFormula(context) self.tm.end() def _dumpNode(self, node): tm = self.tm _anon, _incoming = self._topology(node, context) if isinstance(node, List): tm.startList() [self._dumpNode(x) for x in node] tm.endList() elif isinstance(node, N3Set): pass elif isinstance(node, formula): tm.startFormula() self._dumpFormula(node) tm.endFormula() elif _anon: tm.startAnonymous() self._dumpSubject(context, node) tm.endAnonymous() elif isinstance(node, Literal): tm.addLiteral(node) elif isinstance(node, Symbol): tm.addSymbol(node) else: pass def _dumpFormula(self, node): pass def _dumpSubject(self, formula, node): pass def _dumpPredicate(self, formula, subject, node): pass def dumpFormulaContents(self, context, sink, sorting, equals=0): """ Iterates over statements in formula, bunching them up into a set for each subject. """ allStatements = context.statements[:] if equals: for x, y in context._redirections.items(): if not x.generated() and x not in context.variables(): allStatements.append(StoredStatement( (context, context.store.sameAs, x, y))) allStatements.sort() # context.statements.sort() # @@ necessary? self.dumpVariables(context, sink, sorting, pretty=1) # statements = context.statementsMatching(subj=context) # context is subject # if statements: # progress("@@ Statement with context as subj?!", statements,) # self._dumpSubject(context, context, sink, sorting, statements) currentSubject = None statements = [] for s in allStatements: con, pred, subj, obj = s.quad if subj is con: continue # Done them above if currentSubject is None: currentSubject = subj if subj != currentSubject: self._dumpSubject(currentSubject, context, sink, sorting, statements) statements = [] currentSubject = subj statements.append(s) if currentSubject is not None: self._dumpSubject(currentSubject, context, sink, sorting, statements) def _dumpSubject(self, subj, context, sink, sorting, statements=[]): """ Dump the infomation about one top level subject This outputs arcs leading away from a node, and where appropriate recursively descends the tree, by dumping the object nodes (and in the case of a compact list, the predicate (rest) node). It does NOTHING for anonymous nodes which don't occur explicitly as subjects. The list of statements must be sorted if sorting is true. """ _anon, _incoming = self._topology(subj, context) # Is anonymous? if _anon and _incoming == 1 and not isinstance(subj, Formula): return # Forget it - will be dealt with in recursion if isinstance(subj, List): li = subj else: li = None if isinstance(subj, N3Set): #I hate having to sort things se = [mm for mm in subj] se.sort(Term.compareAnyTerm) li = self.store.newList(se) else: se = None if isinstance(subj, Formula) and subj is not context: sink.startFormulaSubject(auPair(subj)) self.dumpFormulaContents(subj, sink, sorting) sink.endFormulaSubject(auPair(subj)) # Subject is now set up # continue to do arcs elif _anon and (_incoming == 0 or (li is not None and not isinstance(li, EmptyList))): # Will be root anonymous node - {} or [] or () if subj is context: pass else: # Could have alternative syntax here if sorting: statements.sort(StoredStatement.comparePredObj) # @@ Needed now Fs are canonical? if se is not None: a = self.context.newBlankNode() sink.startAnonymousNode(auPair(a)) self.dumpStatement(sink, (context, self.store.owlOneOf, a, li), sorting) for s in statements: # "[] color blue." might be nicer. @@@ Try it? m = s.quad[0:2] + (a, s.quad[3]) self.dumpStatement(sink, m, sorting) sink.endAnonymousNode() return elif li is not None and not isinstance(li, EmptyList): for s in statements: p = s.quad[PRED] if p is not self.store.first and p is not self.store.rest: if verbosity() > 90: progress("Is list, has values for", `p`) break # Something to print (later) else: if subj.generated(): return # Nothing. if "l" not in self.flags: sink.startListSubject(auPair(subj)) for ele in subj: self.dumpStatement(sink, (context, self.store.li, subj, ele), sorting) sink.endListSubject(auPair(subj)) for s in statements: p = s.quad[PRED] if p is not self.store.first and p is not self.store.rest: self.dumpStatement(sink, s.quad, sorting) # Dump the rest outside the () else: # List but explicitly using first and rest sink.startAnonymousNode(auPair(subj)) self.dumpStatement(sink, (context, self.store.first, subj, subj.first), sorting) self.dumpStatement(sink, (context, self.store.rest, subj, subj.rest), sorting) for s in statements: self.dumpStatement(sink, s.quad, sorting) sink.endAnonymousNode() return else: if verbosity() > 90: progress("%s Not list, has property values." % `subj`) sink.startAnonymousNode(auPair(subj)) for s in statements: # "[] color blue." might be nicer. @@@ Try it? try: self.dumpStatement(sink, s.quad, sorting) except TooMuchRecursion: pass sink.endAnonymousNode() return # arcs as subject done if sorting: statements.sort(StoredStatement.comparePredObj) for s in statements: self.dumpStatement(sink, s.quad, sorting) def dumpStatement(self, sink, triple, sorting): "Dump one statement, including structure within object" context, pre, sub, obj = triple if (sub is obj and not isinstance(sub, CompoundTerm)) \ or (isinstance(obj, EmptyList)) \ or isinstance(obj, Literal): self._outputStatement(sink, triple) # Do 1-loops simply return if isinstance(obj, Formula): sink.startFormulaObject(auxPairs(triple)) self.dumpFormulaContents(obj, sink, sorting) sink.endFormulaObject(auPair(pre), auPair(sub)) return if isinstance(obj, NonEmptyList): if verbosity()>99: progress("List found as object of dumpStatement " + `obj` + context.debugString()) collectionSyntaxOK = ("l" not in self.flags) # if "x" in self.flags: # Xml can't serialize literal in collection # for ele in obj: # if isinstance(ele, Literal): # collectionSyntaxOK = 0 # break if collectionSyntaxOK: sink.startListObject(auxPairs(triple)) for ele in obj: self.dumpStatement(sink, (context, self.store.li, obj, ele), sorting) sink.endListObject(auPair(sub), auPair(pre)) else: sink.startAnonymous(auxPairs(triple)) self.dumpStatement(sink, (context, self.store.first, obj, obj.first), sorting) self.dumpStatement(sink, (context, self.store.rest, obj, obj.rest), sorting) sink.endAnonymous(auPair(sub), auPair(pre)) return if isinstance(obj, N3Set): a = self.context.newBlankNode() tempobj = [mm for mm in obj] #I hate sorting things - yosi tempobj.sort(Term.compareAnyTerm) tempList = self.store.newList(tempobj) sink.startAnonymous(auxPairs((triple[CONTEXT], triple[PRED], triple[SUBJ], a))) self.dumpStatement(sink, (context, self.store.owlOneOf, a, tempList), sorting) sink.endAnonymous(auPair(sub), auPair(pre)) return _anon, _incoming = self._topology(obj, context) if _anon and _incoming == 1: # Embedded anonymous node in N3 sink.startAnonymous(auxPairs(triple)) ss = context.statementsMatching(subj=obj) if sorting: ss.sort(StoredStatement.comparePredObj) for t in ss: self.dumpStatement(sink, t.quad, sorting) sink.endAnonymous(sub.asPair(), pre.asPair()) return self._outputStatement(sink, triple) BNodePossibles = None def canItbeABNode(formula, symbol): def returnFunc(): if BNodePossibles is not None: return symbol in BNodePossibles for quad in formula.statements: for s in PRED, SUBJ, OBJ: if isinstance(quad[s], Formula): if BNodePossibles is None: BNodePossible = quad[s].occurringIn( formula.existentials()) else: BNodePossible.update(quad[s].occurringIn( formula.existentials())) return symbol in BNodePossibles return returnFunc #ends cwm-1.2.1/swap/OrderedSequence.py0000644015216600007660000000511110640075637016024 0ustar syosisyosi"""Utility functions for ordered seqeunces When you are dealing with sequences which you know are ordered, then set operations are linear instead of square in the length of the sequences. This makes an ordered sequence a practical representation of a set. @@ Now python has sets, these should be used where the ordering is not otherwise necessary. @@ check $Id: OrderedSequence.py,v 1.2 2007/06/26 02:36:15 syosi Exp $ """ def merge(a,b): """Merge sorted sequences The fact that the sequences are sorted makes this faster""" i = 0 j = 0 m = len(a) n = len(b) result = [] while 1: if i==m: # No more of a, return rest of b return result + b[j:] if j==n: return result + a[i:] if a[i] < b[j]: result.append(a[i]) i = i + 1 elif a[i] > b[j]: result.append(b[j]) j = j + 1 else: # a[i]=b[j] result.append(a[i]) i = i + 1 j = j + 1 def intersection(a,b): """Find intersection of sorted sequences The fact that the sequences are sorted makes this faster""" i = 0 j = 0 m = len(a) n = len(b) # progress(" &&& Intersection of %s and %s" %(a,b)) result = [] while 1: if i==m or j==n: # No more of one, return what we have return result if a[i] < b[j]: i = i + 1 elif a[i] > b[j]: j = j + 1 else: # a[i]=b[j] result.append(a[i]) i = i + 1 j = j + 1 def minus(a,b): """Those in a but not in b for sorted sequences The fact that the sequences are sorted makes this faster""" i = 0 j = 0 m = len(a) n = len(b) result = [] # progress(" &&& minus of %s and %s" %(a,b)) while 1: if j==n: # No more of b, return rest of a return result + a[i:] if i==m: # No more of a, some of b - error raise ValueError("Cannot remove items" + `b[j:]`) return result + b[j:] if a[i] < b[j]: result.append(a[i]) i = i + 1 elif a[i] > b[j]: raise ValueError("Cannot remove item" + `b[j]`) j = j + 1 else: # a[i]=b[j] i = i + 1 j = j + 1 #______________________________________________ More utilities def indentString(str): """ Return a string indented by 4 spaces""" s = " " for ch in str: s = s + ch if ch == "\n": s = s + " " if s.endswith(" "): s = s[:-4] return s cwm-1.2.1/swap/myStore.py0000755015216600007660000001651510655653247014433 0ustar syosisyosi#! /usr/bin/python """ $Id: myStore.py,v 1.14 2007/08/06 16:13:56 syosi Exp $ Process-global store Global variables are often a bad idea. However, the majority of cwm applications involve just one RDF store. One store can contain many formulae. The main thing which these formulae of the same store share is the index with which names and strings are interned. Within a store, you can compare things by comparing memory addresses rather than the whole tring, uri or list. Therefore, it is normal to just use one store. When you do this, the store paremeter to most methods beceomes unnecessary, and you get a simpler API. That is what this module does. If you import it, you will get a global store. This will not stop you using other stores. You also get the Namespace() class which allows you to generate symbols easily. History: Spilt off from thing.py 2003-08-19 $Log: myStore.py,v $ Revision 1.14 2007/08/06 16:13:56 syosi A month of changes Revision 1.13 2007/06/26 02:36:15 syosi fix tabs Revision 1.12 2005/10/24 16:58:38 timbl --n3=B flag introduced. --why improved but not perfect. Revision 1.11 2004/08/08 01:44:49 syosi undo what I did last thing Friday. Those changes are nowhere near ready for the trunk Revision 1.9 2004/07/29 16:16:11 syosi rdflib tests in the default test suite Revision 1.8 2004/04/19 13:32:22 connolly trap __special_names__ in Namespace.__getattr__ so that pychecker can work Revision 1.7 2004/03/21 04:24:35 timbl (See doc/changes.html) on xml output, nodeID was incorrectly spelled. update.py provides cwm's --patch option. diff.py as independent progrem generates patch files for cwm --patch Revision 1.6 2004/03/09 23:55:50 connolly updated load to track change in llyn Revision 1.5 2004/03/06 20:39:38 timbl See http://www.w3.org/2000/10/swap/doc/changes.html for details - Regresssion test incorporates the RDF Core Positive Parser Tests except XMLLiteral & reification - xml:base support was added in the parser. - Use the --rdf=R flag to allow RDF to be parsed even when there is no enveloping tag - nodeid generated on RDF output - Automatically generated terms with no URIs sort after anything which has a URI. - Namespace prefix smarts on output - default ns used for that most frequently used. - suppresses namespace prefix declarations which are not actually needed in the output. - Cwm will also make up prefixes when it needs them for a namespace, and none of the input data uses one.- - Will not use namespace names for URIs which do not have a "#". Including a "/" in the flags overrides. Revision 1.4 2004/01/29 21:10:39 timbl ooops - ref to SYMBOL Revision 1.3 2004/01/28 23:03:00 connolly - added unit tests to confirm that symbol functions take ustrings - wrapped some comments at 79 chars per http://www.python.org/doc/essays/styleguide.html """ import uripath # Allow a strore provdier to register: store = None storeClass = None def setStoreClass(c): """Set the process-global class to be used to generate a new store if needed""" global storeClass storeClass = c def setStore(s): """Set the process-global default store to be used when an explicit store is not""" global store store = s def _checkStore(s=None): """Check that an explict or implicit stroe exists""" global store, storeClass if s != None: return s if store != None: return store if storeClass == None: import llyn # default assert storeClass!= None, "Some storage module must register with myStore.py before you can use it" store = storeClass() # Make new one return store def symbol(uri): """Create or reuse an interned version of the given symbol in the default store. and return it for future use >>> x = symbol(u'http://example.org/#Andr\\xe9') >>> y = symbol(u'http://example.org/#Andr\\xe9') >>> x is y 1 """ return _checkStore().newSymbol(uri) def literal(str, dt=None, lang=None): """Create or reuse, in the default store, an interned version of the given literal string and return it for future use >>> x = literal("#Andr\\xe9") >>> y = literal("#Andr\\xe9") >>> x is y 1 """ return _checkStore().newLiteral(str, dt, lang) def intern(v): return _checkStore().intern(v) def formula(): """Create or reuse, in the default store, a new empty formula (triple people think: triple store) and return it for future use""" return _checkStore().newFormula() #def bNode(str, context): # """Create or reuse, in the default store, a new unnamed node within the given # formula as context, and return it for future use""" # return _checkStore().newBlankNode(context) def existential(str, context, uri): """Create or reuse, in the default store, a new named variable existentially qualified within the given formula as context, and return it for future use""" return _checkStore().newExistential(context, uri) def universal(str, context, uri): """Create or reuse, in the default store, a named variable universally qualified within the given formula as context, and return it for future use""" return _checkStore().newUniversal(context, uri) def load(uri=None, openFormula=None, contentType=None, remember=1, flags=""): """Get and parse document. Guesses format if necessary. uri: if None, load from standard input. remember: if 1, store as metadata the relationship between this URI and this formula. Returns: top-level formula of the parsed document. Raises: IOError, SyntaxError, DocumentError """ return _checkStore().load(uri, openFormula=openFormula, contentType=contentType, remember=remember, flags=flags) def loadMany(uris, openFormula=None, referer=None): """Load a number of resources into the same formula Returns: top-level formula of the parsed information. Raises: IOError, SyntaxError, DocumentError """ return _checkStore().loadMany(uris, openFormula, referer=referer) def bind(prefix, uri): return _checkStore().bind(prefix, uri) class Namespace(object): """A shortcut for getting a symbols as interned by the default store >>> RDF = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#') >>> x = RDF.type >>> y = RDF.type >>> x is y 1 """ def __init__(self, name, store=None): if ':' not in name: #, "must be absolute: %s" % name base = uripath.base() name = uripath.join(base, name) self._name = name self.store = store self._seen = {} def __getattr__(self, lname): """get the lname Symbol in this namespace. lname -- an XML name (limited to URI characters) I hope this is only called *after* the ones defines above have been checked """ if lname.startswith("__"): # python internal raise AttributeError, lname return _checkStore(self.store).symbol(self._name+lname) def sym(self, lname): """For getting a symbol for an expression, rather than a constant. For, and from, pim/toIcal.py""" return _checkStore(self.store).symbol(self._name + lname) __getitem__ = sym def _test(): import llyn store = llyn.RDFStore() setStore(store) import doctest, myStore return doctest.testmod(myStore) if __name__ == "__main__": _test() cwm-1.2.1/swap/dbork/0000755015216600007660000000000010731073447013476 5ustar syosisyosicwm-1.2.1/swap/dbork/__init__.py0000644015216600007660000000000007633466076015610 0ustar syosisyosicwm-1.2.1/swap/dbork/TableRenderer.py0000755015216600007660000001735610640075640016601 0ustar syosisyosi#!/usr/bin/python """ $Id: TableRenderer.py,v 1.3 2007/06/26 02:36:16 syosi Exp $ TableRenderer - spit out data in a space-extended ascii table SYNOPSIS import TableRenderer a = [[1, 'a'], [2, 'b']] renderer = TableRenderer() renderer.addHeaders("int", "char") renderer.addData(a) print renderer.toString()+"\n" DESCRIPTION Display tabular data in a space-extended ascii table. METHODS TableRenderer() - Create a new TableRenderer. Takes arguments in hash or array form. -dataFilter - Specify code to call to manipute the data. This code should alter C<$_> to appear as it should in the serialized ascii table. -headerFilter - Specify code to call to manipute the header labels. This code should alter C<$_> to appear as it should in the serialized ascii table. addHeader - Add headers to the current TableRenderer data set. This is customarily done at the beginning, however, headers may be added anywhere in the data. Headers added after data will, in fact, appear after that data. The headers may be passed in as a list, an array ref, or an array of arrays. The following are all equivilent: renderer.addHeaders('letters', 'numbers') renderer.addHeaders(['letters', 'numbers']) renderer.addHeaders([['letters', 'numbers']]) renderer.addData('letters', 'numbers'), self.underline() See FORMATTING for affects of linefeeds in the data. addData - Add data to the current TableRenderer data set. The data may be passed in as a list, an array ref, or an array of arrays (see addHeader). See FORMATTING for affects of linefeeds in the data. underline ([index]) - Underline (highlight) the last row of data. If a numeric C<$index> is provided, underline only that column. toString - Serialize the added headers and data in an ascii table. FORMATTING Cell entries may have line feeds C<"\n"> embedded in them. In this case, the data is rendered on multiple lines, but the tabular format is preserved. Row data may have more columns than previous headers and data. This will have no affect accept that subsequent calls to L will underline the extra column. TESTING The test included in __main__ should produce this output: +------+------+------+ | my| your| | |letter|number| | |------|------| | | a| 1| | |------|------| | | b| 2| extra| | | |column| |------|------|------| | c| 3| | | d| 4| | | |------| | +------+------+------+ """ # Classes of data cells DATUM = 1 # normal HEADER = 2 # underlined import string from diag import progress # @@ for debugging def Assure(list, index, value): for i in range(len(list), index+1): list.append(value) def _x(char, width): ret = '' for i in range(width): ret = ret+char return ret class TableRenderer: def __init__(self, firstTitle=None, headerFilter=None, dataFilter=None): self.headerFilter = headerFilter self.dataFilter = dataFilter self.data = [] # [rows x columns] matrix of added data self.types = [] # type (DATUM or HEADER) of each row self.widths = [] # widths of each row self.heights = [] # heights of each row if (firstTitle): self.addHeaders(firstTitle) def addHeaders(self, data): self._addData(data, HEADER, self.headerFilter) def addData(self, data): self._addData(data, DATUM, self.dataFilter) def underline(self, index=None): if (index): self.data[-1][index][1] = HEADER else: for column in self.data[-1]: column[1] = HEADER def toString(self): ret = [] ret.append(self._hr()) for rowNo in range(len(self.data)): row = self.data[rowNo] ret.append(string.join(self._renderRow(self.data[rowNo], self.heights[rowNo]), "\n")) ret.append(self._hr()) return string.join(ret, "\n") def _addData(self, data, theType, filter): progress("@@ _addData data=%s theType=%s filter=%s " %(data, theType, filter)) progress("@@@ type ", type(data)) if type(data[0]) is not type([]): data = [data] # resolve ambiguous calling convention try: data[0].isdigit() # Lord, there's got to be a better way. @@@ (@@ to do what? --tim) data = [data] except AttributeError, e: data = data # @@? what does this do - tim mean "pass"? for row in data: rowEntry = [] self.data.append(rowEntry) self.types.append(DATUM) self.heights.append(0) for columnNo in range(len(row)): if (columnNo == len(self.widths)): self.widths.append(0) datum = str(row[columnNo]) if (filter): datum = filter(datum) self._checkWidth(datum, len(self.data) - 1, columnNo) rowEntry.append([datum, theType]) def _hr(self): ret = [] for width in self.widths: ret.append(_x('-', width)) ret[:0] = [''] ret.append('') return string.join(ret, '+') def _checkWidth(self, datum, rowNo, column): lines = string.split(str(datum), "\n") for line in lines: if (len(line) > self.widths[column]): self.widths[column] = len(line) if (len(lines) > self.heights[rowNo]): self.heights[rowNo] = len(lines) def _renderRow(self, row, height): footer = [] rows = [] needsFooter = 0 for column in range(len(self.widths)): if (column == len(row)): row.append(['', DATUM]) width = self.widths[column] datum = row[column] lines = string.split(datum[0], "\n") lineNo = 0 while (lineNo < len(lines)): line = lines[lineNo] Assure(rows, lineNo, []) Assure(rows[lineNo], column, '') rows[lineNo][column] = _x(' ', (width - len(line))) + line lineNo = lineNo+1 while (lineNo < height): Assure(rows, lineNo, []) Assure(rows[lineNo], column, ' ') rows[lineNo][column] = _x(' ', width) lineNo = lineNo+1 if (datum[1] == HEADER): footer.append(_x('-', width)) needsFooter = needsFooter+1 else: footer.append(_x(' ', width)) # might need one on another column if (needsFooter): rows.append(footer) ret = [] for row in rows: row[:0] = [''] row.append('') ret.append(string.join(row, '|')) return ret if __name__ == '__main__': import re def df(datum): return re.sub("trimMe", "", datum) # Any data starting with "trimMe" will have that part removed. # df = None # lamda a: re.sub("trimMe", "", a) renderer = TableRenderer(dataFilter = df) # Add two two-line headers renderer.addHeaders(["my\nletter", "your\nnumber"]) # Add a row of data that's just crying out to be filtered. renderer.addData(['trimMea', 'trimMe1']) # Underline that last row. renderer.underline() # Add another row, this time with an unexpected extra column ... renderer.addData(['trimMeb', 'trimMe2', "extra\ncolumn"]) # ... and underline it. renderer.underline() # Add a two dimensional matrix of data. renderer.addData([['c', 3], ['d', 4]]) # Underline just column 1 of the previous row. renderer.underline(index=1) # Let's see what hath we wrought. print renderer.toString()+"\n" cwm-1.2.1/swap/dbork/SqlDB.py0000755015216600007660000011102010640075640015007 0ustar syosisyosi#!/usr/bin/python """ $Id: SqlDB.py,v 1.26 2007/06/26 02:36:16 syosi Exp $ """ #CONTEXT = 0 #PRED = 1 #SUBJ = 2 #OBJ = 3 CONTEXT = 5 PRED = 0 SUBJ = 1 OBJ = 2 PARTS = PRED, SUBJ, OBJ ALL4 = CONTEXT, PRED, SUBJ, OBJ import string import sys import re import imp import MySQLdb import TableRenderer from TableRenderer import TableRenderer from diag import progress, progressIndent, verbosity, tracking from RDFSink import FORMULA, LITERAL, ANONYMOUS, SYMBOL SUBST_NONE = 0 SUBST_PRED = 1 SUBST_SUBJ = 2 SUBST_OBJ = 4 RE_symbol = re.compile("\?(?P\w+)$") RE_URI = re.compile("\<(?P[^\>]+)\>$") RE_literal = re.compile("\"(?P\w+)\"$") def Assure(list, index, value): for i in range(len(list), index+1): list.append(None) list[index] = value def NTriplesAtom(s, rowBindings, interner): if (s._URI()): subj = interner.intern((SYMBOL, s._URI())) elif (s._literal()): subj = interner.intern((LITERAL, s._literal())) else: try: subj = rowBindings[s.symbol()] except TypeError, e: subj = '"'+str(rowBindings[s.symbol()])+'"' except KeyError, e: print s.toString() print s._literal() subj = '"'+"KeyError:"+str(e)+" "+s.symbol()+'"' return subj def ShowStatement(statement): c, p, s, o = statement return '%s %s %s .' % (s, p, o) class QueryPiece: "base class for query atoms" def __init__(self, datum): self.datum = datum def symbol(self): return None def _URI(self): return None def _literal(self): return None def _const(self): return None def getList(self): return None class ConstantQueryPiece(QueryPiece): "" def _const(self): return self.datum def toString(self): return "\""+self.datum+"\"" class UriQueryPiece(ConstantQueryPiece): "" def _URI(self): return self.datum def toString(self): return "<"+self.datum+">" class LiteralQueryPiece(ConstantQueryPiece): "" def _literal(self): return self.datum def toString(self): return "<"+self.datum+">" class VariableQueryPiece(QueryPiece): "" def __init__(self, symbol, index, existential): QueryPiece.__init__(self, symbol) self.varIndex = index self.existential = existential def symbol(self): return self.datum def getVarIndex(self): return self.varIndex def toString(self): return "?"+self.datum+"" class SetQueryPiece(QueryPiece): "" def __init__(self, datum): QueryPiece.__init__(self, datum) self.disjunction = 0 self.nope = 0 def getList(self): return self.datum def isDisjunction(self): return None def isNot(self): return None def toString(self): ret = [] for s in self.datum: row = [] row.append("(") row.append(s[0].toString()) row.append(" ") row.append(s[1].toString()) row.append(" ") row.append(s[2].toString()) row.append(")") ret.append(string.join(row, "")) return string.join(ret, "\n") class ResultSet: "" def __init__(self): self.varIndex = {} self.indexVar = [] self.results = [] self.symbols = {} self.fragments = {} def myIntern(self, q, index, variables, existentials): if hasattr(q, 'fragid'): symbol = q.fragid # re.sub(':', '_', q.qname()) else: symbol = q.string try: existentials.index(q) try: index = self.varIndex[q] symbol = self.fragments[q] except KeyError, e: index = self.varIndex[q] = len(self.indexVar) self.indexVar.append(q) symbol = self.ensureUniqueSymbol(symbol, q) return (VariableQueryPiece(symbol, index, 1)) # uri1#foo and uri2#foo may collide except ValueError, e: try: variables.index(q) try: index = self.varIndex[q] symbol = self.fragments[q] except KeyError, e: index = self.varIndex[q] = len(self.indexVar) self.indexVar.append(q) symbol = self.ensureUniqueSymbol(symbol, q) return (VariableQueryPiece(symbol, index, 0)) except ValueError, e: try: return (LiteralQueryPiece(q.string)) except AttributeError, e: try: return (UriQueryPiece(q.uriref())) except Exception, e: raise RuntimeError, "what's a \""+q+"\"?" def ensureUniqueSymbol(self, symbol, q): i = 0 base = symbol while self.symbols.has_key(symbol): symbol = base + `i` i = i + 1 # This is always called for new symbols so no need to check the # existent fragment to symbol mapping. # If you don't believe me, uncomment the following: #if self.symbols.has_key(symbol): # if self.symbols[symbol].uriref() == q.uriref(): # print "!!re-used symbol '%s' used for %s and %s" %(symbol, self.symbols[symbol].uriref(), q.uriref()) # else: # print "duplicate symbol '%s' used for %s and %s" %(symbol, self.symbols[symbol].uriref(), q.uriref()) self.symbols[symbol] = q self.fragments[q] = symbol return symbol def buildQuerySetsFromCwm(self, sentences, variables, existentials): set = [] for sentence in sentences: sentStruc = [] set.append(sentStruc) sentStruc.append(self.myIntern(sentence.quad[1], 0, variables, existentials)) sentStruc.append(self.myIntern(sentence.quad[2], 1, variables, existentials)) sentStruc.append(self.myIntern(sentence.quad[3], 2, variables, existentials)) return SetQueryPiece(set) def buildQuerySetsFromArray(self, sentences): # /me thinks that one may group by ^existentials set = [] for sentence in sentences: sentStruc = [] set.append(sentStruc) for word in sentence: m = RE_symbol.match(word) if (m): symbol = m.group("symbol") try: index = self.varIndex[symbol] except KeyError, e: index = self.varIndex[symbol] = len(self.indexVar) self.indexVar.append(symbol) sentStruc.append(VariableQueryPiece(symbol, index, 0)) else: m = RE_URI.match(word) if (m): sentStruc.append(UriQueryPiece(m.group("uri"))) else: m = RE_literal.match(word) if (m): sentStruc.append(LiteralQueryPiece(m.group("literal"))) else: raise RuntimeError, "what's a \""+word+"\"?" return SetQueryPiece(set) def getVarIndex(self, symbol): return self.varIndex[symbol] def setNewResults(self, newResults): self.results = newResults def toString(self, flags): #df = lambda o: o #renderer = TableRenderer(flags, dataFilter=df) renderer = TableRenderer() renderer.addHeaders(self.indexVar) if (len(self.results) == 0): renderer.addData(['-no solutions-']) elif (len(self.results) == 1 and len(self.results[0]) == 0): renderer.addData(['-initialized-']) else: renderer.addData(self.results) return renderer.toString() class RdfDBAlgae: "" class SqlDBAlgae(RdfDBAlgae): def __init__(self, baseURI, tableDescModuleName, user, password, host, database, meta, pointsAt, interner, duplicateFieldsInQuery=0, checkUnderConstraintsBeforeQuery=1, checkOverConstraintsOnEmptyResult=1): # Grab _AllTables from tableDescModuleName, analogous to # import tableDescModuleName # from tableDescModuleName import _AllTables self.user = user if (password): self.password = password else: self.password = "" self.host = host self.database = database self.connection = None self.duplicateFieldsInQuery = duplicateFieldsInQuery self.checkUnderConstraintsBeforeQuery = checkUnderConstraintsBeforeQuery self.checkOverConstraintsOnEmptyResult = checkOverConstraintsOnEmptyResult self.interner = interner # this compilation/import of schemas looks over-engineered, to me --DWC try: fp, path, stuff = imp.find_module(tableDescModuleName) tableDescModule = imp.load_module(tableDescModuleName, fp, path, stuff) if (fp): fp.close self.structure = tableDescModule._AllTables except ImportError, e: print tableDescModuleName, " not found\n" self.structure = None except TypeError, e: self.structure = None self.baseUri = baseURI self.predicateRE = re.compile(baseURI.uri+ "(?P\w+)\#(?P[\w\d\%\.\&]+)$") if (self.structure == None): if verbosity() > 10: progress("analyzing mysql://%s/%s\n" % (host, database)) self.structure = {} cursor = self._getCursor() cursor.execute("SHOW TABLES") while 1: tableName_ = cursor.fetchone() if not tableName_: break self._buildTableDesc(tableName_[0], meta, pointsAt) # SQL query components: self.tableAliases = []; # FROM foo AS bar self.selects = []; # SELECT foo self.labels = []; # AS bar self.selectPunct = []; # pretty printing self.wheres = []; # WHERE foo=bar # Variable, table, column state: self.whereStack = []; # Save WHERES for paren exprs. self.symbolBindings = {}; # Table alias for a given symbol. self.tableBindings = {}; # Next number for a table alias. self.objectBindings = []; # External key targs in SELECT. self.scalarBindings = []; # Literals in SELECT. self.fieldBindings = {}; # Which alias.fields are in SELECT. self.disjunctionBindings = {}; # Which OR clauses are in SELECT. self.scalarReferences = {}; # Where scalar variables were used. # Keeping track of [under]constraints self.constraintReaches = {}; # Transitive closure of all aliases # constrained with other aliases. self.constraintHints = {}; # Aliases constrained in some but not # all paths of an OR. Handy diagnostic. self.overConstraints = {}; # Redundent constraints between aliases. def _buildTableDesc(self, table, meta, pointsAt): self.structure[table] = { '-fields' : {}, '-primaryKey' : [] } cursor = self._getCursor() cursor.execute("SHOW FIELDS FROM " + table) while 1: name_type_null_key_default_extra_ = cursor.fetchone() if not name_type_null_key_default_extra_: break name = name_type_null_key_default_extra_[0] self.structure[table]['-fields'][name] = {} target = meta.any(pred=pointsAt, subj=self.baseUri.store.internURI(self.baseUri.uri+table+"#"+name)) if (target): self.structure[table]['-fields'][name]['-target'] = self.predicateRE.match(target.uriref()).groups() #print "%s#%s -> %s#%s" % (table, name, # self.structure[table]['-fields'][name]['-target'][0], # self.structure[table]['-fields'][name]['-target'][1]) cursor = self._getCursor() cursor.execute("SHOW INDEX FROM " + table) while 1: tableName_nonUnique_keyName_seq_columnName_ = cursor.fetchone() if not tableName_nonUnique_keyName_seq_columnName_: break (tableName, nonUnique, keyName, seq, columnName, d,d,d,d,d) = tableName_nonUnique_keyName_seq_columnName_ if (keyName == 'PRIMARY'): self.structure[table]['-primaryKey'].append(columnName) def _processRow(self, row, statements, implQuerySets, resultSet, messages, flags): #for iC in range(len(implQuerySets)): # print implQuerySets[iC] for term in implQuerySets.getList(): self._walkQuery(term, row, flags) if (self.checkUnderConstraintsBeforeQuery): self._checkForUnderConstraint() self.selectPunct.pop(0) self.selectPunct.append('') query = self._buildQuery(implQuerySets) messages.append("query SQLselect \"\"\""+query+"\"\"\" .") cursor = self._getCursor() cursor.execute(query) #if (cursor.rows() == 0 and self.checkOverConstraintsOnEmptyResult): # self._checkForOverConstraint; nextResults, nextStatements = self._buildResults(cursor, implQuerySets, row, statements) return nextResults, nextStatements def _getCursor(self): if (self.connection == None): self.connection = MySQLdb.connect(self.host, self.user, self.password, self.database) cursor = self.connection.cursor() return cursor def _walkQuery (self, term, row, flags): if (0): # Handle ORs here. tmpWheres = self.wheres else: c = term # @@@ NUKE c p = c[PRED] s = c[SUBJ] o = c[OBJ] sTable, field, oTable, targetField = self._lookupPredicate(p._URI()) sAlias = None; oAlias = None; if (s._const()): uri = s._URI() if (uri): #if (uri.endswith("#item")): # uri = uri[:-5] sAlias = self._bindTableToConstant(sTable, s) else: raise RuntimeError, "not implemented" else: sAlias = self._bindTableToVariable(sTable, s) if (o._const()): if (oTable): oAlias = self._bindTableToConstant(oTable, o) self._addWhere(sAlias+"."+field+"="+oAlias+"."+targetField, term) self._adddReaches(sAlias, oAlias, term) else: self._addWhere(sAlias+"."+field+"=\""+o._const()+"\"", term) else: if (oTable): oAlias = self._bindTableToVariable(oTable, o) self._addWhere(sAlias+"."+field+"="+oAlias+"."+targetField, term) self._addReaches(sAlias, oAlias, term) else: try: scalarReference = self.scalarReferences[o.symbol()] firstAlias, firstField = scalarReference self._addWhere(sAlias+"."+field+"="+firstAlias+"."+firstField, term) self._addReaches(sAlias, firstAlias, term) except KeyError, e: col = self._addSelect(sAlias+"."+field, o.symbol()+"_"+field, "\n ") self.scalarBindings.append([o, [col]]) self.scalarReferences[o.symbol()] = [sAlias, field] def _preferredID (self, table, alias, qp): pk = self.structure[table]['-primaryKey'] try: pk.isdigit() # Lord, there's got to be a better way. @@@ pk = [pk] except AttributeError, e: pk = pk cols = [] fieldz = [] for iField in range(len(pk)): field = pk[iField] if (iField == len(pk)-1): punct = "\n " else: punct = ' ' col = self._addSelect(alias+"."+field, qp.symbol()+"_"+field, punct) cols.append(col) fieldz.append(field) self.objectBindings.append([qp, cols, fieldz, table]) # self.selectPunct.pop() def _addSelect (self, name, label, punct): try: ret = self.fieldBindings[name] if (self.duplicateFieldsInQuery): raise KeyError, "force duplicate fields" except KeyError, e: self.selects.append(name) self.labels.append(label) self.selectPunct.append(punct) self.fieldBindings[name] = ret = len(self.selects)-1 return ret def _bindTableToVariable (self, table, qp): try: self.symbolBindings[qp.symbol()] except KeyError, e: self.symbolBindings[qp.symbol()] = {} try: binding = self.symbolBindings[qp.symbol()][table] except KeyError, e: try: maxForTable = self.tableBindings[table] except KeyError, e: maxForTable = self.tableBindings[table] = 0 binding = table+"_"+repr(maxForTable) self.symbolBindings[qp.symbol()][table] = binding self.tableBindings[table] = self.tableBindings[table] + 1 self.tableAliases.append([table, binding]) self._preferredID(table, binding, qp) # (A_0.u0, A_0.u1) return binding def _bindTableToConstant (self, table, qp): uri = qp._URI() #if (uri.endswith("#item")): # uri = uri[:-5] # assert (0, "don't go there") try: self.symbolBindings[uri] except KeyError, e: self.symbolBindings[uri] = {} try: binding = self.symbolBindings[uri][table] except KeyError, e: try: maxForTable = self.tableBindings[table] except KeyError, e: maxForTable = self.tableBindings[table] = 0 binding = table+"_"+repr(maxForTable) self.symbolBindings[uri][table] = binding self.tableBindings[table] = self.tableBindings[table] + 1 self.tableAliases.append([table, binding]) for where in self._decomposeUniques(uri, binding, table): self._addWhere(where, qp) return binding def _lookupPredicate(self, predicate): m = self.predicateRE.match(predicate) assert m, "Oops predicate=%s doesn't match %s" %(predicate, self.predicateRE.pattern) table = m.group("table") field = m.group("field") try: fieldDesc = self.structure[table]['-fields'][field] except KeyError, e: fieldDesc = None try: target = fieldDesc['-target'] return table, field, target[0], target[1] except KeyError, e: target = None return table, field, None, None def _uniquesFor(self, table): try: pk = self.structure[table]['-primaryKey'] return pk; except KeyError, e: raise RuntimeError, "no primary key for table \"table\"" def _composeUniques(self, values, table): segments = [] pk = self.structure[table]['-primaryKey'] try: pk.isdigit() # Lord, there's got to be a better way. @@@ pk = [pk] except AttributeError, e: pk = pk for field in pk: lvalue = CGI_escape(field) rvalue = CGI_escape(str(values[field])) segments.append(lvalue+"."+rvalue) value = string.join(segments, '.') return self.baseUri.uri+table+'#'+value; # '.'+value+"#item" def _decomposeUniques(self, uri, tableAs, table): m = self.predicateRE.match(uri) assert m, "Oops term=%s doesn't match %s" %(uri, self.predicateRE.pattern) table1 = m.group("table") field = m.group("field") if (table1 != table): raise RuntimeError, "\""+uri+"\" not based on "+self.baseUri.uri+table recordId = CGI_unescape(field) parts = string.split(recordId, '.') constraints = []; while parts: field, value = parts[:2] field = unescapeName(field) value = unescapeName(value) constraints.append(tableAs+"."+field+"=\""+value+"\"") del parts[:2] return constraints def _buildQuery (self, implQuerySets): # assemble the query segments = []; segments.append('SELECT ') tmp = [] for i in range(len(self.selects)): # Note, the " AS self.labels[$i]" is just gravy -- nice in logs. if (i == len(self.selects) - 1): comma = '' else: comma = ',' if (self.labels[i] == None): asStr = '' else: asStr = " AS "+self.labels[i] tmp.append(self.selects[i]+asStr+comma+self.selectPunct[i]) segments.append(string.join(tmp, '')) segments.append("\nFROM ") tmp = [] for i in range(len(self.tableAliases)): tmp.append(self.tableAliases[i][0]+" AS "+self.tableAliases[i][1]) segments.append(string.join (tmp, ', ')) where = whereStr = self._makeWheres(implQuerySets.disjunction, implQuerySets.nope) if (where): segments.append("\nWHERE ") segments.append(whereStr) # if ($flags->{-uniqueResults}) { # push (@$segments, ' GROUP BY '); # push (@$segments, CORE::join (',', @{self.labels})); # } elsif (my $groupBy = $flags->{-groupBy}) { # if (@$groupBy) { # push (@$segments, ' GROUP BY '); # push (@$segments, CORE::join (',', @$groupBy)); # } # } return string.join(segments, '') def _buildResults (self, cursor, implQuerySets, row, statements): nextResults = [] nextStatements = [] uniqueStatementsCheat = {} while 1: answerRow = cursor.fetchone() if not answerRow: break col = 1 nextResults.append(row[:]) nextStatements.append(statements[:]) # Grab objects from the results rowBindings = {} for binding in self.objectBindings: queryPiece, cols, fieldz, table = binding valueHash = {} for i in range(len(cols)): col = cols[i] field = fieldz[i] valueHash[field] = answerRow[col] uri = self.interner.intern((SYMBOL, self._composeUniques(valueHash, table))) Assure(nextResults[-1], queryPiece.getVarIndex(), uri) # nextResults[-1][queryPiece.getVarIndex()] = uri rowBindings[queryPiece.symbol()] = uri # Grab literals from the results for binding in self.scalarBindings: queryPiece, cols = binding st = answerRow[cols[0]] if (hasattr(st, 'strftime')): st = self.interner.intern((LITERAL, st.strftime())) # @@FIXME: should use builtin date data type else: st = self.interner.intern((LITERAL, str(st))) #@@datatypes? Assure(nextResults[-1], queryPiece.getVarIndex(), st) # nextResults[-1][queryPiece.getVarIndex()] = uri rowBindings[queryPiece.symbol()] = st # Grab sub-expressions from the results for qpStr in self.disjunctionBindings.keys(): binding = self.disjunctionBindings[qpStr] qp, cols = binding rowBindings[qp] = self.interner.intern((LITERAL, answerRow[cols[0]])) # ... and the supporting statements. foo = self._bindingsToStatements(implQuerySets, rowBindings, uniqueStatementsCheat) for statement in foo: nextStatements[-1].append(statement) #for s in nextStatements->[-1] # $self->{-db}->applyClosureRules($self->{-db}{INTERFACES_implToAPI}, # $s->getPredicate, $s->getSubject, $s->getObject, # $s->getReifiedAs, $s->getReifiedIn, $s->getAttribution); return nextResults, nextStatements def _bindingsToStatements (self, term, rowBindings, uniqueStatementsCheat): if (term.__class__.__name__ == "SetQueryPiece"): ret = [] if (term.nope == 0): for subTerm in term.getList(): if (term.disjunction): binding = self.disjunctionBindings[subTerm] qp, cols = binding if (rowBindings[qp]): foo = self._bindingsToStatements(subTerm, rowBindings, uniqueStatementsCheat) for statement in foo: ret.append(statement) else: foo = self._bindingsToStatements(subTerm, rowBindings, uniqueStatementsCheat) for statement in foo: ret.append(statement) return ret pred = NTriplesAtom(term[PRED], rowBindings, self.interner) subj = NTriplesAtom(term[SUBJ], rowBindings, self.interner) obj = NTriplesAtom(term[OBJ], rowBindings, self.interner) try: statement = uniqueStatementsCheat[pred][subj][obj] except KeyError, e: statement = ['', pred, subj, obj] try: byPred = uniqueStatementsCheat[pred] try: bySubj = byPred[subj] except KeyError, e: uniqueStatementsCheat[pred][subj] = {obj : statement} except KeyError, e: uniqueStatementsCheat[pred] = {subj : {obj : statement}} return [statement] def _addReaches (self, frm, to, term): # Entries are a list of paths (lists) that connect frm to to and visa # versa. The first path is the first way the tables were constrained. # Additional paths represent over-constraints. self._fromReachesToAndEverythingToReaches(frm, to, [term]) for fromFrom in self.constraintReaches[frm].keys(): if (fromFrom != to): self._fromReachesToAndEverythingToReaches(fromFrom, to, [self.constraintReaches[frm][fromFrom], term]) def _fromReachesToAndEverythingToReaches (self, frm, to, path): try: self.constraintReaches[frm] except KeyError, e: self.constraintReaches[frm] = {} try: self.constraintReaches[to] except KeyError, e: self.constraintReaches[to] = {} try: self.overConstraints[frm][to].append(path) except KeyError, e: # print " [c]-[g]->[p]\n" try: for toTo in self.constraintReaches[to].keys(): toPath = [self.constraintReaches[to][toTo], path] try: self.overConstraints[frm][toTo].append(path) except KeyError, e: self.constraintReaches[frm][toTo] = toPath self.constraintReaches[toTo][frm] = toPath except KeyError, e: self.constraintReaches[to] = {} self.constraintReaches[frm][to] = path self.constraintReaches[to][frm] = path def _showConstraints (self): ret = [] for frm in self.constraintReaches.keys(): for to in self.constraintReaches[frm].keys(): ret.append(self._showConstraint(frm, to)) return string.join(ret, "\n") # def _showConstraint (self, frm, to): # my pathStr = join (' - ', map {_->toString({-brief => 1})} @{self.constraintReaches[frm][to]}) # return "frm:to: pathStr" def _mergeCommonConstraints (self, reachesSoFar, term, subTerm): for fromTable in self.constraintReaches.keys(): try: reachesSoFar[fromTable] except KeyError, e: try: self.constraintHints[fromTable] except KeyError, e: self.constraintHints[fromTable] = {} # push (@{self.constraintHints[fromTable]}, "for fromTable") for toTable in self.constraintReaches[fromTable].keys(): try: reachesSoFar[fromTable][toTable] except KeyError, e: self.constraintHints[fromTable][toTable].append([term, subTerm]) self.constraintHints[toTable][fromTable].append([term, subTerm]) for fromTable in eachesSoFa.keys(): try: self.constraintReaches[fromTable] except KeyError, e: try: self.constraintHints[fromTable] except KeyError, e: self.constraintHints[fromTable] = {} # push (@{self.constraintHints[fromTable]}, "for fromTable") for toTable in reachesSoFar[fromTable].keys(): try: self.constraintReaches[fromTable][toTable] except KeyError, e: del reachesSoFar[fromTable][toTable] del reachesSoFar[toTable][fromTable] self.constraintHints[fromTable][toTable].append([term, subTerm]) self.constraintHints[toTable][fromTable].append([term, subTerm]) def _checkForUnderConstraint (self): firstAlias = self.tableAliases[0][1] messages = [] for iAliasSet in range(1, len(self.tableAliases)): table, alias = self.tableAliases[iAliasSet] try: self.constraintReaches[firstAlias][alias] except KeyError, e: messages.append(" %s not constrained against %s" % (firstAlias, alias)) if (self.constraintReaches.has_key(firstAlias)): for reaches in self.constraintReaches[firstAlias].keys(): messages.append(" %s reaches %s" % (firstAlias, reaches)) else: messages.append(" %s reaches NOTHING" % (firstAlias)) if (self.constraintReaches.has_key(alias)): for reaches in self.constraintReaches[alias].keys(): messages.append(" %s reaches %s" % (alias, reaches)) else: messages.append(" %s reaches NOTHING" % (alias)) if (self.constraintHints.has_key(firstAlias) and self.constraintHints[firstAlias].has_key(alias)): for terms in self.constraintHints[firstAlias][alias]: constrainedByStr = terms[1].toString({-brief : 1}) constrainedInStr = terms[0].toString({-brief : 1}) messages.append(" partially constrained by 'constrainedByStr' in 'constrainedInStr'") if (len(messages) > 0): raise RuntimeError, "underconstraints exception:\n"+string.join(messages, "\n") def _checkForOverConstraint (self): messages = [] done = {} for frm in self.overConstraints.keys(): try: done[frm] except KeyError, e: break done[frm] = 1 for to in self.overConstraints[frm].keys(): try: done[frm] except KeyError, e: break if (to != frm): messages.append(" frm over-constrained against to"._showPath(self.constraintReaches[frm][to])) for path in self.overConstraints[frm][to]: messages.append(' '._showPath(path)) if (len(messages)): raise RuntimeError, "overconstraints exception:\n"+string.join(messages, "\n") def _showPath(path) : # static pathStrs = [] for term in path: pathStrs.append(term.toString({-brief : 1})) return string.join(pathStrs, ' - ') def _addWhere (self, condition, term): self.wheres.append(condition) def _pushWheres (self): self.whereStack.append(self.wheres) self.wheres = [] def _popWheres (self, disjunction, negation): innerWheres = self._makeWheres(disjunction, negation) self.wheres = self.whereStack.pop() if (innerWheres): self.wheres.push("("+innerWheres+")") def _makeWheres (self, disjunction, negation): if (len(self.wheres) < 1): return '' if (disjunction): junction = "\n OR " else: junction = "\n AND " ret = string.join(self.wheres, junction) if (negation): return "NOT (ret)" else: return ret def unescapeName(toEscape): """@@what is this actually doing? --DWC """ a = toEscape # re.sub("\_e", "=", a) a = re.sub("\_e", "\=", a) a = re.sub("\_a", "\&", a) a = re.sub("\_h", "\-", a) a = re.sub("\_d", "\.", a) a = re.sub("\_p", "\%", a) a = re.sub("\_u", "_", a) a = CGI_unescape(a) return a def CGI_escape(a): """@@what is this actually doing? --DWC It seems to turn strings into XML attribute value literals; why is it called CGI_escape? Note the python library has CGI support. """ a = re.sub("&", "\&\;", a) a = re.sub("\"", "\"\;", a) return a def CGI_unescape(a): """@@ what is this actually doing? --DWC """ a = re.sub("\&\;", "&", a) a = re.sub("\"\;", "\"", a) return a if __name__ == '__main__': s = [["", "?urisRow", ""], ["", "?acl", "?access"], ["", "?acl", "?aacl"], ["", "?acl", "?accessor"], ["", "?g1", "?accessor"], ["", "?g1", "?u1"], ["", "?u1", "\"eric\""], ["", "?urisRow", "?aacl"]] rs = ResultSet() qp = rs.buildQuerySetsFromArray(s) a = SqlDBAlgae("mysql://rdftest@swada.w3.org/OrderTracking/", "AclSqlObjects") messages = [] nextResults, nextStatements = a._processRow([], [], qp, rs, messages, {}) rs.results = nextResults def df(datum): return re.sub("http://localhost/SqlDB#", "mysql:", datum) print string.join(messages, "\n") print "query matrix \"\"\""+rs.toString({'dataFilter' : None})+"\"\"\" .\n" for solutions in nextStatements: print "query solution {" for statement in solutions: print ShowStatement(statement) print "} ." blah = """ testing with `python2.2 ./cwm.py test/dbork/aclQuery.n3 -think` aclQuery -- :acl acls:access :access . sentences[1].quad -- (attrib, s, p, o) (0_work, access, acl, access) p.uriref() -- 'file:/home/eric/WWW/2000/10/swap/test/dbork/aclQuery.n3#acl' s.uriref() -- 'mysql://rdftest@swada.w3.org/OrderTracking/acls#access' o.uriref() -- 'file:/home/eric/WWW/2000/10/swap/test/dbork/aclQuery.n3#access' existentials[1] == sentences[1].quad[2] -- 1 n s b 576 c s b 2352 c s this one works: s = [["", "?urisRow", ""], ["", "?urisRow", "?aacl"], ["", "?acl", "?aacl"], ["", "?acl", "?access"], ["", "?u1", "\"eric\""], ["", "?g1", "?u1"], ["", "?g1", "?accessor"], ["", "?acl", "?accessor"]] """ cwm-1.2.1/swap/diag.py0000644015216600007660000000407010642726422013653 0ustar syosisyosi""" Use this with diagnostics so that it can be changed as necessary For example, sometimes want on stdout maybe or in a scroll window.... Let's replace this with pythong logging stuff. at least get it to the point where "make quick" in swap/test works. There is some wierd stuff here because TimBL and I couldn't figure out how to share the chatty global across modules. Surely Daniel K and DanC should be able figure that out. """ import sys import os, traceback from codecs import utf_8_encode ##lineCount = [0] def progress(*args): level = len(traceback.extract_stack()) sys.stderr.write(" "*level) for a in args: i = 0 a = unicode(a) while 1: ## lineCount[0] += 1 i = a.find("\n", i) if i < 0: break a = a[:i+1] + (" "*level) + a[i+1:] i = i+1 q = utf_8_encode(u"%s " % (a,))[0] sys.stderr.write(q) ## if lineCount[0] > 20: ## lineCount[0] = 0 ## sys.stdin.readline() sys.stderr.write("\n") global chatty_flag # verbosity debug flag #chatty_flag =0 chatty_flag = int(os.environ.get("CWM_VERBOSITY", 0)) global print_all_file_names print_all_file_names = int(os.environ.get("CWM_LIST_FILES", 0)) global file_list file_list = [] global tracking tracking = 0 # Are we keeping reason information for proof generation? def setTracking(x): global tracking chatty_flag = x def setVerbosity(x): global chatty_flag chatty_flag = x def verbosity(): global chatty_flag return chatty_flag def printState(prefix="#trace# "): """Output the (caller's) function name and local variables """ import sys frame = sys._getframe(1) # caller's state sys.stderr.write(prefix+ str(frame.f_code.co_name)+" "+ str(frame.f_locals['self'])+"\n") for varname in frame.f_locals.keys(): if varname == "self": continue sys.stderr.write("%s %-8s: %s\n" % (prefix, varname, frame.f_locals[varname])) sys.stderr.write(prefix+"\n") cwm-1.2.1/swap/cwm_crypto.py0000755015216600007660000001402310267737340015143 0ustar syosisyosi#!/usr/bin/python """ Cryptographic Built-Ins for CWM/Llyn The continuing story of cryptographic builtins. cf. http://www.w3.org/2000/10/swap/cwm.py & http://www.amk.ca/python/writing/pycrypt/node16.html """ __author__ = 'Sean B. Palmer' __cvsid__ = '$Id: cwm_crypto.py,v 1.11 2005/07/21 15:22:59 syosi Exp $' __version__ = '$Revision: 1.11 $' import md5, sha, binascii, quopri, base64 from term import Function, ReverseFunction, LightBuiltIn USE_PKC = 1 if USE_PKC: try: import Crypto.Util.randpool as randpool import Crypto.PublicKey.RSA as RSA except ImportError: USE_PKC = 0 # 'we failed') # Some stuff that we need to know about CRYPTO_NS_URI = 'http://www.w3.org/2000/10/swap/crypto#' # A debugging function... def formatObject(obj): """Print the various bits found within a key (works on any object).""" if ' ' in repr(obj): result = repr(obj)[1:].split(' ')[0]+'\n' else: result = '\n' for n in dir(obj): result += str(n)+' '+str(getattr(obj, n))+'\n' return '[[[%s]]]' % result # Functions for constructing keys, and formatting them for use in text def newKey(e, n, d=None, p=None, q=None): """Create a new key.""" key = RSA.RSAobj() # Create a new empty RSA Key key.e, key.n = e, n # Feed it the ee and modulus if d is not None: key.d, key.p, key.q = d, p, q return key else: return key.publickey() # Return the public key variant def keyToQuo(key, joi='\n\n'): """Returns a quoted printable version of a key - ee then m. Leading and trailing whitespace is allowed; stripped by quoToKey.""" e, n = str(key.e), str(key.n) # Convert the ee and mod to strings if key.has_private(): d, p, q = str(key.d), str(key.p), str(key.q) strkey = base64.encodestring(joi.join([e, n, d, p, q])) else: strkey = base64.encodestring('%s%s%s' % (e, joi, n)) return '\n'+quopri.encodestring(strkey).strip()+'\n' def quoToKey(strkey, spl='\n\n'): """Returns a key from quopri (ee then m) version of a key.""" bunc = base64.decodestring(quopri.decodestring(strkey.strip())) bits = bunc.split(spl) if len(bits) == 2: return newKey(long(bits[0]), long(bits[1])) else: e, n, d, p, q = bits return newKey(long(e), long(n), long(d), long(p), long(q)) # Signature encoding and decoding def baseEncode(s): s = base64.encodestring(s) return '\n'+quopri.encodestring(s).strip()+'\n' def baseDecode(s): s = quopri.decodestring(s.strip()) return base64.decodestring(s) # Decimal to binary def decToBin(i): # int to string result = '' while i > 0: d = i % 2 result = str(d)+result i /= 2 return result # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # C R Y P T O G R A H P I C B U I L T - I N s # # At the moment, we only have built-ins that can gague the hash values of # strings. It may be cool to have built ins that can give the hash value # of the content of a work, too, although you can do that with log:content. # # Light Built-in classes # Hash Constructors - light built-ins class BI_md5(LightBuiltIn, Function): def evaluateObject(self, subj_py): m = md5.new(subj_py).digest() return binascii.hexlify(m) class BI_sha(LightBuiltIn, Function): def evaluateObject(self, subj_py): m = sha.new(subj_py).digest() return binascii.hexlify(m) # Create a new RSA key class BI_keyLength(LightBuiltIn, Function, ReverseFunction): def __init__(self, resource, fragid): LightBuiltIn.__init__(self, resource, fragid) Function.__init__(self) ReverseFunction.__init__(self) self.do = 1 def evaluateSubject(self, obj_py): """Generates an RSA keypair, and spews it out as plain text. Has the limitation that it will *only* ever let you generate one key pair (per iteration), in order to work around a bug.""" if self.do: randfunc, self.do = randpool.RandomPool(int(obj_py)), 0 RSAKey = RSA.generate(int(obj_py), randfunc.get_bytes) TextKey = keyToQuo(RSAKey) if TextKey != 'N.': return TextKey def evaluateObject(self, subj_py): RSAKey = quoToKey(subj_py) return str(len(decToBin(RSAKey.n))) # @@ not integer? class BI_sign(LightBuiltIn, Function): def evaluateObject(self, subj_py): """Sign a hash with a key, and get a signature back.""" import time hash, keypair = subj_py RSAKey = quoToKey(keypair) signature = RSAKey.sign(hash, str(time.time())) # sign the hash with the key return baseEncode(str(signature[0])) class BI_verify(LightBuiltIn): def evaluate(self, subj_py, obj_py): """Verify a hash/signature.""" keypair, (hash, signature) = subj_py, obj_py hash = hash.encode('ascii') RSAKey = quoToKey(keypair) # Dequote the key signature = (long(baseDecode(signature)),) # convert the signature back return RSAKey.verify(hash, signature) class BI_verifyBoolean(LightBuiltIn, Function): def evaluateObject(self, subj_py): """Verify a hash/signature.""" keypair, hash, signature = subj_py hash = hash.encode('ascii') RSAKey = quoToKey(keypair) # Dequote the key signature = (long(baseDecode(signature)),) result = RSAKey.verify(hash, signature) return str(result) class BI_publicKey(LightBuiltIn, Function): def evaluateObject(self, subj_py): """Generate a quopri public key from a keypair.""" keypair = quoToKey(subj_py) # Dequote the key publickey = keypair.publickey() # Get the public key return keyToQuo(publickey) # Register the string built-ins with the store def register(store): str = store.symbol(CRYPTO_NS_URI[:-1]) str.internFrag('md5', BI_md5) str.internFrag('sha', BI_sha) if USE_PKC: str.internFrag('keyLength', BI_keyLength) str.internFrag('sign', BI_sign) str.internFrag('verify', BI_verify) str.internFrag('verifyBoolean', BI_verifyBoolean) str.internFrag('publicKey', BI_publicKey) if __name__=="__main__": print __doc__.strip() cwm-1.2.1/swap/isXML.py0000644015216600007660000005070110442165462013744 0ustar syosisyosi"""A series of functions to test if a string is a valid qName $ ID: $ """ import string from unicodedata import category from set_importer import Set LETTER_CATEGORIES = Set(["Ll", "Lu", "Lo", "Lt", "Nl"]) NCNAME_CATEGORIES = LETTER_CATEGORIES.union(Set(["Mc", "Me", "Mn", "Lm", "Nd"])) NCNameChar, NCNameStartChar, NameStartChar, NameChar, \ Letter, Digit, CombiningChar, Extender, BaseChar, Ideographic = \ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 def isXMLChar10(character, char_class): """Is this a valid character char_class is one of NCNameChar, NCNameStartChar, NameStartChar, NameChar, Letter, Digit, CombiningChar, Extender, BaseChar, Ideographic usual use is isXMLChar(character, isXML.NCNameChar) """ num = ord(character) character = unicode(character) if char_class == Letter: return isXMLChar10(character, BaseChar) or \ isXMLChar10(character, Ideographic) ### The following appears to simply be too accepting ### return category(character) in LETTER_CATEGORIES elif char_class == NCNameStartChar: return (character == '_') or \ isXMLChar10(character, Letter) elif char_class == NCNameChar: return (character == '-') or \ (character == '.') or \ isXMLChar10(character, NCNameStartChar) or \ isXMLChar10(character, Digit) or \ isXMLChar10(character, CombiningChar) or \ isXMLChar10(character, Extender) ### The following appears to simply be too accepting ### (character == '_') or \ ### category(character) in NCNAME_CATEGORIES elif char_class == NameStartChar: return character == ':' or isXMLChar10(character, NCNameStartChar) elif char_class == NameChar: return character == ':' or isXMLChar10(character, NCNameChar) elif char_class == BaseChar: return (num >= 0x0041 and num <= 0x005A) or \ (num >= 0x0061 and num <= 0x007A) or \ (num >= 0x00C0 and num <= 0x00D6) or \ (num >= 0x00D8 and num <= 0x00F6) or \ (num >= 0x00F8 and num <= 0x00FF) or \ (num >= 0x0100 and num <= 0x0131) or \ (num >= 0x0134 and num <= 0x013E) or \ (num >= 0x0141 and num <= 0x0148) or \ (num >= 0x014A and num <= 0x017E) or \ (num >= 0x0180 and num <= 0x01C3) or \ (num >= 0x01CD and num <= 0x01F0) or \ (num >= 0x01F4 and num <= 0x01F5) or \ (num >= 0x01FA and num <= 0x0217) or \ (num >= 0x0250 and num <= 0x02A8) or \ (num >= 0x02BB and num <= 0x02C1) or \ (num == 0x0386) or \ (num >= 0x0388 and num <= 0x038A) or \ (num == 0x038C) or \ (num >= 0x038E and num <= 0x03A1) or \ (num >= 0x03A3 and num <= 0x03CE) or \ (num >= 0x03D0 and num <= 0x03D6) or \ (num == 0x03DA) or \ (num == 0x03DC) or \ (num == 0x03DE) or \ (num == 0x03E0) or \ (num >= 0x03E2 and num <= 0x03F3) or \ (num >= 0x0401 and num <= 0x040C) or \ (num >= 0x040E and num <= 0x044F) or \ (num >= 0x0451 and num <= 0x045C) or \ (num >= 0x045E and num <= 0x0481) or \ (num >= 0x0490 and num <= 0x04C4) or \ (num >= 0x04C7 and num <= 0x04C8) or \ (num >= 0x04CB and num <= 0x04CC) or \ (num >= 0x04D0 and num <= 0x04EB) or \ (num >= 0x04EE and num <= 0x04F5) or \ (num >= 0x04F8 and num <= 0x04F9) or \ (num >= 0x0531 and num <= 0x0556) or \ (num == 0x0559) or \ (num >= 0x0561 and num <= 0x0586) or \ (num >= 0x05D0 and num <= 0x05EA) or \ (num >= 0x05F0 and num <= 0x05F2) or \ (num >= 0x0621 and num <= 0x063A) or \ (num >= 0x0641 and num <= 0x064A) or \ (num >= 0x0671 and num <= 0x06B7) or \ (num >= 0x06BA and num <= 0x06BE) or \ (num >= 0x06C0 and num <= 0x06CE) or \ (num >= 0x06D0 and num <= 0x06D3) or \ (num == 0x06D5) or \ (num >= 0x06E5 and num <= 0x06E6) or \ (num >= 0x0905 and num <= 0x0939) or \ (num == 0x093D) or \ (num >= 0x0958 and num <= 0x0961) or \ (num >= 0x0985 and num <= 0x098C) or \ (num >= 0x098F and num <= 0x0990) or \ (num >= 0x0993 and num <= 0x09A8) or \ (num >= 0x09AA and num <= 0x09B0) or \ (num == 0x09B2) or \ (num >= 0x09B6 and num <= 0x09B9) or \ (num >= 0x09DC and num <= 0x09DD) or \ (num >= 0x09DF and num <= 0x09E1) or \ (num >= 0x09F0 and num <= 0x09F1) or \ (num >= 0x0A05 and num <= 0x0A0A) or \ (num >= 0x0A0F and num <= 0x0A10) or \ (num >= 0x0A13 and num <= 0x0A28) or \ (num >= 0x0A2A and num <= 0x0A30) or \ (num >= 0x0A32 and num <= 0x0A33) or \ (num >= 0x0A35 and num <= 0x0A36) or \ (num >= 0x0A38 and num <= 0x0A39) or \ (num >= 0x0A59 and num <= 0x0A5C) or \ (num == 0x0A5E) or \ (num >= 0x0A72 and num <= 0x0A74) or \ (num >= 0x0A85 and num <= 0x0A8B) or \ (num == 0x0A8D) or \ (num >= 0x0A8F and num <= 0x0A91) or \ (num >= 0x0A93 and num <= 0x0AA8) or \ (num >= 0x0AAA and num <= 0x0AB0) or \ (num >= 0x0AB2 and num <= 0x0AB3) or \ (num >= 0x0AB5 and num <= 0x0AB9) or \ (num == 0x0ABD) or \ (num == 0x0AE0) or \ (num >= 0x0B05 and num <= 0x0B0C) or \ (num >= 0x0B0F and num <= 0x0B10) or \ (num >= 0x0B13 and num <= 0x0B28) or \ (num >= 0x0B2A and num <= 0x0B30) or \ (num >= 0x0B32 and num <= 0x0B33) or \ (num >= 0x0B36 and num <= 0x0B39) or \ (num == 0x0B3D) or \ (num >= 0x0B5C and num <= 0x0B5D) or \ (num >= 0x0B5F and num <= 0x0B61) or \ (num >= 0x0B85 and num <= 0x0B8A) or \ (num >= 0x0B8E and num <= 0x0B90) or \ (num >= 0x0B92 and num <= 0x0B95) or \ (num >= 0x0B99 and num <= 0x0B9A) or \ (num == 0x0B9C) or \ (num >= 0x0B9E and num <= 0x0B9F) or \ (num >= 0x0BA3 and num <= 0x0BA4) or \ (num >= 0x0BA8 and num <= 0x0BAA) or \ (num >= 0x0BAE and num <= 0x0BB5) or \ (num >= 0x0BB7 and num <= 0x0BB9) or \ (num >= 0x0C05 and num <= 0x0C0C) or \ (num >= 0x0C0E and num <= 0x0C10) or \ (num >= 0x0C12 and num <= 0x0C28) or \ (num >= 0x0C2A and num <= 0x0C33) or \ (num >= 0x0C35 and num <= 0x0C39) or \ (num >= 0x0C60 and num <= 0x0C61) or \ (num >= 0x0C85 and num <= 0x0C8C) or \ (num >= 0x0C8E and num <= 0x0C90) or \ (num >= 0x0C92 and num <= 0x0CA8) or \ (num >= 0x0CAA and num <= 0x0CB3) or \ (num >= 0x0CB5 and num <= 0x0CB9) or \ (num == 0x0CDE) or \ (num >= 0x0CE0 and num <= 0x0CE1) or \ (num >= 0x0D05 and num <= 0x0D0C) or \ (num >= 0x0D0E and num <= 0x0D10) or \ (num >= 0x0D12 and num <= 0x0D28) or \ (num >= 0x0D2A and num <= 0x0D39) or \ (num >= 0x0D60 and num <= 0x0D61) or \ (num >= 0x0E01 and num <= 0x0E2E) or \ (num == 0x0E30) or \ (num >= 0x0E32 and num <= 0x0E33) or \ (num >= 0x0E40 and num <= 0x0E45) or \ (num >= 0x0E81 and num <= 0x0E82) or \ (num == 0x0E84) or \ (num >= 0x0E87 and num <= 0x0E88) or \ (num == 0x0E8A) or \ (num == 0x0E8D) or \ (num >= 0x0E94 and num <= 0x0E97) or \ (num >= 0x0E99 and num <= 0x0E9F) or \ (num >= 0x0EA1 and num <= 0x0EA3) or \ (num == 0x0EA5) or \ (num == 0x0EA7) or \ (num >= 0x0EAA and num <= 0x0EAB) or \ (num >= 0x0EAD and num <= 0x0EAE) or \ (num == 0x0EB0) or \ (num >= 0x0EB2 and num <= 0x0EB3) or \ (num == 0x0EBD) or \ (num >= 0x0EC0 and num <= 0x0EC4) or \ (num >= 0x0F40 and num <= 0x0F47) or \ (num >= 0x0F49 and num <= 0x0F69) or \ (num >= 0x10A0 and num <= 0x10C5) or \ (num >= 0x10D0 and num <= 0x10F6) or \ (num == 0x1100) or \ (num >= 0x1102 and num <= 0x1103) or \ (num >= 0x1105 and num <= 0x1107) or \ (num == 0x1109) or \ (num >= 0x110B and num <= 0x110C) or \ (num >= 0x110E and num <= 0x1112) or \ (num == 0x113C) or \ (num == 0x113E) or \ (num == 0x1140) or \ (num == 0x114C) or \ (num == 0x114E) or \ (num == 0x1150) or \ (num >= 0x1154 and num <= 0x1155) or \ (num == 0x1159) or \ (num >= 0x115F and num <= 0x1161) or \ (num == 0x1163) or \ (num == 0x1165) or \ (num == 0x1167) or \ (num == 0x1169) or \ (num >= 0x116D and num <= 0x116E) or \ (num >= 0x1172 and num <= 0x1173) or \ (num == 0x1175) or \ (num == 0x119E) or \ (num == 0x11A8) or \ (num == 0x11AB) or \ (num >= 0x11AE and num <= 0x11AF) or \ (num >= 0x11B7 and num <= 0x11B8) or \ (num == 0x11BA) or \ (num >= 0x11BC and num <= 0x11C2) or \ (num == 0x11EB) or \ (num == 0x11F0) or \ (num == 0x11F9) or \ (num >= 0x1E00 and num <= 0x1E9B) or \ (num >= 0x1EA0 and num <= 0x1EF9) or \ (num >= 0x1F00 and num <= 0x1F15) or \ (num >= 0x1F18 and num <= 0x1F1D) or \ (num >= 0x1F20 and num <= 0x1F45) or \ (num >= 0x1F48 and num <= 0x1F4D) or \ (num >= 0x1F50 and num <= 0x1F57) or \ (num == 0x1F59) or \ (num == 0x1F5B) or \ (num == 0x1F5D) or \ (num >= 0x1F5F and num <= 0x1F7D) or \ (num >= 0x1F80 and num <= 0x1FB4) or \ (num >= 0x1FB6 and num <= 0x1FBC) or \ (num == 0x1FBE) or \ (num >= 0x1FC2 and num <= 0x1FC4) or \ (num >= 0x1FC6 and num <= 0x1FCC) or \ (num >= 0x1FD0 and num <= 0x1FD3) or \ (num >= 0x1FD6 and num <= 0x1FDB) or \ (num >= 0x1FE0 and num <= 0x1FEC) or \ (num >= 0x1FF2 and num <= 0x1FF4) or \ (num >= 0x1FF6 and num <= 0x1FFC) or \ (num == 0x2126) or \ (num >= 0x212A and num <= 0x212B) or \ (num == 0x212E) or \ (num >= 0x2180 and num <= 0x2182) or \ (num >= 0x3041 and num <= 0x3094) or \ (num >= 0x30A1 and num <= 0x30FA) or \ (num >= 0x3105 and num <= 0x312C) or \ (num >= 0xAC00 and num <= 0xD7A3) elif char_class == Ideographic: return (num >= 0x4E00 and num <= 0x9FA5) or \ (num == 0x3007) or \ (num >= 0x3021 and num <= 0x3029) elif char_class == Digit: return (num >= 0x0030 and num <= 0x0039) or \ (num >= 0x0660 and num <= 0x0669) or \ (num >= 0x06F0 and num <= 0x06F9) or \ (num >= 0x0966 and num <= 0x096F) or \ (num >= 0x09E6 and num <= 0x09EF) or \ (num >= 0x0A66 and num <= 0x0A6F) or \ (num >= 0x0AE6 and num <= 0x0AEF) or \ (num >= 0x0B66 and num <= 0x0B6F) or \ (num >= 0x0BE7 and num <= 0x0BEF) or \ (num >= 0x0C66 and num <= 0x0C6F) or \ (num >= 0x0CE6 and num <= 0x0CEF) or \ (num >= 0x0D66 and num <= 0x0D6F) or \ (num >= 0x0E50 and num <= 0x0E59) or \ (num >= 0x0ED0 and num <= 0x0ED9) or \ (num >= 0x0F20 and num <= 0x0F29) elif char_class == CombiningChar: return (num >= 0x0300 and num <= 0x0345) or \ (num >= 0x0360 and num <= 0x0361) or \ (num >= 0x0483 and num <= 0x0486) or \ (num >= 0x0591 and num <= 0x05A1) or \ (num >= 0x05A3 and num <= 0x05B9) or \ (num >= 0x05BB and num <= 0x05BD) or \ (num == 0x05BF) or \ (num >= 0x05C1 and num <= 0x05C2) or \ (num == 0x05C4) or \ (num >= 0x064B and num <= 0x0652) or \ (num == 0x0670) or \ (num >= 0x06D6 and num <= 0x06DC) or \ (num >= 0x06DD and num <= 0x06DF) or \ (num >= 0x06E0 and num <= 0x06E4) or \ (num >= 0x06E7 and num <= 0x06E8) or \ (num >= 0x06EA and num <= 0x06ED) or \ (num >= 0x0901 and num <= 0x0903) or \ (num == 0x093C) or \ (num >= 0x093E and num <= 0x094C) or \ (num == 0x094D) or \ (num >= 0x0951 and num <= 0x0954) or \ (num >= 0x0962 and num <= 0x0963) or \ (num >= 0x0981 and num <= 0x0983) or \ (num == 0x09BC) or \ (num == 0x09BE) or \ (num == 0x09BF) or \ (num >= 0x09C0 and num <= 0x09C4) or \ (num >= 0x09C7 and num <= 0x09C8) or \ (num >= 0x09CB and num <= 0x09CD) or \ (num == 0x09D7) or \ (num >= 0x09E2 and num <= 0x09E3) or \ (num == 0x0A02) or \ (num == 0x0A3C) or \ (num == 0x0A3E) or \ (num == 0x0A3F) or \ (num >= 0x0A40 and num <= 0x0A42) or \ (num >= 0x0A47 and num <= 0x0A48) or \ (num >= 0x0A4B and num <= 0x0A4D) or \ (num >= 0x0A70 and num <= 0x0A71) or \ (num >= 0x0A81 and num <= 0x0A83) or \ (num == 0x0ABC) or \ (num >= 0x0ABE and num <= 0x0AC5) or \ (num >= 0x0AC7 and num <= 0x0AC9) or \ (num >= 0x0ACB and num <= 0x0ACD) or \ (num >= 0x0B01 and num <= 0x0B03) or \ (num == 0x0B3C) or \ (num >= 0x0B3E and num <= 0x0B43) or \ (num >= 0x0B47 and num <= 0x0B48) or \ (num >= 0x0B4B and num <= 0x0B4D) or \ (num >= 0x0B56 and num <= 0x0B57) or \ (num >= 0x0B82 and num <= 0x0B83) or \ (num >= 0x0BBE and num <= 0x0BC2) or \ (num >= 0x0BC6 and num <= 0x0BC8) or \ (num >= 0x0BCA and num <= 0x0BCD) or \ (num == 0x0BD7) or \ (num >= 0x0C01 and num <= 0x0C03) or \ (num >= 0x0C3E and num <= 0x0C44) or \ (num >= 0x0C46 and num <= 0x0C48) or \ (num >= 0x0C4A and num <= 0x0C4D) or \ (num >= 0x0C55 and num <= 0x0C56) or \ (num >= 0x0C82 and num <= 0x0C83) or \ (num >= 0x0CBE and num <= 0x0CC4) or \ (num >= 0x0CC6 and num <= 0x0CC8) or \ (num >= 0x0CCA and num <= 0x0CCD) or \ (num >= 0x0CD5 and num <= 0x0CD6) or \ (num >= 0x0D02 and num <= 0x0D03) or \ (num >= 0x0D3E and num <= 0x0D43) or \ (num >= 0x0D46 and num <= 0x0D48) or \ (num >= 0x0D4A and num <= 0x0D4D) or \ (num == 0x0D57) or \ (num == 0x0E31) or \ (num >= 0x0E34 and num <= 0x0E3A) or \ (num >= 0x0E47 and num <= 0x0E4E) or \ (num == 0x0EB1) or \ (num >= 0x0EB4 and num <= 0x0EB9) or \ (num >= 0x0EBB and num <= 0x0EBC) or \ (num >= 0x0EC8 and num <= 0x0ECD) or \ (num >= 0x0F18 and num <= 0x0F19) or \ (num == 0x0F35) or \ (num == 0x0F37) or \ (num == 0x0F39) or \ (num == 0x0F3E) or \ (num == 0x0F3F) or \ (num >= 0x0F71 and num <= 0x0F84) or \ (num >= 0x0F86 and num <= 0x0F8B) or \ (num >= 0x0F90 and num <= 0x0F95) or \ (num == 0x0F97) or \ (num >= 0x0F99 and num <= 0x0FAD) or \ (num >= 0x0FB1 and num <= 0x0FB7) or \ (num == 0x0FB9) or \ (num >= 0x20D0 and num <= 0x20DC) or \ (num == 0x20E1) or \ (num >= 0x302A and num <= 0x302F) or \ (num == 0x3099) or \ (num == 0x309A) elif char_class == Extender: return (num == 0x00B7) or \ (num == 0x02D0) or \ (num == 0x02D1) or \ (num == 0x0387) or \ (num == 0x0640) or \ (num == 0x0E46) or \ (num == 0x0EC6) or \ (num == 0x3005) or \ (num >= 0x3031 and num <= 0x3035) or \ (num >= 0x309D and num <= 0x309E) or \ (num >= 0x30FC and num <= 0x30FE) else: raise NotImplementedError def isXMLChar11(character, char_class): """Is this a valid character char_class is one of NCNameChar, NCNameStartChar, NameStartChar, NameChar, Letter, Digit, CombiningChar, Extender, BaseChar, Ideographic usual use is isXMLChar(character, isXML.NCNameChar) """ num = ord(character) if char_class == NCNameStartChar: return (character in string.lowercase) or \ (character in string.uppercase) or \ (character == '_') or \ (num >= 0xC0 and num <= 0xD6) or \ (num >= 0xD8 and num <= 0xF6) or \ (num >= 0xF8 and num <= 0x2FF) or \ (num >= 0x370 and num <= 0x37D) or \ (num >= 0x37F and num <= 0x1FFF) or \ (num >= 0x200C and num <= 0x200D) or \ (num >= 0x2070 and num <= 0x218F) or \ (num >= 0x2C00 and num <= 0x2FEF) or \ (num >= 0x3001 and num <= 0xD7FF) or \ (num >= 0xF900 and num <= 0xFDCF) or \ (num >= 0xFDF0 and num <= 0xFFFD) or \ (num >= 0x10000 and num <= 0xEFFFF) elif char_class == NCNameChar: return (character in string.digits) or \ (character == '-') or \ (character == '.') or \ (num == 0xB7) or \ (num >= 0x300 and num <= 0x36F) or \ (num >= 0x203F and num <= 0x2040) or \ isXMLChar11(character, NCNameStartChar) elif char_class == NameStartChar: return character == ':' or isXMLChar11(character, NCNameStartChar) elif char_class == NameChar: return character == ':' or isXMLChar11(character, NCNameChar) else: raise NotImplementedError def isXMLChar(character, char_class): """Is this a valid character char_class is one of NCNameChar, NCNameStartChar, NameStartChar, NameChar, Letter, Digit, CombiningChar, Extender, BaseChar, Ideographic usual use is isXMLChar(character, isXML.NCNameChar) """ if XMLVersion == '1.1': return isXMLChar11(character, char_class) else: return isXMLChar10(character, char_class) def isNCName(string): """Is this string a valid NCName """ if not isXMLChar(string[0], NCNameStartChar): return False for a in string[1:]: if not isXMLChar(a, NCNameChar): return False return True def isName(string): """Is this string a valid NCName """ if not isXMLChar(string[0], NameStartChar): return False for a in string[1:]: if not isXMLChar(a, NameChar): return False return True XMLVersion = '1.0' def setXMLVersion(ver): global XMLVersion XMLVersion = ver def getXMLVersion(): return XMLVersion cwm-1.2.1/swap/sax2rdf.py0000644015216600007660000012554310713412506014323 0ustar syosisyosi#! /usr/bin/python """ A parser for RDF/XML built on the sax2 interface; derived from a parser for RDF/XML built on the xmllib XML parser. To do: Passing on namesapce bindings! (dwc: @@huh?) (tbl: The bind call in the RDF stream API is used to pass on the prefixes found, as hints only for generating readable output code) - Add parsing of RDF bags parses DAML_ONT_NS or List_NS lists, generates List_NS References: Python/XML HOWTO The Python/XML Special Interest Group xml-sig@python.org (edited by amk1@bigfoot.com) http://py-howto.sourceforge.net/xml-howto/xml-howto.html http://www.megginson.com/SAX/applications.html#python.parsers http://www.python.org/sigs/xml-sig/ How to on xmllib: http://www.python.org/doc/howto/xml/node7.html RDF grammar http://www.w3.org/TR/rdf-syntax-grammar/ esp sections 6 and 7 ##################################### SAX pointers First hit on Python SAX parser http://www.gca.org/papers/xmleurope2000/papers/s28-04.html#N84395 Howto use SAX in python: http://www.python.org/doc/howto/xml/SAX.html """ # Some of the code adding support for XMLLiteral is # Copyright (c) 2002, Daniel Krech, http://eikeon.com/ # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # * Neither the name of Daniel Krech nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import string import sys import uripath from why import BecauseOfData import isXML import diag #from webAccess import urlopenForRDF # http://www.w3.org/2000/10/swap/ import xml.sax # PyXML stuff # http://sourceforge.net/projects/pyxml # Connolly uses the debian python2-xml 0.6.5-2 package # http://packages.debian.org/testing/interpreters/python2-xml.html # and suggests TimBL try the win32 distribution from # the PyXML sourceforge project # http://prdownloads.sourceforge.net/pyxml/PyXML-0.6.5.win32-py2.1.exe # TimBL points outhe does not use windows env't but cygwin and # giuesses he should compile python2-xml for cygwin. import xml.sax._exceptions from xml.sax.saxutils import quoteattr from xml.sax.handler import feature_namespaces XMLLiteralsAsDomTrees = 1 if XMLLiteralsAsDomTrees: import xml.dom # for XMLLiterals import RDFSink from RDFSink import FORMULA, ANONYMOUS, NODE_MERGE_URI # States: STATE_OUTERMOST = "outermost level" # Before STATE_NOT_RDF = "not RDF" # Before STATE_NO_SUBJECT = "no context" # @@@@@@@@@ use numbers for speed STATE_DESCRIPTION = "Description (have subject)" # STATE_LITERAL = "within XML literal" STATE_VALUE = "plain value" STATE_NOVALUE = "no value" # We already have an object, another would be error STATE_LIST = "within list" RDF_NS_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" # As per the spec RDF_Specification = "http://www.w3.org/TR/REC-rdf-syntax/" # Must come in useful :-) DAML_ONT_NS = "http://www.daml.org/2000/10/daml-ont#" # DAML early version DPO_NS = "http://www.daml.org/2001/03/daml+oil#" # DAML plus oil OWL_NS = "http://www.w3.org/2002/07/owl#" # OWL List_NS = RDF_NS_URI # Changed 200308 XML_NS_URI = "http://www.w3.org/XML/1998/namespace" from diag import verbosity, progress, tracking from set_importer import Set _nextId = 0 # For generation of arbitrary names for anonymous nodes coreSyntaxTerms = ['RDF', 'ID', 'about', 'parseType', 'resource', 'nodeID', 'datatype'] syntaxTerms = coreSyntaxTerms + ['Description', 'li'] oldTerms = ['aboutEach', 'aboutEachPrefix', 'bagID'] nodeElementExceptions = {} for a in coreSyntaxTerms + oldTerms + ['li',]: nodeElementExceptions[RDF_NS_URI + a] = True propertyElementExceptions = {} for a in coreSyntaxTerms + oldTerms + ['Description',]: propertyElementExceptions[RDF_NS_URI + a] = True propertyAttributeExceptions = {} for a in syntaxTerms + oldTerms: propertyAttributeExceptions[RDF_NS_URI + a] = True class RDFHandler(xml.sax.ContentHandler): """RDF Parser using SAX API for XML parsing """ def __init__(self, sink, openFormula, thisDoc, baseURI=None, flags="", why=None): self.testdata = "" if XMLLiteralsAsDomTrees: self.domImplementation = xml.dom.getDOMImplementation() self.domDocument = None self.domElement = None self.flags = flags self._stack =[] # Stack of states self._nsmap = [] # stack of namespace bindings self._prefixMap = [] self.LiteralNS = None self._delayedStatement = None self.sink = sink self._thisDoc = thisDoc if baseURI != None: self._base = baseURI else: self._base = thisDoc self._state = STATE_OUTERMOST # Maybe should ignore RDF outside ?? if sink: if openFormula==None: self._context = sink.newFormula(thisDoc + "#_formula") else: self._context = openFormula self._formula = self._context # Root formula self._genPrefix = uripath.join(thisDoc, "#_rdfxg") # allow parameter override? self.sink.setGenPrefix(self._genPrefix) self.sink.startDoc() self.merge = self.sink.newSymbol(NODE_MERGE_URI) else: self._context = None self._reason = why # Why the parser w self._reason2 = None # Why these triples if diag.tracking: self._reason2 = BecauseOfData( sink.newSymbol(thisDoc), because=self._reason) self._subject = None self._predicate = None self._datatype = None self._language = None self._nodeIDs = {} self._items = [] # for containers self._litDepth = 0 self._usedIDs = Set() version = "$Id: sax2rdf.py,v 1.55 2007/11/04 18:51:43 syosi Exp $" # self.sink.makeComment("RDF parsed by "+version[1:-1]) if "D" in self.flags: # Assume default namespace declaration if sink: self.sink.setDefaultNamespace(self._thisDoc+"#") self._nsmap = [ { "": "#"} ] def characters(self, data): if XMLLiteralsAsDomTrees and (self._state == STATE_LITERAL): t = self.domDocument.createTextNode(data) self.domElement.appendChild(t) return if self._state == STATE_VALUE or \ self._state == STATE_LITERAL: self.testdata += data def flush(self): data = self.testdata if data: self.testdata = "" # print '# flushed data:', `data` def processingInstruction(self, name, data): self.flush() #print 'processing:',name,`data` def uriref(self, str): """ Generate uri from uriref in this document unicode strings OK. """ return uripath.join(self._base, str) def newBlankNode(self): columnNumber = self._p.getColumnNumber() lineNumber = self._p.getLineNumber() bnodeID = self._thisDoc + "#_L%iC%i" % (lineNumber, columnNumber) return self.sink.newBlankNode(self._context, uri=bnodeID, why=self._reason2) #for debugging: encode file/line info def idAboutAttr(self, attrs): #MS1.0 6.5 also proprAttr 6.10 """ set up subject and maybe context from attributes """ self._subject = None self._state = STATE_DESCRIPTION self._items.append(0) properties = [] for name, value in attrs.items(): ns, ln = name if ns: if string.find("ID about aboutEachPrefix bagID type", ln)>0: if ns != RDF_NS_URI: print ("# Warning -- %s attribute in %s namespace not RDF NS." % name, ln) ns = RDF_NS_URI # Allowed as per dajobe: ID, bagID, about, resource, parseType or type uri = (ns + ln) if ns == RDF_NS_URI or ns == None: # Opinions vary sometimes none but RDF_NS is common :-( if ln == "ID": if not isXML.isName(value): raise BadSyntax(sys.exc_info(), 'An ID must be a Name %s' % value) if (self._base, value) in self._usedIDs: raise BadSyntax(sys.exc_info(), "Two elements cannot have the same ID, %s" % value) self._usedIDs.add((self._base, value)) if self._subject: print "# oops - subject already", self._subject raise BadSyntax(sys.exc_info(), ">1 subject") self._subject = self.sink.newSymbol(self.uriref("#" + value)) elif ln == "about": if self._subject: raise BadSyntax(sys.exc_info(), ">1 subject") self._subject = self.sink.newSymbol(self.uriref(value)) elif ln == "nodeID": if self._subject: raise BadSyntax(sys.exc_info(), ">1 subject") if not isXML.isNCName(value): raise BadSyntax(sys.exc_info(), 'A nodeID must be a NCName %s' % value) s = self._nodeIDs.get(value, None) if s == None: s = self.newBlankNode() self._nodeIDs[value] = s self._subject = s elif ln == "aboutEachPrefix": if value == " ": # OK - a trick to make NO subject self._subject = None else: raise ooops # can't do about each prefix yet elif ln == "bagID": if not isXML.isName(value): raise BadSyntax(sys.exc_info(), 'A bagID must be a Name %s' % value) c = self._context #@@dwc: this is broken, no? self._context = FORMULA, self.uriref("#" + value) #@@ non-ascii elif ln == "parseType": pass #later - object-related elif ln == "resource": pass #later elif ln == "datatype": pass #later elif uri in propertyAttributeExceptions: raise BadSyntax(sys.exc_info(), "%s is not a valid attribute named here" % uri) else: if not ns: if "L" not in self.flags: # assume local? raise BadSyntax(sys.exc_info(), "No namespace on property attribute %s" % ln) properties.append((self._thisDoc + "#" + ln, value)) else: properties.append((uri, value))# If no uri, syntax error @@ # self.sink.makeComment("xml2rdf: Ignored attribute "+uri) elif ns == XML_NS_URI: pass # lang already done, others ignored else: # Property attribute propAttr #MS1.0 6.10 properties.append((uri, value)) # print "@@@@@@ <%s> <%s>" % properties[-1] if self._subject == None: self._subject = self.newBlankNode() for pred, obj in properties: if pred == RDF_NS_URI + "type": self.sink.makeStatement(( self._context, self.sink.newSymbol(pred), self._subject, self.sink.newSymbol(self.uriref(obj)) ), why=self._reason2) else: dt = self._datatype if dt == None: lang = self._language else: lang = None self.sink.makeStatement(( self._context, self.sink.newSymbol(pred), self._subject, self.sink.newLiteral(obj, dt, lang) ), why=self._reason2) def _nodeElement(self, tagURI, attrs): #MS1.0 6.2 if tagURI == RDF_NS_URI + "Description": self.idAboutAttr(attrs) # Set up subject and context elif tagURI in nodeElementExceptions: raise ValueError, "%s as typednode not implemented" % tagURI else: # Unknown tag within STATE_NO_SUBJECT: typedNode #MS1.0 6.13 c = self._context # (Might be changed in idAboutAttr) #@@DC: huh? self.idAboutAttr(attrs) assert c != None assert self._subject != None self.sink.makeStatement(( c, self.sink.newSymbol(RDF_NS_URI+"type"), self._subject, self.sink.newSymbol(tagURI) ), why=self._reason2) self._state = STATE_DESCRIPTION def _propertyAttr(self, ns, name, value): "Parse a propertrAttr production. 7.2.25" if verbosity() > 50: progress("_propertyAttr ns=5s name=%s value=%s"% (ns, name, value)) if self._subject == None: # Property as attribute self._subject = self.newBlankNode() self.sink.makeStatement((self._context, self._predicate, self._subject, self._subject ), why=self._reason2) if not ns: if "L" not in self.flags: # assume local? raise BadSyntax(sys.exc_info(), "No namespace on property attribute %s=%s" % (name, value)) ns = self._thisDoc + "#" pred = ns + name if pred == RDF_NS_URI + "type": # special case obj = self.sink.newSymbol(self.uriref(value)) # SYN#7.2.11 step 2/3 else: obj = self.sink.newLiteral(value, self._datatype, self._language) self.sink.makeStatement((self._context, self.sink.newSymbol(self.uriref(pred)), self._subject, obj), why=self._reason2) self._state = STATE_NOVALUE # NOT looking for value return def startPrefixMapping(self, prefix, uri): """Performance note: We make a new dictionary for every binding. This makes lookup quick and easy, but it takes extra space and more time to set up a new binding.""" #print "startPrefixMapping with prefix=", prefix, "uri=", `uri` prefix = prefix or "" uri = uri or "" uri = self.uriref(uri) if self._nsmap: b = self._nsmap[-1].copy() c = self._prefixMap[-1].copy() else: b = {} c = {} b[prefix] = uri c[uri] = prefix self._nsmap.append(b) self._prefixMap.append(c) if self.sink: self.sink.bind(prefix, uri) def endPrefixMapping(self, prefix): del self._nsmap[-1] self._prefixMap.pop() def startElementNS(self, name, qname, attrs): """ Handle start tag. """ if self._state != STATE_LITERAL: self.flush() self.bnode = None tagURI = ((name[0] or "") + name[1]) if verbosity() > 80: indent = ". " * len(self._stack) if not attrs: progress(indent+'# State was', self._state, ', start tag: <' + tagURI + '>') else: str = '# State =%s, start tag= <%s ' %( self._state, tagURI) for name, value in attrs.items(): str = str + " " + `name` + '=' + '"' + `value` + '"' progress(indent + str + '>') self._stack.append([self._state, self._context, self._predicate, self._subject, self._delayedStatement, self._base]) self._delayedStatement = None self._base = uripath.join(self._base, attrs.get((XML_NS_URI, "base"), self._base)) x = self._base.find("#") if x >= 0: self._base = self._base[:x] # See rdf-tests/rdfcore/xmlbase/test013.rdf try: tagURI = uripath.join(self._base, tagURI) # If relative, make absolute. Not needed for standard. except ValueError: pass # Needed for portable RDF generated with --rdf=z self._language = attrs.get((XML_NS_URI, "lang"), None) value = attrs.get((RDF_NS_URI, "datatype"), None) if value != None: self._datatype = self.sink.newSymbol(self.uriref(value)) else: self._datatype = None if self._state == STATE_OUTERMOST: if tagURI == RDF_NS_URI + "RDF": self._state = STATE_NO_SUBJECT else: if "R" not in self.flags: self._state = STATE_NOT_RDF # Ignore random XML without rdf:RDF else: self._nodeElement(tagURI, attrs) # Parse it as RDF. # http://www.w3.org/2000/10/rdf-tests/rdfcore/rdf-element-not-mandatory/test001.rdf elif self._state == STATE_NOT_RDF: if tagURI == RDF_NS_URI + "RDF" and "T" in self.flags: self._state = STATE_NO_SUBJECT else: pass # Ignore embedded RDF elif self._state == STATE_NO_SUBJECT: #MS1.0 6.2 obj :: desription | container self._nodeElement(tagURI, attrs) elif self._state == STATE_DESCRIPTION: # Expect predicate (property) PropertyElt # propertyElt #MS1.0 6.12 # http://www.w3.org/2000/03/rdf-tracking/#rdf-containers-syntax-ambiguity if tagURI == RDF_NS_URI + "li": item = self._items[-1] + 1 self._predicate = self.sink.newSymbol("%s_%s" % (RDF_NS_URI, item)) self._items[-1] = item else: if tagURI in propertyElementExceptions: raise BadSyntax(sys.exc_info(), 'Invalid predicate URI: %s' % tagURI) self._predicate = self.sink.newSymbol(tagURI) self._state = STATE_VALUE # May be looking for value but see parse type # self._datatype = None # self._language = None self.testdata = "" # Flush value data # print "\n attributes:", `attrs` properties = [] gotSubject = 0 haveResource = 0 haveParseType = 0 haveExtras = 0 for name, value in attrs.items(): ns, name = name if name == "ID": print "# Warning: ID=%s on statement ignored" % (value) # I consider these a bug raise ValueError("ID attribute? Reification not supported.") elif name == "parseType": haveParseType = 1 # x = value.find(":") # if x>=0: pref = value[:x] # else: pref = "" # nsURI = self._nsmap[-1].get(pref, None) if value == "Resource": c = self._context s = self._subject # self._subject = self.sink.newBlankNode(self._context, why=self._reason2) self.idAboutAttr(attrs) #@@ not according to current syntax @@@@@@@@@@@ self.sink.makeStatement(( c, self._predicate, s, self._subject), why=self._reason2) self._state = STATE_DESCRIPTION # Nest description elif value == "Quote": c = self._context s = self._subject self.idAboutAttr(attrs) # set subject and context for nested description self._subject = self.sink.newFormula() # Forget anonymous genid - context is subect if self._predicate is self.merge: # magic :-( self._stack[-1][3] = self._subject # St C P S retrofit subject of outer level! self._delayedStatement = 1 # flag else: self._delayedStatement = c, self._predicate, s, self._subject self._context = self._subject self._subject = None self._state = STATE_NO_SUBJECT # Inside quote, there is no subject elif (value=="Collection" or value[-11:] == ":collection"): # Is this a daml:collection qname? self._state = STATE_LIST # Linked list of obj's elif value == "Literal" or "S" in self.flags: # Strictly, other types are literal SYN#7.2.20 self._state = STATE_LITERAL # That's an XML subtree not a string self._litDepth = 1 self.LiteralNS = [{}] self.testdata = '' #"@@sax2rdf.py bug@@" # buggy implementation self._datatype = self.sink.newSymbol("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral") if XMLLiteralsAsDomTrees: self.domDocument = self.domImplementation.createDocument( 'http://www.w3.org/1999/02/22-rdf-syntax-ns', 'envelope', None) self.domElement = self.domDocument.documentElement else: raise SyntaxError("Unknown parse type '%s'" % value ) elif name == "nodeID": assert not gotSubject if not isXML.isNCName(value): raise BadSyntax(sys.exc_info(), 'A nodeID must be a NCName %s' % value) obj = self._nodeIDs.get(value, None) if obj == None: obj = self.newBlankNode() self._nodeIDs[value] = obj self.sink.makeStatement((self._context, self._predicate, self._subject, obj ), why=self._reason2) self._state = STATE_NOVALUE # NOT looking for value self._subject = obj gotSubject = 1 elif name == "resource": haveResource = 1 assert not gotSubject x = self.sink.newSymbol(self.uriref(value)) self.sink.makeStatement((self._context, self._predicate, self._subject, x ), why=self._reason2) self._state = STATE_NOVALUE # NOT looking for value self._subject = x gotSubject = 1 elif name == "datatype": pass # Already set elif ns == XML_NS_URI or name[:3] == "xml": # Ignore (lang is already done) pass # see rdf-tests/rdfcore/unrecognised-xml-attributes/test002.rdf else: haveExtras = 1 properties.append((ns, name, value)) # wait till subject is clear assert haveResource + haveParseType <= 1 assert haveParseType + haveExtras <= 1 if not gotSubject and properties: obj = self.newBlankNode() self.sink.makeStatement((self._context, self._predicate, self._subject, obj ), why=self._reason2) self._state = STATE_NOVALUE # NOT looking for value self._subject = obj for ns, name, value in properties: self._propertyAttr(ns, name, value) elif self._state == STATE_LIST: # damlCollection :: objs - make list # Subject and predicate are set and dangling. c = self._context s = self._subject # The tail of the list so far p = self._predicate pair = self.newBlankNode() # The new pair self.sink.makeStatement(( c, # Link in new pair p, s, pair ), why=self._reason2) self.idAboutAttr(attrs) # set subject (the next item) and context if tagURI != RDF_NS_URI + "Description": self.sink.makeStatement((c, self.sink.newSymbol(RDF_NS_URI +"type"), self._subject, self.sink.newSymbol(tagURI) ), why=self._reason2) self.sink.makeStatement(( c, self.sink.newSymbol(List_NS + "first"), pair, self._subject), why=self._reason2) # new item if "S" in self.flags: # Strictly to spec self.sink.makeStatement(( c, self.sink.newSymbol(RDF_NS_URI + "type"), self.sink.newSymbol(List_NS + "List"), self._subject), why=self._reason2) # new item self._stack[-1][2] = self.sink.newSymbol(List_NS + "rest") # Leave dangling link #@check self._stack[-1][3] = pair # Underlying state tracks tail of growing list elif self._state == STATE_VALUE: # Value :: Obj in this case #MS1.0 6.17 6.2 c = self._context p = self._predicate s = self._subject self._nodeElement(tagURI, attrs) # Parse the object thing's attributes self.sink.makeStatement((c, p, s, self._subject), why=self._reason2) self._stack[-1][0] = STATE_NOVALUE # When we return, cannot have literal now elif self._state == STATE_NOVALUE: str = "" for e in self._stack: str = str + `e`+"\n" raise BadSyntax(sys.exc_info(), """Expected no value, found name=%s; qname=%s, attrs=%s in nested context:\n%s""" %(name, qname, attrs, str)) elif self._state == STATE_LITERAL: self._litDepth = self._litDepth + 1 if XMLLiteralsAsDomTrees: # progress("@@@ XML literal name: ", name) self.literal_element_start_DOM(name, qname, attrs) else: self.literal_element_start(name, qname, attrs) #@@ need to capture the literal else: raise RuntimeError, ("Unknown state in RDF parser", self._stack) # Unknown state # aboutEachprefix { <#> forall r . { r startsWith ppp } l:implies ( zzz } ) # aboutEach { <#> forall r . { ppp rdf:li r } l:implies ( zzz } ) def endElementNS(self, name, qname): """Handle end element event """ if verbosity() > 80: indent = "- " * len(self._stack) progress(indent+'# End %s, State was'%name[1], self._state, ", delayed was ", `self._delayedStatement`) if self._delayedStatement == 1: if verbosity() > 80: progress("Delayed subject "+`self._subject`) self._stack[-1][3] = self._stack[-1][3].close() if self._state == STATE_LITERAL: self._litDepth = self._litDepth - 1 if self._litDepth == 0: buf = self.testdata if XMLLiteralsAsDomTrees: # e = self.domDocument.documentElement.firstChild # while e.nodeType == e.TEXT_NODE: # e = e.nextSibling #progress("@@@ e=", e, e.nodeName) # self.domElement = e # Leave for literal parser to pick up self.domElement = self.domDocument.documentElement #print self.domDocument.toxml() #raise SystemExit() if self.sink: self.sink.makeStatement(( self._context, self._predicate, self._subject, self.sink.newXMLLiteral(self.domDocument.documentElement) ), why=self._reason2) else: self._datatype = self.sink.newSymbol("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral") self.sink.makeStatement(( self._context, self._predicate, self._subject, self.sink.newLiteral(buf, self._datatype) ), why=self._reason2) self.testdata = "" else: if XMLLiteralsAsDomTrees: self.literal_element_end_DOM(name, qname) else: self.literal_element_end(name, qname) self._stack.pop() return # don't pop state elif self._state == STATE_VALUE: buf = self.testdata if self._datatype == None: # RDFCore changes 2003 - can't have dt and lang lang = self._language else: lang = None obj = self.sink.newLiteral(buf, self._datatype, lang) self.sink.makeStatement(( self._context, self._predicate, self._subject, obj), why=self._reason2) self.testdata = "" elif self._state == STATE_LIST: self.sink.makeStatement(( self._context, self.sink.newSymbol(List_NS + "rest"), self._subject, self.sink.newSymbol(List_NS + "nil") ), why=self._reason2) elif self._state == STATE_DESCRIPTION: self._items.pop() elif self._state == STATE_NOVALUE or \ self._state == STATE_NO_SUBJECT or \ self._state == STATE_OUTERMOST or \ self._state == STATE_NOT_RDF: # akuchlin@mems-exchange.org 2002-09-11 pass else: raise RuntimeError, ("Unknown RDF parser state '%s' in end tag" % self._state, self._stack) # c1 = self._context # if self._subject is c1 and self_context is not c1: # self._subject = self._subject.close() # close before use l = self._stack.pop() # self._state = l[0] self._context = l[1] self._predicate = l[2] self._subject = l[3] if self._delayedStatement != None: if self._delayedStatement == 1: pass # progress("Delayed subject "+`self._subject`) # self._subject = self._subject.close() else: c, p, s, o = self._delayedStatement o = o.close() self.sink.makeStatement((c, p, s, o), why=self._reason2) self._delayedStatement = None self._delayedStatement = l[4] self._base = l[5] self.flush() # print '\nend tag: ' def endDocument(self, f=None): self.flush() self.sink.endDoc(self._formula) def literal_element_start(self, name, qname, attrs): declared = self.LiteralNS[-1].copy() self.LiteralNS.append(declared) nsMap = self._prefixMap[-1] if name[0]: prefix = nsMap[name[0]] if prefix: self.testdata += "<%s:%s" % (prefix, name[1]) else: self.testdata += "<%s" % name[1] for ns in [name] + attrs.keys(): ns = ns[0] if not ns in declared: prefix = nsMap.get(ns, None) if prefix is None: columnNumber = self._p.getColumnNumber() lineNumber = self._p.getLineNumber() where = "Undefined namespace '%s' parsing XML at column %i in line %i of <%s>\n\t" % ( ns, columnNumber, lineNumber, self._thisDoc) raise SyntaxError(where + sys.exc_info()[1].__str__()) declared[ns] = prefix if prefix: self.testdata += (' xmlns:%s="%s"' % (prefix, ns)) else: self.testdata += (' xmlns="%s"' % ns) else: self.testdata += "<%s" % name[1] for (name, value) in attrs.items(): if name[0]: name = declared[name[0]] + ":" + name[1] else: name = name[1] self.testdata += (' %s=%s' % (name, quoteattr(value))) self.testdata += ">" def literal_element_start_DOM(self, name, qname, attrs): declared = self.LiteralNS[-1].copy() declared[u'http://www.w3.org/XML/1998/namespace'] = 'xml' self.LiteralNS.append(declared) nsMap = self._prefixMap[-1] if name[0]: prefix = nsMap[name[0]] if prefix: e = self.domDocument.createElementNS(name[0], prefix + ':' + name[1]) else: e = self.domDocument.createElementNS(name[0], name[1]) for ns in [name] + attrs.keys(): ns = ns[0] if ns and not ns in declared: prefix = nsMap.get(ns, None) if prefix is None: columnNumber = self._p.getColumnNumber() lineNumber = self._p.getLineNumber() where = "Undefined namespace '%s' parsing XML at column %i in line %i of <%s>\n\t" % ( ns, columnNumber, lineNumber, self._thisDoc) raise SyntaxError(where + sys.exc_info()[1].__str__()) declared[ns] = prefix if prefix: # self.testdata += (' xmlns:%s="%s"' % (prefix, ns)) e.setAttribute('xmlns:'+prefix, ns) # use setAttributeNS? What NS? else: # self.testdata += (' xmlns="%s"' % ns) e.setAttribute('xmlns', ns) else: e = self.domDocument.createElement(name[1]) self.domElement.appendChild(e) self.domElement = e # progress("@@@ self.domElement.namespaceURI=", self.domElement.namespaceURI) for (name, value) in attrs.items(): if name[0]: e.setAttributeNS(name[0], declared[name[0]] + ":" + name[1], value) else: e.setAttributeNS(None, name[1], value) def literal_element_start_DOM_OLD(self, name, qname, attrs): declared = self.LiteralNS[-1].copy() self.LiteralNS.append(declared) nsMap = self._prefixMap[-1] if name[0]: e = self.domDocument.createElementNS(name[0], name[1]) # progress("@@@ XML literal name: ", name) else: e = self.domDocument.createElement(name[1]) self.domElement.appendChild(e) self.domElement = e # progress("@@@ self.domElement.namespaceURI=", self.domElement.namespaceURI) for (name, value) in attrs.items(): if name[0]: e.setAttributeNS(name[0],name[1], value) else: e.setAttribute(name[1], value) #@@@ Missing prefix on qname #@@@ may need calculating as in the non-dom case, alas. def literal_element_end(self, name, qname): if name[0]: prefix = self._prefixMap[-1][name[0]] if prefix: end = u"" % (prefix, name[1]) else: end = u"" % name[1] else: end = u"" % name[1] self.testdata += end self.LiteralNS.pop() def literal_element_end_DOM(self, name, qname): self.domElement = self.domElement.parentNode self.LiteralNS.pop() class RDFXMLParser(RDFHandler): """XML/RDF parser based on sax XML interface""" flagDocumentation = """ Flags to control RDF/XML INPUT (after --rdf=) follow: S - Strict spec. Unknown parse type treated as Literal instead of error. T - take foreign XML as transparent and parse any RDF in it (default it is to ignore unless rdf:RDF at top level) L - If non-rdf attributes have no namespace prefix, assume in local <#> namespace D - Assume default namespace decalred as local document is assume xmlns="" R - Do not require an outer , treating the file as RDF content (opposite of T) Note: The parser (sax2rdf) does not support reification, bagIds, or parseType=Literal. It does support the rest of RDF inc. datatypes, xml:lang, and nodeIds. """ def __init__(self, sink, openFormula, thisDoc=None, flags="", why=None): RDFHandler.__init__(self, sink, openFormula, thisDoc, flags=flags, why=why) assert (not sink) or (thisDoc is not None), "Need document URI at the moment, sorry" p = xml.sax.make_parser() p.setFeature(feature_namespaces, 1) p.setContentHandler(self) self._p = p self.reason = why def feed(self, data): self._p.feed(data) def loadStream(self, stream): s = xml.sax.InputSource() s.setByteStream(stream) try: self._p.parse(s) except xml.sax._exceptions.SAXException, e: # was: raise SyntaxError() which left no info as to what had happened columnNumber = self._p.getColumnNumber() lineNumber = self._p.getLineNumber() where = "parsing XML at column %i in line %i of <%s>\n\t" % ( columnNumber, lineNumber, self._thisDoc) raise SyntaxError(where + sys.exc_info()[1].__str__()) # self.close() don't do a second time - see endDocument return self._formula def close(self): self._p.reset() self.flush() self.sink.endDoc(self._formula) return self._formula class XMLDOMParser(RDFXMLParser): """XML format to RDF Graph parser based on sax XML interface""" def __init__(self, thisDoc=None, flags="", why=None): RDFHandler.__init__(self, None, None, thisDoc, flags=flags, why=why) RDFXMLParser.__init__(self, None, None, thisDoc=thisDoc, flags=flags, why=why) self._state = STATE_LITERAL self._litDepth = 0 self.LiteralNS = [{}] self._prefixMap = [{}] self.testdata = '' # self._datatype = self.sink.newSymbol("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral") self.domDocument = self.domImplementation.createDocument( 'http://www.w3.org/1999/02/22-rdf-syntax-ns', 'envelope', None) # @@ get rid of this somehow self.domElement = self.domDocument.documentElement # self._subject = self.sink.newSymbol(thisDoc) # self.sink.makeStatement(( self._context, # self.sink.newSymbol(pred), # self._subject, # self.sink.newSymbol(self.uriref(obj)) ), why=self._reason2) class BadSyntax(SyntaxError): def __init__(self, info, message): self._info = info self._message = message def __str__(self): return self._message def XMLtoDOM(str): p = XMLDOMParser("foobar:") # Shouldn't need Doc URI etc p.feed(str) return p.domElement def test(args = None): import sys, getopt import notation3 from time import time if not args: args = sys.argv[1:] opts, args = getopt.getopt(args, 'st') klass = RDFHandler do_time = 0 for o, a in opts: if o == '-s': klass = None #@@ default handler for speed comparison? elif o == '-t': do_time = 1 if args: file = args[0] else: file = 'test.xml' if file == '-': f = sys.stdin else: try: f = open(file, 'r') except IOError, msg: print file, ":", msg sys.exit(1) x = klass(notation3.ToN3(sys.stdout.write), "file:/test.rdf") # test only! p = xml.sax.make_parser() from xml.sax.handler import feature_namespaces p.setFeature(feature_namespaces, 1) p.setContentHandler(x) p.setErrorHandler(xml.sax.ErrorHandler()) s = xml.sax.InputSource() t0 = time() try: if do_time: #print "parsing:", f s.setByteStream(f) p.parse(s) else: data = f.read() #print "data:", data if f is not sys.stdin: f.close() for c in data: p.feed(c, 1) p.close() except RuntimeError, msg: t1 = time() print msg if do_time: print 'total time: %g' % (t1-t0) sys.exit(1) t1 = time() if do_time: print 'total time: %g' % (t1-t0) if __name__ == '__main__': test() cwm-1.2.1/swap/__init__.py0000644015216600007660000000017610077032760014506 0ustar syosisyosi"""Init.py I'm not actually sure what this does. """ __version__ = "$Revision: 1.1 $" __all__ = [ "string" ] cwm-1.2.1/swap/local_decimal.py0000644015216600007660000003166410360736627015535 0ustar syosisyosi"""Decimal datatype This is an implementation of the Decimal XML schema datatype in python magnitude is the log10 of the number we multiply it by to get an integer $Id: local_decimal.py,v 1.2 2006/01/10 13:58:47 syosi Exp $ """ from types import IntType, FloatType, LongType, StringTypes from math import log10 class Decimal: """make a new Decimal Argument can be string, int, long, or float float is not recommended """ _limit = 16 def normalize(self): """convert this Decimal into some sort of canonical form """ if self.value == 0: self.magnitude = 0 return while self.value.__mod__(10) == 0: self.value = self.value / 10 self.magnitude = self.magnitude - 1 ## while self.magnitude > 2 * self.__class__._limit: ## self.value = self.value / 10 ## self.magnitude = self.magnitude - 1 def __init__(self, other=0): """How to get a new Decimal What happened? """ if isinstance(other, Decimal): self.value = other.value self.magnitude = other.magnitude return elif isinstance(other, IntType): self.value = long(other) self.magnitude = 0 self.normalize() return elif isinstance(other, LongType): self.value = other self.magnitude = 0 self.normalize() return elif hasattr(other,'__Decimal__') and callable(getattr(other, '__Decimal__')): a = other.__Decimal__() self.value = a.value self.magnitude = a.magnitude self.normalize() return elif isinstance(other,FloatType): other = `other` try: other[0] except TypeError: other = `other` other = other + 'q' i = 0 value = long(0) magnitude = long(0) sign = 1 newsign = 1 base = 10 magnitude_multiplier = 0 if other[i] == '-': sign = -1 i = i + 1 while other[i] in '0123456789': ours = other[i] i = i+1 value = value*base+int(ours, base) if other[i] == '.': i = i+1 while other[i] in '0123456789': ours = other[i] i = i+1 value = value*base+int(ours, base) magnitude = magnitude + 1 if other[i] in 'eE': i = i+1 if other[i] == '+': i = i+1 elif other[i] == '-': newsign = -1 i = i+1 while other[i] in '0123456789': ours = other[i] i = i+1 magnitude_multiplier = magnitude_multiplier*10+int(ours, 10) self.magnitude = magnitude-newsign*magnitude_multiplier self.value = value*sign self.normalize() def __abs__(self): """x.__abs__() <==> abs(x) """ a = self.__class__(self) a.value = abs(a.value) a.normalize() return a def __add__(self, other): """x.__add__(y) <==> x+y """ # if not isinstance(other, Decimal): # other = self.__class__(other) if other.magnitude < self.magnitude: return other.__add__(self) while other.magnitude > self.magnitude: self.magnitude = self.magnitude+1 self.value = self.value * 10 a = self.__class__() a.value = self.value + other.value a.magnitude = self.magnitude self.normalize() a.normalize() return a def __cmp__(self, other): """x.__cmp__(y) <==> cmp(x,y) """ if not isinstance(other, Decimal): other = self.__class__(other) if other.magnitude < self.magnitude: return -other.__cmp__(self) while other.magnitude > self.magnitude: self.magnitude = self.magnitude+1 self.value = self.value * 10 a = cmp(self.value, other.value) self.normalize() return a def __coerce__(self, other): """x.__coerce__(y) <==> coerce(x, y) """ if other.__class__ == float: return float(self), other return self, self.__class__(other) pass def __div__(self, other): """x.__div__(y) <==> x/y """ while self.magnitude < self.__class__._limit + other.magnitude + int(log10(other)): self.value = self.value * 10 self.magnitude = self.magnitude + 1 if self.value % other.value: a = float(self) / float(other) else: a = self.__class__() a.value = self.value // other.value a.magnitude = self.magnitude - other.magnitude a.normalize() self.normalize() if a == NotImplemented: raise RuntimeError return a def __divmod__(self, other): """x.__divmod__(y) <==> divmod(x, y) """ return (self // other, self % other) def __float__(self): """x.__float__() <==> float(x) """ return float(self.value * 10**(-self.magnitude)) def __floordiv__(self, other): """x.__floordiv__(y) <==> x//y """ # if not isinstance(other, Decimal): # other = self.__class__(other) if other.magnitude < self.magnitude: return other.__rfloordiv__(self) while other.magnitude > self.magnitude: self.magnitude = self.magnitude+1 self.value = self.value * 10 a = self.__class__() a.magnitude = 0 a.value = self.value // other.value a.normalize() return a def __hash__(self): """x.__hash__() <==> hash(x) """ return hash((self.value, self.magnitude)) def __int__(self): """x.__int__() <==> int(x) """ value = self.value power = self.magnitude while power > 0: value = value // 10 power = power - 1 return int(value * 10**(-power)) def __long__(self): """x.__long__() <==> long(x) """ value = self.value power = self.magnitude while power > 0: value = value // 10 power = power - 1 return long(value * 10**(-power)) def __mod__(self, other): """x.__mod__(y) <==> x%y """ # if not isinstance(other, Decimal): # other = self.__class__(other) if other.magnitude < self.magnitude: return other.__rmod__(self) while other.magnitude > self.magnitude: self.magnitude = self.magnitude+1 self.value = self.value * 10 a = self.__class__() a.magnitude = self.magnitude a.value = self.value % other.value a.normalize() return a def __mul__(self, other): """x.__mul__(y) <==> x*y """ # if not isinstance(other, Decimal): # other = self.__class__(other) a = self.__class__() a.value = self.value * other.value a.magnitude = self.magnitude + other.magnitude a.normalize() return a def __neg__(self): """x.__neg__ <==> -x """ a = self.__class__(self) a.value = -a.value return a def __nonzero__(self, other): """x.__nonzero__() <==> x != 0 """ return self.value != 0 def __pos__(self): """x.__pos__() <==> +x """ return self.__class__(self) def __pow__(self, other, mod=0): """x.__pow__(y[, z]) <==> pow(x, y[, z]) If the exponent is not an integer, we will simply convert things to floats first """ if not isinstance(other, Decimal): other = self.__class__(other) while other.magnitude < 0: other.value = other.value*10 other.magnitude = other.magnitude + 1 if other.magnitude == 0: a = self.__class__() a.value = self.value ** other.value a.magnitude = self.magnitude * other.value a.normalize() if mod !=0: a = a%mod return a else: #I honestly think that here we can give up on accuracy ## tempval = self.__class__(self.value ** other.value) ## tempval2 = self.__class__(10 ** (self.magnitude * other.value)) ## temppow = 10 ** other.magnitude ## a = self.__class__(n_root(tempval, temppow)) ## b = self.__class__(n_root(tempval2, temppow)) ## c = a / b ## c.normalize() a = self.__class__(pow(float(self),float(other),mod)) return a def __radd__(self, other): """x.__radd__(y) <==> y+x """ return self.__add__(other) def __rdiv__(self, other): """x.__rdiv__(y) <==> y/x """ if not isinstance(other, Decimal): other = self.__class__(other) return other.__div__(self) def __rdivmod__(self, other): """x.__rdivmod__(y) <==> divmod(y, x) """ return other.__rdivmod__(self) def __repr__(self): """x.__repr__() <==> repr(x) """ return '%s("%s")' % (self.__class__.__name__, str(self)) def __rfloordiv__(self, other): """x.__rfloordiv__(y) <==> y//x """ # if not isinstance(other, Decimal): # other = self.__class__(other) if other.magnitude < self.magnitude: return other.__floordiv__(self) while other.magnitude > self.magnitude: self.magnitude = self.magnitude+1 self.value = self.value * 10 a = self.__class__() a.magnitude = 0 a.value = other.value // self.value a.normalize() return a def __rmod__(self, other): """x.__rmod__(y) <==> y%x """ if not isinstance(other, Decimal): other = self.__class__(other) if other.magnitude < self.magnitude: return other.__mod__(self) while other.magnitude > self.magnitude: self.magnitude = self.magnitude+1 self.value = self.value * 10 a = self.__class__() a.magnitude = self.magnitude a.value = other.value % self.value a.normalize() return a def __rmul__(self, other): """x.__rmul__(y) <==> y*x """ return self.__mul__(other) def __rpow__(self, other, mod=0): """y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ return other.__pow__(self, mod) def __rsub__(self, other): """x.__rsub__(y) <==> y-x """ a = self.__class__(self) a.value = -a.value return a.__add__(other) def __rtruediv__(self, other): """x.__rtruediv__(y) <==> y/x """ return self.__rdiv__(other) # def __setattr__(self, other): # pass def __str__(self): """x.__str__() <==> str(x) """ magnitude = self.magnitude value = self.value output = [] if value == 0: return "0" try: magSign = magnitude / abs(magnitude) except ZeroDivisionError: magSign = 0 sign = value / abs(value) value = abs(value) while magnitude < 0: output.append("0") magnitude = magnitude + 1 while value != 0: if magnitude == 0 and magSign == 1: output.append(".") magSign = 0 digit = value.__mod__(10) value = value // 10 output.append("0123456789"[digit]) magnitude = magnitude-1 while magnitude > 0: output.append("0") magnitude = magnitude - 1 if magSign == 1: output.append('0.') if sign == -1: output.append('-') output.reverse() return "".join(output) def __sub__(self, other): """x.__sub__(y) <==> x-y """ a = self.__class__(other) a.value = -a.value return self.__add__(a) def __truediv__(self, other): """x.__truediv__(y) <==> x/y """ return self.__div__(self.__class__(other)) def n_root(base, power): """Find the nth root of a Decimal """ print 'trying to compute ', base, ' ** 1/ ', power accuracy = Decimal(1) n = 10 #Decimal._limit while n > 0: accuracy = accuracy / 10 n = n-1 oldguess = Decimal(0) guess = Decimal('.00000002') counter = 0 while 1: oldguess = guess counter = counter + 1 if counter == 100: print guess counter = 0 h = 1 - base * (guess ** power) guess = guess + guess * h / power if abs(guess - oldguess) <= accuracy: # print guess break # print guess answer = Decimal(1) / Decimal(guess) print answer return answer cwm-1.2.1/swap/cwm_times.py0000644015216600007660000001376410640063354014744 0ustar syosisyosi# # # # TODO: # - extraction os fields should extend date time if necessary # # See http://www.python.org/doc/current/lib/module-time.html # """ The time built-ins concern dates and times expressed in a specific version of ISO date-time format. These functions allow the various parts of the date and time to be compared, and converted into interger second GMT era format for arithmetic. Be aware that ISo times carry timezone offset information: they cannot be converted to integer second times without a valid timezone offset, such as "Z". """ import re import notation3 # N3 parsers and generators, and RDF generator import isodate # Local, by mnot. implements from diag import progress, verbosity from term import LightBuiltIn, Function, ReverseFunction import time, calendar # Python standard distribution TIMES_NS_URI = "http://www.w3.org/2000/10/swap/times#" __version__ = "0.3" DAY = 24 * 60 * 60 class BI_inSeconds(LightBuiltIn, Function, ReverseFunction): """For a time string, the number of seconds from the era start as an integer-representing string. """ def evaluateObject(self, subj_py): try: return str(isodate.parse(subj_py)) except: return None def evaluateSubject(self, obj_py): return isodate.fullString(int(obj_py)) class BI_equalTo(LightBuiltIn): def evaluate(self, subj_py, obj_py): try: return isodate.parse(subj_py) == isodate.parse(obj_py) except: return None class BI_year(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return subj_py[:4] except: return None class BI_month(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return subj_py[5:7] except: return None class BI_day(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return subj_py[8:10] except: return None class BI_date(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return subj_py[:10] except: return None class BI_hour(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return subj_py[11:13] except: return None class BI_minute(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return subj_py[14:16] except: return None class BI_second(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return subj_py[17:19] except: return None tzone = re.compile(r'.*([-+]\d{1,2}:\d{2,2})') class BI_timeZone(LightBuiltIn, Function): def evaluateObject(self, subj_py): m = tzone.match(subj_py) if m == None: return None return m.group(1) class BI_dayOfWeek(LightBuiltIn, Function): def evaluateObject(self, subj_py): weekdayZero = time.gmtime(0)[6] return str((weekdayZero + int(isodate.parse(subj_py)/DAY)) % 7 ) # class BI_format(LightBuiltIn, Function): def evaluateObject(self, subj_py): """params are ISO time string, format string. Returns reformatted. Ignores TZ@@""" if verbosity() > 80: progress("strTime:format input:"+`subj_py`) str, format = subj_py try: return time.strftime(format, time.gmtime(isodate.parse(str))) except: return None # class BI_gmTime(LightBuiltIn, Function): def evaluateObject(self, subj_py): """Subject is (empty string for standard formatting or) format string. Returns formatted.""" if verbosity() > 80: progress("time:gmTime input:"+`subj_py`) format = subj_py if format =="" : format="%Y-%m-%dT%H:%M:%SZ" try: return time.strftime(format, time.gmtime(time.time())) except: return isodate.asString(time()) class BI_localTime(LightBuiltIn, Function): def evaluateObject(self, subj_py): """Subject is format string or empty string for std formatting. Returns reformatted. @@@@ Ignores TZ""" if verbosity() > 80: progress("time:localTime input:"+`subj_py`) format = subj_py if format =="" : return isodate.asString(time.time()) return time.strftime(format, time.localtime(time.time())) # original things from mNot's cwm_time.py: # # these ise Integer time in seconds from epoch. # class BI_formatSeconds(LightBuiltIn, Function): def evaluateObject(self, subj_py): """params are epoch-seconds time string, format string. Returns reformatted""" if verbosity() > 80: progress("strTime:format input:"+`subj_py`) str, format = subj_py try: return time.strftime(format, time.gmtime(int(str))) except: return None class BI_parseToSeconds(LightBuiltIn, Function): def evaluateObject(self, subj_py): if verbosity() > 80: progress("strTime:parse input:"+`subj_py`) str, format = subj_py try: return str(calendar.timegm(time.strptime(str, format))) except: return None # Register the string built-ins with the store def register(store): str = store.symbol(TIMES_NS_URI[:-1]) str.internFrag("inSeconds", BI_inSeconds) str.internFrag("year", BI_year) str.internFrag("month", BI_month) str.internFrag("day", BI_day) str.internFrag("date", BI_date) str.internFrag("equalTo", BI_equalTo) str.internFrag("hour", BI_hour) str.internFrag("minute", BI_minute) str.internFrag("second", BI_second) str.internFrag("dayOfWeek", BI_dayOfWeek) str.internFrag("timeZone", BI_timeZone) str.internFrag("gmTime", BI_gmTime) str.internFrag("localTime", BI_localTime) str.internFrag("format", BI_format) # str.internFrag("parse", BI_parse) str.internFrag("formatSeconds", BI_formatSeconds) # Deprocate? str.internFrag("parseToSeconds", BI_parseToSeconds) # Deprocate? # ends cwm-1.2.1/swap/notation3.py0000755015216600007660000021477010731063552014677 0ustar syosisyosi#!/usr/local/bin/python """ $Id: notation3.py,v 1.200 2007/12/11 21:18:08 syosi Exp $ This module implements a Nptation3 parser, and the final part of a notation3 serializer. See also: Notation 3 http://www.w3.org/DesignIssues/Notation3 Closed World Machine - and RDF Processor http://www.w3.org/2000/10/swap/cwm To DO: See also "@@" in comments - Clean up interfaces ______________________________________________ Module originally by Dan Connolly, includeing notation3 parser and RDF generator. TimBL added RDF stream model and N3 generation, replaced stream model with use of common store/formula API. Yosi Scharf developped the module, including tests and test harness. """ # Python standard libraries import types, sys import string import codecs # python 2-ism; for writing utf-8 in RDF/xml output import urllib import re from warnings import warn from sax2rdf import XMLtoDOM # Incestuous.. would be nice to separate N3 and XML # SWAP http://www.w3.org/2000/10/swap from diag import verbosity, setVerbosity, progress from uripath import refTo, join import uripath import RDFSink from RDFSink import CONTEXT, PRED, SUBJ, OBJ, PARTS, ALL4 from RDFSink import LITERAL, XMLLITERAL, LITERAL_DT, LITERAL_LANG, ANONYMOUS, SYMBOL from RDFSink import Logic_NS import diag from xmlC14n import Canonicalize from why import BecauseOfData, becauseSubexpression N3_forSome_URI = RDFSink.forSomeSym N3_forAll_URI = RDFSink.forAllSym # Magic resources we know about from RDFSink import RDF_type_URI, RDF_NS_URI, DAML_sameAs_URI, parsesTo_URI from RDFSink import RDF_spec, List_NS, uniqueURI from local_decimal import Decimal ADDED_HASH = "#" # Stop where we use this in case we want to remove it! # This is the hash on namespace URIs RDF_type = ( SYMBOL , RDF_type_URI ) DAML_sameAs = ( SYMBOL, DAML_sameAs_URI ) from RDFSink import N3_first, N3_rest, N3_nil, N3_li, N3_List, N3_Empty LOG_implies_URI = "http://www.w3.org/2000/10/swap/log#implies" INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer" FLOAT_DATATYPE = "http://www.w3.org/2001/XMLSchema#double" DECIMAL_DATATYPE = "http://www.w3.org/2001/XMLSchema#decimal" BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean" option_noregen = 0 # If set, do not regenerate genids on output # @@ I18n - the notname chars need extending for well known unicode non-text # characters. The XML spec switched to assuming unknown things were name # characaters. # _namechars = string.lowercase + string.uppercase + string.digits + '_-' _notQNameChars = "\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~" # else valid qname :-/ _notNameChars = _notQNameChars + ":" # Assume anything else valid name :-/ _rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' N3CommentCharacter = "#" # For unix script #! compatabilty ########################################## Parse string to sink # # Regular expressions: eol = re.compile(r'[ \t]*(#[^\n]*)?\r?\n') # end of line, poss. w/comment eof = re.compile(r'[ \t]*(#[^\n]*)?$') # end of file, poss. w/comment ws = re.compile(r'[ \t]*') # Whitespace not including NL signed_integer = re.compile(r'[-+]?[0-9]+') # integer number_syntax = re.compile(r'(?P[-+]?[0-9]+)(?P\.[0-9]+)?(?Pe[-+]?[0-9]+)?') digitstring = re.compile(r'[0-9]+') # Unsigned integer interesting = re.compile(r'[\\\r\n\"]') langcode = re.compile(r'[a-zA-Z0-9]+(-[a-zA-Z0-9]+)?') #" class SinkParser: def __init__(self, store, openFormula=None, thisDoc="", baseURI=None, genPrefix = "", metaURI=None, flags="", why=None): """ note: namespace names should *not* end in #; the # will get added during qname processing """ self._bindings = {} self._flags = flags if thisDoc != "": assert ':' in thisDoc, "Document URI not absolute: <%s>" % thisDoc self._bindings[""] = thisDoc + "#" # default self._store = store if genPrefix: store.setGenPrefix(genPrefix) # pass it on self._thisDoc = thisDoc self.lines = 0 # for error handling self.startOfLine = 0 # For calculating character number self._genPrefix = genPrefix self.keywords = ['a', 'this', 'bind', 'has', 'is', 'of', 'true', 'false' ] self.keywordsSet = 0 # Then only can others be considerd qnames self._anonymousNodes = {} # Dict of anon nodes already declared ln: Term self._variables = {} self._parentVariables = {} self._reason = why # Why the parser was asked to parse this self._reason2 = None # Why these triples if diag.tracking: self._reason2 = BecauseOfData( store.newSymbol(thisDoc), because=self._reason) if baseURI: self._baseURI = baseURI else: if thisDoc: self._baseURI = thisDoc else: self._baseURI = None assert not self._baseURI or ':' in self._baseURI if not self._genPrefix: if self._thisDoc: self._genPrefix = self._thisDoc + "#_g" else: self._genPrefix = uniqueURI() if openFormula ==None: if self._thisDoc: self._formula = store.newFormula(thisDoc + "#_formula") else: self._formula = store.newFormula() else: self._formula = openFormula self._context = self._formula self._parentContext = None if metaURI: self.makeStatement((SYMBOL, metaURI), # relate doc to parse tree (SYMBOL, PARSES_TO_URI ), #pred (SYMBOL, thisDoc), #subj self._context) # obj self.makeStatement(((SYMBOL, metaURI), # quantifiers - use inverse? (SYMBOL, N3_forSome_URI), #pred self._context, #subj subj)) # obj def here(self, i): """String generated from position in file This is for repeatability when refering people to bnodes in a document. This has diagnostic uses less formally, as it should point one to which bnode the arbitrary identifier actually is. It gives the line and character number of the '[' charcacter or path character which introduced the blank node. The first blank node is boringly _L1C1. It used to be used only for tracking, but for tests in general it makes the canonical ordering of bnodes repeatable.""" return "%s_L%iC%i" % (self._genPrefix , self.lines, i - self.startOfLine + 1) def formula(self): return self._formula def loadStream(self, stream): return self.loadBuf(stream.read()) # Not ideal def loadBuf(self, buf): """Parses a buffer and returns its top level formula""" self.startDoc() self.feed(buf) return self.endDoc() # self._formula def feed(self, octets): """Feed an octet stream tothe parser if BadSyntax is raised, the string passed in the exception object is the remainder after any statements have been parsed. So if there is more data to feed to the parser, it should be straightforward to recover.""" str = octets.decode('utf-8') i = 0 while i >= 0: j = self.skipSpace(str, i) if j<0: return i = self.directiveOrStatement(str,j) if i<0: print "# next char: ", `str[j]` raise BadSyntax(self._thisDoc, self.lines, str, j, "expected directive or statement") def directiveOrStatement(self, str,h): i = self.skipSpace(str, h) if i<0: return i # EOF j = self.directive(str, i) if j>=0: return self.checkDot(str,j) j = self.statement(str, i) if j>=0: return self.checkDot(str,j) return j #@@I18N global _notNameChars #_namechars = string.lowercase + string.uppercase + string.digits + '_-' def tok(self, tok, str, i): """Check for keyword. Space must have been stripped on entry and we must not be at end of file.""" assert tok[0] not in _notNameChars # not for punctuation # was: string.whitespace which is '\t\n\x0b\x0c\r \xa0' -- not ascii whitespace = '\t\n\x0b\x0c\r ' if str[i:i+1] == "@": i = i+1 else: if tok not in self.keywords: return -1 # No, this has neither keywords declaration nor "@" if (str[i:i+len(tok)] == tok and (str[i+len(tok)] in _notQNameChars )): i = i + len(tok) return i else: return -1 def directive(self, str, i): j = self.skipSpace(str, i) if j<0: return j # eof res = [] j = self.tok('bind', str, i) # implied "#". Obsolete. if j>0: raise BadSyntax(self._thisDoc, self.lines, str, i, "keyword bind is obsolete: use @prefix") j = self.tok('keywords', str, i) if j>0: i = self.commaSeparatedList(str, j, res, self.bareWord) if i < 0: raise BadSyntax(self._thisDoc, self.lines, str, i, "'@keywords' needs comma separated list of words") self.setKeywords(res[:]) if diag.chatty_flag > 80: progress("Keywords ", self.keywords) return i j = self.tok('forAll', str, i) if j > 0: i = self.commaSeparatedList(str, j, res, self.uri_ref2) if i <0: raise BadSyntax(self._thisDoc, self.lines, str, i, "Bad variable list after @forAll") for x in res: #self._context.declareUniversal(x) if x not in self._variables or x in self._parentVariables: self._variables[x] = self._context.newUniversal(x) return i j = self.tok('forSome', str, i) if j > 0: i = self. commaSeparatedList(str, j, res, self.uri_ref2) if i <0: raise BadSyntax(self._thisDoc, self.lines, str, i, "Bad variable list after @forSome") for x in res: self._context.declareExistential(x) return i j=self.tok('prefix', str, i) # no implied "#" if j>=0: t = [] i = self.qname(str, j, t) if i<0: raise BadSyntax(self._thisDoc, self.lines, str, j, "expected qname after @prefix") j = self.uri_ref2(str, i, t) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "expected after @prefix _qname_") ns = self.uriOf(t[1]) if self._baseURI: ns = join(self._baseURI, ns) elif ":" not in ns: raise BadSyntax(self._thisDoc, self.lines, str, j, "With no base URI, cannot use relative URI in @prefix <"+ns+">") assert ':' in ns # must be absolute self._bindings[t[0][0]] = ns self.bind(t[0][0], hexify(ns)) return j j=self.tok('base', str, i) # Added 2007/7/7 if j >= 0: t = [] i = self.uri_ref2(str, j, t) if i<0: raise BadSyntax(self._thisDoc, self.lines, str, j, "expected after @base ") ns = self.uriOf(t[0]) if self._baseURI: ns = join(self._baseURI, ns) elif ':' not in ns: raise BadSyntax(self._thisDoc, self.lines, str, j, "With no previous base URI, cannot use relative URI in @base <"+ns+">") assert ':' in ns # must be absolute self._baseURI = ns return i return -1 # Not a directive, could be something else. def bind(self, qn, uri): assert isinstance(uri, types.StringType), "Any unicode must be %x-encoded already" if qn == "": self._store.setDefaultNamespace(uri) else: self._store.bind(qn, uri) def setKeywords(self, k): "Takes a list of strings" if k == None: self.keywordsSet = 0 else: self.keywords = k self.keywordsSet = 1 def startDoc(self): self._store.startDoc() def endDoc(self): """Signal end of document and stop parsing. returns formula""" self._store.endDoc(self._formula) # don't canonicalize yet return self._formula def makeStatement(self, quadruple): #$$$$$$$$$$$$$$$$$$$$$ # print "# Parser output: ", `quadruple` self._store.makeStatement(quadruple, why=self._reason2) def statement(self, str, i): r = [] i = self.object(str, i, r) # Allow literal for subject - extends RDF if i<0: return i j = self.property_list(str, i, r[0]) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "expected propertylist") return j def subject(self, str, i, res): return self.item(str, i, res) def verb(self, str, i, res): """ has _prop_ is _prop_ of a = _prop_ >- prop -> <- prop -< _operator_""" j = self.skipSpace(str, i) if j<0:return j # eof r = [] j = self.tok('has', str, i) if j>=0: i = self.prop(str, j, r) if i < 0: raise BadSyntax(self._thisDoc, self.lines, str, j, "expected property after 'has'") res.append(('->', r[0])) return i j = self.tok('is', str, i) if j>=0: i = self.prop(str, j, r) if i < 0: raise BadSyntax(self._thisDoc, self.lines, str, j, "expected after 'is'") j = self.skipSpace(str, i) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "End of file found, expected property after 'is'") return j # eof i=j j = self.tok('of', str, i) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "expected 'of' after 'is' ") res.append(('<-', r[0])) return j j = self.tok('a', str, i) if j>=0: res.append(('->', RDF_type)) return j if str[i:i+2] == "<=": res.append(('<-', self._store.newSymbol(Logic_NS+"implies"))) return i+2 if str[i:i+1] == "=": if str[i+1:i+2] == ">": res.append(('->', self._store.newSymbol(Logic_NS+"implies"))) return i+2 res.append(('->', DAML_sameAs)) return i+1 if str[i:i+2] == ":=": # patch file relates two formulae, uses this @@ really? res.append(('->', Logic_NS+"becomes")) return i+2 j = self.prop(str, i, r) if j >= 0: res.append(('->', r[0])) return j if str[i:i+2] == ">-" or str[i:i+2] == "<-": raise BadSyntax(self._thisDoc, self.lines, str, j, ">- ... -> syntax is obsolete.") return -1 def prop(self, str, i, res): return self.item(str, i, res) def item(self, str, i, res): return self.path(str, i, res) def blankNode(self, uri=None): if "B" not in self._flags: return self._context.newBlankNode(uri, why=self._reason2) x = self._context.newSymbol(uri) self._context.declareExistential(x) return x def path(self, str, i, res): """Parse the path production. """ j = self.nodeOrLiteral(str, i, res) if j<0: return j # nope while str[j:j+1] in "!^.": # no spaces, must follow exactly (?) ch = str[j:j+1] # @@ Allow "." followed IMMEDIATELY by a node. if ch == ".": ahead = str[j+1:j+2] if not ahead or (ahead in _notNameChars and ahead not in ":?<[{("): break subj = res.pop() obj = self.blankNode(uri=self.here(j)) j = self.node(str, j+1, res) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, j, "EOF found in middle of path syntax") pred = res.pop() if ch == "^": # Reverse traverse self.makeStatement((self._context, pred, obj, subj)) else: self.makeStatement((self._context, pred, subj, obj)) res.append(obj) return j def anonymousNode(self, ln): """Remember or generate a term for one of these _: anonymous nodes""" term = self._anonymousNodes.get(ln, None) if term != None: return term term = self._store.newBlankNode(self._context, why=self._reason2) self._anonymousNodes[ln] = term return term def node(self, str, i, res, subjectAlready=None): """Parse the production. Space is now skipped once at the beginning instead of in multipe calls to self.skipSpace(). """ subj = subjectAlready j = self.skipSpace(str,i) if j<0: return j #eof i=j ch = str[i:i+1] # Quick 1-character checks first: if ch == "[": bnodeID = self.here(i) j=self.skipSpace(str,i+1) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "EOF after '['") if str[j:j+1] == "=": # Hack for "is" binding name to anon node i = j+1 objs = [] j = self.objectList(str, i, objs); if j>=0: subj = objs[0] if len(objs)>1: for obj in objs: self.makeStatement((self._context, DAML_sameAs, subj, obj)) j = self.skipSpace(str, j) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "EOF when objectList expected after [ = ") if str[j:j+1] == ";": j=j+1 else: raise BadSyntax(self._thisDoc, self.lines, str, i, "objectList expected after [= ") if subj is None: subj=self.blankNode(uri= bnodeID) i = self.property_list(str, j, subj) if i<0: raise BadSyntax(self._thisDoc, self.lines, str, j, "property_list expected") j = self.skipSpace(str, i) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "EOF when ']' expected after [ ") if str[j:j+1] != "]": raise BadSyntax(self._thisDoc, self.lines, str, j, "']' expected") res.append(subj) return j+1 if ch == "{": ch2 = str[i+1:i+2] if ch2 == '$': i += 1 j = i + 1 List = [] first_run = True while 1: i = self.skipSpace(str, j) if i<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "needed '$}', found end.") if str[i:i+2] == '$}': j = i+2 break if not first_run: if str[i:i+1] == ',': i+=1 else: raise BadSyntax(self._thisDoc, self.lines, str, i, "expected: ','") else: first_run = False item = [] j = self.item(str,i, item) #@@@@@ should be path, was object if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "expected item in set or '$}'") List.append(self._store.intern(item[0])) res.append(self._store.newSet(List, self._context)) return j else: j=i+1 oldParentContext = self._parentContext self._parentContext = self._context parentAnonymousNodes = self._anonymousNodes grandParentVariables = self._parentVariables self._parentVariables = self._variables self._anonymousNodes = {} self._variables = self._variables.copy() reason2 = self._reason2 self._reason2 = becauseSubexpression if subj is None: subj = self._store.newFormula() self._context = subj while 1: i = self.skipSpace(str, j) if i<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "needed '}', found end.") if str[i:i+1] == "}": j = i+1 break j = self.directiveOrStatement(str,i) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "expected statement or '}'") self._anonymousNodes = parentAnonymousNodes self._variables = self._parentVariables self._parentVariables = grandParentVariables self._context = self._parentContext self._reason2 = reason2 self._parentContext = oldParentContext res.append(subj.close()) # No use until closed return j if ch == "(": thing_type = self._store.newList ch2 = str[i+1:i+2] if ch2 == '$': thing_type = self._store.newSet i += 1 j=i+1 List = [] while 1: i = self.skipSpace(str, j) if i<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "needed ')', found end.") if str[i:i+1] == ')': j = i+1 break item = [] j = self.item(str,i, item) #@@@@@ should be path, was object if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "expected item in list or ')'") List.append(self._store.intern(item[0])) res.append(thing_type(List, self._context)) return j j = self.tok('this', str, i) # This context if j>=0: warn(''.__class__(BadSyntax(self._thisDoc, self.lines, str, i, "Keyword 'this' was ancient N3. Now use @forSome and @forAll keywords."))) res.append(self._context) return j #booleans j = self.tok('true', str, i) if j>=0: res.append(True) return j j = self.tok('false', str, i) if j>=0: res.append(False) return j if subj is None: # If this can be a named node, then check for a name. j = self.uri_ref2(str, i, res) if j >= 0: return j return -1 def property_list(self, str, i, subj): """Parse property list Leaves the terminating punctuation in the buffer """ while 1: j = self.skipSpace(str, i) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "EOF found when expected verb in property list") return j #eof if str[j:j+2] ==":-": i = j + 2 res = [] j = self.node(str, i, res, subj) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "bad {} or () or [] node after :- ") i=j continue i=j v = [] j = self.verb(str, i, v) if j<=0: return i # void but valid objs = [] i = self.objectList(str, j, objs) if i<0: raise BadSyntax(self._thisDoc, self.lines, str, j, "objectList expected") for obj in objs: dir, sym = v[0] if dir == '->': self.makeStatement((self._context, sym, subj, obj)) else: self.makeStatement((self._context, sym, obj, subj)) j = self.skipSpace(str, i) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, j, "EOF found in list of objects") return j #eof if str[i:i+1] != ";": return i i = i+1 # skip semicolon and continue def commaSeparatedList(self, str, j, res, what): """return value: -1 bad syntax; >1 new position in str res has things found appended """ i = self.skipSpace(str, j) if i<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "EOF found expecting comma sep list") return i if str[i] == ".": return j # empty list is OK i = what(str, i, res) if i<0: return -1 while 1: j = self.skipSpace(str, i) if j<0: return j # eof ch = str[j:j+1] if ch != ",": if ch != ".": return -1 return j # Found but not swallowed "." i = what(str, j+1, res) if i<0: raise BadSyntax(self._thisDoc, self.lines, str, i, "bad list content") return i def objectList(self, str, i, res): i = self.object(str, i, res) if i<0: return -1 while 1: j = self.skipSpace(str, i) if j<0: raise BadSyntax(self._thisDoc, self.lines, str, j, "EOF found after object") return j #eof if str[j:j+1] != ",": return j # Found something else! i = self.object(str, j+1, res) if i<0: return i def checkDot(self, str, i): j = self.skipSpace(str, i) if j<0: return j #eof if str[j:j+1] == ".": return j+1 # skip if str[j:j+1] == "}": return j # don't skip it if str[j:j+1] == "]": return j raise BadSyntax(self._thisDoc, self.lines, str, j, "expected '.' or '}' or ']' at end of statement") return i def uri_ref2(self, str, i, res): """Generate uri from n3 representation. Note that the RDF convention of directly concatenating NS and local name is now used though I prefer inserting a '#' to make the namesapces look more like what XML folks expect. """ qn = [] j = self.qname(str, i, qn) if j>=0: pfx, ln = qn[0] if pfx is None: assert 0, "not used?" ns = self._baseURI + ADDED_HASH else: try: ns = self._bindings[pfx] except KeyError: if pfx == "_": # Magic prefix 2001/05/30, can be overridden res.append(self.anonymousNode(ln)) return j raise BadSyntax(self._thisDoc, self.lines, str, i, "Prefix \"%s:\" not bound" % (pfx)) symb = self._store.newSymbol(ns + ln) if symb in self._variables: res.append(self._variables[symb]) else: res.append(symb) # @@@ "#" CONVENTION if not string.find(ns, "#"):progress( "Warning: no # on namespace %s," % ns) return j i = self.skipSpace(str, i) if i<0: return -1 if str[i] == "?": v = [] j = self.variable(str,i,v) if j>0: #Forget varibles as a class, only in context. res.append(v[0]) return j return -1 elif str[i]=="<": i = i + 1 st = i while i < len(str): if str[i] == ">": uref = str[st:i] # the join should dealt with "": if self._baseURI: uref = uripath.join(self._baseURI, uref) else: assert ":" in uref, \ "With no base URI, cannot deal with relative URIs" if str[i-1:i]=="#" and not uref[-1:]=="#": uref = uref + "#" # She meant it! Weirdness in urlparse? symb = self._store.newSymbol(uref) if symb in self._variables: res.append(self._variables[symb]) else: res.append(symb) return i+1 i = i + 1 raise BadSyntax(self._thisDoc, self.lines, str, j, "unterminated URI reference") elif self.keywordsSet: v = [] j = self.bareWord(str,i,v) if j<0: return -1 #Forget varibles as a class, only in context. if v[0] in self.keywords: raise BadSyntax(self._thisDoc, self.lines, str, i, 'Keyword "%s" not allowed here.' % v[0]) res.append(self._store.newSymbol(self._bindings[""]+v[0])) return j else: return -1 def skipSpace(self, str, i): """Skip white space, newlines and comments. return -1 if EOF, else position of first non-ws character""" while 1: m = eol.match(str, i) if m == None: break self.lines = self.lines + 1 i = m.end() # Point to first character unmatched self.startOfLine = i m = ws.match(str, i) if m != None: i = m.end() m = eof.match(str, i) if m != None: return -1 return i def variable(self, str, i, res): """ ?abc -> variable(:abc) """ j = self.skipSpace(str, i) if j<0: return -1 if str[j:j+1] != "?": return -1 j=j+1 i = j if str[j] in "0123456789-": raise BadSyntax(self._thisDoc, self.lines, str, j, "Varible name can't start with '%s'" % str[j]) return -1 while i :abc """ j = self.skipSpace(str, i) if j<0: return -1 if str[j] in "0123456789-" or str[j] in _notNameChars: return -1 i = j while i ('xyz', 'def') If not in keywords and keywordsSet: def -> ('', 'def') :def -> ('', 'def') """ i = self.skipSpace(str, i) if i<0: return -1 c = str[i] if c in "0123456789-+": return -1 if c not in _notNameChars: ln = c i = i + 1 while i < len(str): c = str[i] if c not in _notNameChars: ln = ln + c i = i + 1 else: break else: # First character is non-alpha ln = '' # Was: None - TBL (why? useful?) if i= 0: return j else: j = self.skipSpace(str, i) if j<0: return -1 else: i=j if str[i]=='"': if str[i:i+3] == '"""': delim = '"""' else: delim = '"' i = i + len(delim) j, s = self.strconst(str, i, delim) res.append(self._store.newLiteral(s)) progress("New string const ", s, j) return j else: return -1 def nodeOrLiteral(self, str, i, res): j = self.node(str, i, res) if j>= 0: return j else: j = self.skipSpace(str, i) if j<0: return -1 else: i=j ch = str[i] if ch in "-+0987654321": m = number_syntax.match(str, i) if m == None: raise BadSyntax(self._thisDoc, self.lines, str, i, "Bad number syntax") j = m.end() if m.group('exponent') != None: # includes decimal exponent res.append(float(str[i:j])) # res.append(self._store.newLiteral(str[i:j], # self._store.newSymbol(FLOAT_DATATYPE))) elif m.group('decimal') != None: res.append(Decimal(str[i:j])) else: res.append(long(str[i:j])) # res.append(self._store.newLiteral(str[i:j], # self._store.newSymbol(INTEGER_DATATYPE))) return j if str[i]=='"': if str[i:i+3] == '"""': delim = '"""' else: delim = '"' i = i + len(delim) dt = None j, s = self.strconst(str, i, delim) lang = None if str[j:j+1] == "@": # Language? m = langcode.match(str, j+1) if m == None: raise BadSyntax(self._thisDoc, startline, str, i, "Bad language code syntax on string literal, after @") i = m.end() lang = str[j+1:i] j = i if str[j:j+2] == "^^": res2 = [] j = self.uri_ref2(str, j+2, res2) # Read datatype URI dt = res2[0] if dt.uriref() == "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral": try: dom = XMLtoDOM('' + s + '').firstChild except: raise ValueError('s="%s"' % s) res.append(self._store.newXMLLiteral(dom)) return j res.append(self._store.newLiteral(s, dt, lang)) return j else: return -1 def uriOf(self, sym): if isinstance(sym, types.TupleType): return sym[1] # old system for --pipe return sym.uriref() # cwm api def strconst(self, str, i, delim): """parse an N3 string constant delimited by delim. return index, val """ j = i ustr = u"" # Empty unicode string startline = self.lines # Remember where for error messages while j= 0: uch = '\a\b\f\r\t\v\n\\"'[k] ustr = ustr + uch j = j + 1 elif ch == "u": j, ch = self.uEscape(str, j+1, startline) ustr = ustr + ch elif ch == "U": j, ch = self.UEscape(str, j+1, startline) ustr = ustr + ch else: raise BadSyntax(self._thisDoc, self.lines, str, i, "bad escape") raise BadSyntax(self._thisDoc, self.lines, str, i, "unterminated string literal") def uEscape(self, str, i, startline): j = i count = 0 value = 0 while count < 4: # Get 4 more characters ch = str[j:j+1].lower() # sbp http://ilrt.org/discovery/chatlogs/rdfig/2002-07-05 j = j + 1 if ch == "": raise BadSyntax(self._thisDoc, startline, str, i, "unterminated string literal(3)") k = string.find("0123456789abcdef", ch) if k < 0: raise BadSyntax(self._thisDoc, startline, str, i, "bad string literal hex escape") value = value * 16 + k count = count + 1 uch = unichr(value) return j, uch def UEscape(self, str, i, startline): stringType = type('') j = i count = 0 value = '\\U' while count < 8: # Get 8 more characters ch = str[j:j+1].lower() # sbp http://ilrt.org/discovery/chatlogs/rdfig/2002-07-05 j = j + 1 if ch == "": raise BadSyntax(self._thisDoc, startline, str, i, "unterminated string literal(3)") k = string.find("0123456789abcdef", ch) if k < 0: raise BadSyntax(self._thisDoc, startline, str, i, "bad string literal hex escape") value = value + ch count = count + 1 uch = stringType(value).decode('unicode-escape') return j, uch wide_build = True try: unichr(0x10000) except ValueError: wide_build = False # If we are going to do operators then they should generate # [ is operator:plus of ( \1 \2 ) ] class BadSyntax(SyntaxError): def __init__(self, uri, lines, str, i, why): self._str = str.encode('utf-8') # Better go back to strings for errors self._i = i self._why = why self.lines = lines self._uri = uri def __str__(self): str = self._str i = self._i st = 0 if i>60: pre="..." st = i - 60 else: pre="" if len(str)-i > 60: post="..." else: post="" return 'at line %i of <%s>:\nBad syntax (%s) at ^ in:\n"%s%s^%s%s"' \ % (self.lines +1, self._uri, self._why, pre, str[st:i], str[i:i+60], post) def stripCR(str): res = "" for ch in str: if ch != "\r": res = res + ch return res def dummyWrite(x): pass ################################################################################ def toBool(s): if s == 'true' or s == 'True' or s == '1': return True if s == 'false' or s == 'False' or s == '0': return False raise ValueError(s) class ToN3(RDFSink.RDFSink): """Serializer output sink for N3 keeps track of most recent subject and predicate reuses them. Adapted from Dan's ToRDFParser(Parser); """ flagDocumentation = """Flags for N3 output are as follows:- a Anonymous nodes should be output using the _: convention (p flag or not). d Don't use default namespace (empty prefix) e escape literals --- use \u notation i Use identifiers from store - don't regen on output l List syntax suppression. Don't use (..) n No numeric syntax - use strings typed with ^^ syntax p Prefix suppression - don't use them, always URIs in <> instead of qnames. q Quiet - don't output comments about version and base URI used. r Relative URI suppression. Always use absolute URIs. s Subject must be explicit for every statement. Don't use ";" shorthand. t "this" and "()" special syntax should be suppresed. u Use \u for unicode escaping in URIs instead of utf-8 %XX v Use "this log:forAll" for @forAll, and "this log:forAll" for "@forSome". / If namespace has no # in it, assume it ends at the last slash if outputting. Flags for N3 input: B Turn any blank node into a existentially qualified explicitly named node. """ # " # A word about regenerated Ids. # # Within the program, the URI of a resource is kept the same, and in fact # tampering with it would leave risk of all kinds of inconsistencies. # Hwoever, on output, where there are URIs whose values are irrelevant, # such as variables and generated IDs from anonymous ndoes, it makes the # document very much more readable to regenerate the IDs. # We use here a convention that underscores at the start of fragment IDs # are reserved for generated Ids. The caller can change that. # # Now there is a new way of generating these, with the "_" prefix # for anonymous nodes. def __init__(self, write, base=None, genPrefix = None, noLists=0 , quiet=0, flags=""): gp = genPrefix if gp == None: gp = "#_g" if base!=None: try: gp = uripath.join(base, "#_g") except ValueError: pass # bogus: base eg RDFSink.RDFSink.__init__(self, gp) self._write = self.writeEncoded self._writeRaw = write self._quiet = quiet or "q" in flags self._flags = flags self._subj = None self.prefixes = {} # Look up prefix conventions self.defaultNamespace = None self.indent = 1 # Level of nesting of output self.base = base # self.nextId = 0 # Regenerate Ids on output self.regen = {} # Mapping of regenerated Ids self.noLists = noLists # Suppress generation of lists? self._anodeName = {} # For "a" flag self._anodeId = {} # For "a" flag - reverse mapping self._needNL = 0 # Do we need to have a newline before a new element? if "l" in self._flags: self.noLists = 1 def dummyClone(self): "retun a version of myself which will only count occurrences" return ToN3(write=dummyWrite, base=self.base, genPrefix=self._genPrefix, noLists=self.noLists, quiet=self._quiet, flags=self._flags ) def writeEncoded(self, str): """Write a possibly unicode string out to the output""" try: return self._writeRaw(str.encode('utf-8')) except UnicodeDecodeError: raise UnicodeDecodeError(str, str.__class__) def setDefaultNamespace(self, uri): return self.bind("", uri) def bind(self, prefixString, uri): """ Just accepting a convention here """ assert ':' in uri # absolute URI references only if "p" in self._flags: return # Ignore the prefix system completely # if not prefixString: # raise RuntimError("Please use setDefaultNamespace instead") if (uri == self.defaultNamespace and "d" not in self._flags): return # don't duplicate ?? self._endStatement() self.prefixes[uri] = prefixString if 'r' in self._flags: self._write(u"@prefix %s: <%s> ."%(prefixString, uri)) else: self._write(u"@prefix %s: <%s> ."%(prefixString, refTo(self.base, uri))) self._newline() def setDefaultNamespace(self, uri): if "d" in self._flags or "p" in self._flags: return # Ignore the prefix system completely self._endStatement() self.defaultNamespace = uri if self.base: # Sometimes there is none, and now refTo is intolerant x = refTo(self.base, uri) else: x = uri self._write(u" @prefix : <%s> ." % x ) self._newline() def startDoc(self): if not self._quiet: # Suppress stuff which will confuse test diffs self._write(u"\n# Notation3 generation by\n") idstr = u"$Id: notation3.py,v 1.200 2007/12/11 21:18:08 syosi Exp $" # CVS CHANGES THE ABOVE LINE self._write(u"# " + idstr[5:-2] + u"\n\n") # Strip "$" in case the N3 file is checked in to CVS if self.base: self._write(u"# Base was: " + self.base + u"\n") self._write(u" " * self.indent) self._subj = None # self._nextId = 0 def endDoc(self, rootFormulaPair=None): self._endStatement() self._write(u"\n") if self.stayOpen: return # fo concatenation if not self._quiet: self._write(u"#ENDS\n") return # No formula returned - this is not a store def makeComment(self, str): for line in string.split(str, "\n"): self._write(u"#" + line + "\n") # Newline order??@@ self._write(u" " * self.indent + " ") def _newline(self, extra=0): self._write(u"\n"+ u" " * (self.indent+extra)) def makeStatement(self, triple, why=None, aIsPossible=1): # triple = tuple([a.asPair() for a in triple2]) if ("a" in self._flags and triple[PRED] == (SYMBOL, N3_forSome_URI) and triple[CONTEXT] == triple[SUBJ]) : # and # We assume the output is flat @@@ true, we should not try: aIsPossible = aIsPossible() except TypeError: aIsPossible = 1 if aIsPossible: ty, value = triple[OBJ] i = len(value) while i > 0 and value[i-1] not in _notNameChars+"_": i = i - 1 str2 = value[i:] if self._anodeName.get(str2, None) != None: j = 1 while 1: str3 = str2 + `j` if self._anodeName.get(str3, None) == None: break j = j +1 str2 = str3 if str2[0] in "0123456789": str2 = "a"+str2 if diag.chatty_flag > 60: progress( "Anode %s means %s" % (str2, value)) self._anodeName[str2] = value self._anodeId[value] = str2 return self._makeSubjPred(triple[CONTEXT], triple[SUBJ], triple[PRED]) self._write(self.representationOf(triple[CONTEXT], triple[OBJ])) self._needNL = 1 # Below is for writing an anonymous node # As object, with one incoming arc: def startAnonymous(self, triple): self._makeSubjPred(triple[CONTEXT], triple[SUBJ], triple[PRED]) self._write(u" [") self.indent = self.indent + 1 self._pred = None self._newline() self._subj = triple[OBJ] # The object is now the current subject def endAnonymous(self, subject, verb): # Remind me where we are self._write(u" ]") self.indent = self.indent - 1 self._subj = subject self._pred = verb # As subject: def startAnonymousNode(self, subj): if self._subj: self._write(u" .") self._newline() self.indent = self.indent + 1 self._write(u" [ ") self._subj = subj # The object is not the subject context self._pred = None def endAnonymousNode(self, subj=None): # Remove default subject self._write(u" ]") if not subj: self._write(u".") self.indent = self.indent - 1 self._newline() self._subj = subj self._pred = None # Below we print lists. A list expects to have lots of li links sent # As subject: def startListSubject(self, subj): if self._subj: self._write(u" .") self._newline() self.indent = self.indent + 1 self._write(u" ( ") self._needNL = 0 self._subj = subj # The object is not the subject context self._pred = N3_li # expect these until list ends def endListSubject(self, subj=None): # Remove default subject self._write(u" )") if not subj: self._write(u".") self.indent = self.indent - 1 self._newline() self._subj = subj self._pred = None # As Object: def startListObject(self, triple): self._makeSubjPred(triple[CONTEXT], triple[SUBJ], triple[PRED]) self._subj = triple[OBJ] self._write(u" (") self._needNL = 1 # Choice here of compactness self.indent = self.indent + 1 self._pred = N3_li # expect these until list ends self._subj = triple[OBJ] # The object is now the current subject def endListObject(self, subject, verb): # Remind me where we are self._write(u" )") self.indent = self.indent - 1 self._subj = subject self._pred = verb # Below we print a nested formula of statements def startFormulaSubject(self, context): if self._subj != context: self._endStatement() self.indent = self.indent + 1 self._write(u"{") self._newline() self._subj = None self._pred = None def endFormulaSubject(self, subj): # Remove context self._endStatement() # @@@@@@@@ remove in syntax change to implicit self._newline() self.indent = self.indent - 1 self._write(u"}") self._subj = subj self._pred = None def startFormulaObject(self, triple): self._makeSubjPred(triple[CONTEXT], triple[SUBJ], triple[PRED]) self.indent = self.indent + 1 self._write(u"{") self._subj = None self._pred = None def endFormulaObject(self, pred, subj): # Remove context self._endStatement() # @@@@@@@@ remove in syntax change to implicit self.indent = self.indent - 1 self._write(u"}") # self._newline() self._subj = subj self._pred = pred def _makeSubjPred(self, context, subj, pred): if pred == N3_li: if self._needNL: self._newline() return # If we are in list mode, don't need to. varDecl = (subj == context and "v" not in self._flags and ( pred == (SYMBOL, N3_forAll_URI) or pred == (SYMBOL, N3_forSome_URI))) if self._subj != subj or "s" in self._flags: self._endStatement() if self.indent == 1: # Top level only - extra newline self._newline() if "v" in self._flags or subj != context: self._write(self.representationOf(context, subj)) else: # "this" suppressed if (pred != (SYMBOL, N3_forAll_URI) and pred != (SYMBOL, N3_forSome_URI)): raise ValueError( "On N3 output, 'this' used with bad predicate: %s" % (pred, )) self._subj = subj self._pred = None if self._pred != pred: if self._pred: if "v" not in self._flags and ( self._pred== (SYMBOL, N3_forAll_URI) or self._pred == (SYMBOL, N3_forSome_URI)): self._write(u".") else: self._write(u";") self._newline(1) # Indent predicate from subject elif not varDecl: self._write(u" ") if varDecl: if pred == (SYMBOL, N3_forAll_URI): self._write( u" @forAll ") else: self._write( u" @forSome ") elif pred == (SYMBOL, DAML_sameAs_URI) and "t" not in self._flags: self._write(u" = ") elif pred == (SYMBOL, RDF_type_URI) and "t" not in self._flags: self._write(u" a ") else : self._write( u" %s " % self.representationOf(context, pred)) self._pred = pred else: self._write(u",") self._newline(3) # Same subject and pred => object list def _endStatement(self): if self._subj: self._write(u" .") self._newline() self._subj = None def representationOf(self, context, pair): """ Representation of a thing in the output stream Regenerates genids if required. Uses prefix dictionary to use qname syntax if possible. """ if "t" not in self._flags: if pair == context: return u"this" if pair == N3_nil and not self.noLists: return u"()" ty, value = pair singleLine = "n" in self._flags if ty == LITERAL: return stringToN3(value, singleLine=singleLine, flags = self._flags) if ty == XMLLITERAL: st = u''.join([Canonicalize(x, None, unsuppressedPrefixes=['foo']) for x in value.childNodes]) st = stringToN3(st, singleLine=singleLine, flags=self._flags) return st + u"^^" + self.representationOf(context, (SYMBOL, u"http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral")) if ty == LITERAL_DT: s, dt = value if "b" not in self._flags: if (dt == BOOLEAN_DATATYPE): return toBool(s) and u"true" or u"false" if "n" not in self._flags: dt_uri = dt if (dt_uri == INTEGER_DATATYPE): return unicode(long(s)) if (dt_uri == FLOAT_DATATYPE): retVal = unicode(float(s)) # numeric value python-normalized if 'e' not in retVal: retVal += 'e+00' return retVal if (dt_uri == DECIMAL_DATATYPE): retVal = unicode(Decimal(s)) if '.' not in retVal: retVal += '.0' return retVal st = stringToN3(s, singleLine= singleLine, flags=self._flags) return st + u"^^" + self.representationOf(context, (SYMBOL, dt)) if ty == LITERAL_LANG: s, lang = value return stringToN3(s, singleLine= singleLine, flags=self._flags)+ u"@" + lang aid = self._anodeId.get(pair[1], None) if aid != None: # "a" flag only return u"_:" + aid # Must start with alpha as per NTriples spec. if ((ty == ANONYMOUS) and not option_noregen and "i" not in self._flags ): x = self.regen.get(value, None) if x == None: x = self.genId() self.regen[value] = x value = x # return "<"+x+">" j = string.rfind(value, "#") if j<0 and "/" in self._flags: j=string.rfind(value, "/") # Allow "/" namespaces as a second best if (j>=0 and "p" not in self._flags): # Suppress use of prefixes? for ch in value[j+1:]: # Examples: "." ";" we can't have in qname if ch in _notNameChars: if verbosity() > 20: progress("Cannot have character %i in local name for %s" % (ord(ch), `value`)) break else: namesp = value[:j+1] if (self.defaultNamespace and self.defaultNamespace == namesp and "d" not in self._flags): return u":"+value[j+1:] self.countNamespace(namesp) prefix = self.prefixes.get(namesp, None) # @@ #CONVENTION if prefix != None : return prefix + u":" + value[j+1:] if value[:j] == self.base: # If local to output stream, return u"<#" + value[j+1:] + u">" # use local frag id if "r" not in self._flags and self.base != None: value = hexify(refTo(self.base, value)) elif "u" in self._flags: value = backslashUify(value) else: value = hexify(value) return u"<" + value + u">" # Everything else def nothing(): pass import triple_maker as tm LIST = 10000 QUESTION = 10001 class tmToN3(RDFSink.RDFSink): """ """ def __init__(self, write, base=None, genPrefix = None, noLists=0 , quiet=0, flags=""): gp = genPrefix if gp == None: gp = "#_g" if base!=None: try: gp = uripath.join(base, "#_g") except ValueError: pass # bogus: base eg RDFSink.RDFSink.__init__(self, gp) self._write = self.writeEncoded self._writeRaw = write self._quiet = quiet or "q" in flags self._flags = flags self._subj = None self.prefixes = {} # Look up prefix conventions self.defaultNamespace = None self.indent = 1 # Level of nesting of output self.base = base # self.nextId = 0 # Regenerate Ids on output self.regen = {} # Mapping of regenerated Ids # self.genPrefix = genPrefix # Prefix for generated URIs on output self.noLists = noLists # Suppress generation of lists? self._anodeName = {} # For "a" flag self._anodeId = {} # For "a" flag - reverse mapping if "l" in self._flags: self.noLists = 1 def writeEncoded(self, str): """Write a possibly unicode string out to the output""" return self._writeRaw(str.encode('utf-8')) def _newline(self, extra=0): self._needNL = 0 self._write("\n"+ " " * (self.indent+extra)) def bind(self, prefixString, uri): """ Just accepting a convention here """ assert ':' in uri # absolute URI references only if "p" in self._flags: return # Ignore the prefix system completely if not prefixString: return self.setDefaultNamespace(uri) if (uri == self.defaultNamespace and "d" not in self._flags): return # don't duplicate ?? self.endStatement() self.prefixes[uri] = prefixString self._write(" @prefix %s: <%s> ." % (prefixString, refTo(self.base, uri)) ) self._newline() def setDefaultNamespace(self, uri): if "d" in self._flags or "p" in self._flags: return # no prefix system self.endStatement() self.defaultNamespace = uri if self.base: # Sometimes there is none, and now refTo is intolerant x = refTo(self.base, uri) else: x = uri self._write(" @prefix : <%s> ." % x ) self._newline() def start(self): pass self._parts = [0] self._types = [None] self._nodeEnded = False def end(self): self._write('\n\n#End') def addNode(self, node): self._parts[-1] += 1 if node is not None: self._realEnd() if self._types == LITERAL: lit, dt, lang = node singleLine = "n" in self._flags if dt != None and "n" not in self._flags: dt_uri = dt if (dt_uri == INTEGER_DATATYPE): self._write(str(long(lit))) return if (dt_uri == FLOAT_DATATYPE): self._write(str(float(lit))) # numeric python-normalized return if (dt_uri == DECIMAL_DATATYPE): self._write(str(Decimal(lit))) return st = stringToN3(lit, singleLine= singleLine, flags=self._flags) if lang != None: st = st + "@" + lang if dt != None: st = st + "^^" + self.symbolString(dt) self._write(st) elif self._types == SYMBOL: self._write(self.symbolString(node) + ' ') elif self._types == QUESTION: self._write('?' + node + ' ') def _realEnd(self): if self._nodeEnded: self._nodeEnded = False if self._parts[-1] == 1: self._write(' . \n') elif self._parts[-1] == 2: self._write(';\n') elif self._parts[-1] == 3: self._write(',\n') else: pass def symbolString(self, value): j = string.rfind(value, "#") if j<0 and "/" in self._flags: j=string.rfind(value, "/") # Allow "/" namespaces as a second best if (j>=0 and "p" not in self._flags): # Suppress use of prefixes? for ch in value[j+1:]: # Examples: "." ";" we can't have in qname if ch in _notNameChars: if verbosity() > 0: progress("Cannot have character %i in local name." % ord(ch)) break else: namesp = value[:j+1] if (self.defaultNamespace and self.defaultNamespace == namesp and "d" not in self._flags): return ":"+value[j+1:] self.countNamespace(namesp) prefix = self.prefixes.get(namesp, None) # @@ #CONVENTION if prefix != None : return prefix + ":" + value[j+1:] if value[:j] == self.base: # If local to output stream, return "<#" + value[j+1:] + ">" # use local frag id if "r" not in self._flags and self.base != None: value = refTo(self.base, value) elif "u" in self._flags: value = backslashUify(value) else: value = hexify(value) return "<" + value + ">" # Everything else def IsOf(self): self._write('is ') self._predIsOfs[-1] = FRESH def checkIsOf(self): return self._predIsOfs[-1] def forewardPath(self): self._write('!') def backwardPath(self): self._write('^') def endStatement(self): self._parts[-1] = 0 self._nodeEnded = True def addLiteral(self, lit, dt=None, lang=None): self._types = LITERAL self.addNode((lit, dt, lang)) def addSymbol(self, sym): self._types = SYMBOL self.addNode(sym) def beginFormula(self): self._realEnd() self._parts.append(0) self._write('{') def endFormula(self): self._parts.pop() self._write('}') self._types = None self.addNode(None) def beginList(self): self._realEnd() self._parts.append(-1) self._write('(') def endList(self): self._parts.pop() self._types = LIST self._write(') ') self.addNode(None) def addAnonymous(self, Id): """If an anonymous shows up more than once, this is the function to call """ if Id not in bNodes: a = self.formulas[-1].newBlankNode() bNodes[Id] = a else: a = bNodes[Id] self.addNode(a) def beginAnonymous(self): self._realEnd() self._parts.append(0) self._write('[') def endAnonymous(self): self._parts.pop() self._write(']') self._types = None self.addNode(None) def declareExistential(self, sym): self._write('@forSome ' + sym + ' . ') def declareUniversal(self, sym): self._write('@forAll ' + sym + ' . ') def addQuestionMarkedSymbol(self, sym): self._types = QUESTION self.addNode(sym) ################################################### # # Utilities # Escapes = {'a': '\a', 'b': '\b', 'f': '\f', 'r': '\r', 't': '\t', 'v': '\v', 'n': '\n', '\\': '\\', '"': '"'} forbidden1 = re.compile(ur'[\\\"\a\b\f\r\v\u0080-\U0000ffff]') forbidden2 = re.compile(ur'[\\\"\a\b\f\r\v\t\n\u0080-\U0000ffff]') #" def stringToN3(str, singleLine=0, flags=""): res = u'' if (len(str) > 20 and str[-1] <> u'"' and not singleLine and (string.find(str, u"\n") >=0 or string.find(str, u'"') >=0)): delim= u'"""' forbidden = forbidden1 # (allow tabs too now) else: delim = u'"' forbidden = forbidden2 i = 0 while i < len(str): m = forbidden.search(str, i) if not m: break j = m.start() res = res + str[i:j] ch = m.group(0) if ch == u'"' and delim == u'"""' and str[j:j+3] != u'"""': #" res = res + ch else: k = string.find(u'\a\b\f\r\t\v\n\\"', ch) if k >= 0: res = res + u"\\" + u'abfrtvn\\"'[k] else: if 'e' in flags: # res = res + ('\\u%04x' % ord(ch)) res = res + (u'\\u%04X' % ord(ch)) # http://www.w3.org/TR/rdf-testcases/#ntriples else: res = res + ch i = j + 1 # The following code fixes things for really high range Unicode newstr = u"" for ch in res + str[i:]: if ord(ch)>65535: newstr = newstr + (u'\\U%08X' % ord(ch)) # http://www.w3.org/TR/rdf-testcases/#ntriples else: newstr = newstr + ch # return delim + newstr + delim def backslashUify(ustr): """Use URL encoding to return an ASCII string corresponding to the given unicode""" # progress("String is "+`ustr`) # s1=ustr.encode('utf-8') str = u"" for ch in ustr: # .encode('utf-8'): if ord(ch) > 65535: ch = u"\\U%08X" % ord(ch) elif ord(ch) > 126: ch = u"\\u%04X" % ord(ch) else: ch = u"%c" % ord(ch) str = str + ch return str def hexify(ustr): """Use URL encoding to return an ASCII string corresponding to the given UTF8 string >>> hexify("http://example/a b") 'http://example/a%20b' """ #" # progress("String is "+`ustr`) # s1=ustr.encode('utf-8') str = "" for ch in ustr: # .encode('utf-8'): if ord(ch) > 126 or ord(ch) < 33 : ch = "%%%02X" % ord(ch) else: ch = "%c" % ord(ch) str = str + ch return str def dummy(): res = "" if len(str) > 20 and (string.find(str, "\n") >=0 or string.find(str, '"') >=0): delim= '"""' forbidden = "\\\"\a\b\f\r\v" # (allow tabs too now) else: delim = '"' forbidden = "\\\"\a\b\f\r\v\t\n" for i in range(len(str)): ch = str[i] j = string.find(forbidden, ch) if ch == '"' and delim == '"""' \ and i+1 < len(str) and str[i+1] != '"': j=-1 # Single quotes don't need escaping in long format if j>=0: ch = "\\" + '\\"abfrvtn'[j] elif ch not in "\n\t" and (ch < " " or ch > "}"): ch = "[[" + `ch` + "]]" #[2:-1] # Use python res = res + ch return delim + res + delim def _test(): import doctest doctest.testmod() if __name__ == '__main__': _test() #ends cwm-1.2.1/swap/query.py0000644015216600007660000027433410717716160014131 0ustar syosisyosi""" Query for cwm architecture 2003-09-07 split off from llyn.py """ QL_NS = "http://www.w3.org/2004/ql#" from sparql2cwm import SPARQL_NS from set_importer import Set, ImmutableSet, sorted from RDFSink import Logic_NS, RDFSink, forSomeSym, forAllSym from RDFSink import CONTEXT, PRED, SUBJ, OBJ, PARTS, ALL4 from RDFSink import N3_nil, N3_first, N3_rest, OWL_NS, N3_Empty, N3_List, List_NS from RDFSink import RDF_NS_URI from OrderedSequence import intersection, minus, indentString import diag from diag import chatty_flag, tracking, progress from term import BuiltIn, LightBuiltIn, RDFBuiltIn, ArgumentNotLiteral, \ HeavyBuiltIn, Function, ReverseFunction, MultipleFunction, \ MultipleReverseFunction, UnknownType, Env, \ Literal, Symbol, Fragment, FragmentNil, Term, \ CompoundTerm, List, EmptyList, NonEmptyList, ErrorFlag from formula import StoredStatement, Formula from why import Because, BecauseBuiltIn, BecauseOfRule, \ BecauseOfExperience, becauseSubexpression, Reason, \ BecauseSupports, BecauseMerge ,report, Premise, newTopLevelFormula, isTopLevel BuiltinFeedError = (ArgumentNotLiteral, UnknownType) import types import sys # from sets import Set # only in python 2.3 and following # set_importer does a cleaner job INFINITY = 1000000000 # @@ larger than any number occurences # State values as follows, high value=try first: S_UNKNOWN = 99 # State unknown - to be [re]calculated by setup. S_DONE = 80 # Exhausted all possible ways to saitsfy this. return now. S_LIGHT_UNS_READY= 70 # Light, not searched yet, but can run S_LIGHT_GO = 65 # Light, can run Do this! S_NOT_LIGHT = 60 # Not a light built-in, haven't searched yet. S_LIGHT_EARLY= 50 # Light built-in, not ready to calculate, not searched yet. S_NEED_DEEP= 45 # Can't search because of unbound compound term, # could do recursive unification S_HEAVY_READY= 40 # Heavy built-in, search done, # but formula now has no vars left. Ready to run. S_LIGHT_WAIT= 30 # Light built-in, not enough constants to calculate, search done. S_HEAVY_WAIT= 20 # Heavy built-in, too many variables in args to calculate, search done. S_REMOTE = 10 # Waiting for local query to be resolved as much as possible #S_SATISFIED = 0 # Item has been staisfied, and is no longer a constraint, continue with others stateName = { S_UNKNOWN : "????", S_DONE : "DONE", S_LIGHT_UNS_READY : "LtUsGo", S_LIGHT_GO : "LtGo", S_NOT_LIGHT : "NotLt", S_LIGHT_EARLY : "LtEarly", S_NEED_DEEP : "Deep", S_HEAVY_READY : "HvGo", S_LIGHT_WAIT : "LtWait", S_HEAVY_WAIT : "HvWait", S_REMOTE : "Remote"} # S_SATISFIED: "Satis" } def think(knowledgeBase, ruleFormula=None, mode="", why=None): """Forward-chaining inference In the case in which rules are added back into the store. The store is used for read (normally canonical) and write (normally open) at the samne time. It in fact has to be open. """ if ruleFormula == None: ruleFormula = knowledgeBase assert knowledgeBase.canonical == None , "Must be open to add stuff:"+ `knowledgeBase ` if diag.chatty_flag > 45: progress("think: rules from %s added to %s" %( knowledgeBase, ruleFormula)) return InferenceTask(knowledgeBase, ruleFormula, mode=mode, why=why, repeat=1).run() def applyRules( workingContext, # Data we assume ruleFormula = None, # Where to find the rules targetContext = None): # Where to put the conclusions """Once""" t = InferenceTask(workingContext, ruleFormula, targetContext) result = t.run() del(t) return result def applyQueries( workingContext, # Data we assume ruleFormula = None, # Where to find the rules targetContext = None): # Where to put the conclusions """Once, nothing recusive, for a N3QL query""" t = InferenceTask(workingContext, ruleFormula, targetContext) t.gatherQueries(t.ruleFormula) result = t.runSmart() del(t) return result def applySparqlQueries( workingContext, # Data we assume ruleFormula = None, # Where to find the rules targetContext = None): # Where to put the conclusions """Once, nothing recusive, for a N3QL query""" t = InferenceTask(workingContext, ruleFormula, targetContext, mode="q") t.gatherSparqlQueries(t.ruleFormula) result = t.runSmart() del(t) return result class InferenceTask: """A task of applying rules or filters to information""" def __init__(self, workingContext, # Data we assume ruleFormula = None, # Where to find the rules targetContext = None, # Where to put the conclusions universals = Set(), # Inherited from higher contexts mode="", # modus operandi why=None, # Trace reason for all this repeat = 0): # do it until finished """ Apply rules in one context to the same or another A rule here is defined by log:implies, which associates the template (aka premise, precondidtion, antecedent, body) to the conclusion (aka postcondition, head). """ if diag.chatty_flag >20: progress("New Inference task, rules from %s" % ruleFormula) if targetContext is None: targetContext = workingContext # return new data to store if ruleFormula is None: self.ruleFormula = workingContext # apply own rules else: self.ruleFormula = ruleFormula self.ruleFor = {} self.hasMetaRule = 0 self.workingContext, self.targetContext, self.mode, self.repeat = \ workingContext, targetContext, mode, repeat self.store = self.workingContext.store def runSmart(self): """Run the rules by mapping rule interactions first""" rules= self.ruleFor.values() if self.targetContext is self.workingContext: #otherwise, there cannot be loops for r1 in rules: vars1 = r1.templateExistentials | r1.variablesUsed for r2 in rules: vars2 = r2.templateExistentials | r2.variablesUsed for s1 in r1.conclusion.statements: s2 = None p = None for s2 in r2.template.statements: for p in PRED, SUBJ, OBJ: if ((s1[p] not in vars1 and not isinstance(s1[p], CompoundTerm)) and (s2[p] not in vars2 and not isinstance(s2[p], CompoundTerm)) and (s1[p] is not s2[p])): break else: r1.affects[r2] = 1 # save transfer binding here? if diag.chatty_flag > 20: progress( "%s can affect %s because %s can trigger %s" % (`r1`, `r2`, `s1`, `s2`)) break # can affect else: # that statement couldn't but if diag.chatty_flag > 96: progress("...couldn't beccause of ",s1,s2,p) continue # try next one break # can # Calculate transitive closure of "affects" for r1 in rules: r1.traceForward(r1) # could lazy eval for r1 in rules: r1.indirectlyAffects.sort() r1.indirectlyAffectedBy.sort() # Print the affects matrix if diag.chatty_flag > 30: str = "%4s:" % "Aff" for r2 in rules: str+= "%4s" % `r2` progress(str) for r1 in rules: str= "%4s:" % `r1` for r2 in rules: if r2.affects.get(r1, 0): str+= "%4s" % "X" elif r1 in r2.indirectlyAffects: str +="%4s" % "-" else: str+= "%4s" % " " progress(str) # Find cyclic subsystems # These are connected sets within which you can get from any node back to itself pool = rules[:] pool.sort() # Sorted list, can use merge, intersection, etc cyclics = [] while pool: r1 = pool[0] if r1 not in r1.indirectlyAffects: cyclic = [ r1 ] pool.remove(r1) else: if diag.chatty_flag > 90: progress("%s indirectly affects %s and is affected by %s" % (r1, r1.indirectlyAffects, r1.indirectlyAffectedBy)) cyclic = intersection(r1.indirectlyAffects, r1.indirectlyAffectedBy) pool = minus(pool, cyclic) cyclics.append(CyclicSetOfRules(cyclic)) if diag.chatty_flag > 90: progress("New cyclic: %s" % cyclics[-1]) # Because the cyclic subsystems contain any loops, we know # there are no cycles between them. Therefore, there is a partial # ordering. If we order them in that way, then we can resolve each # one just once without violating pool = cyclics[:] seq = [] while pool: cy = pool[0] # pick random one seq = partialOrdered(cy, pool) + seq if diag.chatty_flag > 10: progress("In order:" + `seq`) # TEMPORARY: test that n = len(seq) for i in range(n): for j in range(i-1): if compareCyclics(seq[i], seq[j]) < 0: raise RuntimeError("Should not be: %s < %s" %(seq[i], seq[j])) # Run the rules total = 0 for cy in seq: total += cy.run() if diag.chatty_flag > 9: progress("Grand total %i facts found" % total) return total def run(self): """Perform task. Return number of new facts""" self.gatherRules(self.ruleFormula) if self.hasMetaRule or not self.repeat: return self.runLaborious() return self.runSmart() def runLaborious(self): """Perform task. Return number of new facts. Start again if new rule mayhave been generated.""" grandtotal = 0 iterations = 0 self.ruleFor = {} needToCheckForRules = 1 while 1: if needToCheckForRules: self.gatherRules(self.ruleFormula) needToCheckForRules = 0 _total = 0 iterations = iterations + 1 for rule in self.ruleFor.values(): found = rule.once() if (diag.chatty_flag >50): progress( "Laborious: Found %i new stmts on for rule %s" % (found, rule)) _total = _total+found if found and (rule.meta or self.targetContext._closureMode): needToCheckForRules = 1 if diag.chatty_flag > 5: progress( "Total of %i new statements on iteration %i." % (_total, iterations)) if _total == 0: break grandtotal= grandtotal + _total if not self.repeat: break if diag.chatty_flag > 5: progress( "Grand total of %i new statements in %i iterations." % (grandtotal, iterations)) return grandtotal def gatherRules(self, ruleFormula): universals = Set() # @@ self.universals?? for s in ruleFormula.statementsMatching(pred=self.store.implies): r = self.ruleFor.get(s, None) if r != None: continue con, pred, subj, obj = s.quad if (isinstance(subj, Formula) and isinstance(obj, Formula)): v2 = universals | ruleFormula.universals() # Note new variables can be generated r = Rule(self, antecedent=subj, consequent=obj, statement=s, variables=v2) self.ruleFor[s] = r if r.meta: self.hasMetaRule = 1 if (diag.chatty_flag >30): progress( "Found rule %r for statement %s " % (r, s)) for F in ruleFormula.each(pred=self.store.implies, obj=self.store.Truth): #@@ take out when --closure=T ?? self.gatherRules(F) #See test/rules13.n3, test/schema-rules.n3 etc def gatherQueries(self, ruleFormula): "Find a set of rules in N3QL" universals = Set() # @@ self.universals?? ql_select = self.store.newSymbol(QL_NS + "select") ql_where = self.store.newSymbol(QL_NS + "where") for s in ruleFormula.statementsMatching(pred=ql_select): r = self.ruleFor.get(s, None) if r != None: continue con, pred, query, selectClause = s.quad whereClause= ruleFormula.the(subj=query, pred=ql_where) if whereClause == None: continue # ignore (warning?) if (isinstance(selectClause, Formula) and isinstance(whereClause, Formula)): v2 = universals | ruleFormula.universals() # Note new variables can be generated r = Rule(self, antecedent=whereClause, consequent=selectClause, statement=s, variables=v2) self.ruleFor[s] = r if r.meta: self.hasMetaRule = 1 if (diag.chatty_flag >30): progress( "Found rule %r for statement %s " % (r, s)) def gatherSparqlQueries(self, ruleFormula): "Find the rules in SPARQL" store = self.store sparql = store.newSymbol(SPARQL_NS) for from_statement in ruleFormula.statementsMatching(pred=sparql['data']): working_context_stand_in = from_statement.object() ruleFormula = ruleFormula.substitution({working_context_stand_in: self.workingContext}) query_root = ruleFormula.any(pred=store.type, obj=sparql['ConstructQuery']) if not query_root: # This is wrong query_root = ruleFormula.any(pred=store.type, obj=sparql['SelectQuery']) if not query_root: query_root = ruleFormula.any(pred=store.type, obj=sparql['AskQuery']) # query_root is a very boring bNode if query_root: #construct query for where_triple in ruleFormula.statementsMatching(subj=query_root, pred=sparql['where']): where_clause = where_triple.object() #where_clause is the tail of the rule implies_clause = ruleFormula.the(subj=where_clause, pred=store.implies) assert implies_clause is not None, ("where=%s, f=%s" % (where_clause.debugString(), ruleFormula.debugString())) #implies_clause is the head of the rule v2 = ruleFormula.universals().copy() r = Rule(self, antecedent=where_clause, consequent=implies_clause, statement=where_triple, variables=v2) self.ruleFor[where_triple] = r if r.meta: self.hasMetaRule = 1 if (diag.chatty_flag >30): progress( "Found rule %r for statement %s " % (r, where_triple)) def partialOrdered(cy1, pool): """Return sequence conforming to the partially order in a set of cyclic subsystems Basially, we find the dependencies of a node and remove them from the pool. Then, any node in the pool can be done earlier, because has no depndency from those done. """ seq = [] for r1 in cy1: # @@ did just chose first rule cy[0], but didn't get all for r2 in r1.affects: if r2 not in cy1: # An external dependency cy2 = r2.cycle if cy2 in pool: seq = partialOrdered(cy2, pool) + seq pool.remove(cy1) if diag.chatty_flag > 90: progress("partial topo: %s" % `[cy1] + seq`) return [cy1] + seq class CyclicSetOfRules: """A set of rules which are connected """ def __init__(self, rules): self.rules = rules for r1 in rules: r1.cycle = self def __getitem__(self, i): return self.rules[i] def __repr__(self): return `self.rules` def run(self): "Run a cyclic subset of the rules" if diag.chatty_flag > 20: progress() progress("Running cyclic system %s" % (self)) if len(self.rules) == 1: rule = self.rules[0] if not rule.affects.get(rule, 0): # rule.already = None # Suppress recording of previous answers # - no, needed to remove dup bnodes as in test/includes/quant-implies.n3 --think # When Rule.once is smarter about not iterating over things not mentioned elsewhere, # can remove this. return rule.once() agenda = self.rules[:] total = 0 for r1 in self.rules: af = r1.affects.keys() af.sort() r1.affectsInCyclic = intersection(self.rules, af) while agenda: rule = agenda[0] agenda = agenda[1:] found = rule.once() if diag.chatty_flag > 20: progress("Rule %s gave %i. Affects:%s." %( rule, found, rule.affectsInCyclic)) if found: total = total + found for r2 in rule.affectsInCyclic: if r2 not in agenda: if diag.chatty_flag > 30: progress("...rescheduling", r2) agenda.append(r2) if diag.chatty_flag > 20: progress("Cyclic subsystem exhausted") return total def buildPattern(workingContext, template): """Make a list of unmatched statements including special builtins to check something is universally quantified""" unmatched = template.statements[:] for v in template.occurringIn(template.universals()): if diag.chatty_flag > 100: progress( "Template %s has universalVariableName %s, formula is %s" % (template, v, template.debugString())) unmatched.append(StoredStatement((workingContext, template.store.universalVariableName, workingContext, v # workingContext.store.newLiteral(v.uriref()) ))) return unmatched def buildStrictPattern(workingContext, template): unmatched = buildPattern(workingContext, template) for v in template.occurringIn(template.existentials()): if diag.chatty_flag > 100: progress( "Tempate %s has existentialVariableName %s, formula is %s" % (template, v, template.debugString())) unmatched.append(StoredStatement((workingContext, template.store.existentialVariableName, workingContext, v # workingContext.store.newLiteral(v.uriref()) ))) ## for v in template.variables(): ## if diag.chatty_flag > 100: progress( ## "Tempate %s has enforceUniqueBinding %s, formula is %s" % (template, v, template.debugString())) ## unmatched.append(StoredStatement((workingContext, ## template.store.enforceUniqueBinding, ## v, ## workingContext.store.newLiteral(v.uriref()) ## ))) return unmatched nextRule = 0 class Rule: def __init__(self, task, antecedent, consequent, statement, variables): """Try a rule Beware lists are corrupted. Already list is updated if present. The idea is that, for a rule which may be tried many times, the constant processing is done in this rather than in Query(). The already dictionary is used to track bindings. This less useful when not repeating (as in --filter), but as in fact there may be several ways in which one cane get the same bindings, even without a repeat. """ global nextRule self.task = task self.template = antecedent self.conclusion = consequent self.store = self.template.store self.statement = statement # original statement self.number = nextRule = nextRule+1 self.meta = self.conclusion.contains(pred=self.conclusion.store.implies) #generate rules? # if task.repeat: self.already = [] # No neat to track dups if not # else: self.already = None self.already = [] self.affects = {} self.indirectlyAffects = [] self.indirectlyAffectedBy = [] self.affectsInCyclic = [] self.cycle = None # When the template refers to itself, the thing we are # are looking for will refer to the context we are searching # Similarly, references to the working context have to be moved into the # target context when the conclusion is drawn. # if self.template.universals() != Set(): # raise RuntimeError("""Cannot query for universally quantified things. # As of 2003/07/28 forAll x ...x cannot be on left hand side of rule. # This/these were: %s\n""" % self.template.universals()) self.unmatched = buildPattern(task.workingContext, self.template) self.templateExistentials = self.template.existentials().copy() _substitute({self.template: task.workingContext}, self.unmatched) variablesMentioned = self.template.occurringIn(variables) self.variablesUsed = self.conclusion.occurringIn(variablesMentioned) for x in variablesMentioned: if x not in self.variablesUsed: self.templateExistentials.add(x) if diag.chatty_flag >20: progress("New Rule %s ============ looking for:" % `self` ) for s in self.template.statements: progress(" ", `s`) progress("=>") for s in self.conclusion.statements: progress(" ", `s`) progress("Universals declared in outer " + seqToString(variables)) progress(" mentioned in template " + seqToString(variablesMentioned)) progress(" also used in conclusion " + seqToString(self.variablesUsed)) progress("Existentials in template " + seqToString(self.templateExistentials)) return def once(self): if diag.chatty_flag >20: progress("Trying rule %s ===================" % self ) progress( setToString(self.unmatched)) task = self.task query = Query(self.store, unmatched = self.unmatched[:], template = self.template, variables = self.variablesUsed.copy(), existentials = self.templateExistentials.copy(), workingContext = task.workingContext, conclusion = self.conclusion, targetContext = task.targetContext, already = self.already, ### rule = self.statement, ### interpretBuiltins = 1, # (...) meta = task.workingContext, mode = task.mode) Formula.resetRenames() total = query.resolve() Formula.resetRenames(False) if diag.chatty_flag > 20: progress("Rule try generated %i new statements" % total) return total def __repr__(self): if self in self.affects: return "R"+`self.number`+ "*" return "R"+`self.number` def compareByAffects(other): if other in self.indirectlyAffects: return -1 # Do me earlier if other in self.indirectlyAffectedBy: return 1 return 0 def traceForward(self, r1): for r2 in r1.affects: if r2 not in self.indirectlyAffects: self.indirectlyAffects.append(r2) r2.indirectlyAffectedBy.append(self) self.traceForward(r2) # else: # self.__setattr__("leadsToCycle", 1) def testIncludes(f, g, _variables=Set(), bindings={}, interpretBuiltins = 0): """Return whether or nor f contains a top-level formula equvalent to g. Just a test: no bindings returned.""" if diag.chatty_flag >30: progress("testIncludes ============\nseeing if %s entails %s" % (f, g)) # raise RuntimeError() if not(isinstance(f, Formula) and isinstance(g, Formula)): return 0 assert f.canonical is f, f.debugString() assert g.canonical is g m = diag.chatty_flag diag.chatty_flag = 0 if m > 60: progress("Before rename: ", f.debugString()) f = f.renameVars() if m > 60: progress("After rename: ", f.debugString()) diag.chatty_flag = m if diag.chatty_flag >100: progress("Formula we are searching in is\n%s" % g.debugString()) unmatched = buildPattern(f, g) templateExistentials = g.existentials() more_variables = g.universals().copy() _substitute({g: f}, unmatched) # if g.universals() != Set(): # raise RuntimeError("""Cannot query for universally quantified things. # As of 2003/07/28 forAll x ...x cannot be on left hand side of rule. # This/these were: %s\n""" % g.universals()) # if bindings != {}: _substitute(bindings, unmatched) if diag.chatty_flag > 20: progress( "# testIncludes BUILTIN, %i terms in template %s, %i unmatched, %i template variables" % ( len(g.statements), `g`[-8:], len(unmatched), len(templateExistentials))) if diag.chatty_flag > 80: for v in _variables: progress( " Variable: " + `v`[-8:]) result = Query(f.store, unmatched=unmatched, template = g, variables=Set(), interpretBuiltins = interpretBuiltins, existentials=_variables | templateExistentials | more_variables, justOne=1, mode="").resolve() if diag.chatty_flag >30: progress("=================== end testIncludes =" + `result`) return result def n3Equivalent(g, f, env1, env2, vars=Set([]), universals=Set(), existentials=Set([]), n1Source=42, n2Source=42): """Return whether or nor f contains a top-level formula equvalent to g. Just a test: no bindings returned.""" if diag.chatty_flag >30: progress("Query.py n3Equivalent ============\nseeing if %s equals %s" % (f, g)) # raise RuntimeError() if not(isinstance(f, Formula) and isinstance(g, Formula)): pass elif f is g: yield env1, env2 elif len(f) > len(g): pass else: assert f.canonical is f, "%s, %s" % (f.debugString(), f.canonical.debugString()) assert g.canonical is g, "%s, %s" % (g.debugString(), g.canonical.debugString()) m = diag.chatty_flag diag.chatty_flag = 0 if m > 60: progress("Before rename: ", f.debugString()) f = f.renameVars() if m > 60: progress("After rename: ", f.debugString()) diag.chatty_flag = m unmatched = buildStrictPattern(f, g) templateExistentials = g.existentials() | g.universals() | existentials more_variables = Set(vars) _substitute({g: f}, unmatched) if env1: _substitute(env1.asDict(), unmatched) if diag.chatty_flag > 20: progress( "# testEqual BUILTIN, %i terms in template %s, %i unmatched, %i template variables" % ( len(g.statements), `g`[-8:], len(unmatched), len(templateExistentials))) if diag.chatty_flag > 80: for v in vars: progress( " Variable: " + `v`[-8:]) result = Query(f.store, unmatched=unmatched, template = g, variables=more_variables, workingContext = f, interpretBuiltins = False, existentials= templateExistentials , justReturn=1, mode="").resolve() if diag.chatty_flag >30: progress("=================== end n3Equivalent =" + `result`) if not result: result = [] for x in result: for k, (v, source) in x.items(): env1 = env1.bind(k, (v, env2.id)) yield env1, env2 ## return [(x, None) for x in result] ############################################################## Query engine # # Template matching in a graph # # Optimizations we have NOT done: # - storing the tree of bindings so that we don't have to duplicate them another time # - using that tree to check only whether new data would extend it (very cool - memory?) # (this links to dynamic data, live variables.) # - recognising in advance disjoint graph templates, doing cross product of separate searches # # Built-Ins: # The trick seems to be to figure out which built-ins are going to be faster to # calculate, and so should be resolved before query terms involving a search, and # which, like those involving recursive queries or net access, will be slower than a query term, # and so should be left till last. # I feel that it should be possible to argue about built-ins just like anything else, # so we do not exclude these things from the query system. We therefore may have both light and # heavy built-ins which still have too many variables to calculate at this stage. # When we do the variable substitution for new bindings, these can be reconsidered. class Queue([].__class__): __slots__ = ['statements', 'bNodes'] list = [].__class__ def __init__(self, other=[], metaSource = None): self.list.__init__(self, other) if isinstance(metaSource, Queue): for k in self.__slots__: setattr(self, k, getattr(metaSource, k).copy()) else: self.statements = Set() self.bNodes = Set() pass #fill in slots here def popBest(self): best = len(self) -1 # , say... i = best - 1 while i >=0: if (self[i].state > self[best].state or (self[i].state == self[best].state and self[i].short < self[best].short)): best=i i = i - 1 item = self[best] self.remove(item) return item def __repr__(self): return 'Queue(%s, bNodes=%s)' % (list.__repr__(self), self.bNodes) #Queue = [].__class__ class Chain_Step(object): def __init__(self, vars, existentials, queue, env, parent=None, evidence=[]): self.vars = vars self.existentials = existentials self.lines = queue self.env = env assert parent is None self.parent = parent self.evidence = evidence def popBest(self): return self.lines.popBest() def copy(self): retVal = self.__class__(self.vars, self.existentials, self.lines, self.env, self.parent, self.evidence) return retVal def done(self): return not self.lines def __cmp__(self, other): return cmp(len(other.lines), len(self.lines)) def __repr__(self): return "%s(lines=%r,\n\tenv=%r,\n\tparent=%r,\n\tevidence=%r)" % (self.__class__.__name__, self.lines, self.env, self.parent, self.evidence) def returnWrapper(f): def g(*args, **keywords): retVal = f(*args, **keywords) progress('%s() returns %s' % (f.func_name, retVal)) return retVal return g class Query(Formula): """A query holds a hypothesis/antecedent/template which is being matched aginst (unified with) the knowledge base.""" def __init__(self, store, unmatched=[], # Tuple of interned quads we are trying to match CORRUPTED template = None, # Actually, must have one variables=Set(), # List of variables to match and return CORRUPTED existentials=Set(), # List of variables to match to anything # Existentials or any kind of variable in subexpression workingContext = None, conclusion = None, targetContext = None, already = None, # Dictionary of matches already found rule = None, # The rule statement interpretBuiltins = 0, # List of contexts in which to use builtins justOne = 0, # Flag: Stop when you find the first one justReturn = 0, # Flag: Return bindings, don't conclude mode = "", # Character flags modifying modus operandi meta = None): # Context to check for useful info eg remote stuff if diag.chatty_flag > 50: progress( "Query: created with %i terms. (justone=%i, wc=%s)" % (len(unmatched), justOne, workingContext)) if diag.chatty_flag > 80: progress( setToString(unmatched)) if diag.chatty_flag > 90 and interpretBuiltins: progress( "iBuiltIns=1 ") Formula.__init__(self, store) self.statements = Queue() # Unmatched with more info # self.store = store # Initialized by Formula self.variables = variables self._existentialVariables = existentials self.workingContext = workingContext self.conclusion = conclusion self.targetContext = targetContext self.justOne = justOne self.already = already self.rule = rule self.template = template # For looking for lists self.meta = meta self.mode = mode self.lastCheckedNumberOfRedirections = 0 self.bindingList = [] self.justReturn = justReturn realMatchCount = 0 if justReturn and not variables: self.justOne = True for quad in unmatched: item = QueryItem(self, quad) if not item.setup(allvars=variables|existentials, unmatched=unmatched, interpretBuiltins=interpretBuiltins, mode=mode): if diag.chatty_flag > 80: progress( "match: abandoned, no way for "+`item`) self.noWay = 1 return # save time if not item.builtIn: realMatchCount += 1 self.statements.append(item) if justReturn and realMatchCount > len(workingContext): self.noWay = 1 return return def resolve(self): if hasattr(self, "noWay"): return 0 k = self.matchFormula(self.statements, self.variables, self._existentialVariables) if self.justReturn: return self.bindingList return k def checkRedirectsInAlready(self): """Kludge""" n = len(self.targetContext._redirections) if n > self.lastCheckedNumberOfRedirections: self.lastCheckedNumberOfRedirections = n self.redirect(self.targetContext._redirections) def redirect(self, redirections): for bindings in self.already: for var, value in bindings.items(): try: x = redirections[value] except: pass else: if diag.chatty_flag>29: progress("Redirecting binding %r to %r" % (value, x)) bindings[var] = x def conclude(self, bindings, evidence = [], extraBNodes = Set(), allBindings=None): """When a match found in a query, add conclusions to target formula. Returns the number of statements added.""" if self.justOne: self.bindingList = [{}] return 1 # If only a test needed if self.justReturn: if bindings not in self.bindingList: # progress('CONCLUDE bindings = %s' % bindings) self.bindingList.append(bindings) return 1 if diag.chatty_flag >60: progress( "Concluding tentatively...%r" % bindings) if self.already != None: self.checkRedirectsInAlready() # @@@ KLUDGE - use delegation and notification systme instead if bindings in self.already: if diag.chatty_flag > 30: progress("@@ Duplicate result: %r is in %r" % (bindings, self.already)) return 0 if diag.chatty_flag > 30: progress("Not duplicate: %r" % bindings) self.already.append(bindings) else: if diag.chatty_flag >60: progress( "No duplication check") if diag.tracking: if allBindings is None: allBindings = bindings for loc in xrange(len(evidence)): r = evidence[loc] if isinstance(r, BecauseSupportsWill): evidence[loc] = BecauseSupports(*([smarterSubstitution(k, allBindings, r.args[1], why=Because("I support it: "), exception=[r.args[2]]) for k in r.args] + [[k for k in evidence if isinstance(k, (StoredStatement, Reason))]])) if isinstance(r, BecauseBuiltInWill): evidence[loc] = BecauseBuiltIn(*[smarterSubstitution(k, allBindings, r.args[0], why=Because("I include it: " + k.debugString() + `allBindings`)) for k in r.args[1:]]) reason = BecauseOfRule(self.rule, bindings=allBindings, knownExistentials = extraBNodes, evidence=evidence, kb=self.workingContext) # progress("We have a reason for %s of %s with bindings %s" % (self.rule, reason, alBindings)) else: reason = None es, exout = (self.workingContext.existentials() | extraBNodes), Set() #self.workingContext.existentials() | for var, (val, source) in bindings.items(): if isinstance(val, Exception): if "q" in self.mode: # How nice are we? raise ValueError(val) return 0 intersection = val.occurringIn(es) # Take time for large number of bnodes? if intersection: exout.update(intersection) if diag.chatty_flag > 25: progress( "Match found to that which is only an existential: %s -> %s" % (var, val)) for val2 in intersection: if val not in self.targetContext.existentials(): if self.conclusion.occurringIn([var]): self.targetContext.declareExistential(val2) # Variable renaming b2 = bindings.asDict() # b2[self.conclusion] = self.targetContext # What does this mean? ok = self.targetContext.universals() # It is actually ok to share universal variables with other stuff poss = self.conclusion.universals().copy() for x in poss.copy(): if x in ok: poss.remove(x) poss_sorted = list(poss) poss_sorted.sort(Term.compareAnyTerm) #progress(poss) # vars = self.conclusion.existentials() + poss # Terms with arbitrary identifiers # clashes = self.occurringIn(targetContext, vars) Too slow to do every time; play safe if diag.chatty_flag > 25: s="" for v in poss_sorted: v2 = self.targetContext.newUniversal() b2[v] =v2 # Regenerate names to avoid clash if diag.chatty_flag > 25: s = s + ",uni %s -> %s" %(v, v2) for v in sorted(list(self.conclusion.existentials()), Term.compareAnyTerm): if v not in exout: v2 = self.targetContext.newBlankNode() b2[v] =v2 # Regenerate names to avoid clash if diag.chatty_flag > 25: s = s + ",exi %s -> %s" %(v, v2) else: if diag.chatty_flag > 25: s = s + (", (%s is existential in kb)"%v) if diag.chatty_flag > 25: progress("Variables regenerated: universal " + `poss` + " existential: " +`self.conclusion.existentials()` + s) if diag.chatty_flag>19: progress("Concluding DEFINITELY" + bindingsToString(b2) ) before = self.store.size _, delta = self.targetContext.loadFormulaWithSubstitution( self.conclusion, b2, why=reason, cannon=True) if diag.chatty_flag>29 and delta: progress(" --- because of: %s => %s, with bindings %s" % (self.template.debugString(), self.conclusion.debugString(), b2)) if diag.chatty_flag> 40: progress("Added %i, nominal size of store changed from %i to %i."%(delta, before, self.store.size)) return delta # self.store.size - before ################################################################################## def matchFormula(query, queue, variables, existentials, env=Env()): total = 0 stack = [Chain_Step(variables, existentials, queue, env)] while stack: if diag.chatty_flag > 150: progress(stack) workingStep = stack.pop() if not workingStep.done(): queue = workingStep.lines evidence = workingStep.evidence bindings = workingStep.env variables = workingStep.vars existentials = workingStep.existentials item = workingStep.popBest() con, pred, subj, obj = item.quad state = item.state if state == S_DONE: # After bindNew, could be undoable. nbs = [] elif state == S_LIGHT_UNS_READY: # Search then nbs = item.tryBuiltin(queue, bindings, evidence=evidence) item.state = S_LIGHT_EARLY # Unsearched, try builtin @@@@@@@@@ <== need new state here elif state == S_LIGHT_GO: nbs = item.tryBuiltin(queue, bindings, evidence=evidence) item.state = S_DONE # Searched. elif (state == S_LIGHT_EARLY or state == S_NOT_LIGHT or state == S_NEED_DEEP): # Not searched yet nbs = item.tryDeepSearch(queue, bindings) elif state == S_HEAVY_READY: # not light, may be heavy; or heavy ready to run if pred is query.store.includes: # and not diag.tracking: # don't optimize when tracking? variables = variables.copy() existentials = existentials.copy() nbs = item.doIncludes(queue, existentials, variables, bindings) elif pred is query.store.supports: variables = variables.copy() existentials = existentials.copy() nbs = item.doSupports(queue, existentials, variables, bindings) else: item.state = S_HEAVY_WAIT # Assume can't resolve nbs = item.tryBuiltin(queue, bindings, evidence=evidence) item.state = S_DONE elif state == S_REMOTE: # Remote query -- need to find all of them for the same service items = [item] for i in queue[:]: if i.state == S_REMOTE and i.service is item.service: #@@ optimize which group is done first! items.append(i) queue.remove(i) nbs = query.remoteQuery(items) item.state = S_DONE # do not put back on list elif state ==S_HEAVY_WAIT or state == S_LIGHT_WAIT: if item.quad[PRED] is query.store.universalVariableName or \ item.quad[PRED] is query.store.existentialVariableName: ### We will never bind this variable in the first place item.state = S_DONE nbs = [] else: if diag.chatty_flag > 20 : progress("@@@@ Warning: query can't find term which will work.") progress( " state is %s, queue length %i" % (state, len(queue)+1)) progress("@@ Current item: %s" % `item`) progress(queueToString(queue)) continue # Forget it else: raise RuntimeError, "Unknown state " + `state` stack_extent = [] for nb, reason in nbs: assert isinstance(nb, dict), nb q2 = Queue([], queue) if query.justReturn: ### What does the following do? ### If we are doing a 1::1 match, record everything we have matched if isinstance(reason, StoredStatement): if reason not in q2.statements and \ reason[CONTEXT] is query.workingContext: q2.statements.add(reason) else: continue if isinstance(reason, StoredStatement): if True or reason[CONTEXT] is not query.workingContext: for m in nb.values(): if isinstance(m, tuple): m = m[0] if m in reason[CONTEXT].existentials(): q2.bNodes.add(m) if diag.chatty_flag > 80: ### These get picked up from log:includes ### {[:b :c]} log:includes {?X :b :c} ... progress('Adding bNode %s, now %s' % (m, q2.bNodes)) new_thing = False try: new_env = bindings.flatten(nb) except ValueError: pass else: new_thing = True for i in queue: newItem = i.clone() newItem.bindNew(new_env) ## Is this right? I was hoping to avoid this q2.append(newItem) #@@@@@@@@@@ If exactly 1 binding, loop (tail recurse) if new_thing: if diag.chatty_flag > 70: progress("query.py bindings nb new_entry:", bindings, nb, new_env) new_step = Chain_Step(variables, existentials, q2, new_env, workingStep.parent, workingStep.evidence + [reason]) stack_extent.append(new_step) if item.state != S_DONE: queue.append(item) new_step = workingStep.copy() stack_extent.append(new_step) stack.extend(stack_extent) else: if workingStep.parent is not None: raise RuntimeError("We are not chaining yet.\n How did I get here?") else: total = query.conclude(workingStep.env.filter(workingStep.vars), allBindings=workingStep.env , evidence=workingStep.evidence, extraBNodes = workingStep.lines.bNodes) + total # No terms left .. success! #raise RuntimeError("I need to conclude here, workingStep=%s" % workingStep) pass return total def matchFormula2(query, queue, # Set of items we are trying to match CORRUPTED variables, # List of variables to match and return CORRUPTED existentials, # List of variables to match to anything # Existentials or any kind of variable in subexpression bindings = Env(), # Bindings discovered so far newBindings = Env(), # New bindings not yet incorporated evidence = []): # List of statements supporting the bindings so far """ Iterate on the remaining query items bindings collected matches already found newBindings matches found and not yet applied - used in recursion You probably really need the state diagram to understand this http://www.w3.org/2000/10/swap/doc/states.svg even if it is a bit out of date. """ total = 0 assert isinstance(bindings, Env) assert isinstance(newBindings, Env), 'env is an %s, not an %s' % (newBindings.__class__, Env) if diag.chatty_flag > 59: progress( "QUERY2: called %i terms, %i bindings %s, (new: %s)" % (len(queue), len(bindings), `bindings`, `newBindings`)) if diag.chatty_flag > 90: progress( queueToString(queue)) newBindingItems = newBindings.items() while newBindingItems: # Take care of business left over from recursive call pair = newBindingItems.pop(0) if isinstance(pair[1], tuple): pair = (pair[0], pair[1][0]) else: raise RuntimeError if diag.chatty_flag>95: progress(" new binding: %s -> %s" % (`pair[0]`, `pair[1]`)) if pair[0] in variables: variables.remove(pair[0]) bindings = bindings.newBinding(pair[0], (pair[1], None)) else: # Formulae aren't needed as existentials, unlike lists. hmm. ### bindings.update({pair[0]: pair[1]}) # remove me!!!!! # if diag.tracking: raise RuntimeError(pair[0], pair[1]) #bindings.update({pair[0]: pair[1]}) # Record for proof only if pair[0] not in existentials: if isinstance(pair[0], List): # pair[0] should be a variable, can't be a list, surely del newBindings[pair[0]] #We can accidently bind a list using (1 2 3) rdf:rest (?x 3). #This finds the true binding reallyNewBindingsList = pair[0].unify( pair[1], bindings, Env(), variables | existentials) ## I'm a bit parenoid. If we did not find a binding ... if not reallyNewBindingsList or not hasattr( reallyNewBindingsList, '__iter__'): return 0 reallyNewBindingsList = [x for x in reallyNewBindingsList] try: reallyNewBindings = reallyNewBindingsList[0][0] #We don't deal # with multiple ways to bind except: print 'we lost' print pair[0], pair[1] a = pair[0].unify( pair[1], variables, existentials, bindings) print a print a[0] print a[0][0] raise newBindingItems.extend(reallyNewBindings.items()) newBindings = newBindings.update2(reallyNewBindings) else: if diag.chatty_flag > 40: # Reasonable progress("Not in existentials or variables but now bound:", `pair[0]`) elif diag.tracking: bindings = bindings.newBinding(pair[0], (pair[1], None)) if not isinstance(pair[0], CompoundTerm) and ( # Hack - else rules13.n3 fails @@ pair[0] in existentials): # Hack ... could be bnding from nested expression existentials.remove(pair[0]) # Can't match anything anymore, need exact match # Perform the substitution, noting where lists become boundLists. # We do this carefully, messing up the order only of things we have already processed. if newBindings != {}: for item in queue: if item.bindNew(newBindings) == 0: return 0 while len(queue) > 0: if (diag.chatty_flag > 90): progress( "query iterating with %i terms, %i bindings: %s; %i new bindings: %s ." % (len(queue), len(bindings),bindingsToString(bindings), len(newBindings),bindingsToString(newBindings))) progress ( queueToString(queue)) # Take best. (Design choice: search here or keep queue in order) # item = queue.pop() item = queue.popBest() if diag.chatty_flag>49: progress( "Looking at " + `item`) progress( "...with vars("+seqToString(variables)+")" + " ExQuVars:("+seqToString(existentials)+")") con, pred, subj, obj = item.quad state = item.state if state == S_DONE: # After bindNew, could be undoable. return total # Forget it -- must be impossible if state == S_LIGHT_UNS_READY: # Search then nbs = item.tryBuiltin(queue, bindings, evidence=evidence) item.state = S_LIGHT_EARLY # Unsearched, try builtin @@@@@@@@@ <== need new state here elif state == S_LIGHT_GO: nbs = item.tryBuiltin(queue, bindings, evidence=evidence) item.state = S_DONE # Searched. elif (state == S_LIGHT_EARLY or state == S_NOT_LIGHT or state == S_NEED_DEEP): # Not searched yet nbs = item.tryDeepSearch(queue, Env()) elif state == S_HEAVY_READY: # not light, may be heavy; or heavy ready to run if pred is query.store.includes: # and not diag.tracking: # don't optimize when tracking? nbs = item.doIncludes(queue, existentials, variables, bindings) elif pred is query.store.supports: nbs = item.doSupports(queue, existentials, variables, bindings) else: item.state = S_HEAVY_WAIT # Assume can't resolve nbs = item.tryBuiltin(queue, bindings, evidence=evidence) item.state = S_DONE elif state == S_REMOTE: # Remote query -- need to find all of them for the same service items = [item] for i in queue[:]: if i.state == S_REMOTE and i.service is item.service: #@@ optimize which group is done first! items.append(i) queue.remove(i) nbs = query.remoteQuery(items) item.state = S_DONE # do not put back on list elif state ==S_HEAVY_WAIT or state == S_LIGHT_WAIT: if item.quad[PRED] is query.store.universalVariableName or \ item.quad[PRED] is query.store.existentialVariableName: ### We will never bind this variable in the first place item.state = S_DONE nbs = [] else: if diag.chatty_flag > 20 : progress("@@@@ Warning: query can't find term which will work.") progress( " state is %s, queue length %i" % (state, len(queue)+1)) progress("@@ Current item: %s" % `item`) progress(queueToString(queue)) return total # Forget it else: raise RuntimeError, "Unknown state " + `state` if diag.chatty_flag > 90: progress("nbs=" + `nbs`) # query.py Removed as I added this and wasn't sure whether it works with justReturn change below -tbl # # Optimization when sucess but no bindings # if (len(nbs) == 1 and nbs[0][0] == {} and nbs[0][1] is None and # if nbs == [({}, None)] and # state == S_DONE): # if diag.chatty_flag>90: progress("LOOP to next, state="+`state`) # continue # Loop around and do the next one. optimization. for nb, reason in nbs: assert isinstance(nb,types.DictType), nb q2 = Queue([], queue) if query.justReturn: ### What does the following do? ### If we are doing a 1::1 match, record everything we have matched if isinstance(reason, StoredStatement): if reason not in q2.statements and \ reason[CONTEXT] is query.workingContext: q2.statements.add(reason) else: continue if isinstance(reason, StoredStatement): if True or reason[CONTEXT] is not query.workingContext: for m in nb.values(): if isinstance(m, tuple): m = m[0] if m in reason[CONTEXT].existentials(): q2.bNodes.add(m) if diag.chatty_flag > 80: ### These get picked up from log:includes ### {[:b :c] log:includes {?X :b :c} ... progress('Adding bNode %s, now %s' % (m, q2.bNodes)) for i in queue: newItem = i.clone() q2.append(newItem) #@@@@@@@@@@ If exactly 1 binding, loop (tail recurse) found = query.matchFormula(q2, variables.copy(), existentials.copy(), bindings.copy(), nb, evidence = evidence + [reason]) if diag.chatty_flag > 91: progress( "Nested query returns %i (nb= %r)" % (found, nb)) total = total + found if query.justOne and total: return total # NO - more to do return total # The called recursive calls above will have generated the output @@@@ <====XXXX if diag.chatty_flag > 80: progress("Item state %i, returning total %i" % (item.state, total)) if (item.state == S_DONE): return total queue.append(item) # And loop back to take the next item if diag.chatty_flag>50: progress("QUERY MATCH COMPLETE with bindings: " + `bindings`) if query.justReturn: try: len(queue.statements) len(query.workingContext) except: print type(queue.statements) print type(query.workingContext) raise if len(queue.statements) != len(query.workingContext): return total newTotal = query.conclude(bindings, evidence=evidence, extraBNodes = queue.bNodes, allBindings=bindings) + total # No terms left .. success! if total: progress('newTotal=%s, total=%s' % (newTotal, total)) raise RuntimeError('How did I get here?') return newTotal def remoteQuery(query, items): """Perform remote query as client on remote store Currently this only goes to an SQL store, but should later use SPARQL etc in remote HTTP/SOAP call.""" if diag.chatty_flag > 90: progress(" Remote service %s" % (items)) serviceURI = items[0].service.uri if serviceURI.startswith("http:"): from sparql.sparqlClient import SparqlQuery return SparqlQuery(query, items, serviceURI) elif not serviceURI.startswith("mysql:"): raise ValueError("Unknown URI scheme for remote query service: %s" % serviceURI) import dbork.SqlDB from dbork.SqlDB import ResultSet, SqlDBAlgae, ShowStatement # SqlDB stores results in a ResultSet. rs = ResultSet() # QueryPiece qp stores query tree. qp = rs.buildQuerySetsFromCwm(items, query.variables, query._existentialVariables) # Extract access info from the first item. if diag.chatty_flag > 90: progress(" Remote service %s" %items[0].service.uri) (user, password, host, database) = re.match( "^mysql://(?:([^@:]+)(?::([^@]+))?)@?([^/]+)/([^/]+)/$", items[0].service.uri).groups() # Look for one of a set of pre-compiled rdb schemas. HostDB2SchemeMapping = { "mysql://root@localhost/w3c" : "AclSqlObjects" } if (HostDB2SchemeMapping.has_key(items[0].service.uri)): cachedSchema = HostDB2SchemeMapping.get(items[0].service.uri) else: cachedSchema = None # The SqlDBAlgae object knows how to compile SQL query from query tree qp. a = SqlDBAlgae(query.store.symbol(items[0].service.uri), cachedSchema, user, password, host, database, query.meta, query.store.pointsAt, query.store) # Execute the query. messages = [] nextResults, nextStatements = a._processRow([], [], qp, rs, messages, {}) # rs.results = nextResults # Store results as initial state for next use of rs. if diag.chatty_flag > 90: progress(string.join(messages, "\n")) if diag.chatty_flag > 90: progress("query matrix \"\"\""+ rs.toString({'dataFilter' : None})+"\"\"\" .\n") nbs = [] reason = Because("Remote query") # could be messages[0] which is the query # Transform nextResults to format cwm expects. for resultsRow in nextResults: boundRow = {} for i in range(len(query.variables)): v = query.variables[i] index = rs.getVarIndex(v) interned = resultsRow[index] boundRow[v] = interned # bindings nbs.append((boundRow, reason)) if diag.chatty_flag > 10: progress("====> bindings from remote query:"+`nbs`) return nbs # No bindings for testing class BetterNone(object): __slots__ = [] def __new__(cls): try: return cls.__val__ except: cls.__val__ = object.__new__(cls) return cls.__val__ def __hash__(self): raise TypeError def __str__(self): raise NotImplementedError def __eq__(self, other): raise NotImplementedError __neq__ = __eq__ __lt__ = __gt__ = __leq__ = __geq__ = __eq__ BNone = BetterNone() class QueryItem(StoredStatement): # Why inherit? Could be useful, and is logical... """One line in a query being resolved. To a large extent, each line can keep track of its own state. When a remote query is done, query lines to the same server have to be coordinated again. """ def __init__(self, query, quad): quad = lookupQuad(quad[CONTEXT]._redirections, quad) #print quad[CONTEXT]._redirections self.quad = quad self.query = query self.searchPattern = None # Will be list of variables self.store = query.store self.state = S_UNKNOWN # Invalid self.short = INFINITY self.neededToRun = None # see setup() self.myIndex = None # will be list of satistfying statements self.service = None # Remote database server for this predicate? self.builtIn = False return def clone(self): """Take a copy when for iterating on a query""" x = QueryItem(self.query, self.quad) x.state = self.state x.short = self.short x.neededToRun = [] x.searchPattern = self.searchPattern[:] for p in ALL4: # Deep copy! Prevent crosstalk x.neededToRun.append(self.neededToRun[p].copy()) x.myIndex = self.myIndex try: x.interpretBuiltins = self.interpretBuiltins except AttributeError: pass return x def setup(self, allvars, unmatched, interpretBuiltins=[], mode=""): """Check how many variables in this term, and how long it would take to search Returns, true normally or false if there is no way this query will work. Only called on virgin query item. The mode is a set of character flags about how we think.""" con, pred, subj, obj = self.quad self.interpretBuiltins = interpretBuiltins self.service = None if diag.chatty_flag > 800: progress("setup:" + `allvars`) if "r" in mode: schema = None if "s" in mode: schema = pred.dereference(mode, self.query.workingContext) if schema != None: if "a" in mode: if diag.chatty_flag > 95: progress("Axiom processing for %s" % (pred)) ns = pred.resource rules = schema.any(subj=ns, pred=self.store.docRules) rulefile = rulefile.dereference("m", self.query.workingContext) self.service = schema.any(pred=self.store.definitiveService, subj=pred) if self.service == None and self.query.meta != None: self.service = self.query.meta.any(pred=self.store.definitiveService, subj=pred) if self.service == None: uri = pred.uriref() if uri[:4] == "mysql:": j = uri.rfind("/") if j>0: self.service = meta.newSymbol(uri[:j]) if diag.chatty_flag > 90 and self.service: progress("We have a Remote service %s for %s." %(self.service, pred)) if not self.service: authDoc = None if schema != None: authDoc = schema.any(pred=self.store.definitiveDocument, subj=pred) if authDoc == None and self.query.meta != None: authDoc = self.query.meta.any(pred=self.store.definitiveDocument, subj=pred) if authDoc != None: if diag.chatty_flag > 90: progress("We have a definitive document %s for %s." %(authDoc, pred)) authFormula = authDoc.dereference(mode, self.query.workingContext) if authFormula != None: self.quad = (authFormula, pred, subj, obj) con = authFormula self.neededToRun = [ Set(), Set(), Set(), Set() ] # for each part of speech self.searchPattern = [con, pred, subj, obj] # What do we search for? hasUnboundCoumpundTerm = 0 for p in PRED, SUBJ, OBJ : x = self.quad[p] if x in allvars: # Variable self.neededToRun[p] = Set([x]) self.searchPattern[p] = None # can bind this elif isinstance(x, Formula) or isinstance(x, List): # expr @@ Set @@@@@@@@@@ Check and CompundTerm>??? ur = x.occurringIn(allvars) self.neededToRun[p] = ur if ur != Set() or isinstance(x, Formula) or (isinstance(x, List) and hasFormula(x)): hasUnboundCoumpundTerm = 1 # Can't search directly self.searchPattern[p] = None # can bind this if we recurse if diag.chatty_flag > 98: progress(" %s needs to run: %s"%(`x`, `self.neededToRun[p]`)) self.updateMyIndex(con) if isinstance(pred, RDFBuiltIn) or ( interpretBuiltins and isinstance(pred, BuiltIn)): self.builtIn = True if isinstance(pred, RDFBuiltIn) or ( interpretBuiltins and isinstance(pred, LightBuiltIn)): if self.canRun(): self.state = S_LIGHT_UNS_READY # Can't do it here else: self.state = S_LIGHT_EARLY # Light built-in, can't run yet, not searched elif self.short == 0: # Skip search if no possibilities! self.searchDone() elif hasUnboundCoumpundTerm: self.state = S_NEED_DEEP # Put off till later than non-deep ones else: self.state = S_NOT_LIGHT # Not a light built in, not searched. if diag.chatty_flag > 80: progress("setup:" + `self`) if self.state == S_DONE: return False return True def doIncludes(item, queue, existentials, variables, bindings): """Implement log:includes by adding all the statements on the LHS to the query items. The plan is that this should""" con, pred, subj, obj = item.quad state = item.state nbs = [] # Failure if (isinstance(subj, Formula) and isinstance(obj, Formula)): oldsubj = subj subj = subj.renameVars() more_unmatched = buildPattern(subj, obj) more_variables = obj.variables().copy() _substitute({obj: subj}, more_unmatched) _substitute(bindings, more_unmatched) existentials = existentials | more_variables allvars = variables | existentials for quad in more_unmatched: newItem = QueryItem(item.query, quad) queue.append(newItem) if not newItem.setup(allvars, interpretBuiltins = 0, unmatched=more_unmatched, mode=item.query.mode): return [] if diag.chatty_flag > 40: progress("log:Includes: Adding %i new terms and %s as new existentials."% (len(more_unmatched), seqToString(more_variables))) rea = BecauseBuiltInWill(subj, con, oldsubj, pred, obj) ## nbs = [({oldsubj: subj}, rea)] nbs = [(Env(), rea)] else: # if isinstance(subj, Formula): subj = subj.n3String() # if isinstance(obj, Formula): obj = obj.n3String() #raise RuntimeError("Cannot do {%s} log:includes {%s} " % (subj, obj)) progress("""Warning: Type error ignored on builtin: log:includes only on formulae """+`item`) #@@ was RuntimeError exception item.state = S_DONE return nbs def doSupports(item, queue, existentials, variables, bindings): """Real implementation of log:supports. Have fun. """ con, pred, subj, obj = item.quad state = item.state store = con.store #statementObject = iter(con.statementsMatching(subj=subj, pred=pred, obj=obj)).next() nbs = [] # Failure if (isinstance(subj, Formula) and isinstance(obj, Formula)): assert subj.canonical != None F = store.any((store._experience, store.cufi, subj, None)) # Cached value? if F != None: if diag.chatty_flag > 10: progress("Bultin: " + `subj`+ " cached log:conclusion " + `F`) else: oldSubj = subj newSubj = subj.renameVars() F = subj.newFormula() newTopLevelFormula(F) if diag.tracking: reason = Premise("Assumption of builtin", item) #reason = BecauseMerge(F, subj) # F.collector = reason # proof.append(reason) else: reason = None if diag.chatty_flag > 10: progress("Bultin: " + `subj`+ " log:conclusion " + `F`) F.loadFormulaWithSubstitution(subj, why=reason, cannon=True) # leave open think(F) F4 = F.close() if F4 is not F: raise RuntimeError ### oh no! we've hit something old! if F is subj: ### absolute worst --- cannot be allowed! F.add(F.newBlankNode(), F.newBlankNode(), F.newBlankNode()) F4 = F.close() F = F4 assert subj.canonical != None store.storeQuad((store._experience, store.cufi, oldSubj, F), why=BecauseOfExperience("conclusion")) # Cache for later more_unmatched = buildPattern(F, obj) more_variables = obj.variables().copy() _substitute({obj: F}, more_unmatched) _substitute(bindings, more_unmatched) existentials = existentials | more_variables allvars = variables | existentials for quad in more_unmatched: newItem = QueryItem(item.query, quad) queue.append(newItem) if not newItem.setup(allvars, interpretBuiltins = 0, unmatched=more_unmatched, mode=item.query.mode): return [] if diag.chatty_flag > 40: progress("log:Includes: Adding %i new terms and %s as new existentials."% (len(more_unmatched), seqToString(more_variables))) rea = BecauseSupportsWill(con, subj, F, pred, obj) ## nbs = [({oldsubj: subj}, rea)] nbs = [(Env(), rea)] else: if isinstance(subj, Formula): subj = subj.n3String() if isinstance(obj, Formula): obj = obj.n3String() #raise RuntimeError("Cannot do {%s} log:includes {%s} " % (subj, obj)) progress("""Warning: Type error ignored on builtin: log:include only on formulae """+`item`) #@@ was RuntimeError exception item.state = S_DONE return nbs def tryBuiltin(self, queue, bindings, evidence): """Check for built-in functions to see whether it will resolve. Return codes: 0 - give up; [] - success, no new bindings, (action has been called) [...] list of binding lists, each a pair of bindings and reason.""" con, pred, subj, obj = self.quad proof = [] # place for built-in to hang a justification rea = None # Reason for believing this item is true if "q" in self.query.mode: caughtErrors = (TypeError, ValueError, AttributeError, AssertionError, ArgumentNotLiteral, UnknownType) else: caughtErrors = () try: if self.neededToRun[SUBJ] == Set(): if self.neededToRun[OBJ] == Set(): # bound expression - we can evaluate it try: # if pred.eval(subj, obj, queue, bindings.copy(), proof, self.query): if pred.eval(subj, obj, BNone, BNone, proof, BNone): if diag.chatty_flag > 80: progress( "Builtin buinary relation operator succeeds") if diag.tracking: rea = BecauseBuiltIn(con, subj, pred, obj) return [(Env(), rea)] # Involves extra recursion just to track reason return [(Env(), None)] # No new bindings but success in logical operator else: return [] # We absoluteley know this won't match with this in it except caughtErrors: progress( "Warning: Built-in %s %s %s failed because:\n %s: %s" % (`subj`, `pred`, `obj`, sys.exc_info()[0].__name__ , sys.exc_info()[1].__str__() )) if "h" in self.query.mode: raise return [] except BuiltinFeedError: return [] else: if isinstance(pred, Function): if diag.chatty_flag > 97: progress("Builtin function call %s(%s)"%(pred, subj)) try: # result = pred.evalObj(subj, queue, bindings.copy(), proof, self.query) result = pred.evalObj(subj, BNone, BNone, proof, BNone) except caughtErrors: errVal = ( "Warning: Built-in %s!%s failed because:\n %s: %s" % (`pred`, `subj`, sys.exc_info()[0].__name__ , sys.exc_info()[1].__str__() )) progress(errVal) if "h" in self.query.mode: raise if isinstance(pred, MultipleFunction): result = [ErrorFlag(errVal)] else: result = ErrorFlag(errVal) except BuiltinFeedError: return [] if result != None: self.state = S_DONE rea=None if isinstance(result, Formula): if self.quad[OBJ] in self.query.variables: result.reopen() result = result.canonicalize(cannon=True) assert result.canonical is result if diag.tracking: if isinstance(result, Formula): result2 = result.renameVars() assert result.canonical is result, result.debugString() else: result2 = result if isinstance(pred, MultipleFunction): return [(Env({obj:(x, None)}), diag.tracking and BecauseBuiltIn(con, subj, pred, x) ) for x in result] else: return [(nb1, diag.tracking and BecauseBuiltIn(con, subj, pred, result)) for nb1, env3 in obj.unify(result, Env(), Env(), self.neededToRun[OBJ])] ## return [(Env({obj: (result, None)}), ## diag.tracking and BecauseBuiltIn(con, subj, pred, result))] else: return [] else: if (self.neededToRun[OBJ] == Set()): if isinstance(pred, ReverseFunction): if diag.chatty_flag > 97: progress("Builtin Rev function call %s(%s)"%(pred, obj)) try: # result = pred.evalSubj(obj, queue, bindings.copy(), proof, self.query) result = pred.evalSubj(obj, BNone, BNone, proof, BNone) except caughtErrors: errVal = ( "Warning: Built-in %s^%s failed because:\n %s: %s" % (`pred`, `obj`, sys.exc_info()[0].__name__ , sys.exc_info()[1].__str__() )) progress(errVal) if "h" in self.query.mode: raise if isinstance(pred, MultipleReverseFunction): result = [ErrorFlag(errVal)] else: result = ErrorFlag(errVal) except BuiltinFeedError: return [] if result != None: self.state = S_DONE if isinstance(pred, MultipleReverseFunction): return [(Env({subj:(x,None)}), diag.tracking and \ BecauseBuiltIn(con, x, pred, obj)) \ for x in result] else: return [(nb1, diag.tracking and BecauseBuiltIn(con, subj, pred, result)) for nb1, env3 in subj.unify(result, Env(), Env(), self.neededToRun[SUBJ])] ## return [(Env({subj: (result,None)}), ## diag.tracking and \ ## BecauseBuiltIn(con, result, pred, obj) ## )] else: return [] else: if isinstance(pred, FiniteProperty): result = pred.ennumerate() if result != 0: self.state = S_DONE return result # Generates its own list of (list of bindings, reason)s else: return [] if diag.chatty_flag > 30: progress("Builtin could not give result"+`self`) return [] # no solution # @@@ remove dependency on 'heavy' above and remove heavy as param except (IOError, SyntaxError): raise BuiltInFailed(sys.exc_info(), self, pred ),None def tryDeepSearch(self, queue, oldBindings=Env()): """Search the store, unifying nested compound structures Returns lists of list of bindings, attempting if necessary to unify any nested compound terms. Added 20030810, not sure whether it is worth the execution time in practice. It could be left to a special magic built-in like "matches" or something if it is only occasionnaly used. Used in state S_NEED_DEEP """ nbs = [] # Assume failure if self.short == INFINITY: if diag.chatty_flag > 36: progress( "Can't deep search for %s" % `self`) else: if diag.chatty_flag > 36: progress( "Searching (S=%i) %i for %s" %(self.state, self.short, `self`)) try: for s in self.myIndex: pass except: print self.myIndex, self raise for s in self.myIndex : # for everything matching what we know, if self.query.justReturn and s in queue.statements: continue env_queue = [(oldBindings, Env())] ### Why not just unify here? if diag.chatty_flag > 106: progress("...checking %r" % s) for p in PRED, SUBJ, OBJ: if self.searchPattern[p] == None: # Need to check eq = env_queue env_queue = [] for nb, env2 in eq: x = self.quad[p] if self.neededToRun[p] == Set([x]): # a term with no variables if nb.canBind(x, s.quad[p]): nb = nb.bind(x, (s.quad[p], env2)) env_queue.append((nb, env2)) else: # Deep case if diag.chatty_flag > 70: progress( "Deep: Unify %s with %s vars=%s; ee=%s" % (x, s.quad[p], `self.query.variables`[4:-1], `self.query._existentialVariables`[4:-1])) for nb1, env3 in x.unify(s.quad[p], nb, env2, self.neededToRun[p]): env_queue.append((nb1, env3)) ## nbs1 = x.unify(s.quad[p], self.neededToRun[p] & self.query.variables, ## self.neededToRun[p] & self.query._existentialVariables, {}) # Bindings have all been bound for nb, _ in env_queue: nbs.append((nb, s)) # Add the new bindings into the set self.searchDone() # State transitions return nbs # End try deep search def searchDone(self): """Search has been done: figure out next state.""" con, pred, subj, obj = self.quad if self.state == S_LIGHT_EARLY: # Light, can't run yet. self.state = S_LIGHT_WAIT # Search done, can't run elif self.state == S_LIGHT_UNS_READY: # Still have to run this light one return elif self.service: self.state = S_REMOTE # Search done, need to synchronize with other items elif not isinstance(pred, HeavyBuiltIn) or not self.interpretBuiltins: self.state = S_DONE # Done with this one: Do new bindings & stop elif self.canRun(): self.state = S_HEAVY_READY else: self.state = S_HEAVY_WAIT if diag.chatty_flag > 90: progress("...searchDone, now ",self) return def canRun(self): "Is this built-in ready to run?" if (self.neededToRun[SUBJ] == Set()): if (self.neededToRun[OBJ] == Set()): return 1 else: pred = self.quad[PRED] return (isinstance(pred, Function) or pred is self.store.includes or pred is self.store.supports) # Can use variables else: if (self.neededToRun[OBJ] == Set()): return isinstance(self.quad[PRED], ReverseFunction) def bindNew(self, newBindings): """Take into account new bindings from query processing to date The search may get easier, and builtins may become ready to run. Lists may either be matched against store by searching, and/or may turn out to be bound and therefore ready to run. Return: 0 No way can this item ever complete. None Binding done, see item.state """ con, pred, subj, obj = self.quad if diag.chatty_flag > 90: progress(" binding ", `self` + " with "+ `newBindings`) q=[con, pred, subj, obj] for p in ALL4: changed = 0 for var, val in newBindings.items(): if var in self.neededToRun[p]: self.neededToRun[p].remove(var) changed = 1 if q[p] is var and self.searchPattern[p]==None: self.searchPattern[p] = val # const now changed = 1 self.neededToRun[p].clear() # Now it is definitely all bound if changed: q[p] = q[p].substitution(newBindings.asDict(), why=becauseSubexpression) # possibly expensive if self.searchPattern[p] != None: self.searchPattern[p] = q[p] self.quad = q[0], q[1], q[2], q[3] # yuk if self.state in [S_NOT_LIGHT, S_LIGHT_EARLY, S_NEED_DEEP, S_LIGHT_UNS_READY]: # Not searched yet hasUnboundCoumpundTerm = 0 for p in PRED, SUBJ, OBJ : x = self.quad[p] if hasFormula(x): # expr @@ Set @@@@@@@@@@ Check and CompundTerm>??? # ur = x.freeVariables() ur = x.occurringIn(self.neededToRun[p]) self.neededToRun[p] = ur hasUnboundCoumpundTerm = 1 # Can't search directly self.searchPattern[p] = None # can bind this if we recurse ## for p in PRED, SUBJ, OBJ: ## x = self.quad[p] ## if isinstance(x, Formula): ## if self.neededToRun[p]!= Set(): ## self.short = INFINITY # Forget it ## break else: self.updateMyIndex(con) if self.short == 0: self.searchDone() else: self.short = 7700+self.state # Should not be used self.myIndex = None if isinstance(self.quad[PRED], BuiltIn): if self.canRun(): if self.state == S_LIGHT_EARLY: self.state = S_LIGHT_UNS_READY elif self.state == S_LIGHT_WAIT: self.state = S_LIGHT_GO elif self.state == S_HEAVY_WAIT: self.state = S_HEAVY_READY if diag.chatty_flag > 90: progress("...bound becomes ", `self`) if self.state == S_DONE: return [] return [({}, None)] # continue def updateMyIndex(self, formula): self.short, self.myIndex = formula.searchable( self.searchPattern[SUBJ], self.searchPattern[PRED], self.searchPattern[OBJ]) if isinstance(self.quad[SUBJ], Formula) and self.short: self.short = self.short * 3 + len(self.quad[SUBJ]) * 100 if isinstance(self.quad[OBJ], Formula) and self.short: self.short = self.short * 3 + len(self.quad[OBJ]) * 100 for p in SUBJ, OBJ : if isinstance(self.quad[p], Formula) and not self.neededToRun[p]: newIndex = [] for triple in self.myIndex: if isinstance(triple[p], Formula) and len(triple[p]) == len(self.quad[p]): newIndex.append(triple) self.myIndex = newIndex ## self.myIndex = [] ## for triple in myIndex: ## for loc in SUBJ, PRED, OBJ: ## node = triple[loc] ## if node in formula.variables() and self.searchPattern[loc] is not None: ## break ## else: ## self.myIndex.append(triple) def __repr__(self): """Diagnostic string only""" s = "%3i) short=%i, %s" % ( self.state, self.short, quadToString(self.quad, self.neededToRun, self.searchPattern)) if self.service: s += (", servce=%s " % self.service) return s ############## # Compare two cyclic subsystem sto see which should be done first def compareCyclics(self,other): """Note the set indirectly affected is the same for any member of a cyclic subsystem""" if other[0] in self[0].indirectlyAffects: return -1 # Do me earlier if other[0] in self[0].indirectlyAffectedBy: return 1 return 0 ############# Substitution functions def _substitute(bindings, list): """Subsitustes IN-LINE into a list of quads""" for i in range(len(list)): q = list[i] list[i] = lookupQuad(bindings, q) def lookupQuad(bindings, q): "Return a subsituted quad" context, pred, subj, obj = q return (bindings.get(context, context), bindings.get(pred, pred), bindings.get(subj, subj), bindings.get(obj, obj)) def lookupQuadRecursive(bindings, q, why=None): context, pred, subj, obj = q if diag.chatty_flag > 99: progress("\tlookupQuadRecursive:", q) return ( context.substitution(bindings), pred.substitution(bindings), subj.substitution(bindings), obj.substitution(bindings) ) # DIAGNOSTIC STRING OUTPUT # def queueToString(queue): str = "" for item in queue: str = str + `item` + "\n" return str def setToString(set): str = "" for q in set: str = str+ " " + quadToString(q) + "\n" return str def quadToString(q, neededToRun=[[],[],[],[]], pattern=[1,1,1,1]): qm=[" "," "," "," "] for p in ALL4: n = neededToRun[p] if n == []: qm[p]="" else: qm[p] = "(" + `n`[5:-2] + ")" # Set([...]) -> (...) if pattern[p]==None: qm[p]=qm[p]+"?" return "%s%s :: %8s%s %8s%s %8s%s." %(`q[CONTEXT]`, qm[CONTEXT], `q[SUBJ]`,qm[SUBJ], `q[PRED]`,qm[PRED], `q[OBJ]`,qm[OBJ]) def seqToString(set): # return `set` set = list(set) str = "" for x in set[:-1]: str = str + `x` + "," for x in set[-1:]: str = str+ `x` return str def bindingsToString(bindings): # return `bindings` str = "" for x, y in bindings.items(): str = str + (" %s->%s " % ( `x`, `y`)) return str class BecauseBuiltInWill(object): def __init__(self, *args): self.args = args class BecauseSupportsWill(object): def __init__(self, *args): self.args = args class BuiltInFailed(Exception): def __init__(self, info, item, pred): progress("BuiltIn %s FAILED" % pred, `info`) self._item = item self._info = info self._pred = pred def __str__(self): reason = indentString(self._info[1].__str__()) # return "reason=" + reason return ("Error during built-in operation\n%s\nbecause:\n%s" % ( `self._item`, # `self._info`)) `reason`)) def hasFormula(l): if not isinstance(l, (List, Formula)): return False if isinstance(l, Formula): return True for x in l: if hasFormula(x): return True return False from term import AnonymousNode, CompoundTerm def smarterSubstitution(f, bindings, source, why=None, exception=[]): bindings = bindings.asDict() if f in exception: return f if isinstance(f, Formula): f2 = f.newFormula() newBindings, _ = f2.loadFormulaWithSubstitution(f, bindings, why=Because("I said so #2", why)) if f is not source: newExistentials = f2.occurringIn(source.existentials().intersection(Set(bindings.values()))) for n in newExistentials: f2.declareExistential(n) ## for k in bindings.values(): ## if k not in newExistentials and isinstance(k, AnonymousNode) and not isinstance(k,CompoundTerm) and f2.occurringIn(Set([k])) and len(f2) < 20: ## raise RuntimeError('How did I get here? newBindings=%s, bindings=%s, k=%s, f=%s, source=%s' % (newBindings, bindings, k, f2.debugString(), source.debugString())) rr = f2.close() return rr rr = f.substitution(bindings, why=Because("I said so #3", why)) return rr # ends cwm-1.2.1/swap/cwm_math.py0000755015216600007660000001741210640075637014560 0ustar syosisyosi#!/usr/bin/python """ Matematical Built-Ins for CWM/Llyn Allows CWM to do addition, multiplication, subtraction, division, remainders, negation, exponentiation, count the members in a DAML list, and do the normal truth checking functions, only sub classed for numeric values. Note: see maths with an s for te string-oriented versions. cf. http://www.w3.org/2000/10/swap/cwm.py and http://ilrt.org/discovery/chatlogs/rdfig/2001-12-01.txt from "01:20:58" onwards. """ __author__ = 'Sean B. Palmer' __cvsid__ = '$Id: cwm_math.py,v 1.26 2007/06/26 02:36:15 syosi Exp $' __version__ = '$Revision: 1.26 $' import sys, string, re, urllib from term import LightBuiltIn, Function, ReverseFunction, ArgumentNotLiteral, Literal from local_decimal import Decimal import types # from RDFSink import DAML_LISTS, RDF_type_URI, DAML_sameAs_URI MATH_NS_URI = 'http://www.w3.org/2000/10/swap/math#' from diag import progress import sys, traceback def obsolete(): progress("Warning: Obsolete math built-in used.") traceback.print_stack() def tidy(x): #DWC bugfix: "39.03555" got changed to "393555" if x == None: return None s = str(x) if s[-2:] == '.0': s=s[:-2] return s def isString(x): # in 2.2, evidently we can test for isinstance(types.StringTypes) return type(x) is type('') or type(x) is type(u'') # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # M A T H E M A T I C A L B U I L T - I N s # # Some mathematical built-ins: the heaviest one gets the amount of list # members in a DAML list. # # Thanks to deltab, bijan, and oierw for helping me to name the # properties, and to TimBL for CWM and the built-in templates in the # first place. # # Light Built-in classes - these are all reverse functions # add, take, multiply, divide def numeric(s): if type(s) == types.IntType or \ type(s) == types.LongType or \ type(s) is types.FloatType or \ isinstance(s,Decimal): return s if not isinstance(s, (Literal, str, unicode)): raise ArgumentNotLiteral(s) if s.find('.') < 0 and s.find('e') < 0 : return long(s) if 'e' not in s and 'E' not in s: return Decimal(s) return float(s) class BI_absoluteValue(LightBuiltIn, Function): def evaluateObject(self, subj_py): return abs(numeric(subj_py)) class BI_rounded(LightBuiltIn, Function): def evaluateObject(self, subj_py): return round(float(subj_py)) class BI_sum(LightBuiltIn, Function): def evaluateObject(self, subj_py): t = 0 for x in subj_py: t += numeric(x) return t class BI_sumOf(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): t = 0 obsolete() for x in obj_py: t += numeric(x) return t class BI_difference(LightBuiltIn, Function): def evaluateObject(self, subj_py): if len(subj_py) == 2: return numeric(subj_py[0]) - numeric(subj_py[1]) class BI_differenceOf(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): obsolete() if len(obj_py) == 2: return numeric(obj_py[0]) - numeric(obj_py[1]) class BI_product(LightBuiltIn, Function): def evaluateObject(self, subj_py): t = 1 for x in subj_py: t *= numeric(x) return t class BI_factors(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): obsolete() t = 1 for x in obj_py: t *= numeric(x) return t class BI_quotient(LightBuiltIn, Function): def evaluateObject(self, subj_py): if len(subj_py) == 2: if isinstance(numeric(subj_py[0]), long): return numeric(subj_py[1]).__rtruediv__(numeric(subj_py[0])) return numeric(subj_py[0]).__truediv__(numeric(subj_py[1])) class BI_integerQuotient(LightBuiltIn, Function): def evaluateObject(self, subj_py): if len(subj_py) == 2: return long(subj_py[0]) / long(subj_py[1]) class BI_bit(LightBuiltIn, Function): """@@needs a test.""" def evaluateObject(self, subj_py): if len(subj_py) == 2: x = subj_py[0] b = subj_py[1] return (x >> b) & 1 class BI_quotientOf(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): obsolete() if len(obj_py) == 2: return numeric(obj_py[0]).__truediv__(numeric(obj_py[1])) # remainderOf and negationOf class BI_remainder(LightBuiltIn, Function): def evaluateObject(self, subj_py): if len(subj_py) == 2: return numeric(subj_py[0]) % numeric(subj_py[1]) class BI_remainderOf(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): obsolete() if len(obj_py) == 2: return numeric(obj_py[0]) % numeric(obj_py[1]) class BI_negation(LightBuiltIn, Function, ReverseFunction): def evaluateSubject(self, obj_py): return -numeric(obj_py) def evaluateObject(self, subj_py): return -numeric(subj_py) # Power class BI_exponentiation(LightBuiltIn, Function): def evaluateObject(self, subj_py): if len(subj_py) == 2: return numeric(subj_py[0]) ** numeric(subj_py[1]) class BI_exponentiationOf(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): obsolete() if len(obj_py) == 2: return numeric(obj_py[0]) ** numeric(obj_py[1]) # Math greater than and less than etc., modified from cwm_string.py # These are truth testing things - Binary logical operators class BI_greaterThan(LightBuiltIn): def evaluate(self, subject, object): return (float(subject) > float(object)) class BI_notGreaterThan(LightBuiltIn): def evaluate(self, subject, object): return (float(subject) <= float(object)) class BI_lessThan(LightBuiltIn): def evaluate(self, subject, object): return (float(subject) < float(object)) class BI_notLessThan(LightBuiltIn): def evaluate(self, subject, object): return (float(subject) >= float(object)) class BI_equalTo(LightBuiltIn): def evaluate(self, subject, object): return (float(subject) == float(object)) class BI_notEqualTo(LightBuiltIn): def evaluate(self, subject, object): try: return (float(subject) != float(object)) except (ValueError, AttributeError): return None # AttributeError: Symbol instance has no attribute '__float__' # or: ValueError: invalid literal for float(): PT1H # memberCount - this is a proper forward function class BI_memberCount(LightBuiltIn, Function): def evaluateObject(self, subj_py): return len(subj_py) # Register the string built-ins with the store def register(store): str = store.symbol(MATH_NS_URI[:-1]) str.internFrag('sum', BI_sum) str.internFrag('difference', BI_difference) str.internFrag('product', BI_product) str.internFrag('quotient', BI_quotient) str.internFrag('integerQuotient', BI_integerQuotient) str.internFrag('remainder', BI_remainder) str.internFrag('exponentiation', BI_exponentiation) str.internFrag('sumOf', BI_sumOf) str.internFrag('differenceOf', BI_differenceOf) str.internFrag('factors', BI_factors) str.internFrag('bit', BI_bit) str.internFrag('quotientOf', BI_quotientOf) str.internFrag('remainderOf', BI_remainderOf) str.internFrag('exponentiationOf', BI_exponentiationOf) str.internFrag('negation', BI_negation) str.internFrag('absoluteValue', BI_absoluteValue) str.internFrag('rounded', BI_rounded) str.internFrag('greaterThan', BI_greaterThan) str.internFrag('notGreaterThan', BI_notGreaterThan) str.internFrag('lessThan', BI_lessThan) str.internFrag('notLessThan', BI_notLessThan) str.internFrag('equalTo', BI_equalTo) str.internFrag('notEqualTo', BI_notEqualTo) str.internFrag('memberCount', BI_memberCount) if __name__=="__main__": print string.strip(__doc__) cwm-1.2.1/swap/sparql/0000755015216600007660000000000010731073447013677 5ustar syosisyosicwm-1.2.1/swap/sparql/sparql_table.py0000644015216600007660000124627110265052357016736 0ustar syosisyosi#!/usr/bin/env python """n3meta - For use with n3p.py.""" # Automatically generated by n3mp.py import re branches = {u'http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#ArgList': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#AskQuery': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASK': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASK', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QDatasetClause_E_Star', 'http://www.w3.org/2000/10/swap/grammar/sparql#WhereClause']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#BaseDecl': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BASE': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_BASE', 'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#BlankNode': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#BlankNodePropertyList': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#BooleanLiteral': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_false'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_true']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#BrackettedExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#Var', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#RegexExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#FunctionCall'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#FunctionCall'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#FunctionCall']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Collection': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Constraint': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER', 'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QBrackettedExpression_E__Or__QCallExpression_E__C']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#ConstructQuery': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_CONSTRUCT': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_CONSTRUCT', 'http://www.w3.org/2000/10/swap/grammar/sparql#ConstructTemplate', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QDatasetClause_E_Star', 'http://www.w3.org/2000/10/swap/grammar/sparql#WhereClause', 'http://www.w3.org/2000/10/swap/grammar/sparql#SolutionModifier']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#ConstructTemplate': {u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QTriples_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#DatasetClause': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FROM': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_FROM', 'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDefaultGraphClause_E__Or__QNamedGraphClause_E__C']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#DefaultGraphClause': {u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#SourceSelector'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#SourceSelector'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#SourceSelector']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#DescribeQuery': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESCRIBE': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESCRIBE', 'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QVarOrIRIref_E_Plus_Or__QTIMES_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QDatasetClause_E_Star', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QWhereClause_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#SolutionModifier']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Expression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalOrExpression']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#FunctionCall': {u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#ArgList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#ArgList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#ArgList']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#GraphGraphPattern': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH', 'http://www.w3.org/2000/10/swap/grammar/sparql#VarOrBlankNodeOrIRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#GroupGraphPattern']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#TriplesNode'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#TriplesNode'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail': {u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QGraphPatternList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': ['http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QGraphPatternList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesList']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriples': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': ['http://www.w3.org/2000/10/swap/grammar/sparql#Constraint'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphGraphPattern'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#OptionalGraphPattern'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#GroupOrUnionGraphPattern']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesList': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriples', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriples', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriples', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriples', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesTail']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesTail': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#GroupGraphPattern': {u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList', 'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#GroupOrUnionGraphPattern': {u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#GroupGraphPattern', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QUNION_E____QGroupGraphPattern_E__C_E_Star']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#IRIref': {u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#QName'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#QName'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#IRIrefOrFunc': {u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QArgList_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QArgList_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QArgList_E_Opt']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#LimitClause': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LIMIT': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_LIMIT', 'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#NamedGraphClause': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_NAMED': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_NAMED', 'http://www.w3.org/2000/10/swap/grammar/sparql#SourceSelector']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#NamelessBlank': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#AdditiveExpression']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#NumericLiteral': {u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Object': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#TriplesNode'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#TriplesNode'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#ObjectList': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Object', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#OffsetClause': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET', 'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#OptionalGraphPattern': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL', 'http://www.w3.org/2000/10/swap/grammar/sparql#GroupGraphPattern']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#OrderClause': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ORDER': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_ORDER', 'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BY', 'http://www.w3.org/2000/10/swap/grammar/sparql#OrderCondition', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderCondition_E_Plus']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#OrderCondition': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QFunctionCall_E__Or__QVar_E__Or__QBrackettedExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASC': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QASC_E__Or__QDESC_E____QBrackettedExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESC': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QASC_E__Or__QDESC_E____QBrackettedExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QFunctionCall_E__Or__QVar_E__Or__QBrackettedExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QFunctionCall_E__Or__QVar_E__Or__QBrackettedExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QFunctionCall_E__Or__QVar_E__Or__QBrackettedExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QFunctionCall_E__Or__QVar_E__Or__QBrackettedExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QFunctionCall_E__Or__QVar_E__Or__QBrackettedExpression_E__C']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#PrefixDecl': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_PREFIX': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_PREFIX', 'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS', 'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#BrackettedExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#BuiltinCallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Prolog': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASK': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QBaseDecl_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QPrefixDecl_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BASE': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QBaseDecl_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QPrefixDecl_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_CONSTRUCT': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QBaseDecl_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QPrefixDecl_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESCRIBE': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QBaseDecl_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QPrefixDecl_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_PREFIX': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QBaseDecl_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QPrefixDecl_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_SELECT': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QBaseDecl_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QPrefixDecl_E_Star']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_a': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#Verb', 'http://www.w3.org/2000/10/swap/grammar/sparql#ObjectList', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QSEMI_E____QPropertyList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#Verb', 'http://www.w3.org/2000/10/swap/grammar/sparql#ObjectList', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QSEMI_E____QPropertyList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_a': ['http://www.w3.org/2000/10/swap/grammar/sparql#Verb', 'http://www.w3.org/2000/10/swap/grammar/sparql#ObjectList', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QSEMI_E____QPropertyList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#Verb', 'http://www.w3.org/2000/10/swap/grammar/sparql#ObjectList', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QSEMI_E____QPropertyList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#Verb', 'http://www.w3.org/2000/10/swap/grammar/sparql#ObjectList', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QSEMI_E____QPropertyList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#Verb', 'http://www.w3.org/2000/10/swap/grammar/sparql#ObjectList', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QSEMI_E____QPropertyList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Verb', 'http://www.w3.org/2000/10/swap/grammar/sparql#ObjectList', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QSEMI_E____QPropertyList_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Verb', 'http://www.w3.org/2000/10/swap/grammar/sparql#ObjectList', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QSEMI_E____QPropertyList_E__C_E_Opt']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#QName': {u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#QNAME'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Query': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASK': ['http://www.w3.org/2000/10/swap/grammar/sparql#Prolog', 'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QSelectQuery_E__Or__QConstructQuery_E__Or__QDescribeQuery_E__Or__QAskQuery_E__C', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BASE': ['http://www.w3.org/2000/10/swap/grammar/sparql#Prolog', 'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QSelectQuery_E__Or__QConstructQuery_E__Or__QDescribeQuery_E__Or__QAskQuery_E__C', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_CONSTRUCT': ['http://www.w3.org/2000/10/swap/grammar/sparql#Prolog', 'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QSelectQuery_E__Or__QConstructQuery_E__Or__QDescribeQuery_E__Or__QAskQuery_E__C', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESCRIBE': ['http://www.w3.org/2000/10/swap/grammar/sparql#Prolog', 'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QSelectQuery_E__Or__QConstructQuery_E__Or__QDescribeQuery_E__Or__QAskQuery_E__C', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_PREFIX': ['http://www.w3.org/2000/10/swap/grammar/sparql#Prolog', 'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QSelectQuery_E__Or__QConstructQuery_E__Or__QDescribeQuery_E__Or__QAskQuery_E__C', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_SELECT': ['http://www.w3.org/2000/10/swap/grammar/sparql#Prolog', 'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QSelectQuery_E__Or__QConstructQuery_E__Or__QDescribeQuery_E__Or__QAskQuery_E__C', 'http://www.w3.org/2000/10/swap/grammar/bnf#eof']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#RDFLiteral': {u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#String', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#String', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#String', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#String', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C_E_Opt']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#RDFTerm': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#BlankNode'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#BooleanLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#BooleanLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFLiteral']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#RDFTermOrFunc': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#BlankNode'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#BooleanLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#BooleanLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIrefOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIrefOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIrefOrFunc'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFLiteral'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#RDFLiteral']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#RegexExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA', 'http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#SelectQuery': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_SELECT': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_SELECT', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QDISTINCT_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QVar_E_Plus_Or__QTIMES_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QDatasetClause_E_Star', 'http://www.w3.org/2000/10/swap/grammar/sparql#WhereClause', 'http://www.w3.org/2000/10/swap/grammar/sparql#SolutionModifier']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#SolutionModifier': {u'http://www.w3.org/2000/10/swap/grammar/bnf#eof': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderClause_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QLimitClause_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOffsetClause_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LIMIT': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderClause_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QLimitClause_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOffsetClause_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderClause_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QLimitClause_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOffsetClause_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ORDER': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderClause_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QLimitClause_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOffsetClause_E_Opt']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#SourceSelector': {u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#String': {u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Triples': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Triples1': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#Triples2'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#Triples3'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Triples2': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_a': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Triples3': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus', 'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#TriplesNode': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#BlankNodePropertyList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#Collection']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS', 'http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT', 'http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS', 'http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrimaryExpression']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#RelationalExpression']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Var': {u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VAR1'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VAR2']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#VarOrBlankNodeOrIRIref': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#BlankNode'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#NamelessBlank'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#VarOrIRIref': {u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#IRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#VarOrTerm': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphTerm'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#Verb': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrBlankNodeOrIRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrBlankNodeOrIRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_a': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_a'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrBlankNodeOrIRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrBlankNodeOrIRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrBlankNodeOrIRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrBlankNodeOrIRIref'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrBlankNodeOrIRIref']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#WhereClause': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_WHERE': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QWHERE_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GroupGraphPattern'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QWHERE_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GroupGraphPattern']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QAND_E____QValueLogical_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_AND': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_AND', 'http://www.w3.org/2000/10/swap/grammar/sparql#ValueLogical']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QASC_E__Or__QDESC_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASC': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASC'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESC': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESC']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QASC_E__Or__QDESC_E____QBrackettedExpression_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASC': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QASC_E__Or__QDESC_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#BrackettedExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESC': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QASC_E__Or__QDESC_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#BrackettedExpression']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QBrackettedExpression_E__Or__QCallExpression_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#BrackettedExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#CallExpression']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QCOMMA_E____QExpression_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA', 'http://www.w3.org/2000/10/swap/grammar/sparql#Expression']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QCOMMA_E____QObjectList_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA', 'http://www.w3.org/2000/10/swap/grammar/sparql#ObjectList']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDTYPE_E____QIRIref_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_DTYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_DTYPE', 'http://www.w3.org/2000/10/swap/grammar/sparql#IRIref']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDefaultGraphClause_E__Or__QNamedGraphClause_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_NAMED': ['http://www.w3.org/2000/10/swap/grammar/sparql#NamedGraphClause'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#DefaultGraphClause'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#DefaultGraphClause'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#DefaultGraphClause']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E_Opt___QGraphPatternList_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E____QGraphPatternList_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': ['http://www.w3.org/2000/10/swap/grammar/sparql#Dot', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternList']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E____QTriples_E_Opt_C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': ['http://www.w3.org/2000/10/swap/grammar/sparql#Dot', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QTriples_E_Opt']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_EQUAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_EQUAL', 'http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GE': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_GE', 'http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GT': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_GT', 'http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LE': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_LE', 'http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LT': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_LT', 'http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NEQUAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_NEQUAL', 'http://www.w3.org/2000/10/swap/grammar/sparql#NumericExpression']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Expression', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QFunctionCall_E__Or__QVar_E__Or__QBrackettedExpression_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#BrackettedExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#FunctionCall'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#FunctionCall'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#FunctionCall'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_DTYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDTYPE_E____QIRIref_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#LANGTAG': ['http://www.w3.org/2000/10/swap/grammar/sparql#LANGTAG']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QOR_E____QConditionalAndExpression_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_OR': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_OR', 'http://www.w3.org/2000/10/swap/grammar/sparql#ConditionalAndExpression']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS', 'http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS', 'http://www.w3.org/2000/10/swap/grammar/sparql#MultiplicativeExpression']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QSEMI_E____QPropertyList_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_SEMI': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_SEMI', 'http://www.w3.org/2000/10/swap/grammar/sparql#PropertyList']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QSelectQuery_E__Or__QConstructQuery_E__Or__QDescribeQuery_E__Or__QAskQuery_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASK': ['http://www.w3.org/2000/10/swap/grammar/sparql#AskQuery'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_CONSTRUCT': ['http://www.w3.org/2000/10/swap/grammar/sparql#ConstructQuery'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESCRIBE': ['http://www.w3.org/2000/10/swap/grammar/sparql#DescribeQuery'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_SELECT': ['http://www.w3.org/2000/10/swap/grammar/sparql#SelectQuery']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_DIVIDE': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_DIVIDE', 'http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_TIMES': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_TIMES', 'http://www.w3.org/2000/10/swap/grammar/sparql#UnaryExpression']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriples', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriples', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriples', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriples', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternNotTriplesTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples1', 'http://www.w3.org/2000/10/swap/grammar/sparql#GraphPatternListTail']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QUNION_E____QGroupGraphPattern_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_UNION': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_UNION', 'http://www.w3.org/2000/10/swap/grammar/sparql#GroupGraphPattern']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QVarOrIRIref_E_Plus_Or__QTIMES_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_TIMES': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_TIMES'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrIRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVarOrIRIref_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrIRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVarOrIRIref_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrIRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVarOrIRIref_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrIRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVarOrIRIref_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrIRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVarOrIRIref_E_Plus']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_O_QVar_E_Plus_Or__QTIMES_E__C': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_TIMES': ['http://www.w3.org/2000/10/swap/grammar/sparql#GT_TIMES'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVar_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVar_E_Plus']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QArgList_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_AND': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_DIVIDE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_EQUAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#ArgList'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NEQUAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_OR': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_TIMES': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QBaseDecl_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASK': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BASE': ['http://www.w3.org/2000/10/swap/grammar/sparql#BaseDecl'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_CONSTRUCT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESCRIBE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_PREFIX': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_SELECT': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QDISTINCT_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_TIMES': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DISTINCT': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_DISTINCT'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QDatasetClause_E_Star': {u'http://www.w3.org/2000/10/swap/grammar/bnf#eof': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FROM': ['http://www.w3.org/2000/10/swap/grammar/sparql#DatasetClause', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QDatasetClause_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LIMIT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ORDER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_WHERE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QDot_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': ['http://www.w3.org/2000/10/swap/grammar/sparql#Dot'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Plus']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#GraphNode', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QGraphNode_E_Star']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QLimitClause_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/bnf#eof': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LIMIT': ['http://www.w3.org/2000/10/swap/grammar/sparql#LimitClause'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QOffsetClause_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/bnf#eof': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': ['http://www.w3.org/2000/10/swap/grammar/sparql#OffsetClause']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderClause_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/bnf#eof': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LIMIT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ORDER': ['http://www.w3.org/2000/10/swap/grammar/sparql#OrderClause']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderCondition_E_Plus': {u'http://www.w3.org/2000/10/swap/grammar/bnf#eof': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#OrderCondition', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderCondition_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASC': ['http://www.w3.org/2000/10/swap/grammar/sparql#OrderCondition', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderCondition_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESC': ['http://www.w3.org/2000/10/swap/grammar/sparql#OrderCondition', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderCondition_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LIMIT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#OrderCondition', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderCondition_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#OrderCondition', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderCondition_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#OrderCondition', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderCondition_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#OrderCondition', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderCondition_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#OrderCondition', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QOrderCondition_E_Plus']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QPrefixDecl_E_Star': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASK': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_CONSTRUCT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESCRIBE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_PREFIX': ['http://www.w3.org/2000/10/swap/grammar/sparql#PrefixDecl', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QPrefixDecl_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_SELECT': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QPropertyListNotEmpty_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_a': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#PropertyListNotEmpty']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QTriples_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Triples']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QVarOrIRIref_E_Plus': {u'http://www.w3.org/2000/10/swap/grammar/bnf#eof': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FROM': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LIMIT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ORDER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_WHERE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrIRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVarOrIRIref_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrIRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVarOrIRIref_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrIRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVarOrIRIref_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrIRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVarOrIRIref_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#VarOrIRIref', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVarOrIRIref_E_Plus']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QVar_E_Plus': {u'http://www.w3.org/2000/10/swap/grammar/bnf#eof': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FROM': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LIMIT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ORDER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_WHERE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVar_E_Plus'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#Var', 'http://www.w3.org/2000/10/swap/grammar/sparql#_QVar_E_Plus']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QWHERE_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_WHERE': ['http://www.w3.org/2000/10/swap/grammar/sparql#IT_WHERE'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_QWhereClause_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/bnf#eof': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LIMIT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_ORDER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_WHERE': ['http://www.w3.org/2000/10/swap/grammar/sparql#WhereClause'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#WhereClause']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_AND': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QAND_E____QValueLogical_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QAND_E____QValueLogical_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_OR': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QCOMMA_E____QExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QCOMMA_E____QExpression_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QCOMMA_E____QObjectList_E__C_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QCOMMA_E____QObjectList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_SEMI': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QGraphPatternList_E__C_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E____QGraphPatternList_E__C']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QDot_E____QTriples_E_Opt_C_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QDot_E____QTriples_E_Opt_C']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_AND': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_EQUAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GE': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GT': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LE': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LT': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NEQUAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_OR': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_AND': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_DIVIDE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_DTYPE': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_EQUAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NEQUAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_OR': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_SEMI': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_TIMES': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_a': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#LANGTAG': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_OR': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QOR_E____QConditionalAndExpression_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_AND': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_EQUAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NEQUAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_OR': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QSEMI_E____QPropertyList_E__C_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_SEMI': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QSEMI_E____QPropertyList_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': []}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star': {u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_AND': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_DIVIDE': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_EQUAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_GT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LE': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_NEQUAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_OR': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_TIMES': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C'], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C']}, u'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QUNION_E____QGroupGraphPattern_E__C_E_Star': {u'http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#Dot': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#INTEGER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_UNION': ['http://www.w3.org/2000/10/swap/grammar/sparql#_O_QUNION_E____QGroupGraphPattern_E__C', 'http://www.w3.org/2000/10/swap/grammar/sparql#_Q_O_QUNION_E____QGroupGraphPattern_E__C_E_Star'], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': [], u'http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': []}} regexps = { } if __name__=="__main__": print __doc__ cwm-1.2.1/swap/sparql/Makefile0000644015216600007660000000141510300141346015322 0ustar syosisyosi# $Id $ PYTHON:=python CWM:=../cwm.py DELITSUB = 'data:text/rdf+n3;charset=utf-8,%40prefix%20log%3A%20%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F10%2Fswap%2Flog%23%3E%20.%0D%0A%7B%20%3Fs%20%3Fp%20%3Fo%3B%20log%3ArawType%20%5B%20log%3AnotEqualTo%20log%3ALiteral%20%5D%20%7D%20%0D%0A%20%20%20%3D%3E%20%7B%20%3Fs%20%3Fp%20%3Fo%20%7D%20.' sparql_table.py: table_generator.py sparql-selectors.rdf $(PYTHON) table_generator.py --grammar=sparql-selectors.rdf sparql_table.py sparql-selectors.rdf: %.rdf: %.n3 $(PYTHON) $(CWM) --n3 $< --filter=$(DELITSUB) --rdf > $@ sparql-selectors.n3: bnf-token-rules.n3 $(PYTHON) $(CWM) http://www.w3.org/2000/10/swap/grammar/sparql bnf-token-rules.n3 --think --purge --data > $@ .PHONY : clean clean: rm *.rdf sparql-selectors.n3 sparql_table.py cwm-1.2.1/swap/sparql/__init__.py0000644015216600007660000000000010255426063015773 0ustar syosisyosicwm-1.2.1/swap/sparql/sparql_parser.py0000644015216600007660000001060510277134345017131 0ustar syosisyosi#!/usr/bin/env python """ sparql_parser. A parser of SPARQL based on N3P - An N3 Parser using n3.n3 Author: Sean B. Palmer, inamidst.com Licence: http://www.w3.org/Consortium/Lega l/copyright-software Documentation: http://inamidst.com/n3p/ Derived from: http://www.w3.org/2000/10/swap/grammar/predictiveParser.py - predictiveParser.py, Tim Berners-Lee, 2004 Sparql_parser is by Yosi Scharf, and quite heavily modified from n3p """ try: Set = set except NameError: from sets import Set import sys, os, re, urllib import sparql_tokens tokens = Set() import cPickle as pickle try: import sparql_table branches = sparql_table.branches except ImportError: for path in sys.path: fn = os.path.join(path, 'sparql.pkl') if os.path.isfile(fn): f = open(fn, 'rb') n3meta = pickle.load(f) f.close() branches = n3meta['branches'] break start = 'http://www.w3.org/2000/10/swap/grammar/sparql#Query' def abbr(prodURI): return prodURI.split('#').pop() class N3Parser(object): def __init__(self, buffer, branches, sink, ve=0): lexer = sparql_tokens.Lexer() lexer.input(buffer) tokens.update(sparql_tokens.tokens) self.data = lexer.token self.newToken() self.branches = branches self.productions = [] self.memo = {} self.sink = sink self.verbose = ve def parse(self, prod): todo_stack = [[prod, None]] while todo_stack: #print todo_stack #prod = todo_stack.pop() if todo_stack[-1][1] is None: todo_stack[-1][1] = [] tok = self.token # Got an opened production self.onStart(abbr(todo_stack[-1][0])) if not tok: return tok # EOF try: prodBranch = self.branches[todo_stack[-1][0]] except: print todo_stack print self.branches.keys() raise #print prodBranch sequence = prodBranch.get(tok[0], None) if sequence is None: print >> sys.stderr, 'prodBranch', prodBranch raise Exception("Found %s when expecting a %s . todo_stack=%s" % (tok, todo_stack[-1][0], `todo_stack`)) for term in sequence: todo_stack[-1][1].append(term) while todo_stack[-1][1]: term = todo_stack[-1][1].pop(0) if term in tokens: name, word, line = self.token if name == term: self.onToken(term, word) self.newToken() else: raise Exception("Found %s; %s expected" % \ (`self.token`, term)) else: todo_stack.append([term, None]) while todo_stack and todo_stack[-1][1] == []: todo_stack.pop() if not todo_stack: return self.onFinish() self.onFinish() def newToken(self): self.token = self.data() def onStart(self, prod): if self.verbose: print (' ' * len(self.productions)) + `prod` self.productions.append([prod]) def onFinish(self): prod = self.sink.prod(self.productions.pop()) if self.productions: self.productions[-1].append(prod) if self.verbose: print (' ' * len(self.productions)) + '/' + `prod` return prod def onToken(self, prod, tok): self.productions[-1].append((prod, tok)) if self.verbose: print (' ' * len(self.productions)) + `(prod, tok)` class nullProductionHandler(object): def prod(self, production): return production[0] def main(argv=None): if argv is None: argv = sys.argv from swap import sparql2cwm, myStore, notation3 _outSink = notation3.ToN3(sys.stdout.write, quiet=1, flags='') sink = sparql2cwm.FromSparql(myStore._checkStore(), ve=1) if len(argv) == 3: sink = nullProductionHandler() p = N3Parser(file(argv[1], 'r'), branches, sink, ve=1) p.parse(start) if len(argv) == 2: p = N3Parser(file(argv[1], 'r'), branches, sink, ve=1) print "About to parse" f = p.parse(start).close() myStore._checkStore().dumpNested(f, _outSink) if __name__=="__main__": main() cwm-1.2.1/swap/sparql/sparqlClient.py0000644015216600007660000002610610663332731016715 0ustar syosisyosi""" SPARQL Client Query for cwm architecture """ QL_NS = "http://www.w3.org/2004/ql#" from sparql2cwm import SPARQL_NS from swap.term import Env from RDFSink import CONTEXT, PRED, SUBJ, OBJ, PARTS, ALL4 from RDFSink import LITERAL, XMLLITERAL, LITERAL_DT, LITERAL_LANG, ANONYMOUS, SYMBOL from xmlC14n import Canonicalize import urllib #from set_importer import Set, ImmutableSet #from OrderedSequence import merge, intersection, minus, indentString import diag from diag import chatty_flag, tracking, progress def makeVarCounter(string): counter = [0] def makeVar(): counter[0] += 1 return string + str(counter[0]) return makeVar makeVar = makeVarCounter('?x') makeExistential = makeVarCounter('_:a') def SparqlQuery(query, items, serviceURI): """Perform remote query as client on remote store. See $SWAP/query.py """ ## diag.chatty_flag = 99 # @@@@@@ if diag.chatty_flag > 10: progress("SPARQL Query on service %s,\n\tvariables: %s;\n\texistentials: %s" % (serviceURI, query.variables, query.existentials())) for item in items: progress("\tSparql query line: %s" % (`item`)) # s = query.n3String() # progress("QUERY IS ", s) ## To make it easy to map the variables used to the ones ## we get back, use strings, and go both ways. vars = {} reverseVars = {} for var in query.variables: varString = makeVar() vars[var] = varString reverseVars[varString] = var patterns = [] for item in items: p = [] for part in SUBJ, PRED, OBJ: term = item[part] p.append(vars.get(term, representationOf(term))) patterns.append(' '.join([x for x in p])) queryString = "SELECT * WHERE { %s }" % ('. '.join(patterns) ) url = serviceURI + '?' + urllib.urlencode({'query': queryString}) response = urllib.urlopen(url) results = parseSparqlResults(query.store, response) nbs = [] for binding in results: newBinding = Env() for key, val in binding.items(): var = reverseVars['?' + key] newBinding = newBinding.bind(var, (val, newBinding.id)) nbs.append((newBinding, None)) # raise NotImplementedError(results) if diag.chatty_flag > 50: progress('remote query done, nbs=%s' % nbs) return nbs # No bindings for testing from xml.sax import make_parser from xml.sax.saxutils import handler, quoteattr, escape from xml.sax.handler import ErrorHandler ## Lots of SAX magic follows def parseSparqlResults(store, resultString): parser = make_parser() # Workaround for bug in expatreader.py. Needed when # expatreader is trying to guess a prefix. parser.start_namespace_decl("xml", "http://www.w3.org/XML/1998/namespace") parser.setFeature(handler.feature_namespaces, 1) sparqlResults = SparqlResultsHandler(store) parser.setContentHandler(sparqlResults) parser.setErrorHandler(ErrorHandler()) sparqlResults.setDocumentLocator(parser) parser.parse(resultString) return sparqlResults.results RESULTS_NS = 'http://www.w3.org/2005/sparql-results#' class BadSyntax(SyntaxError): pass class SparqlResultsHandler(handler.ContentHandler): states = ('sparql', 'start', 'head', 'var', 'afterHead', 'results', 'result', 'binding') def __init__(self, store): self.store = store def setDocumentLocator(self, locator): self.locator = locator def onError(self, explanation): documentLocation = "%s:line:%s, column:%s" % (self.locator.getSystemId(), self.locator.getLineNumber(), self.locator.getColumnNumber()) raise BadSyntax(explanation + '\n' + documentLocation) def startDocument(self): # progress('starting document') self.state = 'start' def endDocument(self): # progress('ending document') pass # raise NotImplementedError def startElementNS(self, name, qname, attrs): self.text = u'' (ns, lname) = name if ns != RESULTS_NS: self.onError('The tag %s does not belong anywhere!' % (ns + lname)) try: processor = self.tagStateStartHandlers[(self.state, lname)] except KeyError: self.onError("The tag %s does not belong here\nI'm in state %s" % (ns + lname, self.state)) processor(self, attrs) self.text = '' def endElementNS(self, name, qname): (ns, lname) = name processor = self.tagEndHandlers[lname] processor(self) def characters(self, content): self.text = content def startSparql(self, attrs): self.state = 'sparql' def sparqlHead(self, attrs): self.state = 'head' def variable(self, attrs): self.state = 'var' # progress('I need to declare %s' % dict(attrs)) def results(self, attrs): self.state = 'results' self.results = [] def result(self, attrs): self.state = 'result' self.result = {} def binding(self, attrs): try: self.varName = attrs[(None, 'name')] except KeyError: self.error('We need a name') self.state = 'binding' def uri(self, attrs): self.state = 'uri' def bnode(self, attrs): self.state = 'bnode' def literal(self, attrs): self.state = 'literal' # progress('The attrs are %s' % dict(attrs)) self.dt = attrs.get((None, 'datatype'), None) if self.dt is not None: self.dt = self.store.newSymbol(self.dt) self.lang = attrs.get(('http://www.w3.org/XML/1998/namespace', 'lang'), None) def boolean(self, attrs): self.state = 'boolean' tagStateStartHandlers = \ {('start', 'sparql'): startSparql, ('sparql', 'head'): sparqlHead, ('head', 'variable'): variable, ('afterHead', 'results'): results, ('afterHead', 'boolean'): boolean, ('results', 'result'): result, ('result', 'binding'): binding, ('binding', 'uri'): uri, ('binding', 'bnode'): bnode, ('binding', 'literal'): literal} def endHead(self): self.state = 'afterHead' def endVar(self): self.state = 'head' def endResults(self): self.state = 'sparql' def endResult(self): self.results.append(self.result) self.state = 'results' def endBinding(self): self.result[self.varName] = self.val self.state = 'result' def endLiteral(self): self.state = 'endBinding' self.val = self.store.newLiteral(self.text, self.dt, self.lang) def endUri(self): self.state = 'endBinding' self.val = self.store.newSymbol(self.text) def endBnode(self): self.state = 'endBinding' self.val = makeExistential() def endBoolean(self): self.results = (self.text == 'true') tagEndHandlers = \ {'sparql': lambda x: None, 'head': endHead, 'variable': endVar, 'results': endResults, 'result': endResult, 'binding': endBinding, 'literal': endLiteral, 'uri': endUri, 'bnode': endBnode, 'boolean': endBoolean} from notation3 import stringToN3, backslashUify, N3_nil from pretty import auPair def representationOf(pair): """ Representation of a thing in the output stream Regenerates genids if required. Uses prefix dictionary to use qname syntax if possible. """ pair = auPair(pair) _flags = '' if "t" not in _flags: if pair == N3_nil: return"()" ty, value = pair singleLine = False if ty == LITERAL: return stringToN3(value, singleLine=singleLine, flags = _flags) if ty == XMLLITERAL: st = Canonicalize(value, None, unsuppressedPrefixes=['foo']) st = stringToN3(st, singleLine=singleLine, flags=_flags) return st + "^^" + representationOf((SYMBOL, "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral")) if ty == LITERAL_DT: s, dt = value if "b" not in _flags: if (dt == BOOLEAN_DATATYPE): return toBool(s) and "true" or "false" if "n" not in _flags: dt_uri = dt # dt_uri = dt.uriref() if (dt_uri == INTEGER_DATATYPE): return str(long(s)) if (dt_uri == FLOAT_DATATYPE): retVal = str(float(s)) # numeric value python-normalized if 'e' not in retVal: retVal += 'e+00' return retVal if (dt_uri == DECIMAL_DATATYPE): retVal = str(Decimal(s)) if '.' not in retVal: retVal += '.0' return retVal st = stringToN3(s, singleLine= singleLine, flags=_flags) return st + "^^" + representationOf((SYMBOL, dt)) if ty == LITERAL_LANG: s, lang = value return stringToN3(s, singleLine= singleLine, flags=_flags)+ "@" + lang # aid = self._anodeId.get(pair[1], None) # if aid != None: # "a" flag only # return "_:" + aid # Must start with alpha as per NTriples spec. ## if ((ty == ANONYMOUS) ## and not option_noregen and "i" not in self._flags ): ## x = self.regen.get(value, None) ## if x == None: ## x = self.genId() ## self.regen[value] = x ## value = x ### return "<"+x+">" ## ## ## j = string.rfind(value, "#") ## if j<0 and "/" in self._flags: ## j=string.rfind(value, "/") # Allow "/" namespaces as a second best ## ## if (j>=0 ## and "p" not in self._flags): # Suppress use of prefixes? ## for ch in value[j+1:]: # Examples: "." ";" we can't have in qname ## if ch in _notNameChars: ## if verbosity() > 0: ## progress("Cannot have character %i in local name." ## % ord(ch)) ## break ## else: ## namesp = value[:j+1] ## if (self.defaultNamespace ## and self.defaultNamespace == namesp ## and "d" not in self._flags): ## return ":"+value[j+1:] ## self.countNamespace(namesp) ## prefix = self.prefixes.get(namesp, None) # @@ #CONVENTION ## if prefix != None : return prefix + ":" + value[j+1:] ## ## if value[:j] == self.base: # If local to output stream, ## return "<#" + value[j+1:] + ">" # use local frag id ## if "r" not in self._flags and self.base != None: ## value = hexify(refTo(self.base, value)) ## elif "u" in self._flags: value = backslashUify(value) ## else: value = hexify(value) return "<" + value + ">" # Everything else cwm-1.2.1/swap/sparql/sparql_tokens.py0000644015216600007660000003540110303444674017140 0ustar syosisyosi"""Use ply to tokenize a SPARQL expression """ import re import sys #import lex import time bufsiz = 3 tryLongest = True import cPickle as pickle def abbr(prodURI): if prodURI is None: return None return prodURI.split('#').pop() wide_build = (len(u"\U00012345") == 1) def smartCompile(pattern, flags=0): if not wide_build: pattern = pattern.replace(u"\U00010000-\U000effff", u"\ud800-\udb7f\udc00-\udfff") return re.compile(pattern, flags) def importTokens(): global tokens if tokens is None: try: t0 = time.time() from sparql_tokens_table import tokens as ts, regexps as rs t1 = time.time() print >> sys.stderr, 'loaded from file ', t1 - t0 tokens = ts for k, v in rs.iteritems(): setattr(Tokens, k, v) except ImportError: from swap import myStore store = myStore._checkStore() F = myStore.load('http://www.w3.org/2000/10/swap/grammar/sparql') BNF = myStore.Namespace("http://www.w3.org/2000/10/swap/grammar/bnf#") regexps = {} k = F.statementsMatching(pred=BNF.tokens) if len(k) != 1: raise RuntimeError("Expected 1 occurrence of bnf:tokens, got %i: %s" % (len(k), `k`)) for triple in k: tokens = [x.uriref() for x in triple.object()] tokens.append(BNF.PASSED_TOKENS.uriref()) for triple in F.statementsMatching(pred=BNF.matches): s, p, o = triple.spo() key = s.uriref() val = o.value() if key in tokens: setattr(Tokens, 't_' + key, val) regexps['t_' + key] = val setattr(Tokens, 'c_' + key, smartCompile(val, re.I)) regexps['c_' + key] = smartCompile(val, re.I) pklVal = {'tokens': tokens, 'regexps': regexps} try: import imp, os.path try: path = imp.find_module('sparql')[1] except ImportError: path = '' # path = '' f = file(os.path.join(path, 'sparql_tokens_table.py'), 'w') mkmodule(pklVal, f) f.close() except: raise def mkmodule(result, out): import pprint tokens = result['tokens'] regexps = result['regexps'] pp = pprint.PrettyPrinter() print >> out, '#!/usr/bin/env python' print >> out, '"""sparql_tokens_table - For use with sparql_tokens.py."""' print >> out, '# Automatically generated by sparql_tokens.py' print >> out print >> out, 'import re' print >> out print >> out, 'wide_build = (len(u"\U00012345") == 1)' print >> out, 'def smartCompile(pattern, flags=0):' print >> out, ' if not wide_build:' print >> out, ' pattern = pattern.replace(u"\U00010000-\U000effff", u"\ud800-\udb7f\udc00-\udfff")' print >> out, ' return re.compile(pattern, flags)' print >> out print >> out, 'tokens =', pp.pformat(tokens) print >> out, 'regexps = {' for (key, regexp) in regexps.iteritems(): if isinstance(regexp, unicode): print >> out, ' %r: %r, ' % (key, regexp) else: print >> out, ' %r: smartCompile(%r, re.I), ' % (key, regexp.pattern) print >> out, '}' print >> out print >> out, 'if __name__=="__main__": ' print >> out, ' print __doc__' tokens = None class Tokens(object): pass ##class Tokens(object): ## #literal strings ## t_IT_SELECT = u'SELECT' ## t_IT_DISTINCT = u'DISTINCT' ## t_IT_CONSTRUCT = u'CONSTRUCT' ## t_IT_DESCRIBE = u'DESCRIBE' ## t_IT_ASK = u'ASK' ## t_IT_BASE = u'BASE' ## t_IT_PREFIX = u'PREFIX' ## t_FROM_NAMED = u'FROM(?:(?:\u0008)|(?:(?:\\n)|(?:(?:\\r)|(?:(?: )|(?:(?:\u00A0)|(?:(?:[\u2000-\u200B])|(?:(?:\u202F)|(?:(?:\u205F)|(?:\u3000)))))))))+NAMED' ## t_IT_FROM = u'FROM' ## t_IT_WHERE = u'WHERE' ## t_IT_ORDER = u'ORDER' ## t_IT_BY = u'BY' ## t_IT_ASC = u'ASC' ## t_IT_DESC = u'DESC' ## t_IT_LIMIT = u'LIMIT' ## t_IT_OFFSET = u'OFFSET' ## t_IT_UNION = u'UNION' ## t_IT_OPTIONAL = u'OPTIONAL' ## t_IT_GRAPH = u'GRAPH' ## t_IT_FILTER = u'FILTER' ## t_IT_STR = u'STR' ## t_IT_LANG = u'LANG' ## t_IT_DATATYPE = u'DATATYPE' ## t_IT_REGEX = u'REGEX' ## t_IT_BOUND = u'BOUND' ## t_IT_isURI = u'isURI' ## t_IT_isBLANK = u'isBLANK' ## t_IT_isLITERAL = u'isLITERAL' ## t_IT_true = u'true' ## t_IT_false = u'false' ## ## ## t_QuotedIRIref = u'<[^> ]*>' ## ## ## t_FLOATING_POINT = u'(?:[0-9]+\\.[0-9]*(?:[eE][\\+-]?[0-9]+)?)|(?:(?:\\.[0-9]+(?:[eE][\\+-]?[0-9]+)?)|(?:[0-9]+(?:[eE][\\+-]?[0-9]+)))' ## t_DECIMAL = u'(?:[0-9]+\\.[0-9]*)|(?:\\.[0-9]+)' ## t_INTEGER = u'[0-9]+' ## t_STRING_LITERAL_LONG1 = u'"""(?:(?:[^"\\\\])|(?:(?:(?:\\\\[^\\n\\r]))|(?:(?:(?:"[^"]))|(?:(?:""[^"])))))*"""' ## t_STRING_LITERAL_LONG2 = u'\'\'\'(?:(?:[^\'\\\\])|(?:(?:(?:\\\\[^\\n\\r]))|(?:(?:(?:\'[^\']))|(?:(?:\'\'[^\'])))))*\'\'\'' ## t_STRING_LITERAL1 = u'\'(?:(?:[^\'\\\\\\n\\r])|(?:(?:\\\\[^\\n\\r])))*\'' ## t_STRING_LITERAL2 = u'"(?:(?:[^"\\\\\\n\\r])|(?:(?:\\\\[^\\n\\r])))*"' ## t_LANGTAG = u'@[a-zA-Z]+(?:-[a-zA-Z0-9]+)*' ## t_BNODE_LABEL = u'_:(?:(?:(?:_)|(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:[\uF900-\uFFFE]))))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:[\uF900-\uFFFE])))))))))))))|(?:(?:_)|(?:(?:-)|(?:(?:\\.)|(?:(?:[0-9])|(?:\u00B7))))))*)' ## t_QNAME = u'(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:[\uF900-\uFFFE]))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:[\uF900-\uFFFE])))))))))))))|(?:(?:_)|(?:(?:-)|(?:(?:\\.)|(?:(?:[0-9])|(?:\u00B7))))))*)?:(?:(?:(?:_)|(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:[\uF900-\uFFFE]))))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:[\uF900-\uFFFE])))))))))))))|(?:(?:_)|(?:(?:-)|(?:(?:\\.)|(?:(?:[0-9])|(?:\u00B7))))))*)' ## t_QNAME_NS = u'(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:[\uF900-\uFFFE]))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:[\uF900-\uFFFE])))))))))))))|(?:(?:_)|(?:(?:-)|(?:(?:\\.)|(?:(?:[0-9])|(?:\u00B7))))))*)?:' ## t_VAR2 = u'\\$(?:(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:[\uF900-\uFFFE])))))))))))))|(?:(?:_)|(?:(?:[0-9])|(?:\u00B7))))*)' ## t_VAR1 = u'\\?(?:(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:[\uF900-\uFFFE])))))))))))))|(?:(?:_)|(?:(?:[0-9])|(?:\u00B7))))*)' ## t_CloseSquare = u',?(?:(?:\u0008)|(?:(?:\\n)|(?:(?:\\r)|(?:(?: )|(?:(?:\u00A0)|(?:(?:[\u2000-\u200B])|(?:(?:\u202F)|(?:(?:\u205F)|(?:\u3000)))))))))*;?(?:(?:\u0008)|(?:(?:\\n)|(?:(?:\\r)|(?:(?: )|(?:(?:\u00A0)|(?:(?:[\u2000-\u200B])|(?:(?:\u202F)|(?:(?:\u205F)|(?:\u3000)))))))))*\\]' ## t_CloseCurly = u',?(?:(?:\u0008)|(?:(?:\\n)|(?:(?:\\r)|(?:(?: )|(?:(?:\u00A0)|(?:(?:[\u2000-\u200B])|(?:(?:\u202F)|(?:(?:\u205F)|(?:\u3000)))))))))*;?(?:(?:\u0008)|(?:(?:\\n)|(?:(?:\\r)|(?:(?: )|(?:(?:\u00A0)|(?:(?:[\u2000-\u200B])|(?:(?:\u202F)|(?:(?:\u205F)|(?:\u3000)))))))))*\\.?(?:(?:\u0008)|(?:(?:\\n)|(?:(?:\\r)|(?:(?: )|(?:(?:\u00A0)|(?:(?:[\u2000-\u200B])|(?:(?:\u202F)|(?:(?:\u205F)|(?:\u3000)))))))))*\\}' ## t_OptDot = u'\\.(?=((?:(?:(?:\u0008)|(?:(?:\\n)|(?:(?:\\r)|(?:(?: )|(?:(?:\u00A0)|(?:(?:[\u2000-\u200B])|(?:(?:\u202F)|(?:(?:\u205F)|(?:\u3000)))))))))*(?:(?:(?:(?:UNION)|(?:(?:OPTIONAL)|(?:(?:GRAPH)|(?:FILTER))))[^a-z])|(?:\\{)))))' ## t_EmptyPattern = u'\\{(?:(?:\u0008)|(?:(?:\\n)|(?:(?:\\r)|(?:(?: )|(?:(?:\u00A0)|(?:(?:[\u2000-\u200B])|(?:(?:\u202F)|(?:(?:\u205F)|(?:\u3000)))))))))*\\}' ## ## #ignored ## t_PASSED_TOKENS = u'(?:(?:(?:\u0008)|(?:(?:\\n)|(?:(?:\\r)|(?:(?: )|(?:(?:\u00A0)|(?:(?:[\u2000-\u200B])|(?:(?:\u202F)|(?:(?:\u205F)|(?:\u3000)))))))))+)|(?:(?:#[^\\n]*\\n)|(?:/\\*(?:(?:/[^\\*])|(?:[^/\\*]))*\\*/))' ## ## #two characters ## t_GT_OR = u'\\|\\|' ## t_GT_AND = u'&&' ## t_GT_NEQUAL = u'!=' ## t_GT_LE = u'<=' ## t_GT_GE = u'>=' ## t_GT_DTYPE = u'\\^\\^' ## ## #single character ## t_GT_TIMES = u'\\*' ## t_GT_LPAREN = u'\\(' ## t_GT_RPAREN = u'\\)' ## t_GT_SEMI = u';' ## t_GT_COMMA = u',' ## t_IT_a = u'a' ## t_GT_EQUAL = u'=' ## t_GT_LT = u'<' ## t_GT_GT = u'>' ## t_GT_PLUS = u'\\+' ## t_GT_MINUS = u'-' ## t_GT_DIVIDE = u'/' ## t_GT_NOT = u'!' ## t_Dot = u'\\.' ## t_OpenCurly = u'\\{' ## t_OpenSquare = u'\\[' ## ## ##tokens = ('IT_SELECT', ## 'IT_DISTINCT', ## 'IT_CONSTRUCT', ## 'IT_DESCRIBE', ## 'IT_ASK', ## 'IT_BASE', ## 'IT_PREFIX', ## 'FROM_NAMED', ## 'IT_FROM', ## 'IT_WHERE', ## 'IT_ORDER', ## 'IT_BY', ## 'IT_ASC', ## 'IT_DESC', ## 'IT_LIMIT', ## 'IT_OFFSET', ## 'IT_UNION', ## 'IT_OPTIONAL', ## 'IT_GRAPH', ## 'IT_FILTER', ## 'IT_STR', ## 'IT_LANG', ## 'IT_DATATYPE', ## 'IT_REGEX', ## 'IT_BOUND', ## 'IT_isURI', ## 'IT_isBLANK', ## 'IT_isLITERAL', ## 'IT_true', ## 'IT_false', ## 'QuotedIRIref', ## 'FLOATING_POINT', ## 'DECIMAL', ## 'INTEGER', ## 'STRING_LITERAL_LONG1', ## 'STRING_LITERAL_LONG2', ## 'STRING_LITERAL1', ## 'STRING_LITERAL2', ## 'LANGTAG', ## 'BNODE_LABEL', ## 'QNAME', ## 'QNAME_NS', ## 'VAR2', ## 'VAR1', ## 'CloseSquare', ## 'CloseCurly', ## 'OptDot', ## 'EmptyPattern', ## 'PASSED_TOKENS', ## 'GT_OR', ## 'GT_AND', ## 'GT_NEQUAL', ## 'GT_LE', ## 'GT_GE', ## 'GT_DTYPE', ## 'GT_TIMES', ## 'GT_LPAREN', ## 'GT_RPAREN', ## 'GT_SEMI', ## 'GT_COMMA', ## 'IT_a', ## 'GT_EQUAL', ## 'GT_LT', ## 'GT_GT', ## 'GT_PLUS', ## 'GT_MINUS', ## 'GT_DIVIDE', ## 'GT_NOT', ## 'Dot', ## 'OpenCurly', ## 'OpenSquare', ## 'eof') class Lexer(object): def __init__(self): self.uri = None self.buffer = None self.tokenStream = None self.chunk = '' self.was = '' self.line = 0 self.fixTokens() def input(self, buf): self.buffer = buf self.line = 0 self.tokenStream = self.parse() #print [m for m in self.parse()] def parse(self): while True: self.chunk += self.buffer.read().decode('utf_8') if not self.chunk: break for token in self.tokenize(): yield token def tokenize(self): """Tokenize the current chunk.""" while True: if not self.chunk: break waslen = len(self.was) (name, m) = self.match(self.was + self.chunk, waslen) if m: token = (self.was + self.chunk)[m.start():m.end()] self.was = token self.line += len(token.split('\n')) - 1 if abbr(name) != "PASSED_TOKENS": yield (name, token, self.line) endpos = (m.end() - waslen) if not endpos: raise ValueError, "Got zero-length token" self.chunk = self.chunk[endpos:] else: break def token(self): if not self.tokenStream: return None try: return self.tokenStream.next() except StopIteration: self.tokenStream = None return ('http://www.w3.org/2000/10/swap/grammar/bnf#eof', '', -1) def fixTokens(self): importTokens() #print dir(Tokens) #print "Tokens = ", `tokens` def match(self, string, offset): """try everything in the list ``tokens'' """ sayAll = hasattr(self, 'sayAll') length = -1 retVal = None for name in tokens: if hasattr(Tokens, 'c_' + name): if sayAll: print "Trying to match ", name, " to ", string[offset:offset+10] pattern = getattr(Tokens, 'c_' + name) r = pattern.match(string, offset) if r: if not tryLongest: return (name, r) extra = 0 if r.lastindex: extra = r.end(1) - r.start(1) if retVal is None or length < r.end() + extra: retVal = (name, r) length = r.end() + extra if not retVal and offset', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': re.compile(u'!', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': u'_:[_A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][_\\-\\.0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u036f\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': re.compile(u'"(?:(?:[^"\\\\\\n\\r])|(?:(?:\\\\[^\\r\\n])))*"', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': u'GRAPH', u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESCRIBE': u'DESCRIBE', u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_DTYPE': u'\\^\\^', u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_SEMI': u';', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_GE': re.compile(u'>=', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_OR': re.compile(u'\\|\\|', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG2': re.compile(u'"""(?:(?:[^"\\\\])|(?:(?:(?:\\\\[^\\r\\n]))|(?:(?:(?:"[^"]))|(?:(?:""[^"])))))*"""', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': u'false', u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASK': u'ASK', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_CONSTRUCT': re.compile(u'CONSTRUCT', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESCRIBE': re.compile(u'DESCRIBE', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': re.compile(u'(?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][_\\-\\.0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u036f\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*)?:(?:[_A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][_\\-\\.0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u036f\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*)?', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': u'true', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET': re.compile(u'\\]', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': re.compile(u'\\[', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_a': u'a', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': re.compile(u'FILTER', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': re.compile(u'\\{', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_BY': re.compile(u'BY', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_AND': re.compile(u'&&', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': u'OFFSET', u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_DISTINCT': u'DISTINCT', u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_BASE': u'BASE', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_isURI': re.compile(u'isURI', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': re.compile(u'\\+', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_MINUS': re.compile(u'-', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_EQUAL': u'=', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_NAMED': re.compile(u'NAMED', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': u'LANG', u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_DIVIDE': u'/', u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': u'isBLANK', u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_LIMIT': u'LIMIT', u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_FILTER': u'FILTER', u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_NOT': u'!', u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESC': u'DESC', u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_AND': u'&&', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_OPTIONAL': re.compile(u'OPTIONAL', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_LBRACKET': u'\\[', u'c_http://www.w3.org/2000/10/swap/grammar/bnf#PASSED_TOKENS': re.compile(u'(?:(?:(?:\\t)|(?:(?:\\n)|(?:(?:\\r)|(?:(?:[ ])|(?:(?:\xa0)|(?:(?:[\u2000-\u200b])|(?:(?:\u202f)|(?:(?:\u205f)|(?:\u3000)))))))))+)|(?:#[^\\n]*\\n)', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': u'(?:[0-9]+\\.[0-9]*(?:[eE][\\+-]?[0-9]+)?)|(?:(?:\\.[0-9]+(?:[eE][\\+-]?[0-9]+)?)|(?:[0-9]+(?:[eE][\\+-]?[0-9]+)))', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#BNODE_LABEL': re.compile(u'_:[_A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][_\\-\\.0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u036f\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_SELECT': u'SELECT', u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_PREFIX': u'PREFIX', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': re.compile(u'isLITERAL', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#QNAME': u'(?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][_\\-\\.0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u036f\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*)?:(?:[_A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][_\\-\\.0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u036f\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*)?', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': re.compile(u'BOUND', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#CloseCurly': re.compile(u'\\}', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_UNION': re.compile(u'UNION', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_COMMA': re.compile(u',', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_WHERE': re.compile(u'WHERE', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': re.compile(u'(?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][_\\-\\.0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u036f\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*)?:', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#FLOATING_POINT': re.compile(u'(?:[0-9]+\\.[0-9]*(?:[eE][\\+-]?[0-9]+)?)|(?:(?:\\.[0-9]+(?:[eE][\\+-]?[0-9]+)?)|(?:[0-9]+(?:[eE][\\+-]?[0-9]+)))', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASK': re.compile(u'ASK', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': u'\\(', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASC': re.compile(u'ASC', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_REGEX': u'REGEX', u't_http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': u'\\?[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][_0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u036f\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*', u't_http://www.w3.org/2000/10/swap/grammar/sparql#VAR2': u'\\$[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][_0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u036f\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*', u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_ASC': u'ASC', u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_LT': u'<', u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_PLUS': u'\\+', u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_UNION': u'UNION', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_EQUAL': re.compile(u'=', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#VAR1': re.compile(u'\\?[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][_0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u036f\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_FROM': re.compile(u'FROM', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_LE': u'<=', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_OFFSET': re.compile(u'OFFSET', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': u'\\)', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_RPAREN': re.compile(u'\\)', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_NEQUAL': re.compile(u'!=', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_true': re.compile(u'true', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_BOUND': u'BOUND', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_SELECT': re.compile(u'SELECT', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_DATATYPE': re.compile(u'DATATYPE', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_ORDER': re.compile(u'ORDER', re.I), u't_http://www.w3.org/2000/10/swap/grammar/bnf#PASSED_TOKENS': u'(?:(?:(?:\\t)|(?:(?:\\n)|(?:(?:\\r)|(?:(?:[ ])|(?:(?:\xa0)|(?:(?:[\u2000-\u200b])|(?:(?:\u202f)|(?:(?:\u205f)|(?:\u3000)))))))))+)|(?:#[^\\n]*\\n)', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_a': re.compile(u'a', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_DIVIDE': re.compile(u'/', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_DESC': re.compile(u'DESC', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_ORDER': u'ORDER', u't_http://www.w3.org/2000/10/swap/grammar/sparql#QNAME_NS': u'(?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][_\\-\\.0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0300-\u036f\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*)?:', u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_RBRACKET': u'\\]', u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_OR': u'\\|\\|', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_LE': re.compile(u'<=', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_LANG': re.compile(u'LANG', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_GRAPH': re.compile(u'GRAPH', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_SEMI': re.compile(u';', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': re.compile(u'<[^> ]*>', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_LT': re.compile(u'<', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL_LONG1': re.compile(u"'''(?:(?:[^'\\\\])|(?:(?:(?:\\\\[^\\r\\n]))|(?:(?:(?:'[^']))|(?:(?:''[^'])))))*'''", re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_FROM': u'FROM', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_false': re.compile(u'false', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#QuotedIRIref': u'<[^> ]*>', u't_http://www.w3.org/2000/10/swap/grammar/sparql#Dot': u'\\.', u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_GE': u'>=', u't_http://www.w3.org/2000/10/swap/grammar/sparql#LANGTAG': u'@[a-zA-Z]+(?:-[a-zA-Z0-9]+)*', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_STR': re.compile(u'STR', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_LPAREN': re.compile(u'\\(', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_NAMED': u'NAMED', u't_http://www.w3.org/2000/10/swap/grammar/sparql#GT_GT': u'>', u't_http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL2': u'"(?:(?:[^"\\\\\\n\\r])|(?:(?:\\\\[^\\r\\n])))*"', u't_http://www.w3.org/2000/10/swap/grammar/sparql#STRING_LITERAL1': u"'(?:(?:[^'\\\\\\n\\r])|(?:(?:\\\\[^\\r\\n])))*'", u't_http://www.w3.org/2000/10/swap/grammar/sparql#OpenCurly': u'\\{', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#Dot': re.compile(u'\\.', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_isLITERAL': u'isLITERAL', u'c_http://www.w3.org/2000/10/swap/grammar/sparql#GT_TIMES': re.compile(u'\\*', re.I), u'c_http://www.w3.org/2000/10/swap/grammar/sparql#IT_isBLANK': re.compile(u'isBLANK', re.I), u't_http://www.w3.org/2000/10/swap/grammar/sparql#IT_BY': u'BY', } if __name__=="__main__": print __doc__ cwm-1.2.1/swap/sparql/webserver.py0000644015216600007660000000677010277134345016267 0ustar syosisyosi""" A webserver for SPARQL """ __version__ = '$Id: webserver.py,v 1.9 2005/08/09 20:55:16 syosi Exp $' import BaseHTTPServer, urllib from cgi import parse_qs from sys import exc_info def sparql_handler(s): return s default_string = ''' Cwm SPARQL Server The Cwm SPARQL server at %s

Enter a query here:

''' ##file_open = file ##m_types = { ## 'html': 'text/html', ## 'css': 'text/css', ## 'js': 'text/javascript', ## 'gif': 'image/gif', ## 'jpeg': 'image/jpeg' ## } class SPARQL_request_handler(BaseHTTPServer.BaseHTTPRequestHandler): server_version = "CWM/" + __version__[1:-1] query_file = '/' default = default_string % query_file def do_GET(self): try: file, query = self.path.split('?', 1) except ValueError: file, query = self.path, '' ## if file[:13] == '/presentation': ## try: ## dot = file.rfind('.') ## if dot>0: ## c_type = m_types.get(file[dot+1:], 'text/plain') ## else: ## c_type = 'text/plain' ## s = file_open('/home/syosi/server_present/'+file[14:], 'r').read() ## self.send_response(200) ## self.send_header("Content-type", c_type) ## self.send_header("Content-Length", str(len(s))) ## self.end_headers() ## self.wfile.write(s) ## return ## except: ## pass if file != self.query_file: self.send_error(404, "File not found") return args = parse_qs(query) print args query = args.get('query', [''])[0] if not query: self.send_response(200) self.send_header("Content-type", 'text/html') self.send_header("Content-Length", str(len(self.default))) self.end_headers() self.wfile.write(self.default) else: try: retVal, ctype= sparql_handler(query) except: self.send_response(400) resp = str(exc_info()[1]) print 'error is', resp self.send_header("Content-type", 'text/plain') self.send_header("Content-Length", str(len(resp))) self.end_headers() self.wfile.write(resp) else: retVal = retVal.encode('utf_8') print ctype self.send_response(200) self.send_header("Content-type", ctype) self.send_header("Content-Length", str(len(retVal))) self.end_headers() self.wfile.write(retVal) do_POST = do_GET def run(server_class=BaseHTTPServer.HTTPServer, handler_class=SPARQL_request_handler): server_address = ('', 8000) httpd = server_class(server_address, handler_class) httpd.serve_forever() if __name__ == '__main__': run() cwm-1.2.1/swap/pycwmko.py0000644015216600007660000005025110713412505014433 0ustar syosisyosi#!/usr/bin/env python """ """ from pychinko import terms, interpreter #from pychinko import N3Loader from pychinko.helpers import removedups, convertBNodeToFact from swap import term, formula from swap.set_importer import Set import time #from rdflib import BNode, Store # from rdflib.constants import TYPE, FIRST, REST, LIST, NIL, OWLNS LOG_IMPLIES = 'http://www.w3.org/2000/10/swap/log#' try: reversed except NameError: def reversed(l): ll = [a for a in l] b = len(l) while b > 0: b -= 1 yield ll[b] from pychinko import nodes, rete class fullSet(object): def __contains__(self, other): return True from sys import stderr class directPychinkoQuery(object): def __init__(self, workingContext, rulesFormula=None, target=None): self.extra = [] self.store = workingContext.store self.workingContext = workingContext if rulesFormula is None: rulesFormula = workingContext if target is None: target = workingContext t = time.time() self.rules = self.buildRules(rulesFormula) self.interp = interpreter.Interpreter(self.rules) #print "rules" #print self.rules self.facts = self.buildFacts(rulesFormula) print "converting and adding time:", time.time() - t t = time.time() # self.interp.addFacts(Set(self.facts), initialSet=True) #print self.rules #print "add facts time:", time.time() - t t = time.time() self.interp.run() print "interp.run() time:", time.time() - t print len(self.interp.inferredFacts), ' inferred fact(s)' #print "size of inferred facts:", len(self.interp.inferredFacts) # print self.interp.inferredFacts # add the inferred facts back to cwm store t = time.time() for i in self.interp.inferredFacts: # convertFromPystore(); # if isinstance(i.o, str): # print type(i.o) # elif isinstance(i.o, unicode): # print('unicode') # convert them to term.Symbols # cannot convert to term.Symbol if it's a literal # print i.s, i.p, i.o # print self.convFromRete(i.s), self.convFromRete(i.p), self.convFromRete(i.o) newTriple = self.convFromRete(i.s), self.convFromRete(i.p), self.convFromRete(i.o) self.workingContext.add(*newTriple) # if not self.workingContext.contains(newTriple): # self.workingContext.add(*newTriple) # else: # print "contains!" print "add facts time to cwm:", time.time() - t """ print "facts" print self.facts self.workingContext = workingContext self.target = target if workingContext is target: self.loop = True else: self.loop = False""" def convFromRete(self, t): if not t: return None # print "cnv:", t, type(t) if isinstance(t,unicode): return self.workingContext.newSymbol(t) elif isinstance(t,str): return self.workingContext.newLiteral(t) return term.Symbol(t, self.store) def convType(self, t, F, K=None): # print "type:",t, type(t) """print "t:", t print type(t) print "f unis:", F.universals() if (K): print "k exis:", K.existentials()""" if isinstance(t, term.NonEmptyList): #convert the name of the list to an exivar and return it #self.convertListToRDF(t, listId, self.extra) #return terms.Exivar('_:' + str(t)) return '_:' + str(t) #raise RuntimeError if t in F.universals(): return terms.Variable(t) if K is not None and t in K.existentials(): # print "returning existential:", t return terms.Exivar(t) if isinstance(t, term.Symbol): return terms.URIRef(t.uri) if isinstance(t, term.BuiltIn): return t.uriref() if isinstance(t, term.Fragment): # print "uriref:",terms.URIRef(t.uriref()) # print type(t.uriref()) return terms.URIRef(t.uriref()) # print type(t) # print "returning URI",t return str(t) """def processBetaNode(self, betaNode): retVal = False inferences = betaNode.join() self.joinedBetaNodes.add(betaNode) if inferences: if betaNode.rule: #self.rulesThatFired.add(betaNode.rule) #######this test will be moved into `matchingFacts' for rhsPattern in betaNode.rule.rhs: results = betaNode.matchingFacts(rhsPattern, inferences) ### @@@ here we need to add to the workingcontext for triple in results: addedResult = self.workingContext.add(*triple.t) if addedResult: retVal = True self.newStatements.add( self.workingContext.statementsMatching( subj=triple.s, pred=triple.p, obj=triple.o)[0]) # retVal = retVal or addedResult else: for child in betaNode.children: #process children of BetaNode.. betaNodeProcessed = self.processBetaNode(child) retVal = retVal or betaNodeProcessed return retVal""" def _listsWithinLists(self, L, lists): if L not in lists: lists.append(L) for i in L: if isinstance(i, term.NonEmptyList): self._listsWithinLists(i, lists) def dumpLists(self, context): "Dump lists out as first and rest. Not used in pretty." listList = {} result = [] #context = self.workingContext #sink = self.sink lists = [] for s in context.statements: #print "s:", s for x in s.predicate(), s.subject(), s.object(): if isinstance(x, term.NonEmptyList): self._listsWithinLists(x, lists) for l in lists: list = l while not isinstance(list, term.EmptyList): if list not in listList: #print list, " rdf:type rdf:list" #self._outputStatement(sink, (context, self.store.forSome, context, list)) listList[list] = 1 list = list.rest listList = {} for l in lists: list = l while (not isinstance(list, term.EmptyList)) and list not in listList: result.append(terms.Pattern(terms.Exivar("_:" + str(list)), "http://www.w3.org/1999/02/22-rdf-syntax-ns#first", self.convType(list.first, self.workingContext, context))) if isinstance(list.rest, term.EmptyList): #print "_:", list, " rdf:rest rdf:nil" result.append(terms.Pattern(terms.Exivar("_:" + str(list)), "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest", "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil")) else: result.append(terms.Pattern(terms.Exivar("_:" + str(list)), "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest", self.convType(list.rest, self.workingContext, context))) #print list, " rdf:rest ", list.rest #self._outputStatement(sink, (context, self.store.first, list, list.first)) #self._outputStatement(sink, (context, self.store.rest, list, list.rest)) listList[list] = 1 list = list.rest return result def buildRules(self, indexedFormula): rules = [] for rule in indexedFormula.statementsMatching(pred=indexedFormula.store.implies): subj, predi, obj = rule.spo() if not isinstance(subj, formula.Formula) or \ not isinstance(obj, formula.Formula): continue head = [] tail = [] for fr, to in (subj, tail), (obj, head): self.extra = self.dumpLists(fr) #use extra for the list-related triples for quad in fr: #if not isinstance(quad.subject(), term.NonEmptyList): s, p, o = [self.convType(x, indexedFormula, fr) for x in quad.spo()] #to get variables. #Not good enough for Lists # print "spo:", s,p,o for f in (self.extra + [(s,p,o)]): to.append(terms.Pattern(*f)) rules.append(terms.Rule(tail, head, (subj, predi, obj) )) return rules def buildFacts(self, indexedFormula): facts = [] for f in self.dumpLists(indexedFormula): facts.append(terms.Fact(convertBNodeToFact(f.s),f.p, convertBNodeToFact(f.o))) # for alphaNode in self.interp.rete.alphaNodeStore: # print alphaNode # i = alphaNode.pattern.noneBasedPattern() # pattern = self.convFromRete(i[0]), self.convFromRete(i[1]), self.convFromRete(i[2]) # print "pattern:", pattern # for quad in indexedFormula.statementsMatching( # subj=pattern[0], # pred=pattern[1], # obj =pattern[2]): ## print "quad:", quad # if isinstance(subj, formula.Formula) or isinstance(obj, formula.Formula): # print "The RETE engine cannot process nested formulas currently" # continue # # s, p, o = [self.convType(x, indexedFormula, None) for x in quad.spo()] # # alphaNode.add(terms.Fact(s,p,o)) for fact in indexedFormula.statements: subj, predi, obj = fact.spo() # ignore formulas for now if isinstance(subj, formula.Formula) or \ isinstance(obj, formula.Formula): print "The RETE cannot process nested formulas at the time - use it for ntriples only" # raise NotImplementedError continue # only get top level facts head = [] tail = [] s, p, o = [self.convType(x, indexedFormula, None) for x in fact.spo()] #to get variables. #Not good enough for Lists, but they're taken care of earlier facts.append(terms.Fact(s, p, o)) self.interp.addFacts(Set(facts), initialSet=True) return facts def add(self, triple): t = triple.t status = False if self.workingContext.add(*t): alphaMatches = self.rete.alphaIndex.match(f) for anode in alphaMatches: if anode.add(f): status = True return Status """ def __call__(self): #convert it to a set of facts (simply take all triples in a formula and add them as facts) #as first cut rules = self.rules indexedFormula = self.workingContext self.newStatements = fullSet() self.rete = rete.RuleCompiler().compile(rules) newStuff = True first = True while newStuff and (first or self.loop): #print >> stderr, "starting loop" first = False newStuff = False needToRun = False for alphaNode in self.rete.alphaNodeStore: pattern = alphaNode.pattern.noneBasedPattern() for quad in indexedFormula.statementsMatching( subj=pattern[0], pred=pattern[1], obj =pattern[2]): self.extra = [] if quad in self.newStatements: s, p, o = [self.convType(x, indexedFormula) for x in quad.spo()] for f in (self.extra + [(s,p,o)]): if alphaNode.add(terms.Fact(*f)): needToRun = True self.newStatements = Set() self.joinedBetaNodes = Set() if needToRun: for alphaNode in self.rete.alphaNodeStore: for betaNode in alphaNode.betaNodes: if betaNode in self.joinedBetaNodes: continue newNewStuff = self.processBetaNode(betaNode) newStuff = newStuff or newNewStuff print self.newStatements # self.rete.printNetwork() class ToPyStore(object): def __init__(self, pyStore): self.pyStore = pyStore self.lists = {} self.typeConvertors = [ (formula.Formula , self.formula), (formula.StoredStatement, self.triple), (term.LabelledNode, self.URI), (term.Fragment, self.URI), (term.AnonymousNode, self.BNode), (term.Literal, self.literal), (term.List, self.list), (term.N3Set, self.set)] def lookup(self, node): for theType, function in self.typeConvertors: if isinstance(node, theType): return function(node) raise RuntimeError(`node` + ' ' + `node.__class__`) def formula(self, node): subFormulaRef = self.pyStore.create_clause() subFormula = self.pyStore.get_clause(subFormulaRef) subConvertor = self.__class__(subFormula) subConvertor.statements(node) return subFormulaRef def URI(self, node): return terms.URI(node.uriref()) def BNode(self, node): return BNode.BNode(node.uriref()) def literal(self, node): string = node.string dt = node.datatype if not dt: dt = '' lang = node.lang if not lang: lang = '' return terms.Literal(string, lang, dt) def list(self, node): if node in self.lists: return self.lists[node] newList = [].__class__ next = NIL for item in reversed(newList(node)): bNode = BNode.BNode() self.pyStore.add((bNode, REST, next)) self.pyStore.add((bNode, FIRST, self.lookup(item))) next = bNode self.lists[node] = next return next def set(self, node): bNode = BNode.BNode() l = self.list(node) self.pyStore.add((bNode, OWLNS['oneOf'], l)) return bNode def statements(self, formula): for var in formula.universals(): self.pyStore.add_universal(self.lookup(var)) for var in formula.existentials(): if not isinstance(var, term.AnonymousNode): self.pyStore.add_existential(self.lookup(var)) for statement in formula: self.triple(statement) def triple(self, statement): try: self.pyStore.add([self.lookup(item) for item in statement.spo()]) except: raise class FromPyStore(object): def __init__(self, formula, pyStore, parent=None): self.parent = parent self.formula = formula self.store = formula.store self.pyStore = pyStore self.bNodes = {} self.typeConvertors = [ (Store.Store, self.subStore), (terms.Exivar, self.existential), (terms.Variable, self.variable), (terms.URIRef, self.URI), (BNode.BNode, self.BNode), (terms.Literal, self.literal)] self.stores = [ (N3Loader.ClauseLoader, self.patterns), (N3Loader.N3Loader, self.facts_and_rules), (Store.Store, self.triples)] def lookup(self, node): for theType, function in self.typeConvertors: if isinstance(node, theType): return function(node) raise RuntimeError(`node` + ' ' + `node.__class__`) def run(self): node = self.pyStore for theType, function in self.stores: if isinstance(node, theType): return function(node) raise RuntimeError(`node` + ' ' + `node.__class__`) def URI(self, node): return self.formula.newSymbol(node) def variable(self, node): if self.pyStore.get_clause(node.name) is not None: return self.subStore(self.pyStore.get_clause(node.name)) v = self.URI(node.name) self.parent.declareUniversal(v) return v def existential(self, node): if self.pyStore.get_clause(node.name) is not None: return self.subStore(self.pyStore.get_clause(node.name)) v = self.URI(node.name) self.formula.declareExistential(v) return v def BNode(self, node): if self.pyStore.get_clause(node) is not None: return self.subStore(self.pyStore.get_clause(node)) bNodes = self.bNodes if node not in bNodes: bNodes[node] = self.formula.newBlankNode(node) return bNodes[node] def literal(self, node): return self.formula.newLiteral(node, node.datatype or None, node.language or None) def subStore(self, node): f = self.formula.newFormula() self.__class__(f, node, self.formula).run() return f.close() def facts_and_rules(self, pyStore): patternMap = {} for nodeID in pyStore.list_clauses(): patternMap[tuple(removedups(pyStore.get_clause(nodeID).patterns))] = pyStore.get_clause(nodeID) for fact in pyStore.facts: self.formula.add( self.lookup(fact.s), self.lookup(fact.p), self.lookup(fact.o)) for rule in pyStore.rules: self.formula.add( self.subStore(patternMap[tuple(removedups(rule.lhs))]), self.store.implies, self.subStore(patternMap[tuple(removedups(rule.rhs))])) def patterns(self, pyStore): patternMap = {} for nodeID in pyStore.list_clauses(): patternMap[tuple(removedups(pyStore.get_clause(nodeID).patterns))] = pyStore.get_clause(nodeID) for pattern in pyStore.patterns: if isinstance(pattern.s, terms.Rule): rule = pattern.s self.formula.add( self.subStore(patternMap[tuple(removedups(rule.lhs))]), self.store.implies, self.subStore(patternMap[tuple(removedups(rule.rhs))])) else: self.formula.add( self.lookup(pattern.s), self.lookup(pattern.p), self.lookup(pattern.o)) def triples(self, pyStore): pass if __name__ == '__main__': import sys #sys.path.append('/home/syosi') from swap import llyn #from pychinko.N3Loader import N3Loader store = llyn.RDFStore() from swap import webAccess f = webAccess.load(store, sys.argv[1]) pyf = N3Loader.N3Loader() conv = ToPyStore(pyf) conv.statements(f) print "facts = " + ',\n'.join([repr(a) for a in pyf.facts]) print "rules = " + ',\n'.join([repr(a) for a in pyf.rules]) print '----' g = store.newFormula() reConv = FromPyStore(g, pyf) reConv.run() print g.close().n3String() """ cwm-1.2.1/swap/rdfxml.py0000644015216600007660000000114710331501213014225 0ustar syosisyosi#! /usr/bin/python """ A module to allow one to chose which RDF parser to use. This is not done correctly, so I don't expect this file to last very long. $Id: rdfxml.py,v 1.3 2005/10/24 16:58:38 timbl Exp $ """ def rdfxmlparser(store, openFormula, thisDoc=None, flags="", why=None, parser='sax2rdf'): if parser == 'rdflib': import rdflib_user return rdflib_user.rdflib_handoff(store, openFormula,thisDoc, why=why) else: # parser == sax2xml import sax2rdf return sax2rdf.RDFXMLParser(store, openFormula, thisDoc=thisDoc, flags=flags, why=why) cwm-1.2.1/swap/cwm_sparql.py0000644015216600007660000003421310717716424015125 0ustar syosisyosi#!/usr/bin/env python """ Builtins for doing SPARQL queries in CWM $Id: cwm_sparql.py,v 1.22 2007/11/18 02:01:56 syosi Exp $ """ from swap.term import LightBuiltIn, Function, ReverseFunction, MultipleFunction,\ MultipleReverseFunction, typeMap, LabelledNode, \ CompoundTerm, N3Set, List, EmptyList, NonEmptyList, \ Symbol, Fragment, Literal, Term, AnonymousNode, HeavyBuiltIn, toBool import diag progress = diag.progress from RDFSink import RDFSink from set_importer import Set import uripath from toXML import XMLWriter try: from decimal import Decimal except ImportError: from local_decimal import Decimal from term import ErrorFlag as MyError SPARQL_NS = 'http://www.w3.org/2000/10/swap/sparqlCwm' class BI_truthValue(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): if isinstance(subj, Literal): ## print '%s makes %s' % (subj, toBool(str(subj), subj.datatype.fragid)) ## print '%s makes %s' % (obj, toBool(str(obj), obj.datatype.fragid)) ## print 'I got here on %s, %s, returning %s' % (subj, obj, toBool(str(subj), subj.datatype.fragid) is toBool(str(obj), obj.datatype.fragid)) return toBool(str(subj), subj.datatype) is toBool(str(obj), obj.datatype) raise TypeError("%s type cannot be converted to boolean" % `subj.__class`) class BI_typeErrorIsTrue(LightBuiltIn): """ Subject is anything (must be bound. 1 works well) Object is a formula containing the test as its only triple """ def eval(self, subj, obj, queue, bindings, proof, query): if len(obj) != 1: raise TypeError statement = obj.statements[0] try: return statement.predicate().eval(statement.subject(), statement.object(), queue, bindings, proof, query) except: return True class BI_typeErrorReturner(LightBuiltIn, Function): def evalObj(self, subj, queue, bindings, proof, query): if len(subj) != 1: raise TypeError statement = subj.statements[0] try: return statement.predicate().evalObj(statement.subject(), queue, bindings, proof, query) except: return MyError() class BI_equals(LightBuiltIn, Function, ReverseFunction): def eval(self, subj, obj, queue, bindings, proof, query): xsd = self.store.integer.resource if isinstance(subj, Symbol) and isinstance(obj, Symbol): return subj is obj if isinstance(subj, Fragment) and isinstance(obj, Fragment): return subj is obj if isinstance(subj, Literal) and isinstance(obj, Literal): if subj.datatype == xsd['boolean'] or obj.datatype == xsd['boolean']: return (toBool(str(subj), subj.datatype.resource is xsd and subj.datatype.fragid or None) == toBool(str(obj), obj.datatype.resource is xsd and obj.datatype.fragid or None)) if not subj.datatype and not obj.datatype: return str(subj) == str(obj) if subj.datatype.fragid in typeMap and obj.datatype.fragid in typeMap: return subj.value() == obj.value() if subj.datatype != obj.datatype: raise TypeError(subj, obj) return str(subj) == str(obj) raise TypeError(subj, obj) def evalSubj(self, obj, queue, bindings, proof, query): return obj def evalObj(self,subj, queue, bindings, proof, query): return subj class BI_lessThan(LightBuiltIn): def evaluate(self, subject, object): return (subject < object) class BI_greaterThan(LightBuiltIn): def evaluate(self, subject, object): return (subject > object) class BI_notGreaterThan(LightBuiltIn): def evaluate(self, subject, object): return (subject <= object) class BI_notLessThan(LightBuiltIn): def evaluate(self, subject, object): return (subject >= object) class BI_notEquals(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return not self.store.newSymbol(SPARQL_NS)['equals'].eval(subj, obj, queue, bindings, proof, query) class BI_dtLit(LightBuiltIn, Function, ReverseFunction): def evalObj(self,subj, queue, bindings, proof, query): subj = [a for a in subj] if len(subj) != 2: raise ValueError subject, datatype = subj if not isinstance(subj, Literal) or not isinstance(datatype, LabelledNode): raise TypeError if subj.datatype: raise TypeError('%s must not have a type already' % subj) return self.store.newLiteral(str(subj), dt=datatype) def evalSubj(self, obj, queue, bindings, proof, query): if not isinstance(obj, Literal): raise TypeError('I can only find the datatype of a Literal, not a %s' % `obj.__class__.__name__`) return self.store.newList([self.store.newLiteral(str(obj)), obj.datatype]) class BI_langLit(LightBuiltIn, Function, ReverseFunction): def evalObj(self,subj, queue, bindings, proof, query): subj = [a for a in subj] if len(subj) != 2: raise ValueError subject, lang = subj if not isinstance(subj, Literal) or not isinstance(lang, Literal): raise TypeError if not lang: lang = None else: lang = str(lang) if subj.lang: raise TypeError('%s must not have a lang already' % subj) return self.store.newLiteral(str(subj), lang=lang) def evalSubj(self, obj, queue, bindings, proof, query): if not isinstance(obj, Literal): raise TypeError('I can only find the datatype of a Literal, not a %s' % `obj.__class__.__name__`) lang = obj.lang if not obj.lang: lang = '' return self.store.newList([self.store.newLiteral(str(obj)), self.store.newLiteral(lang)]) class BI_lamePred(HeavyBuiltIn, MultipleReverseFunction): def eval(self, subj, obj, queue, bindings, proof, query): return True def evalSubj(self, obj, queue, bindings, proof, query): #really slow. Return every list I know anything about. Should I do this at all? retVals = Set([self.store.nil]) retValCopy = Set() n = 0 while retVals != retValCopy: print n, retVals, retValCopy n += 1 retValCopy = retVals.copy() for node in retValCopy: retVals.update(node._prec.values()) a = query.workingContext.occurringIn(retVals) ## Really slow. Need to generate this on the fly? print 'a=', a return a ############################# ############################# # Builtins useful from within cwm, not within SPARQL # ############################# ############################# class BI_query(LightBuiltIn, Function): def evalObj(self,subj, queue, bindings, proof, query): from query import applySparqlQueries ns = self.store.newSymbol(SPARQL_NS) assert isinstance(subj, List) subj = [a for a in subj] assert len(subj) == 2 source, query = subj F = self.store.newFormula() applySparqlQueries(source, query, F) if query.contains(obj=ns['ConstructQuery']): return F if query.contains(obj=ns['SelectQuery']) or query.contains(obj=ns['AskQuery']): return self.store.newLiteral(sparql_output(query, F)) def bnode_replace(self, string): if string in self: return self[string] hash = string.find('#') base = string[:hash] self[string] = base + '#_bnode_' + str(self['counter']) self['counter'] += 1 return self[string] bnode_replace = bnode_replace.__get__({'counter':0}) def sparql_output(query, F): store = F.store RESULTS_NS = 'http://www.w3.org/2005/sparql-results#' ns = store.newSymbol(SPARQL_NS) if query.contains(obj=ns['SelectQuery']): node = query.the(pred=store.type, obj=ns['SelectQuery']) outputList = [] prefixTracker = RDFSink() prefixTracker.setDefaultNamespace(RESULTS_NS) prefixTracker.bind('', RESULTS_NS) xwr = XMLWriter(outputList.append, prefixTracker) xwr.makePI('xml version="%s"' % '1.0') xwr.startElement(RESULTS_NS+'sparql', [], prefixTracker.prefixes) xwr.startElement(RESULTS_NS+'head', [], prefixTracker.prefixes) vars = [] for triple in query.the(subj=node, pred=ns['select']): vars.append(triple.object()) xwr.emptyElement(RESULTS_NS+'variable', [(RESULTS_NS+' name', str(triple.object()))], prefixTracker.prefixes) xwr.endElement() xwr.startElement(RESULTS_NS+'results', [], prefixTracker.prefixes) resultFormulae = [aa for aa in F.each(pred=store.type, obj=ns['Result'])] try: resultFormulae.sort(Term.compareAnyTerm) except: print [type(x) for x in resultFormulae] print Term raise for resultFormula in resultFormulae: xwr.startElement(RESULTS_NS+'result', [], prefixTracker.prefixes) for var in vars: binding = resultFormula.the(pred=ns['bound'], obj=var) if binding: xwr.startElement(RESULTS_NS+'binding', [(RESULTS_NS+' name', str(var))], prefixTracker.prefixes) if isinstance(binding, LabelledNode): xwr.startElement(RESULTS_NS+'uri', [], prefixTracker.prefixes) xwr.data(binding.uriref()) xwr.endElement() elif isinstance(binding, (AnonymousNode, List)): xwr.startElement(RESULTS_NS+'bnode', [], prefixTracker.prefixes) xwr.data(bnode_replace(binding.uriref())) xwr.endElement() elif isinstance(binding, Literal): props = [] if binding.datatype: props.append((RESULTS_NS+' datatype', binding.datatype.uriref())) if binding.lang: props.append(("http://www.w3.org/XML/1998/namespace lang", binding.lang)) xwr.startElement(RESULTS_NS+'literal', props, prefixTracker.prefixes) xwr.data(unicode(binding)) xwr.endElement() xwr.endElement() else: pass xwr.endElement() xwr.endElement() xwr.endElement() xwr.endDocument() return u''.join(outputList) if query.contains(obj=ns['AskQuery']): node = query.the(pred=store.type, obj=ns['AskQuery']) outputList = [] prefixTracker = RDFSink() prefixTracker.setDefaultNamespace(RESULTS_NS) prefixTracker.bind('', RESULTS_NS) xwr = XMLWriter(outputList.append, prefixTracker) xwr.makePI('xml version="%s"' % '1.0') xwr.startElement(RESULTS_NS+'sparql', [], prefixTracker.prefixes) xwr.startElement(RESULTS_NS+'head', [], prefixTracker.prefixes) vars = [] # for triple in query.the(subj=node, pred=ns['select']): # vars.append(triple.object()) # xwr.emptyElement(RESULTS_NS+'variable', [(RESULTS_NS+'name', str(triple.object()))], prefixTracker.prefixes) xwr.endElement() xwr.startElement(RESULTS_NS+'boolean', [], prefixTracker.prefixes) if F.the(pred=store.type, obj=ns['Success']): xwr.data('true') else: xwr.data('false') xwr.endElement() xwr.endElement() xwr.endDocument() return ''.join(outputList) def sparql_queryString(source, queryString): from query import applySparqlQueries store = source.store ns = store.newSymbol(SPARQL_NS) from sparql import sparql_parser import sparql2cwm convertor = sparql2cwm.FromSparql(store) import StringIO p = sparql_parser.N3Parser(StringIO.StringIO(queryString), sparql_parser.branches, convertor) q = p.parse(sparql_parser.start).close() F = store.newFormula() applySparqlQueries(source, q, F) F = F.close() ## print 'result is ', F ## print 'query is ', q.n3String() return outputString(q, F) def outputString(q, F): store = q.store ns = store.newSymbol(SPARQL_NS) if q.contains(obj=ns['ConstructQuery']): return F.rdfString().decode('utf_8'), 'application/rdf+xml' if q.contains(obj=ns['SelectQuery']) or q.contains(obj=ns['AskQuery']): return sparql_output(q, F), 'application/sparql-results+xml' class BI_semantics(HeavyBuiltIn, Function): """ The semantics of a resource are its machine-readable meaning, as an N3 forumula. The URI is used to find a represnetation of the resource in bits which is then parsed according to its content type.""" def evalObj(self, subj, queue, bindings, proof, query): store = subj.store if isinstance(subj, Fragment): doc = subj.resource else: doc = subj F = store.any((store._experience, store.semantics, doc, None)) if F != None: if diag.chatty_flag > 10: progress("Already read and parsed "+`doc`+" to "+ `F`) return F if diag.chatty_flag > 10: progress("Reading and parsing " + doc.uriref()) inputURI = doc.uriref() F = self.store.load(inputURI, contentType="x-application/sparql") if diag.chatty_flag>10: progress(" semantics: %s" % (F)) if diag.tracking: proof.append(F.collector) return F.canonicalize() def register(store): ns = store.newSymbol(SPARQL_NS) ns.internFrag('equals', BI_equals) ns.internFrag('lessThan', BI_lessThan) ns.internFrag('greaterThan', BI_greaterThan) ns.internFrag('notGreaterThan', BI_notGreaterThan) ns.internFrag('notLessThan', BI_notLessThan) ns.internFrag('notEquals', BI_notEquals) ns.internFrag('typeErrorIsTrue', BI_typeErrorIsTrue) ns.internFrag('typeErrorReturner', BI_typeErrorReturner) ns.internFrag('truthValue', BI_truthValue) ns.internFrag('lamePred', BI_lamePred) ns.internFrag('query', BI_query) ns.internFrag('semantics', BI_semantics) ns.internFrag('dtLit', BI_dtLit) ns.internFrag('langLit', BI_langLit) cwm-1.2.1/swap/cwm_maths.py0000755015216600007660000001626110254404273014735 0ustar syosisyosi#!/usr/bin/python """ Matematical Built-Ins for CWM/Llyn using Strings Allows CWM to do addition, multiplication, subtraction, division, remainders, negation, exponentiation, count the members in a DAML list, and do the normal truth checking functions, only sub classed for numeric values. All values are represented by string types (untyped literals in RDF). See math (no s) for versions using numeric types. cf. http://www.w3.org/2000/10/swap/cwm.py and http://ilrt.org/discovery/chatlogs/rdfig/2001-12-01.txt from "01:20:58" onwards. """ __author__ = 'Sean B. Palmer' __cvsid__ = '$Id: cwm_maths.py,v 1.11 2005/06/09 21:05:14 syosi Exp $' __version__ = '$Revision: 1.11 $' import sys, string, re, urllib from term import LightBuiltIn, Function, ReverseFunction from local_decimal import Decimal MATHS_NS_URI = 'http://www.w3.org/2000/10/swap/maths#' def tidy(x): #DWC bugfix: "39.03555" got changed to "393555" if x == None: return None s = str(x) if s[-2:] == '.0': s=s[:-2] return s def isString(x): # in 2.2, evidently we can test for isinstance(types.StringTypes) return type(x) is type('') or type(x) is type(u'') # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # M A T H E M A T I C A L B U I L T - I N s # # Some mathematical built-ins: the heaviest one gets the amount of list # members in a DAML list. # # Thanks to deltab, bijan, and oierw for helping me to name the # properties, and to TimBL for CWM and the built-in templates in the # first place. # # Light Built-in classes - these are all reverse functions # add, take, multiply, divide class BI_absoluteValue(LightBuiltIn, Function): def evaluateObject(self, x): t = abs(Decimal(x)) if t is not None: return tidy(t) class BI_rounded(LightBuiltIn, Function): def evaluateObject(self, x): t = round(float(x)) if t is not None: return tidy(t) class BI_sum(LightBuiltIn, Function): def evaluateObject(self, subj_py): t = 0 for x in subj_py: if not isString(x): return None t += Decimal(x) return tidy(t) class BI_sumOf(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): t = 0 for x in obj_py: t += Decimal(x) return tidy(t) class BI_difference(LightBuiltIn, Function): def evaluateObject(self, subj_py): t = None if len(subj_py) == 2: t = Decimal(subj_py[0]) - Decimal(subj_py[1]) return tidy(t) class BI_differenceOf(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): t = None if len(obj_py) == 2: t = Decimal(obj_py[0]) - Decimal(obj_py[1]) return tidy(t) class BI_product(LightBuiltIn, Function): def evaluateObject(self, subj_py): t = 1 for x in subj_py: t *= Decimal(x) return tidy(t) class BI_factors(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): t = 1 for x in obj_py: t *= Decimal(x) return tidy(t) class BI_quotient(LightBuiltIn, Function): def evaluateObject(self, subj_py): t = None if len(subj_py) == 2: t = float(subj_py[0]) / float(subj_py[1]) return tidy(t) class BI_integerQuotient(LightBuiltIn, Function): def evaluateObject(self, subj_py): t = None if len(subj_py) == 2: t = long(subj_py[0]) / long(subj_py[1]) return tidy(t) class BI_quotientOf(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): t = None if len(obj_py) == 2: t = float(obj_py[0]) / float(obj_py[1]) return tidy(t) # remainderOf and negationOf class BI_remainder(LightBuiltIn, Function): def evaluateObject(self, subj_py): t = None if len(subj_py) == 2: t = float(subj_py[0]) % float(subj_py[1]) return tidy(t) class BI_remainderOf(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): t = None if len(obj_py) == 2: t = float(obj_py[0]) % float(obj_py[1]) return tidy(t) class BI_negation(LightBuiltIn, Function, ReverseFunction): def evalaluateObject(self, subject): t = -Decimal(subject) if t is not None: return tidy(t) def evalaluateSubject(self, object): t = -Decimal(object) if t is not None: return tidy(t) # Power class BI_exponentiation(LightBuiltIn, Function): def evaluateObject(self, subj_py): t = None if len(subj_py) == 2: t = float(subj_py[0]) ** float(subj_py[1]) return tidy(t) class BI_exponentiationOf(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): t = None if len(obj_py) == 2: t = float(obj_py[0]) ** float(obj_py[1]) return tidy(t) # Math greater than and less than etc., modified from cwm_string.py # These are truth testing things - Binary logical operators class BI_greaterThan(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (float(subj.string) > float(obj.string)) class BI_notGreaterThan(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (float(subj.string) <= float(obj.string)) class BI_lessThan(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (float(subj.string) < float(obj.string)) class BI_notLessThan(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (float(subj.string) >= float(obj.string)) class BI_equalTo(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (float(subj.string) == float(obj.string)) class BI_notEqualTo(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (float(subj.string) != float(obj.string)) # memberCount - this is a proper forward function class BI_memberCount(LightBuiltIn, Function): def evaluateObject(self, subj_py): t = len(subj_py) return tidy(t) # Register the string built-ins with the store def register(store): str = store.symbol(MATHS_NS_URI[:-1]) str.internFrag('sum', BI_sum) str.internFrag('difference', BI_difference) str.internFrag('product', BI_product) str.internFrag('quotient', BI_quotient) str.internFrag('integerQuotient', BI_integerQuotient) str.internFrag('remainder', BI_remainder) str.internFrag('exponentiation', BI_exponentiation) str.internFrag('sumOf', BI_sumOf) str.internFrag('differenceOf', BI_differenceOf) str.internFrag('factors', BI_factors) str.internFrag('quotientOf', BI_quotientOf) str.internFrag('remainderOf', BI_remainderOf) str.internFrag('exponentiationOf', BI_exponentiationOf) str.internFrag('negation', BI_negation) str.internFrag('absoluteValue', BI_absoluteValue) str.internFrag('rounded', BI_rounded) str.internFrag('greaterThan', BI_greaterThan) str.internFrag('notGreaterThan', BI_notGreaterThan) str.internFrag('lessThan', BI_lessThan) str.internFrag('notLessThan', BI_notLessThan) str.internFrag('equalTo', BI_equalTo) str.internFrag('notEqualTo', BI_notEqualTo) str.internFrag('memberCount', BI_memberCount) if __name__=="__main__": print string.strip(__doc__) cwm-1.2.1/swap/triple_maker.py0000644015216600007660000002051410174265754015434 0ustar syosisyosi"""Triple Maker $Id: triple_maker.py,v 1.10 2005/01/21 20:54:04 syosi Exp $ Explanation of the API the functions are addNode(),addNode(), addNode() endStatement() to add a triple never call addNode() yourself addSymbol() and addLiteral() are there for those if a Node is a compound structure (like a formula) then call beginFormula(), add all of the structure to the substructure, then all endFormula() and that will call addNode() for you. For your convinience, if you call IsOf() before adding the predicate, it will reverse the subject and object in the final triple Also for your convience, you CAN call addNode() with None as the node, and it will just leave that as the previous node in that position. Note that calling addNode() with None as the first triple in a formula or bNode is an error, and will be flagged when you try to endStatement() """ import diag # problems importing the tracking flag, and chatty_flag must be explicit it seems diag.tracking from diag import progress, verbosity from term import BuiltIn, LightBuiltIn, \ HeavyBuiltIn, Function, ReverseFunction, \ Literal, Symbol, Fragment, FragmentNil, Term,\ CompoundTerm, List, EmptyList, NonEmptyList, AnonymousNode import RDFSink N3_forSome_URI = RDFSink.forSomeSym N3_forAll_URI = RDFSink.forAllSym NOTHING = -1 SUBJECT = 0 PREDICATE = 1 OBJECT = 2 FORMULA = 0 LIST = 1 ANONYMOUS = 2 NO = 0 STALE = 1 FRESH = 2 def swap(List, a, b): q = List[a] List[a] = List[b] List[b] = q class TripleMaker: """This is the example of the new interface. It will convert from the abstract interface into formulas, lists and triples """ def __init__(self, formula=None, store=None): if formula is None: formula = store.newFormula if store is None: store = formula.store self.formulas = [formula] self.store = store self.forSome = formula.newSymbol(N3_forSome_URI) self.forAll = formula.newSymbol(N3_forAll_URI) def start(self): self._parts = [NOTHING] self._triples = [[None, None, None]] self.lists = [] self._modes = [FORMULA] self.bNodes = [] self.addedBNodes = [{}] self._predIsOfs = [NO] self._pathModes = [False] self.store.startDoc() def end(self): assert len(self.formulas) == 1 assert len(self.lists) == 0 self.store.endDoc(self.formulas[0]) return self.formulas[0] def addNode(self, node): if self._modes[-1] == ANONYMOUS and node is not None and self._parts[-1] == NOTHING: raise ValueError('You put a dot in a bNode') if self._modes[-1] == FORMULA or self._modes[-1] == ANONYMOUS: self._parts[-1] = self._parts[-1] + 1 if self._parts[-1] > 3: raise ValueError('Try ending the statement') if node is not None: #print node, '+', self._triples, '++', self._parts self._triples[-1][self._parts[-1]] = node if self._parts[-1] == PREDICATE and self._predIsOfs[-1] == STALE: self._predIsOfs[-1] = NO if self._modes[-1] == ANONYMOUS and self._pathModes[-1] == True: self.endStatement() self.endAnonymous() elif self._modes[-1] == LIST: self.lists[-1].append(node) def IsOf(self): self._predIsOfs[-1] = FRESH def checkIsOf(self): return self._predIsOfs[-1] def forewardPath(self): if self._modes[-1] == LIST: a = self.lists[-1].pop() else: a = self._triples[-1][self._parts[-1]] self._parts[-1] = self._parts[-1] - 1 self.beginAnonymous() self.addNode(a) self._predIsOfs[-1] = FRESH self._pathModes[-1] = True def backwardPath(self): if self._modes[-1] == LIST: a = self.lists[-1].pop() else: a = self._triples[-1][self._parts[-1]] self._parts[-1] = self._parts[-1] - 1 self.beginAnonymous() self.addNode(a) self._pathModes[-1] = True def endStatement(self): if self._parts[-1] == SUBJECT: pass else: if self._parts[-1] != OBJECT: raise ValueError('try adding more to the statement' + `self._triples`) formula = self.formulas[-1] if self._pathModes[-1]: swap(self._triples[-1], PREDICATE, OBJECT) if self._predIsOfs[-1]: swap(self._triples[-1], SUBJECT, OBJECT) self._predIsOfs[-1] = STALE subj, pred, obj = self._triples[-1] if subj == '@this': if pred == self.forSome: formula.declareExistential(obj) elif pred == self.forAll: formula.declareUniversal(obj) else: raise ValueError("This is useless!") else: #print 'I got here!!!!!!!!!!!!!!!!!!!!!!!!!!!' formula.add(subj, pred, obj) if self._predIsOfs[-1]: swap(self._triples[-1], SUBJECT, OBJECT) self._parts[-1] = NOTHING if self._modes[-1] == ANONYMOUS and self._pathModes[-1]: self._parts[-1] = SUBJECT def addLiteral(self, lit, dt=None, lang=None): if dt: if dt[:2] == '_:': if dt not in self.addedBNodes[-1]: a = self.formulas[-1].newBlankNode() self.addedBNodes[-1][dt] = a dt = a else: dt = self.addedBNodes[-1][dt] else: dt = self.store.newSymbol(dt) a = self.store.intern(lit, dt, lang) self.addNode(a) def addSymbol(self, sym): a = self.store.newSymbol(sym) self.addNode(a) def beginFormula(self): a = self.store.newFormula() self.formulas.append(a) self.addedBNodes.append({}) self._modes.append(FORMULA) self._triples.append([None, None, None]) self._parts.append(NOTHING) self._predIsOfs.append(NO) self._pathModes.append(False) def endFormula(self): if self._parts[-1] != NOTHING: self.endStatement() a = self.formulas.pop().close() self.addedBNodes.pop() self._modes.pop() self._triples.pop() self._parts.pop() self.addNode(a) self._predIsOfs.pop() self._pathModes.pop() def beginList(self): a = [] self.lists.append(a) self._modes.append(LIST) self._parts.append(NOTHING) def endList(self): a = self.store.newList(self.lists.pop()) self._modes.pop() self._parts.pop() self.addNode(a) def addAnonymous(self, Id): """If an anonymous shows up more than once, this is the function to call """ if Id not in self.addedBNodes[-1]: a = self.formulas[-1].newBlankNode() self.addedBNodes[-1][Id] = a else: a = self.addedBNodes[-1][Id] self.addNode(a) def beginAnonymous(self): a = self.formulas[-1].newBlankNode() self.bNodes.append(a) self._modes.append(ANONYMOUS) self._triples.append([a, None, None]) self._parts.append(SUBJECT) self._predIsOfs.append(NO) self._pathModes.append(False) def endAnonymous(self): if self._parts[-1] != NOTHING: self.endStatement() a = self.bNodes.pop() self._modes.pop() self._triples.pop() self._parts.pop() self._predIsOfs.pop() self._pathModes.pop() self.addNode(a) def declareExistential(self, sym): formula = self.formulas[-1] a = formula.newSymbol(sym) formula.declareExistential(a) def declareUniversal(self, sym): formula = self.formulas[-1] a = formula.newSymbol(sym) formula.declareUniversal(a) def addQuestionMarkedSymbol(self, sym): formula = self.formulas[-2] a = formula.newSymbol(sym) formula.declareUniversal(a) self.addNode(a) def bind(self, prefix, uri): if prefix == "": self.store.setDefaultNamespace(uri) else: self.store.bind(prefix, uri) cwm-1.2.1/swap/rdflib_user.py0000644015216600007660000000657310640065527015261 0ustar syosisyosi#! /usr/bin/python """ The only way I can find of using rdflib's parser, and our store. It seems the RDFlib people agree --- just use the store's own types, With a usual dispatch to convert them. $ID $ """ try: from rdflib.syntax.parser import ParserDispatcher except ImportError: from rdflib.syntax.parsers.RDFXMLParser import RDFXMLParser class ParserDispatcher(object): def __init__(self, sink): self.sink = sink self.realParser = RDFXMLParser() def __call__(self, source, format): self.realParser.parse(source, self.sink) from rdflib.StringInputSource import StringInputSource from rdflib.URIRef import URIRef from rdflib.BNode import BNode from rdflib.Literal import Literal from RDFSink import FORMULA, ANONYMOUS, SYMBOL import diag from diag import progress class rdflib_handoff: """There is a better way of doing this""" def __init__(self, store, openFormula, thisDoc, flags="", why=None): self.parser = ParserDispatcher(self) self.store = store self.format = 'xml' self.formula = openFormula self.asIfFrom = thisDoc self.ns_prefix_map = {} self.prefix_ns_map = {} self.anonymousNodes = {} self._reason = why # Why the parser w self._reason2 = None # Why these triples if diag.tracking: self._reason2 = BecauseOfData(sink.newSymbol(thisDoc), because=self._reason) def prefix_mapping(self, prefix, uri, override=False): self.prefix_ns_map[prefix] = uri self.ns_prefix_map[uri] = prefix # print 'why was I told about: ', prefix, uri # raise RuntimeError(prefix, prefix.__class__, uri, uri.__class__) bind = prefix_mapping def feed(self, buffer): self.parser(StringInputSource(buffer), self.format) def add(self, (subject, predicate, object)): # print subject, ", a ", type(subject) # print '---- has the property of ', predicate, ', of type ', type(predicate) # print '---- with the value of ', object, ', of type ', type(object), '.' self.store.makeStatement((self.formula, self.convertRDFlibTypes(predicate), self.convertRDFlibTypes(subject), self.convertRDFlibTypes(object)), self._reason2) return self def close(self): for prefix, uri in self.prefix_ns_map.items(): if prefix == None: prefix = "" if ':' not in uri: uri = self.asIfFrom + uri # print '=+++++++++++++=', uri, "is a ", prefix self.store.bind(prefix,uri) return self.formula def convertRDFlibTypes(self, s): lang = None dt = None if isinstance(s, Literal): what = s if s.language != '': lang = s.language if s.datatype != '' and s.datatype != None: dt = self.store.newSymbol(s.datatype) elif isinstance(s,BNode): try: what = self.anonymousNodes[s] except KeyError: self.anonymousNodes[s] = self.store.newBlankNode(self.formula,uri=s) what = self.anonymousNodes[s] elif ':' in s: what = (SYMBOL, s) else: #if s[0] == '#': what = (SYMBOL, self.asIfFrom + s) # else: # what = s return self.store.intern(what,dt=dt, lang=lang) cwm-1.2.1/swap/sparql2cwm.py0000644015216600007660000016412610655653250015055 0ustar syosisyosi#!/usr/bin/env python """sparql2cwm This is meant to be used with a sparql.n3 based SPARQL parser, to add the query to cwm $Id: sparql2cwm.py,v 1.24 2007/08/06 16:13:56 syosi Exp $ """ from set_importer import Set import uripath from term import Term, CompoundTerm from formula import Formula import diag from why import BecauseOfData from cwm_sparql import SPARQL_NS knownFunctions = {} def value(self, newVal=None): if newVal is not None: self[0] = newVal return self[0] verbose = value.__get__([0]) reason2 = value.__get__([0]) def abbr(prodURI): return prodURI.split('#').pop() class typedThing(unicode): def __new__(cls, val, retType=None, ArgTypes=[], trueOnError=False): ret = unicode.__new__(cls, val) ret.retType = retType ret.argTypes = ArgTypes ret.trueOnError = trueOnError return ret def __call__(self): return unicode(self) + '__' + unicode(self.retType) + '__' + {False:'', True:'lenient__'}[self.trueOnError] + '_'.join(self.argTypes) def getType(ex): if isinstance(ex, typedThing): return ex.retType return None def getTrueOnError(ex): if isinstance(ex, typedThing): return ex.trueOnError return False ORED_AND = typedThing('And', 'boolean', trueOnError=True) AND = typedThing('And', 'boolean') OR = typedThing('Or', 'boolean') ORED_NOT = typedThing('Not', 'Boolean', trueOnError=True) NOT = typedThing('Not', 'boolean') class andExtra(tuple): def __new__(cls, val, extra): ret = tuple.__new__(cls, val) ret.extra = extra return ret def __repr__(self): return repr(tuple(self)) + '+' + repr(self.extra) def getExtra(ex): if isinstance(ex, andExtra): return ex.extra return [] class multimap(dict): """ A class to handle where each element maps to a set of elements It would perhaps be simpler to have used dict.setdefault(), but this has the advantage of merging instead of nesting sets """ class innerSet(Set): pass def __init__(self, olddict={}, **values): self.update(olddict) self.update(values) def __setitem__(self, key, value): if isinstance(value, tuple): raise RuntimeError(key, value) if not key in self: dict.__setitem__(self, key, self.innerSet()) if isinstance(value, self.innerSet): self[key].update(value) elif value: self[key].add(value) def update(self, other={}, **values): if values: self.update(values) for key, val in other.iteritems(): self[key] = val def translate(self, fromkey, tokey): if fromkey not in self: return m = self[fromkey] del self[fromkey] self[tokey] = m def __add__(self, other): k = self.__class__() k.update(self) k.update(other) return k def _fromTuples(cls, iterator): m = cls() for key, val in iterator: m[key] = val return m fromTuples = classmethod(_fromTuples) def makeTriple(subj, pred, obj, safeVersion=False): if safeVersion: store = pred[1].store typeErrorIsTrue = store.newSymbol(SPARQL_NS + '#typeErrorIsTrue') return ('Triple', (('Literal', store.intern(1)), ('predicateList', [(('symbol', typeErrorIsTrue), ('objectList', [('formula', TripleHolder((subj[1], pred[1], obj[1])))]))]))) return ('Triple', (subj, ('predicateList', [(pred, ('objectList', [obj]))]))) def makeSafeVal(val, (subj, pred, obj), safeVersion=False): if safeVersion: store = pred[1].store typeErrorReturner = store.newSymbol(SPARQL_NS + '#typeErrorReturner') replacement = ('Literal', store.intern(1)) if subj==val: subj=replacement return makeTriple(val, ('formula', TripleHolder((subj[1], pred[1], obj[1]))), ('symbol', typeErrorReturner)) if obj==val: obj=replacement return makeTriple(('formula', TripleHolder((subj[1], pred[1], obj[1]))), ('symbol', typeErrorReturner), val) return makeTriple(subj, pred, obj) def makeTripleObjList(subj, pred, obj): return ('Triple', (subj, ('predicateList', [(pred, ('objectList', obj))]))) def normalize(expr): """ The mapping from SPARQL syntax to n3 is decidedly nontrivial at this point, we have done the first step, building an AST that is (relatively) independant of all of the oddities that you get from the grammar Normalize does a couple of top down transforms on the tree. The first is a type determiner; it determines what needs to be coerced to a boolean. The second does boolean logic and pushes ``not''s all the way in. After normalize, the last bottom up step to generate the n3 can be done. """ if verbose(): print expr step1 = Coerce()(expr) return NotNot()(step1) class Coerce(object): def __init__(self): self.k = 0 def __call__(self, expr, coerce=True): try: if verbose(): print ' ' * self.k, expr, coerce self.k = self.k + 1 if expr[0] in ('Var', 'Literal', 'Number', 'String', 'symbol'): ww = self.atom(expr, coerce) elif expr[0] in ('subtract', 'add', 'multiply', 'divide', 'lang', 'datatype'): ww = self.on_math(expr, coerce) elif expr[0] in ('less', 'equal', 'notEqual', 'greater', 'notLess', 'notGreater'): ww = self.on_pred(expr, coerce) else: ww = getattr(self, 'on_' + expr[0])(expr, coerce) self.k = self.k - 1 if verbose(): print ' ' * self.k, '/', ww return ww except AttributeError: raise RuntimeError("COERCE why don't you define a %s function, to call on %s?" % ('on_' + expr[0], `expr`)) def on_function(self, p, coerce): if coerce: return ('BoolVal', self(p, False)) return [p[0], p[1]] + [self(q, False) for q in p[2:]] def on_Or(self, p, coerce): if len(p) == 2: return self(p[1], coerce) return [p[0]] + [self(q, True) for q in p[1:]] def on_And(self, p, coerce): if len(p) == 2: return self(p[1], coerce) return [p[0]] + [self(q, True) for q in p[1:]] def on_BoolVal(self, p, coerce): if coerce: return [p[0], self(p[1], False)] return self(p[1], False) def atom(self, p, coerce): if coerce: return ('BoolVal', p) return p def on_math(self, p, coerce): retVal = [p[0]] + [self(q, False) for q in p[1:]] if coerce: return ('BoolVal', retVal) return retVal def on_Boolean(self, p, coerce): if coerce: return ('BoolVal', p) return p def on_Bound(self, p, coerce): return p def on_Regex(self, p, coerce): return [p[0]] + [self(q, False) for q in p[1:]] def on_pred(self, p, coerce): return [p[0]] + [self(q, False) for q in p[1:]] def on_Not(self, p, coerce): return [p[0], self(p[1], True)] def on_isURI(self, p, coerce): return [p[0], self(p[1], False)] def on_isLiteral(self, p, coerce): return [p[0], self(p[1], False)] def on_isBlank(self, p, coerce): return [p[0], self(p[1], False)] class NotNot(object): """ This class is used to figure out the inverses of all SPARQL boolean tests, and invert all functions """ inverse_operators = {'less' : 'notLess', 'greater' : 'notGreater', 'notLess' : 'less', 'notGreater' : 'greater', 'equal' : 'notEqual', 'notEqual': 'equal', 'isURI' : 'isNotURI', 'isNotURI' : 'isURI', 'isLiteral' : 'isNotLiteral', 'isNotLiteral' : 'isLiteral', 'isBlank' : 'isNotBlank', 'isNotBlank' : 'isBlank', ## 'Not', 'BoolVal', ## 'BoolVal', 'Not', 'Bound': 'notBound' } def __init__(self): self.k = 0 def __call__(self, expr, inv=False, Ored=False): try: if verbose(): print ' ' * self.k, expr, inv self.k = self.k + 1 if not isinstance(expr, (list, tuple)): return expr if expr[0] in self.inverse_operators: ww = self.expr(expr, inv, Ored) elif expr[0] in ('Var', 'Literal', 'Number', 'subtract', 'add', 'datatype', 'multiply', 'divide', 'String', 'symbol', 'function', 'lang'): ww = self.atom(expr, inv, Ored) else: ww = getattr(self, 'on_' + expr[0])(expr, inv, Ored) self.k = self.k - 1 if verbose(): print ' ' * self.k, '/', ww return ww except AttributeError: raise RuntimeError("NOTNOT why don't you define a %s function, to call on %s?" % ('on_' + expr[0], `expr`)) def expr(self, p, inv, ored): if inv: return [typedThing(self.inverse_operators[p[0]], 'boolean', trueOnError=ored)] + [self(q, False, ored) for q in p[1:]] return [typedThing(p[0], trueOnError=ored)] + [self(q, False, ored) for q in p[1:]] def atom(self, p, inv, ored): if ored: p = [typedThing(p[0], getType(p[0]), trueOnError=True)] + [self(q, False, True) for q in p[1:]] if inv and ored: return (ORED_NOT, p) if inv: return (NOT, p) ## if ored: ## return ('typesafe', p) return p def on_Not(self, p, inv, ored): if inv: return self(p[1], False, ored) return self(p[1], True, ored) def on_Regex(self, p, inv, ored): if inv: return [typedThing('notMatches', trueOnError=ored)] + [self(q, False, ored) for q in p[1:]] return [typedThing(p[0], trueOnError=ored)] + [self(q, False, ored) for q in p[1:]] def on_notMatches(self, p, inv): if inv: return [typedThing('Regex', trueOnError=ored)] + [self(q, False, ored) for q in p[1:]] return [typedThing(p[0], trueOnError=ored)] + [self(q, False, ored) for q in p[1:]] def on_Or(self, p, inv, ored): if inv: return [ORED_AND] + [self(q, True, True) for q in p[1:]] return [p[0]] + [self(q, False, False) for q in p[1:]] def on_And(self, p, inv, ored): if inv: return [OR] + [self(q, True, ored) for q in p[1:]] return [p[0]] + [self(q, False, ored) for q in p[1:]] def on_BoolVal(self, p, inv, ored): if inv and ored: return [ORED_NOT, self(p[1], False)] if inv: return [NOT, self(p[1], False)] return [p[0], self(p[1], False)] def on_Boolean_Gen(true, false): def on_Boolean(self, p, inv, ored): if (inv and p[1] != false) or (not inv) and p[1] == false: return (p[0], false) return (p[0], true) return on_Boolean class AST(object): def __init__(self, ast, sink=None): self.ast = ast if sink: self.sink = sink else: self.sink = self def prod(self, thing): return thing[0] def abbr(self, prodURI): return prodURI.split('#').pop() def run(self): self.productions = [] stack = [[self.ast, 0]] while stack: if not isinstance(stack[-1][0][1], (tuple, list)): a = self.onToken(stack[-1][0][0], stack[-1][0][1]) if a: return a stack.pop() elif stack[-1][1] >= len(stack[-1][0]): k = self.onFinish() stack.pop() else: k = stack[-1][1] stack[-1][1] = k + 1 if k == 0: self.onStart(stack[-1][0][0]) else: stack.append([stack[-1][0][k], 0]) return k def onStart(self, prod): if verbose(): if callable(prod): print (' ' * len(self.productions)) + prod() else: print (' ' * len(self.productions)) + `prod` #if callable(prod): # prod = prod() self.productions.append([prod]) def onFinish(self): k = self.productions.pop() prodName = self.abbr(k[0]) prod = self.sink.prod(k) if self.productions: self.productions[-1].append(prod) if verbose(): print (' ' * len(self.productions)) + '/' + prodName + ': ' + `prod` return prod def onToken(self, prod, tok): k = self.sink.prod((prod, tok)) try: self.productions[-1].append(k) except IndexError: return k if verbose(): print (' ' * len(self.productions)) + `(prod, tok)` class productionHandler(object): def prod(self, production): if hasattr(self, 'on_' + abbr(production[0])): try: return getattr(self, 'on_' + abbr(production[0]))(production) except: print production raise if True: # len(production) > 1: raise RuntimeError("why don't you define a %s function, to call on %s?" % ('on_' + abbr(production[0]), `production`)) return production class TripleHolder(tuple): def __new__(cls, *args, **keywords): self = tuple.__new__(cls, *args, **keywords) if len(self) != 3: raise TypeError return self class FilterExpr(productionHandler): def __init__(self, store, parent): self.store = store self.parent = parent self.bnode = parent.new_bnode self.string = store.newSymbol('http://www.w3.org/2000/10/swap/string') self.anything = self.parent.sparql self.math = self.parent.math self.log = self.parent.store.newSymbol('http://www.w3.org/2000/10/swap/log') def on_function(self, p): args = [] extra = [] keepGoing = getTrueOnError(p[0]) rawArgs = p[2:] for rawArg in rawArgs: if not isinstance(rawArg, tuple): return ['Error'] extra.extend(getExtra(rawArg)) args.append(tuple(rawArg)) if p[1] not in knownFunctions: raise NotImplementedError('''I don't support the ``%s'' function''' % p[1]) try: node, triples = knownFunctions[p[1]](self, keepGoing, *args) return andExtra(node, triples + extra) except TypeError: # raise return ['Error'] def typeConvert(self, keepGoing, uri, val): retVal = self.bnode() return (retVal, [makeSafeVal(retVal, (('List', [val[1], self.store.newSymbol(uri)]), ('symbol', self.anything['dtLit']), retVal), safeVersion=keepGoing)]) def on_BoolVal(self, p): extra = getExtra(p[1]) val = tuple(p[1]) return [makeTriple(val, ('symbol', self.anything['truthValue']), ('symbol', self.parent.true), safeVersion=getTrueOnError(p[0]))] + extra def on_Not(self, p): extra = getExtra(p[1]) val = tuple(p[1]) if val == ('Error',): return ['Error'] return [makeTriple(val, ('symbol', self.anything['truthValue']), ('symbol', self.parent.false), safeVersion=getTrueOnError(p[0]))] + extra def on_And(self, p): vals = [] succeedAnyway = getTrueOnError(p[0]) things = p[1:] for thing in things: if thing == ['Error']: if succeedAnyway: continue return ['Error'] vals.extend(thing) return vals def on_Or(self, p): p = p[1:] returns = [] for val in p: if val != ['Error']: returns.extend(self.parent.on_GroupGraphPattern([None, None, val, None], True)) return [('union', returns)] def on_Regex(self, p): if str(p[3][1]): raise NotImplementedError('I don\'t know how to deal with flags. The flag is: %r' % p[3][1]) extra = getExtra(p[1]) + getExtra(p[2]) string = tuple(p[1]) regex = tuple(p[2]) return [makeTriple(string, ('symbol', self.string['matches']), regex, safeVersion=getTrueOnError(p[0]))] + extra def compare(self, p, op): if not isinstance(p[1], tuple) or not isinstance(p[2], tuple): return ['Error'] extra = getExtra(p[1]) + getExtra(p[2]) op1 = tuple(p[1]) op2 = tuple(p[2]) return [makeTriple(op1, ('symbol', op), op2, safeVersion=getTrueOnError(p[0]))] + extra def on_less(self, p): return self.compare(p, self.anything['lessThan']) def on_notLess(self, p): return self.compare(p, self.anything['notLessThan']) def on_equal(self, p): return self.compare(p, self.anything['equals']) def on_notEqual(self, p): return self.compare(p, self.anything['notEquals']) def on_greater(self, p): return self.compare(p, self.anything['greaterThan']) def on_notGreater(self, p): return self.compare(p, self.anything['notGreaterThan']) def arithmetic(self, p, op): if not isinstance(p[1], tuple) or not isinstance(p[2], tuple): return ['Error'] extra = getExtra(p[1]) + getExtra(p[2]) op1 = tuple(p[1]) op2 = tuple(p[2]) retVal = self.bnode() triple = makeSafeVal(retVal, (('List', [op1[1], op2[1]]), ('symbol', op), retVal), safeVersion=getTrueOnError(p[0])) return andExtra(retVal, [triple] + extra) def on_subtract(self, p): return self.arithmetic(p, self.math['difference']) def on_add(self, p): return self.arithmetic(p, self.math['sum']) def on_multiply(self, p): return self.arithmetic(p, self.math['product']) def on_divide(self, p): return self.arithmetic(p, self.math['quotient']) def on_Var(self, p): return p def on_symbol(self, p): return p def on_Literal(self, p): return p def on_Boolean(self, p): return p def on_Number(self, p): return p def on_String(self, p): return p def on_funcName(self, p): return p[1] def on_notBound(self, var): var = ('Literal', self.store.newLiteral(var[1][1].uriref())) return [makeTriple(self.bnode(), ('symbol', self.parent.sparql['notBound']), var)] def on_Bound(self, var): var = ('Literal', self.store.newLiteral(var[1][1].uriref())) return [makeTriple(self.bnode(), ('symbol', self.parent.sparql['bound']), var)] def on_isURI(self, p): return [makeTriple(p[1], ('symbol', self.log['rawType']), ('symbol', self.parent.store.Other), safeVersion=getTrueOnError(p[0]))] def on_isNotURI(self, p): k = self.bnode() return [makeTriple(p[1], ('symbol', self.log['rawType']), k, safeVersion=getTrueOnError(p[0])), makeTriple(k, ('symbol', self.log['notEqualTo']), ('symbol', self.parent.store.Other))] def on_lang(self, p): if not isinstance(p[1], tuple): return ['Error'] extra = getExtra(p[1]) op1 = tuple(p[1]) retVal = self.bnode() meaningLess = self.bnode() triple = makeSafeVal(retVal, (('List', [meaningLess[1], retVal[1]]), ('symbol', self.anything['langLit']), p[1]), safeVersion=getTrueOnError(p[0])) return andExtra(retVal, [triple] + extra) def on_datatype(self, p): if not isinstance(p[1], tuple): return ['Error'] extra = getExtra(p[1]) op1 = tuple(p[1]) retVal = self.bnode() meaningLess = self.bnode() triple = makeSafeVal(retVal, (('List', [meaningLess[1], retVal[1]]), ('symbol', self.anything['dtLit']), p[1]), safeVersion=getTrueOnError(p[0])) return andExtra(retVal, [triple] + extra) class FromSparql(productionHandler): def __init__(self, store, formula=None, ve=0, why=None): verbose(ve) self.store = store if formula is None: self.formula = store.newFormula() else: self.formula = formula self.prefixes = {} self.vars = {} self.base = 'http://yosi.us/sparql#' self.sparql = store.newSymbol(SPARQL_NS) self.xsd = store.newSymbol('http://www.w3.org/2001/XMLSchema') self.math = store.newSymbol('http://www.w3.org/2000/10/swap/math') self.numTypes = Set([self.xsd[k] for k in ['unsignedShort', 'short', 'nonPositiveInteger', 'decimal', 'unsignedInt', 'long', 'nonNegativeInteger', 'int', 'unsignedByte', 'positiveInteger', 'integer', 'byte', 'negativeInteger', 'unsignedLong']]) self.true = store.newLiteral('true', dt=self.xsd['boolean']) self.false = store.newLiteral('false', dt=self.xsd['boolean']) self.anonymous_counter = 0 self.uribase = uripath.base() self.dataSets = None NotNot.on_Boolean = on_Boolean_Gen(self.true, self.false) self._reason = why # Why the parser w _reason2 = None # Why these triples if diag.tracking: _reason2 = BecauseOfData(store.newSymbol(self.base), because=self._reason) reason2(_reason2) self.anNodes = {} def anonymize(self, formula, uri = None): if uri is not None: if isinstance(uri, TripleHolder): f = formula.newFormula() f.add(*[self.anonymize(formula, k) for k in uri]) return f.close() if isinstance(uri, list): return formula.newList([self.anonymize(formula, k) for k in uri]) if isinstance(uri, Formula): return uri.close() if isinstance(uri, Term): return uri try: if uri in self.anNodes: return self.anNodes[uri] except: print uri print 'uri = ', uri raise self.anNodes[uri] = formula.newBlankNode(why=reason2()) return self.anNodes[uri] return formula.newBlankNode(why=reason2()) def new_bnode(self): self.anonymous_counter += 1 return ('anonymous', '_:%s' % str(self.anonymous_counter)) def absolutize(self, uri): return uripath.join(self.uribase, uri) def on_Query(self, p): return self.formula def on_BaseDecl(self, p): self.uribase = p[2][1][1:-1] def makePatterns(self, f, node, patterns): sparql = self.sparql knowledge_base_f = f.newFormula() if not self.dataSets: knowledge_base = f.newBlankNode() f.add(self.uribase, sparql['data'], knowledge_base, why=reason2()) else: knowledge_base = knowledge_base_f.newBlankNode(why=reason2()) sources = self.store.nil #raise RuntimeError(self.dataSets) for uri in self.dataSets: stuff = knowledge_base_f.newBlankNode(why=reason2()) uri2 = self.anonymize(knowledge_base_f,uri[1]) knowledge_base_f.add(uri2, self.store.semantics, stuff, why=reason2()) sources = sources.prepend(stuff) knowledge_base_f.add(sources, self.store.newSymbol('http://www.w3.org/2000/10/swap/log#conjunction'), knowledge_base) for pattern in patterns: tail = f.newFormula() tail.loadFormulaWithSubstitution(pattern[1], why=reason2()) tail.loadFormulaWithSubstitution(knowledge_base_f, why=reason2()) includedStuff = pattern[4] notIncludedStuff = pattern[5] for nodeName, graphIntersection in includedStuff.iteritems(): if not graphIntersection: continue graph = f.newFormula() for subGraph in graphIntersection: graph.loadFormulaWithSubstitution(subGraph, why=reason2()) graph = graph.close() if nodeName is not None: nameNode = self.anonymize(tail, nodeName[1]) semantics = tail.newBlankNode(why=reason2()) tail.add(nameNode, self.store.semantics, semantics, why=reason2()) else: semantics = knowledge_base tail.add(semantics, self.store.includes, graph, why=reason2()) includedVars = Set(self.vars.values()) excludedVars = includedVars.difference(tail.occurringIn(includedVars)) for nodeName, graphIntersection in notIncludedStuff.iteritems(): if not graphIntersection: continue ## graph = f.newFormula() for subGraph in graphIntersection: ## graph.loadFormulaWithSubstitution(subGraph) ## graph = graph.close() if nodeName is not None: nameNode = self.anonymize(tail, nodeName[1]) semantics = tail.newBlankNode(why=reason2()) tail.add(nameNode, self.store.semantics, semantics, why=reason2()) else: semantics = knowledge_base excludedMap = {} bNodedSubGraph = subGraph.newFormula() for v in excludedVars: excludedMap[v] = bNodedSubGraph.newBlankNode() bNodedSubGraph.loadFormulaWithSubstitution(subGraph, excludedMap) tail.add(semantics, self.store.smartNotIncludes, bNodedSubGraph.close(), why=reason2()) f.add(node, sparql['where'], tail.close(), why=reason2()) ## for parent in pattern[2]: ## f.add(pattern[1], sparql['andNot'], parent) def on_SelectQuery(self, p): sparql = self.sparql store = self.store f = self.formula ## for v in self.vars: ## f.declareUniversal(v) q = f.newBlankNode() f.add(q, store.type, sparql['SelectQuery'], why=reason2()) variable_results = store.newFormula() for v in p[3][1]: # variable_results.add(v, store.type, sparql['Binding']) variable_results.add(v, sparql['bound'], abbr(v.uriref()), why=reason2()) f.add(q, sparql['select'], variable_results.close(), why=reason2()) if p[2]: f.add(q, store.type, sparql['Distinct']) self.makePatterns(f, q, p[5]) f3 = RulesMaker(self.sparql).implications(q, f, variable_results) for triple in f3.statementsMatching(pred=sparql['implies']): f4 = f3.newFormula() f4.add(triple.object(), store.type, sparql['Result'], why=reason2()) f.add(triple.subject(), store.implies, f4.close(), why=reason2()) #TODO: I'm missing sorting and datasets if p[6] and p[6] != (None, None, None): raise NotImplementedError('Cwm does not support output modifiers yet') sort, limit, offset = p[6] if sort: l = self.store.newList(sort) f.add(q, sparql['sort'], l) if limit: f.add(q, sparql['limit'], limit) if offset: f.add(q, sparql['offset'], offset) # raise RuntimeError(`p[6]`) return None def on_ConstructQuery(self, p): sparql = self.sparql store = self.store f = self.formula ## for v in self.vars: ## f.declareUniversal(v) q = f.newBlankNode() f.add(q, store.type, sparql['ConstructQuery']) f.add(q, sparql['construct'], p[2]) knowledge_base = f.newFormula() self.makePatterns(f, q, p[4]) f3 = RulesMaker(self.sparql).implications(q, f, p[2]) for triple in f3.statementsMatching(pred=sparql['implies']): f.add(triple.subject(), store.implies, triple.object()) return None def on_AskQuery(self, p): sparql = self.sparql store = self.store f = self.formula ## for v in self.vars: ## f.declareUniversal(v) q = f.newBlankNode() f.add(q, store.type, sparql['AskQuery']) only_result = store.newFormula() only_result.add(q, store.type, sparql['Success']) only_result = only_result.close() self.makePatterns(f, q, p[3]) f3 = RulesMaker(self.sparql).implications(q, f, only_result) for triple in f3.statementsMatching(pred=sparql['implies']): f.add(triple.subject(), store.implies, only_result) return None def on_WhereClause(self, p): stuff2 = p[2] stuff = [] # raise RuntimeError(`p`) for k in stuff2: append = True positiveTriples = None freeVariables = None included = k[5]+k[3]+{None: k[1]} notIncluded = k[6] ## print '+++++++++++++' ## print 'included=', included ## print 'notIncluded=', notIncluded for pred, obj in k[4]: if positiveTriples is None: positiveTriples = self.store.newFormula() for formSet in included.values(): for form in formSet: positiveTriples.loadFormulaWithSubstitution(form) positiveTriples = positiveTriples.close() freeVariables = Set([x.uriref() for x in positiveTriples.freeVariables()]) if pred is self.sparql['bound']: variable = unicode(obj) if variable not in freeVariables: append = False elif pred is self.sparql['notBound']: ##@@@ This is broken!! variable = unicode(obj) if variable in freeVariables: append = False if append: stuff.append((k[0], k[2], k[3], k[4], included, notIncluded)) ## ## Formula.doesNodeAppear = realNodeAppear # raise RuntimeError(stuff) return stuff def on_SolutionModifier(self, p): if len(p) == 1: return None return tuple(p[1:]) def on__QOrderClause_E_Opt(self, p): if len(p) == 1: return None return p[1] def on__QLimitClause_E_Opt(self, p): if len(p) == 1: return None return p[1] def on__QOffsetClause_E_Opt(self, p): if len(p) == 1: return None return p[1] def on__QBaseDecl_E_Opt(self, p): return None def on_PrefixDecl(self, p): self.prefixes[p[2][1][:-1]] = self.absolutize(p[3][1][1:-1]) self.store.bind(p[2][1][:-1],self.absolutize(p[3][1][1:-1])) return None def on__QDISTINCT_E_Opt(self, p): if len(p) == 1: return None return None raise NotImplementedError(`p`) def on_Var(self, p): uri = self.base + p[1][1][1:] if uri not in self.vars: self.vars[uri] = self.formula.newUniversal(uri) ## self.vars.add(var) return ('Var', self.vars[uri]) def on__QVar_E_Plus(self, p): if len(p) == 1: return [] return p[2] + [p[1]] def on__O_QVar_E_Plus_Or__QTIMES_E__C(self, p): if len(p) == 3: varList = [x[1] for x in p[2] + [p[1]]] else: class ___(object): def __iter__(s): return iter(self.vars.values()) varList = ___() return ('SelectVars', varList) def on__QDatasetClause_E_Star(self, p): return None def on_VarOrTerm(self, p): return p[1] def on_QName(self, p): qn = p[1][1].split(':') if len(qn) != 2: raise RuntimeError return ('QuotedIRIref', '<' + self.prefixes[qn[0]] + qn[1] + '>') def on_IRIref(self, p): return ('symbol', self.store.newSymbol(self.absolutize(p[1][1][1:-1]))) def on_VarOrBlankNodeOrIRIref(self, p): return p[1] def on_String(self, p): return ('str', unEscape(p[1][1])) def on_Verb(self, p): if abbr(p[1][0]) == 'IT_a': return ('symbol', self.store.type) return p[1] def on__Q_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C_E_Opt(self, p): if len(p) == 1: return (None, None) return p[1] def on_RDFLiteral(self, p): return ('Literal', self.store.newLiteral(p[1][1], dt=p[2][0], lang=p[2][1])) def on_NumericLiteral(self, p): if abbr(p[1][0]) == 'INTEGER': return ('Literal', self.store.newLiteral(`int(p[1][1])`, dt=self.xsd['integer'], lang=None)) if abbr(p[1][0]) == 'FLOATING_POINT': return ('Literal', self.store.newLiteral(`float(p[1][1])`, dt=self.xsd['double'], lang=None)) raise RuntimeError(`p`) def on_RDFTerm(self, p): return p[1] def on_GraphTerm(self, p): return p[1] def on_Object(self, p): if p[1][0] != 'andExtra': return ('andExtra', p[1], []) return p[1] def on__Q_O_QCOMMA_E____QObjectList_E__C_E_Opt(self, p): if len(p) == 1: return ('andExtra', [], []) return p[1] def on_ObjectList(self, p): extras = p[2][2] + p[1][2] objects = p[2][1] + [p[1][1]] return ('andExtra', ('objectList', [k for k in objects]), extras) def on__Q_O_QSEMI_E____QPropertyList_E__C_E_Opt(self, p): if len(p) == 1: return ('andExtra', ('predicateList', []), []) return p[1] def on_PropertyListNotEmpty(self, p): extra = p[2][2] + p[3][2] pred = (p[1], p[2][1]) preds = p[3][1][1] + [pred] return ('andExtra', ('predicateList', [k for k in preds]), extra) def on_Triples1(self, p): if abbr(p[1][0]) == 'GT_LBRACKET': return p[2] if abbr(p[1][0]) == 'GT_LPAREN': return p[2] extra = p[2][2] return [('Triple', (p[1], p[2][1]))] + extra def on_Triples2(self, p): if len(p) == 4: predList = ('predicateList', p[1][1][1] + p[3][1][1]) extra = p[1][2] + p[3][2] else: predList = p[2][1] extra = p[2][2] return [('Triple', (self.new_bnode(), predList))] + extra def on_Triples3(self, p): store = self.store if len(p) == 3: return [('Triple', (('symbol', store.nil), p[2][1]))] + p[2][2] extra = p[1][2] + p[2][2] + p[4][2] nodes = [p[1][1]] + p[2][1] pred = p[4][1] realPred = pred[1] if realPred == []: realPred.append((('symbol', self.sparql['lamePred']), ('objectList', [('symbol', self.sparql['LameObject'])]))) List = ('List', [k[1] for k in nodes]) return [('Triple', (List, pred))] + extra def on_GraphPatternListTail(self, p): if len(p) == 1: return [] return p[1] def on__O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C(self, p): return p[2] + p[1] def on__Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt(self, p): if len(p) == 1: return [] return p[1] def on_GraphPatternList(self, p): if len(p) == 1: return [] if len(p) == 2: return p[1] return p[1] + p[2] def on__O_QDot_E____QGraphPatternList_E__C(self, p): return p[2] def on__Q_O_QDot_E____QGraphPatternList_E__C_E_Opt(self, p): if len(p) == 1: return [] return p[1] def on_GroupGraphPattern(self, p, fromFilter = False): store = self.store triples = p[2] options = [] alternates = [] parents = multimap() bounds = [] subGraphs = [] f = self.store.newFormula() for triple in triples: if triple == 'Error': return [] try: if triple[0] == 'union': alternates.append([k[1:] for k in triple[1]]) continue if triple[0] == 'SubGraph': subGraphs.append(triple[1:]) continue rest1 = triple[1] subject = rest1[0] predicateList = rest1[1][1] for rest2 in predicateList: predicate = rest2[0] objectList = rest2[1][1] for object in objectList: try: subj = self.anonymize(f, subject[1]) pred = self.anonymize(f, predicate[1]) if pred is self.sparql['OPTIONAL']: options.append(object) else: obj = self.anonymize(f, object[1]) if pred is self.sparql['bound'] or pred is self.sparql['notBound']: bounds.append((pred, obj)) #print alternates, object[1], isinstance(object[1], Term), self.anonymize(f, object[1]) ## elif isinstance(obj, Formula): ## options.extend(object[2]) ## f.add(subj, pred, obj) else: f.add(subj, pred, obj, why=reason2()) except: print '================' print 'subject= ', subject print 'predicate= ', predicate print 'pred= ', pred is self.sparql['OPTIONAL'], id(pred), id(self.sparql['OPTIONAL']) print 'object= ', object raise except: print 'triples=',triples print 'triple=',triple raise f = f.close() if fromFilter: retVal = [('formula', self.store.newFormula(), f, parents, bounds, multimap(), multimap())] else: retVal = [('formula', f, self.store.newFormula(), parents, bounds, multimap(), multimap())] for nodeName, subGraphList in subGraphs: oldRetVal = retVal retVal = [] for _, f, filters, p, b, i, nI in oldRetVal: node = self.anonymize(f, nodeName[1]) for __, subF, filters2, p2, b2, i2, nI2 in subGraphList: #@@@@@ What do I do with b2? newF = f.newFormula() newF.loadFormulaWithSubstitution(f) newFilters = f.newFormula() newFilters.loadFormulaWithSubstitution(filters) newFilters.loadFormulaWithSubstitution(filters2) i2.translate(None, nodeName) nI2.translate(None, nodeName) p2.translate(None, nodeName) retVal.append(('formula', newF.close(), newFilters.close(), p+p2, b+b2, i + i2 + {nodeName: subF}, nI + nI2)) for alternate in alternates: oldRetVal = retVal retVal = [] for formula1, filters1, parents1, bounds1, include1, notInclude1 in alternate: for ss, formula2, filters2, parents2, bounds2, include2, notInclude2 in oldRetVal: f = self.store.newFormula() if formula1: f.loadFormulaWithSubstitution(formula1) f.loadFormulaWithSubstitution(formula2) newFilters = f.newFormula() newFilters.loadFormulaWithSubstitution(filters1) newFilters.loadFormulaWithSubstitution(filters2) retVal.append(('formula', f.close(), newFilters.close(), parents1 + parents2, bounds1 + bounds2, include1 + include2, notInclude1 + notInclude2)) for alternate in options: oldRetVal = retVal retVal = [] for ss, formula1, filters1, parents1, bounds1, i1, nI1 in alternate: for ss, formula2, filters2, parents2, bounds2, i2, nI2 in oldRetVal: f1 = self.store.newFormula() f1.loadFormulaWithSubstitution(formula1, why=reason2()) f1.loadFormulaWithSubstitution(formula2, why=reason2()) f1 = f1.close() f2 = self.store.newFormula() f2.loadFormulaWithSubstitution(formula2, why=reason2()) f3 = formula1.newFormula() f3.loadFormulaWithSubstitution(formula1, why=reason2()) for document in i1: semantics = f3.newBlankNode() f3.add(document[1], self.store.semantics, semantics) totalFormula = f3.newFormula() for f4 in i1[document]: totalFormula.loadFormulaWithSubstitution(f4, why=reason2()) f3.add(semantics, self.store.includes, totalFormula.close()) f3.loadFormulaWithSubstitution(filters1, why=reason2()) f3 = f3.close() newFilters1 = f1.newFormula() newFilters1.loadFormulaWithSubstitution(filters1, why=reason2()) newFilters1.loadFormulaWithSubstitution(filters2, why=reason2()) newFilters2 = f2.newFormula() newFilters2.loadFormulaWithSubstitution(filters2, why=reason2()) retVal.append(('formula', formula2.close(), newFilters1.close(), parents1 + parents2+{None:formula1}, bounds1 + bounds2, i1+i2, nI1+nI2)) retVal.append(('formula', formula2.close(), newFilters2.close(), parents2, bounds1 + bounds2, i2, nI2+{None:f3})) return retVal ## ## if len(p) == 2: ## p.append([]) ## if p[1][0][0] == 'Triple': ## p[2] = p[1][1:] + p[2] ## p[1] = p[1][0] ## if p[1][0] == 'Triple': ## ## ## elif p[1][0][0] == 'formula': ## if p[2]: ## raise RuntimeError(`p`) ## graphs = p[1] ## return graphs ## else: ## raise RuntimeError(`p`) def on__QPropertyListNotEmpty_E_Opt(self, p): if len(p) == 1: return ('andExtra', ('predicateList', []), []) return p[1] def on_PropertyList(self, p): return p[1] def on_NamelessBlank(self, p): return self.new_bnode() def on_BlankNode(self, p): return ('anonymous', p[1][1]) def on_BlankNodePropertyList(self, p): extra = p[2][2] preds = p[2][1] anon = self.new_bnode() extra.append(('Triple', (anon, preds))) return ('andExtra', anon, extra) def on_TriplesNode(self, p): return p[1] def on__O_QSEMI_E____QPropertyList_E__C(self, p): return p[2] def on_GraphNode(self, p): if p[1][0] != 'andExtra': return ('andExtra', p[1], []) return p[1] def on__QGraphNode_E_Plus(self, p): return self.on__QGraphNode_E_Star(p) def on__QGraphNode_E_Star(self, p): if len(p) == 1: return ('andExtra', [], []) nodes = [p[1][1]] + p[2][1] extra = p[1][2] + p[2][2] return ('andExtra', nodes, extra) def on_Collection(self, p): extra = p[2][2] nodes = p[2][1] List = ('List', [k[1] for k in nodes]) return ('andExtra', List, extra) def on_GraphPatternNotTriplesList(self, p): return p[1] + p[2] ### End Triples Stuff #GRAPH def on_GraphGraphPattern(self, p): return [('SubGraph', p[2], p[3])] ## semantics = self.new_bnode() ## return [makeTriple(p[2], ('symbol', self.store.semantics), semantics), ## ('SubGraph', semantics, p[3]) ### makeTripleObjList(semantics, ('symbol', self.store.includes), p[3]) ## ] #OPTIONAL def on_GraphPatternNotTriples(self, p): return p[1] def on_GraphPatternNotTriplesTail(self, p): if len(p) == 1: return [] return p[1] def on__O_QDot_E_Opt___QGraphPatternList_E__C(self, p): return p[2] def on_OptionalGraphPattern(self, p): return [makeTriple(self.new_bnode(), ('symbol', self.sparql['OPTIONAL']), p[2])] #UNION def on__O_QUNION_E____QGroupGraphPattern_E__C(self, p): return p[2] def on__Q_O_QUNION_E____QGroupGraphPattern_E__C_E_Star(self, p): if len(p) == 1: return [] return p[1] + p[2] def on_GroupOrUnionGraphPattern(self, p): return [('union', p[1] + p[2])] #FILTER def on_PrimaryExpression(self, p): return p[1] def on_UnaryExpression(self, p): if len(p) == 2: ## if getType(p[1][0]) != 'boolean': ## return (typedThing('BoolVal', 'boolean'), p[1]) return p[1] if abbr(p[1][0]) == 'GT_NOT': return (typedThing('Not', 'boolean'), p[2]) raise RuntimeError(`p`) def on__Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star(self, p): if len(p) == 1: return [] if not p[2]: return p[1] return (p[1][0], (p[2][0], p[1][1], p[2][1])) def on_MultiplicativeExpression(self, p): if p[2] == []: return p[1] return (p[2][0], p[1], p[2][1]) def on__Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star(self, p): if len(p) == 1: return [] if not p[2]: return p[1] return (p[1][0], (p[2][0], p[1][1], p[2][1])) def on_AdditiveExpression(self, p): if p[2] == []: return p[1] return (p[2][0], p[1], p[2][1]) def on_NumericExpression(self, p): return p[1] def on__Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt(self, p): if len(p) == 1: return None return p[1] def on_RelationalExpression(self, p): if p[2] is None: return p[1] ## if p[2][0] != 'less': ## raise RuntimeError(p[2], getType(p[2][1][0])) if p[2][0] == 'equal': t1, t2 = getType(p[1][0]), getType(p[2][1][0]) if t1 == 'boolean' or t2 == 'boolean': return (OR, (AND, p[1], p[2][1]), (AND, (NOT, p[1]), (NOT, p[2][1]))) if p[2][0] == 'notEqual': t1, t2 = getType(p[1]), getType(p[2][1]) if t1 == 'boolean' or t2 == 'boolean': return (OR, (AND, (NOT, p[1]), p[2][1]), (AND, p[1], (NOT, p[2][1]))) return (typedThing(p[2][0], 'boolean'), p[1], p[2][1]) def on_ValueLogical(self, p): return p[1] def on__Q_O_QAND_E____QValueLogical_E__C_E_Star(self, p): if len(p) == 1: return [] return [p[1]] + p[2] def on_ConditionalAndExpression(self, p): if p[2]: return [AND, p[1]] + p[2] return p[1] def on__Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star(self, p): if len(p) == 1: return [] return [p[1]] + p[2] def on_ConditionalOrExpression(self, p): if p[2]: return [OR, p[1]] + p[2] return p[1] def on_Expression(self, p): return p[1] def on_BrackettedExpression(self, p): return p[2] def on__O_QBrackettedExpression_E__Or__QCallExpression_E__C(self, p): """see normalize for an explanation of what we are doing""" return normalize(p[1]) def on_Constraint(self, p): val = AST(p[2], FilterExpr(self.store, self)).run() return [('union', self.on_GroupGraphPattern([None, None, val, None], True))] #useless def on__QPrefixDecl_E_Star(self, p): return None def on_Prolog(self, p): return None def on__QWHERE_E_Opt(self, p): return None def on__O_QSelectQuery_E__Or__QConstructQuery_E__Or__QDescribeQuery_E__Or__QAskQuery_E__C(self, p): return None def on__QDot_E_Opt(self, p): return None ### AutoGenerated def on_OffsetClause(self, p): return self.on_NumericLiteral(p[1:])[1] def on_DescribeQuery(self, p): raise RuntimeError(`p`) def on__QVarOrIRIref_E_Plus(self, p): raise RuntimeError(`p`) def on__O_QVarOrIRIref_E_Plus_Or__QTIMES_E__C(self, p): raise RuntimeError(`p`) def on__QWhereClause_E_Opt(self, p): raise RuntimeError(`p`) def on_DatasetClause(self, p): return None def on__O_QDefaultGraphClause_E__Or__QNamedGraphClause_E__C(self, p): return None def on_DefaultGraphClause(self, p): if not self.dataSets: self.dataSets = [] self.dataSets.append(p[1]) return None def on_NamedGraphClause(self, p): return None def on_SourceSelector(self, p): return p[1] def on_OrderClause(self, p): clauses = [p[3]] + p[4] return clauses raise RuntimeError(`p`) def on__QOrderCondition_E_Plus(self, p): if len(p) == 1: return [] return [p[1]] + p[2] raise RuntimeError(`p`) def on_OrderCondition(self, p): def listize(thing): if len(thing) == 2 and isinstance(thing[1], Term): return thing[1] if thing[0] == 'function': return self.store.newList([self.store.newSymbol(thing[1][1])] + [listize(x) for x in thing[2:]]) return self.store.newList([self.store.newLiteral(thing[0])] + [listize(x) for x in thing[1:]]) return listize(p[1]) raise RuntimeError(`p`) def on__O_QASC_E__Or__QDESC_E__C(self, p): return p[1][1] def on__O_QASC_E__Or__QDESC_E____QBrackettedExpression_E__C(self, p): return p[1:] def on__O_QFunctionCall_E__Or__QVar_E__Or__QBrackettedExpression_E__C(self, p): return p[1] def on_LimitClause(self, p): return self.on_NumericLiteral(p[1:])[1] def on_ConstructTemplate(self, p): return self.on_GroupGraphPattern(p)[0][1] def on__QTriples_E_Opt(self, p): if len(p) == 1: return [] return p[1] def on_Triples(self, p): return p[1] + p[2] def on__QTriples_E_Opt(self, p): if len(p) == 1: return [] return p[1] def on__O_QDot_E____QTriples_E_Opt_C(self, p): return p[2] def on__Q_O_QDot_E____QTriples_E_Opt_C_E_Opt(self, p): if len(p) == 1: return [] return p[1] def on__O_QCOMMA_E____QObjectList_E__C(self, p): #raise RuntimeError(`p`) return (p[2][0], p[2][1][1], p[2][2]) def on_VarOrIRIref(self, p): raise RuntimeError(`p`) def on__O_QOR_E____QConditionalAndExpression_E__C(self, p): return p[2] def on__O_QAND_E____QValueLogical_E__C(self, p): return (AND, p[2]) def on__O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C(self, p): op = p[1][1] opTable = { '>': 'greater', '<': 'less', '>=': 'notLess', '<=': 'notGreater', '=': 'equal', '!=': 'notEqual'} return (opTable[op], p[2]) def on__O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C(self, p): return ({'+': typedThing('add', 'number'), '-': typedThing('subtract', 'number')}[p[1][1]], p[2]) def on__O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C(self, p): return ({'*': typedThing('multiply', 'number'), '/': typedThing('divide', 'number')}[p[1][1]], p[2]) def on_CallExpression(self, p): return p[1] def on_BuiltinCallExpression(self, p): if len(p) == 2: return p[1] funcName = abbr(p[1][0]) if funcName == 'IT_BOUND': return (typedThing('Bound', 'boolean', ['variable']), p[3]) if funcName == 'IT_isURI': return (typedThing('isURI', 'boolean'), p[3]) if funcName == 'IT_STR': return (typedThing('String', 'literal', ['literal', 'symbol']), p[3]) if funcName == 'IT_LANG': return (typedThing('lang', 'literal', ['literal']), p[3]) if funcName == 'IT_DATATYPE': return (typedThing('datatype', 'symbol', ['literal']), p[3]) if funcName == 'IT_isBLANK': return (typedThing('isBlank', 'boolean'), p[3]) if funcName == 'IT_isLITERAL': return (typedThing('isLiteral', 'boolean'), p[3]) raise RuntimeError(`p`) def on_RegexExpression(self, p): return ('Regex', p[3], p[5], p[6]) def on__O_QCOMMA_E____QExpression_E__C(self, p): return p[2] def on__Q_O_QCOMMA_E____QExpression_E__C_E_Opt(self, p): if len(p) == 1: return ('Literal', self.store.newLiteral('')) return p[1] def on_FunctionCall(self, p): return ['function', ("funcName", p[1][1].uriref(),)] + p[2] def on_ArgList(self, p): return p[2] def on__Q_O_QCOMMA_E____QExpression_E__C_E_Star(self, p): if len(p) == 1: return [] return [p[1]] + p[2] def on__O_QExpression_E____QCOMMA_E____QExpression_E_Star_C(self, p): return [p[1]] + p[2] def on__Q_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C_E_Opt(self, p): if len(p) == 1: return [] return p[1] def on_RDFTermOrFunc(self, p): if p[1][0] == 'Literal': lit = p[1][1] if not lit.datatype: return (typedThing('String', 'string'), lit) if lit.datatype in self.numTypes: return (typedThing('Number', 'number'), lit) if lit.datatype == self.xsd['boolean']: return (typedThing('Boolean', 'boolean'), lit) return p[1] def on_IRIrefOrFunc(self, p): if p[2] == None: return p[1] return ['function', ("funcName", p[1][1].uriref(),)] + p[2] def on__QArgList_E_Opt(self, p): if len(p) == 1: return None return p[1] def on__O_QDTYPE_E____QIRIref_E__C(self, p): return (p[1][0], p[2][1]) def on__O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C(self, p): if abbr(p[1][0]) == 'LANGTAG': return (None, p[1][1][1:]) if abbr(p[1][0]) == 'GT_DTYPE': return (p[1][1], None) raise RuntimeError(`p`) def on_BooleanLiteral(self, p): return ('Literal', (p[1][1] == u'true' and self.true or self.false)) class RulesMaker(object): def __init__(self, ns): self.ns = ns def implications(self, query, formula, totalResult): retFormula = formula.newFormula() for where in formula.each(subj=query, pred=self.ns['where']): F = formula.newFormula() F.existentials().update(totalResult.existentials()) bound_vars = self.find_vars(formula.universals(), where) # print where, bound_vars unbound_vars = formula.universals() - bound_vars self.matching_subformula(F, unbound_vars, totalResult) retFormula.add(where, self.ns['implies'], F.close(), why=reason2()) return retFormula def find_vars(self, vars, f): # print 'find_vars on:', f, vars retVal = Set() for var in vars: if f.contains(subj=var) or f.contains(pred=var) or f.contains(obj=var): retVal.add(var) for statement in f.statementsMatching(pred=f.store.includes): retVal.update(self.find_vars(vars, statement.object())) # print 'find_vars found:', retVal, ' on ', f, vars return retVal def matching_subformula(self, retF, illegals, F): def clear(node): return node not in illegals and not (isinstance(node, CompoundTerm) and False in [clear(a) for a in node]) for triple in F: if (clear(triple.subject()) and clear(triple.predicate()) and clear(triple.object())): retF.add(*triple.spo(), **{'why':reason2()}) # else: # print triple, illegals def unEscape(string): if string[:1] == '"': delin = '"' if string[:3] == '"""': real_str = string[3:-3] triple = True else: real_str = string[1:-1] triple = False else: delin = "'" if string[:3] == "'''": real_str = string[3:-3] triple = True else: real_str = string[1:-1] triple = False ret = u'' n = 0 while n < len(real_str): ch = real_str[n] if ch == '\r': pass elif ch == '\\': a = real_str[n+1:n+2] if a == '': raise RuntimeError k = 'abfrtvn\\"\''.find(a) if k >= 0: ret += '\a\b\f\r\t\v\n\\"\''[k] n += 1 elif a == 'u': m = real_str[n+2:n+6] assert len(m) == 4 ret += unichr(int(m, 16)) n += 5 elif a == 'U': m = real_str[n+2:n+10] assert len(m) == 8 ret += unichr(int(m, 16)) n += 9 else: raise ValueError('Bad Escape') else: ret += ch n += 1 return ret def intConvert(self, keepGoing, val): return self.typeConvert(keepGoing, 'http://www.w3.org/2001/XMLSchema#integer', val) knownFunctions['http://www.w3.org/2001/XMLSchema#integer'] = intConvert def sparqlLookup(uri, server, property): pass cwm-1.2.1/swap/why.py0000755015216600007660000007202510717732004013562 0ustar syosisyosi#! /usr/bin/python """ $Id: why.py,v 1.53 2007/06/27 17:58:39 syosi Exp $ A class for storing the reason why something is known. The dontAsk constant reason is used as a reason for the explanations themselves- we could make it more complicated here for the recursively minded but i don't see the need at the moment. Assumes wwe are using the process-global store -- uses Namespace() @@@ """ flagHelp = """ n use iNdirect formulas when they get too large g always give the :gives clause, even when not needed """ import string #import re #import StringIO import sys import weakref from set_importer import Set, sorted # import notation3 # N3 parsers and generators, and RDF generator # import sax2rdf # RDF1.0 syntax parser to N3 RDF stream import urllib # for hasContent import uripath # DanC's tested and correct one import md5, binascii # for building md5 URIs from uripath import refTo from myStore import Namespace from term import Literal, CompoundTerm, AnonymousNode, List # from formula import Formula import diag from diag import verbosity, progress REIFY_NS = 'http://www.w3.org/2004/06/rei#' #from RDFSink import CONTEXT, PRED, SUBJ, OBJ, PARTS, ALL4 #from RDFSink import FORMULA, LITERAL, ANONYMOUS, SYMBOL from RDFSink import runNamespace rdf=Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") log=Namespace("http://www.w3.org/2000/10/swap/log#") reason=Namespace("http://www.w3.org/2000/10/swap/reason#") global dontAsk global proofsOf proofsOf = weakref.WeakKeyDictionary() # Track collectors for formulae # origin = {} # track (statement, formula) to reason # Reporting functions called from te rest of the system: def smushedFormula(F, G): """The formula F has been replaced by G Because this module tracks formula in stores, if ever the address of a formula is changed, that is (currently) when it is canonicalized, then the fact must be reported here. """ progress("why: Formula %s has been replaced by %s" %(F,G)) pF = proofsOf[F] pG = proofsOf[G] proofsOf[G] = pF + pG raise RuntimeError("@@@@ temp flag - we got to line 71 of why.py") del proofsOf[F] def newTopLevelFormula(f): if f not in proofsOf: proofsOf[f] = [ KBReasonTracker(f) ] def isTopLevel(f): return f in proofsOf def report(statement, why): """Report a new statement to the reason tracking software This module stores the reasons. The store should call this method to report new data. See the KBReasonTracker class Most formulas don't need collectors. Let's see if we can change that. """ if why is dontAsk: return f = statement.context() collectors = proofsOf.get(f, []) if collectors == []: return None if diag.chatty_flag>50: progress("Adding %s. New collector for %s" % (statement, why)) collector = KBReasonTracker(f) proofsOf[f] = [ collector ] elif len(collectors) != 1: raise RuntimeError("""More than one tracker for formula %s. Means formula must already have been closed, so shouldn't be added to.""" % f) else: collector = collectors[0] return collector.newStatement(statement, why) def explainFormula(f, flags=""): "Return the explanation formula for f" tr = proofsOf.get(f, None) if tr is None: raise ValueError( "No tracker. This may happen if the formula is validly empty. f=%s, proofsOf=%s" % (f, dict(proofsOf))) if not tr: raise ValueError(dict(proofsOf)) try: return tr[0].explanation(flags=flags) except: print f.debugString() raise # Internal utility def _giveTerm(x, ko): """Describe a term in a proof This reifies symbols and bnodes. Internal utility """ #" from formula import Formula if isinstance(x, Formula): b = ko.newBlankNode(why=dontAsk) ko.add(subj=x, pred=ko.store.sameAs, obj=b, why=dontAsk) return b elif isinstance(x, (Literal, CompoundTerm)): return x elif isinstance(x, AnonymousNode): b = ko.newBlankNode(why=dontAsk) ko.add(subj=b, pred=ko.newSymbol(REIFY_NS+"nodeId"), obj=x.uriref(), why=dontAsk) return b else: return x.reification(ko, why=dontAsk) def _subsetFormula(ss): """Return a subset formula containing the given statements The statements are all in the same context.""" #. s = ss.pop() # @@ better way to pick one? f=s.context() ss.add(s) g = f.newFormula() for s in ss: try: g.add(s.subject(), s.predicate(), s.object(), why=dontAsk) except: print s print s.__class__ print s.quad raise # progress("&&&&&&&&&&&&&&&&&&&&&&& ", g.n3String()) #@@@@@@@@@@ g._existentialVariables = g.occurringIn(f._existentialVariables) g._universalVariables = g.occurringIn(f._universalVariables) g = g.close() return g class Reason: """The Reason class holds a reason for having some information. Well, its subclasses actually do hold data. This class should not be used itself to make instances. Reasons may be given to any functions which put data into stores, is tracking or proof/explanation generation may be required""" def __init__(self): self.me = {} return def meIn(self, ko): "The representation of this object in the formula ko" assert self.me.get(ko, None) is None me = ko.newBlankNode(why= dontAsk) # @@ ko-specific, not reentrant self.me[ko] = me return me def explain(self, ko, flags): """Describe this reason to an RDF store Returns the value of this object as interned in the store. """ raise RuntimeError("What, no explain method for this class?") MAX_INLINE_SIZE = 10 def formulaStandIn(self, ko,f, flags): if 'n' not in flags: return f if len(f) <= MAX_INLINE_SIZE: return f try: m = self[(ko,f)] #progress('cache hit, we save $$!') return m except KeyError: from formula import Formula, StoredStatement if 'l' in flags: standIn = ko.newBlankNode(why= dontAsk) else: self[id(self)] += 1 standIn = ko.newSymbol(runNamespace()+'_efm' + str(self[id(self)])) self[(ko,f)] = standIn ko.add(subj=f, pred=ko.store.sameAs, obj=standIn, why=dontAsk) return standIn formulaStandIn = formulaStandIn.__get__({}) formulaStandIn.im_self[id(formulaStandIn.im_self)] = 0 class KBReasonTracker(Reason): """A reason tracker tracks the reasons for the statements in its formula. Beware that when a new formula is interned, the proofsOf dict must be informed that its identity has changed. The ForumulaReason is informed of each statement added to the knowlege base. A knowledge base (open formula) is made from the addition of forumlae, which result from, for example parsing a document or doing inference. Within such added formulae, there are variables, including bnodes, which have a cetain scope. It is impossible to consider the process as being one of simply adding statements, as the cross-reference of the vaiables within the add formuls mst be preserved. Variable renaming may occur as thr formula is added. When we track these operations for generating a proof, a proof reason such as an BecauseOfRule or BecauseOfData corresponds to an added formula. The KBReasonTracker tracks which statements in a formula came from which addion operations. """ def __init__(self, formula=None): Reason.__init__(self) self._string = str self.formula = formula if formula != None: proofsOf[formula] = [self] self.reasonForStatement = {} return def newStatement(self, s, why): if verbosity() > 80 and why is not dontAsk: progress("Believing %s because of %s"%(s, why)) import formula for x in s.quad[1:]: if isinstance(x, formula.Formula): if x.canonical is not x: raise RuntimeError(x) assert why is not self self.reasonForStatement[s]=why if isinstance(why, (Premise, BecauseOfRule, BecauseOfData)): why.statements.add(s) def explanation(self, ko=None, flags=""): """Produce a justification for this formula into the output formula Creates an output formula if necessary. returns it. (This is different from reason.explain(ko) which returns the reason)""" if ko == None: ko = self.formula.store.newFormula() ko.bind("n3", "http://www.w3.org/2004/06/rei#") ko.bind("log", "http://www.w3.org/2000/10/swap/log#") ko.bind("pr", "http://www.w3.org/2000/10/swap/reason#") ko.bind("run", runNamespace()) me=self.explain(ko, flags) ko.add(me, rdf.type, reason.Proof, why=dontAsk) return ko def explain(self, ko, flags): me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) g = self.formula e = g.existentials() if g.occurringIn(e) != e: raise RuntimeError(g.debugString()) qed = ko.newBlankNode(why= dontAsk) standIn = formulaStandIn(ko,self.formula, flags) ko.add(subj=me, pred=reason.gives, obj=standIn, why=dontAsk) statementsForReason = {} # reverse index: group by reason for s, rea in sorted(self.reasonForStatement.items()): x = statementsForReason.get(rea, None) if x is None: statementsForReason[rea] = [s] else: x.append(s) if diag.chatty_flag > 29: progress( "Collector %s (->%s), explaining %i reasons for total of %i statements:-" % (self, me, len(statementsForReason), len(self.reasonForStatement))) progress("reasonForStatement", self.reasonForStatement) progress("statementsForReason", statementsForReason) # @@ Should special case (no conjunction) if only one r if len(statementsForReason) != 1: ko.add(subj=me, pred=rdf.type, obj=reason.Conjunction, why=dontAsk) for r, ss in statementsForReason.items(): assert r is not self, ("Loop in reasons!", self, id(self), s) try: r1 = r.explain(ko, flags=flags) except: print ss raise if diag.chatty_flag > 29: progress( "\tExplaining reason %s (->%s) for %i statements" % (r, r1, len(ss))) for s in ss: progress("\t Statement %s" % (s)) if len(statementsForReason) == 1: ## No need for conjunction ko.substituteEqualsInPlace({r1: me}, why=dontAsk) else: ko.add(me, reason.component, r1, why=dontAsk) return me class BecauseMerge(KBReasonTracker): """Because this formula is a merging of others""" def __init__(self, f, set): raise RuntimeError(f, set) KBReasonTracker.__init__(self, f) self.fodder = Set() def newStatement(self, s, why): # Why isn't a reason here, it is the source if verbosity() > 80:progress("Merge: Believing %s because of merge"%(s)) self.fodder.add(why) self.reasonForStatement[s] = why def explain(self, ko, flags): me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) qed = ko.newBlankNode(why= dontAsk) ko.add(subj=me, pred=rdf.type, obj=reason.Conjunction, why=dontAsk) if 'g' in flags: standIn = formulaStandIn(ko,self.formula, flags=flags) ko.add(subj=me, pred=reason.gives, obj=standIn, why=dontAsk) for x in self.fodder: ko.add(subj=me, pred=reason.mergeOf, obj=x.explain(ko, flags), why=dontAsk) return me class BecauseSubexpression(Reason): """This was generated as part of a calculatio of a subexpression. It is is not necessarily believed""" def explain(self, ko, flags): """Describe this reason to an RDF store Returns the value of this reason as interned in the store. """ me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) ko.add(subj=me, pred=rdf.type, obj=reason.TextExplanation, why=dontAsk) ko.add(subj=me, pred=reason.text, obj=ko.newLiteral("(Subexpression)"), why=dontAsk) return me becauseSubexpression = BecauseSubexpression() class Because(Reason): """For the reason given on the string. This is a kinda end of the road reason. A nested reason can also be given. """ def __init__(self, str, because=None): Reason.__init__(self) self._string = str self._reason = because return def explain(self, ko, flags): """Describe this reason to an RDF store Returns the value of this reason as interned in the store. """ raise RuntimeError("An internal Object slipped out, but we caught it.") me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) ko.add(subj=me, pred=rdf.type, obj=reason.TextExplanation, why=dontAsk) ko.add(subj=me, pred=reason.text, obj=ko.newLiteral(self._string), why=dontAsk) if self._reason is not None: ko.add(subj=me, pred=reason.because, obj=self._reason.explain(ko, flags=flags), why=dontAsk) return me dontAsk = Because("Generating explanation") class Premise(Reason): """For the reason given on the string. This is a kinda end of the road reason. It contais the info which was literally supplied as a premise. A nested reason can also be given. Because a premise has to be taken for granted, the tracker has to tell a Premis what statements it has. """ def __init__(self, str, because=None): Reason.__init__(self) self._string = str self._reason = because self.statements = Set() return def explain(self, ko, flags): """Describe this reason to an RDF store Returns the value of this reason as interned in the store. """ me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) if diag.chatty_flag>49: progress("Premise reason=%s ko=%s"%(self,me)) ko.add(subj=me, pred=rdf.type, obj=reason.Premise, why=dontAsk) ko.add(subj=me, pred=reason.text, obj=ko.newLiteral(self._string), why=dontAsk) if not self.statements: pass ## raise RuntimeError("No given data for Premise %s" % self) else: prem = _subsetFormula(self.statements) standIn = formulaStandIn(ko,prem, flags=flags) ko.add(me, reason.gives, standIn, why=dontAsk) if diag.chatty_flag >59: progress("Premise (%s) is:\n%s" % ( self._string, prem.n3String())) return me class BecauseOfRule(Reason): def __init__(self, rule, bindings, knownExistentials, evidence, kb, because=None): #print rule #raise Error Reason.__init__(self) self._bindings = bindings self._rule = rule self._evidence = evidence # Set of statements etc to justify LHS self._kb = kb # The formula the rule was trusting at base self._reason = because self._existentials = knownExistentials self.statements = Set() return def explain(self, ko, flags): """Describe this reason to an RDF store Returns the value of this reason as interned in the store. """ me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) if diag.chatty_flag>49: progress("Inference=%s ko=%s"%(self,me)) ko.add(subj=me, pred=rdf.type, obj=reason.Inference, why=dontAsk) for var, (val, source) in self._bindings.items(): b = ko.newBlankNode(why= dontAsk) ko.add(subj=me, pred=reason.binding, obj=b, why= dontAsk) ko.add(subj=b, pred=reason.variable, obj=_giveTerm(var,ko),why= dontAsk) valObject = _giveTerm(val, ko) ko.add(subj=b, pred=reason.boundTo, obj=valObject, why= dontAsk) if val in self._existentials: ko.add(subj=valObject, pred=rdf.type, obj=reason.Existential, why=dontAsk) if diag.chatty_flag>49: progress("rule:") ru = explainStatement(self._rule,ko, flags=flags) ko.add(subj=me, pred=reason.rule, obj=ru, why=dontAsk) if diag.chatty_flag>49: progress("evidence:") ev = [] # For PML compatability we will store it as a collection realStatements = [] for s in self._evidence: if isinstance(s, BecauseBuiltIn): try: e = s.explain(ko, flags=flags) except: print s raise ev.append(e) else: f = s.context() if f is self._kb: # Normal case ## We need something a little more complicated realStatements.append(s) if s.predicate() is f.store.includes: for t in self.evidence: if t.context() is s.subject(): progress("Included statement used:" + `t`) try: ko.add(e, reason.includeEvidence, explainStatement(t, ko)) except: print s raise # else: # progress("Included statement found:" + `s`) ev.extend(explainStatements(realStatements, ko)) ko.add(subj=me, pred=reason.evidence, obj=ev, why= dontAsk) if "g" in flags: prem = _subsetFormula(self.statements) standIn = formulaStandIn(ko,prem, flags=flags) ko.add(me, reason.gives, standIn, why=dontAsk) if diag.chatty_flag >59: progress("Rule (%s) is:\n%s" % ( self._string, prem.n3String())) return me def getStatementReason(s): f = s.context() KBReasonTrackers = proofsOf.get(f, None) if KBReasonTrackers is None: raise RuntimeError( """Ooops, no reason collector for this formula?! No proof for formula: %s Needed for statement: %s Only have proofs for %s. Formula contents as follows: %s """ % ( f, s, dict(proofsOf), f.debugString())) tracker = KBReasonTrackers[0] return tracker.reasonForStatement.get(s, None) def subFormulaStandIn(self, ko,f, flags): if 'n' not in flags: return f from formula import Formula if isinstance(f, List): return ko.store.newList([subFormulaStandIn(ko,x, flags) for x in f]) if not isinstance(f, Formula) or len(f) <= MAX_INLINE_SIZE: return f try: m = self[(ko,f)] #progress('cache hit, we save $$!') return m except KeyError: if 'l' in flags: standIn = ko.newBlankNode(why= dontAsk) else: self[id(self)] += 1 standIn = ko.newSymbol(runNamespace()+'_fm' + str(self[id(self)])) self[(ko,f)] = standIn ko.add(subj=f, pred=reason.representedBy, obj=standIn, why=dontAsk) return standIn subFormulaStandIn = subFormulaStandIn.__get__({}) subFormulaStandIn.im_self[id(subFormulaStandIn.im_self)] = 0 def explainStatement(s, ko, ss=None, flags=""): si = describeStatement([s], ko, flags=flags) statementReason = getStatementReason(s) if statementReason == None: raise RuntimeError( """Ooops, no reason for this statement?! Collector: %s Formula: %s No reason for statement: %s Reasons for statements we do have: %s Formula contents as follows: %s """ % (tracker, f, s, tracker.reasonForStatement, f.debugString())) if diag.chatty_flag >49: progress("explaining statement: %s" % (s)) ri = statementReason.explain(ko, flags=flags) ko.add(subj=si, pred=reason.because, obj=ri, why=dontAsk) return si def explainStatements(s_l, ko, ss=None, flags=""): if not s_l: return [] reasonsForStatement = {} f = s_l[0].context() for s in s_l: statementReason = getStatementReason(s) if statementReason == None: raise RuntimeError( """Ooops, no reason for this statement?! Collector: %s Formula: %s No reason for statement: %s Reasons for statements we do have: %s Formula contents as follows: %s """ % (tracker, f, s, tracker.reasonForStatement, f.debugString())) reasonsForStatement.setdefault(statementReason, []).append(s) si_l = [] for r, statements in reasonsForStatement.items(): si = describeStatement(statements, ko, flags=flags) si_l.append(si) ri = r.explain(ko, flags=flags) ko.add(subj=si, pred=reason.because, obj=ri, why=dontAsk) return si_l def describeStatement(s_l, ko, flags): "Describe the statement into the output formula ko" from formula import StoredStatement f = s_l[0].context() s_l2 = [] for s in s_l: con, pred, subj, obj = s subj = subFormulaStandIn(ko, subj, flags) obj = subFormulaStandIn(ko, obj, flags) s = StoredStatement([con, pred, subj, obj]) s_l2.append(s) si = ko.newBlankNode(why=dontAsk) ko.add(si, rdf.type, reason.Extraction, why=dontAsk) standIn = formulaStandIn(ko, f.subSet(s_l2, why=dontAsk), flags=flags) ko.add(si, reason.gives, standIn, why=dontAsk) return si class BecauseOfData(Because): """Directly from data in the resource whose URI is the string. A nested reason can also be given, for why this resource was parsed. """ pass def __init__(self, source, because=None): Reason.__init__(self) self._source = source self._reason = because self.statements = Set() return def explain(self, ko, flags): """Describe this reason to an RDF store Returns the value of this reason as interned in the store. """ me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) if diag.chatty_flag>49: progress("Parsing reason=%s ko=%s"%(self,me)) ko.add(subj=me, pred=rdf.type, obj=reason.Parsing, why=dontAsk) ko.add(subj=me, pred=reason.source, obj=self._source, why=dontAsk) if self._reason: ko.add(subj=me, pred=reason.because, obj=self._reason.explain(ko, flags=flags), why=dontAsk) if "g" in flags: prem = _subsetFormula(self.statements) standIn = formulaStandIn(ko,prem, flags=flags) ko.add(me, reason.gives, standIn, why=dontAsk) if diag.chatty_flag >59: progress("Rule (%s) is:\n%s" % ( self._string, prem.n3String())) return me class BecauseOfCommandLine(Because): """Because of the command line given in the string""" def explain(self, ko, flags): """Describe this reason to an RDF store Returns the value of this reason as interned in the store. """ me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) if diag.chatty_flag>49: progress("CommandLine reason=%s ko=%s"%(self,me)) ko.add(subj=me, pred=rdf.type, obj=reason.CommandLine, why=dontAsk) ko.add(subj=me, pred=reason.args, obj=self._string, why=dontAsk) return me class BecauseOfExperience(Because): """Becase of the experience of this agent, as described in the string""" pass class BecauseBuiltIn(Reason): """Because the built-in function given concluded so. A nested reason for running the function must be given""" def __init__(self, context, subj, pred, obj): Reason.__init__(self) self._subject = subj self._predicate = pred self._object = obj self._context = context def explain(self, ko, flags): "This is just a plain fact - or was at the time." me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) if diag.chatty_flag>49: progress("Fact reason=%s ko=%s"%(self,me)) fact = ko.newFormula() fact.add(subj=subFormulaStandIn(ko, self._subject, flags=flags), pred=self._predicate, obj=subFormulaStandIn(ko, self._object, flags=flags), why=dontAsk) fact = fact.close() ko.add(me, rdf.type, reason.Fact, why=dontAsk) standIn = formulaStandIn(ko,fact, flags=flags) ko.add(me, reason.gives, standIn, why=dontAsk) ## if (1==0) and False and 'g' in flags: ## for x in self._subject, self._object: ## proofs = proofsOf.get(x, None) ## if proofs != None: ## ko.add(me, reason.proof, proofs[0].explain(ko, flags=flags), why=dontAsk) # if self._proof != None: # ko.add(me, reason.proof, self._proof.explain(ko), why=dontAsk) return me class BecauseIncludes(BecauseBuiltIn): """Because of the speific built-in log:includes""" pass class BecauseSupports(BecauseBuiltIn): """Because of the very special build-in log:supports""" def __init__(self, context, subj, conclusion, pred, obj, reason): BecauseBuiltIn.__init__(self, context, subj, pred, obj) self.reason = [] for statement in reason: if isinstance(statement, Reason): if isinstance(statement, BecauseBuiltIn): if statement._context is conclusion: self.reason.append(statement) progress(statement) progress("Is anybody home?") else: if statement.context() is conclusion: self.reason.append(statement) self.conclusion = conclusion assert isTopLevel(conclusion) def __repr__(self): return '%s(%s,%s,%s,%s,%s,%s)' % (self.__class__.__name__, self._context, self._subject, self.conclusion, self._predicate, self._object, self.reason ) def explain(self, ko, flags): "This is just a plain fact - or was at the time." me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) if diag.chatty_flag>49: progress("Fact reason=%s ko=%s"%(self,me)) fact = ko.newFormula() m = ko.newBlankNode(why= dontAsk) # raise RuntimeError(m) fact.add(subj=self._subject, pred=self._predicate, obj=self._object, why=dontAsk) fact = fact.close() ko.add(me, rdf.type, reason.Conclusion, why=dontAsk) standIn = formulaStandIn(ko,fact, flags=flags) ko.add(me, reason.gives, standIn, why=dontAsk) ko.add(subj=m, pred=rdf.type, obj=reason.Conjunction, why=dontAsk) ko.add(me, reason.because, m, why=dontAsk) statementsForReason = {} # reverse index: group by reason for s in self.reason: try: rea = getStatementReason(s) except: print s raise x = statementsForReason.get(rea, None) if x is None: statementsForReason[rea] = [s] else: x.append(s) for e in statementsForReason: r1 = e.explain(ko, flags=flags) ko.add(m, reason.component, r1, why=dontAsk) ## if 'g' in flags: ## for x in self._subject, self._object: ## proofs = proofsOf.get(x, None) ## if proofs != None: ## ko.add(me, reason.proof, proof[0].explain(ko, flags=flags), why=dontAsk) # if self._proof != None: # ko.add(me, reason.proof, self._proof.explain(ko), why=dontAsk) return me # ends cwm-1.2.1/swap/cwm_time.py0000644015216600007660000001427310640063301014545 0ustar syosisyosi# # Note - see also times for string-oriented versions # # TODO: # - extraction os fields should extend date time if necessary # # See http://www.python.org/doc/current/lib/module-time.html # """ The time built-ins concern dates and times expressed in a specific version of ISO date-time format. These functions allow the various parts of the date and time to be compared, and converted into interger second GMT era format for arithmetic. Be aware that ISo times carry timezone offset information: they cannot be converted to integer second times without a valid timezone offset, such as "Z". """ import string import re import notation3 # N3 parsers and generators, and RDF generator import isodate # Local, by mnot. implements from diag import progress, verbosity from term import LightBuiltIn, Function, ReverseFunction import time, calendar # Python standard distribution TIME_NS_URI = "http://www.w3.org/2000/10/swap/time#" __version__ = "0.3" DAY = 24 * 60 * 60 class BI_inSeconds(LightBuiltIn, Function, ReverseFunction): """For a time string, the number of seconds from the era start as an integer-representing string. """ def evaluateObject(self, subj_py): try: return float(isodate.parse(subj_py)) except ValueError, AssertionError: progress("Warning: Failed to parse time string '%s'" % subj_py) return None def evaluateSubject(self, obj_py): return isodate.fullString(int(obj_py)) class BI_equalTo(LightBuiltIn): def evaluate(self, subj_py, obj_py): try: return isodate.parse(subj_py) == isodate.parse(obj_py) except ValueError: return None class BI_year(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return int(subj_py[:4]) except: return None class BI_month(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return int(subj_py[5:7]) except: return None class BI_day(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return int(subj_py[8:10]) except: return None class BI_date(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return subj_py[:10] except: return None class BI_hour(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return int(subj_py[11:13]) except: return None class BI_minute(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return int(subj_py[14:16]) except: return None class BI_second(LightBuiltIn, Function): def evaluateObject(self, subj_py): try: return int(subj_py[17:19]) except: return None tzone = re.compile(r'.*([-+]\d{1,2}:\d{2,2})') class BI_timeZone(LightBuiltIn, Function): def evaluateObject(self, subj_py): m = tzone.match(subj_py) if m == None: return None return m.group(1) class BI_dayOfWeek(LightBuiltIn, Function): def evaluateObject(self, subj_py): weekdayZero = time.gmtime(0)[6] return (weekdayZero + int(isodate.parse(subj_py)/DAY)) % 7 # class BI_format(LightBuiltIn, Function): def evaluateObject(self, subj_py): """params are ISO time string, format string. Returns reformatted. Ignores TZ@@""" if verbosity() > 80: progress("strTime:format input:"+`subj_py`) str, format = subj_py try: return time.strftime(format, time.gmtime(isodate.parse(str))) except: return None # class BI_gmTime(LightBuiltIn, Function): def evaluateObject(self, subj_py): """Subject is (empty string for standard formatting or) format string. Returns formatted.""" if verbosity() > 80: progress("time:gmTime input:"+`subj_py`) format = subj_py if format =="" : format="%Y-%m-%dT%H:%M:%SZ" try: return time.strftime(format, time.gmtime(time.time())) except: return isodate.asString(time()) class BI_localTime(LightBuiltIn, Function): def evaluateObject(self, subj_py): """Subject is format string or empty string for std formatting. Returns reformatted. @@@@ Ignores TZ""" if verbosity() > 80: progress("time:localTime input:"+`subj_py`) format = subj_py if format =="" : return isodate.asString(time.time()) return time.strftime(format, time.localtime(time.time())) # original things from mNot's cwm_time.py: # # these ise Integer time in seconds from epoch. # class BI_formatSeconds(LightBuiltIn, Function): def evaluateObject(self, subj_py): """params are epoch-seconds time string, format string. Returns reformatted""" if verbosity() > 80: progress("strTime:format input:"+`subj_py`) str, format = subj_py try: return time.strftime(format, time.gmtime(int(str))) except: return None class BI_parseToSeconds(LightBuiltIn, Function): def evaluateObject(self, subj_py): if verbosity() > 80: progress("strTime:parse input:"+`subj_py`) str, format = subj_py try: return calendar.timegm(time.strptime(str, format)) except: return None # Register the string built-ins with the store def register(store): str = store.symbol(TIME_NS_URI[:-1]) str.internFrag("inSeconds", BI_inSeconds) str.internFrag("year", BI_year) str.internFrag("month", BI_month) str.internFrag("day", BI_day) str.internFrag("date", BI_date) str.internFrag("equalTo", BI_equalTo) str.internFrag("hour", BI_hour) str.internFrag("minute", BI_minute) str.internFrag("second", BI_second) str.internFrag("dayOfWeek", BI_dayOfWeek) str.internFrag("timeZone", BI_timeZone) str.internFrag("gmTime", BI_gmTime) str.internFrag("localTime", BI_localTime) str.internFrag("format", BI_format) # str.internFrag("parse", BI_parse) str.internFrag("formatSeconds", BI_formatSeconds) # Deprocate? str.internFrag("parseToSeconds", BI_parseToSeconds) # Deprocate? # ends cwm-1.2.1/swap/webAccess.py0000755015216600007660000003115610655653251014661 0ustar syosisyosi#!/usr/local/bin/python """Web Access This module implements some basic bits of the web architecture: dereferencing a URI to get a document, with content negotiation, and deciding on the basis of the Internet Content Type what to do with it. $Id: webAccess.py,v 1.34 2007/08/06 16:13:56 syosi Exp $ Web access functionality building on urllib2 """ import sys, os #import urllib import urllib2, urllib # Python standard from why import newTopLevelFormula import uripath # http://www.w3.org/2000/10/swap/uripath.py import diag from diag import progress import notation3 # Parser @@@ Registery of parsers vs content types woudl be better. from OrderedSequence import indentString HTTP_Content_Type = 'content-type' #@@ belongs elsewhere? print_all_file_names = diag.print_all_file_names # for listing test files class SecurityError(IOError): pass # A little code to represent a value that can be set # and read; a singleton. In essence, this is a little # prettier than a one element list def setting(self, val=None): if val is not None: self[0] = val return self[0] sandBoxed = setting.__get__([False]) def cacheHack(addr): """ If on a plane, hack remote w3.org access to local access """ real = "http://www.w3.org/" local = "/devel/WWW/" suffixes = [ "", ".rdf", ".n3" ] if addr.startswith(real): rest = local + addr[len(real):] for s in suffixes: fn = rest + s try: os.stat(fn) progress("Offline: Using local copy %s" % fn) return "file://" + fn except OSError: continue return addr def urlopenForRDF(addr, referer=None): """Access the web, with a preference for RDF """ return webget(addr, types=['text/rdf+n3', 'application/rdf+xml' # ,'application/x-turtle' # Why not ask for turtle? ], referer = referer) def webget(addr, referer=None, types=[]): """Open a URI for reading; return a file-like object with .headers cf http://www.w3.org/TR/2004/REC-webarch-20041215/#dereference-uri """ if diag.chatty_flag > 7: progress("Accessing: " + addr) if sandBoxed(): if addr[:5] == 'file:': raise SecurityError('local file access prohibited') # addr = cacheHack(addr) # work around python stdlib bugs with data: URIs # buggy in 2.4.2 with CStringIO if addr[:5] == 'data:': # return open_data(addr) return urllib.urlopen(addr) req = urllib2.Request(addr) if types: req.add_header('Accept', ','.join(types)) if referer: #consistently misspelt req.add_header('Referer', referer) stream = urllib2.urlopen(req) if print_all_file_names: diag.file_list.append(addr) return stream def load(store, uri=None, openFormula=None, asIfFrom=None, contentType=None, flags="", referer=None, why=None, topLevel=False): """Get and parse document. Guesses format if necessary. uri: if None, load from standard input. remember: if 1, store as metadata the relationship between this URI and this formula. Returns: top-level formula of the parsed document. Raises: IOError, SyntaxError, DocumentError This is an independent function, as it is fairly independent of the store. However, it is natural to call it as a method on the store. And a proliferation of APIs confuses. """ # if referer is None: # raise RuntimeError("We are trying to force things to include a referer header") try: baseURI = uripath.base() if uri != None: addr = uripath.join(baseURI, uri) # Make abs from relative if diag.chatty_flag > 40: progress("Taking input from " + addr) netStream = urlopenForRDF(addr, referer) if diag.chatty_flag > 60: progress(" Headers for %s: %s\n" %(addr, netStream.headers.items())) receivedContentType = netStream.headers.get(HTTP_Content_Type, None) else: if diag.chatty_flag > 40: progress("Taking input from standard input") addr = uripath.join(baseURI, "STDIN") # Make abs from relative netStream = sys.stdin receivedContentType = None # if diag.chatty_flag > 19: progress("HTTP Headers:" +`netStream.headers`) # @@How to get at all headers?? # @@ Get sensible net errors and produce dignostics guess = None if receivedContentType: if diag.chatty_flag > 9: progress("Recieved Content-type: " + `receivedContentType` + " for "+addr) if receivedContentType.find('xml') >= 0 or ( receivedContentType.find('rdf')>=0 and not (receivedContentType.find('n3')>=0) ): guess = "application/rdf+xml" elif receivedContentType.find('n3') >= 0: guess = "text/rdf+n3" if guess== None and contentType: if diag.chatty_flag > 9: progress("Given Content-type: " + `contentType` + " for "+addr) if contentType.find('xml') >= 0 or ( contentType.find('rdf') >= 0 and not (contentType.find('n3') >= 0 )): guess = "application/rdf+xml" elif contentType.find('n3') >= 0: guess = "text/rdf+n3" elif contentType.find('sparql') >= 0 or contentType.find('rq'): guess = "x-application/sparql" buffer = netStream.read() if guess == None: # can't be XML if it starts with these... if buffer[0:1] == "#" or buffer[0:7] == "@prefix": guess = 'text/rdf+n3' elif buffer[0:6] == 'PREFIX' or buffer[0:4] == 'BASE': guess = "x-application/sparql" elif buffer.find('xmlns="') >=0 or buffer.find('xmlns:') >=0: #" guess = 'application/rdf+xml' else: guess = 'text/rdf+n3' if diag.chatty_flag > 9: progress("Guessed ContentType:" + guess) except (IOError, OSError): raise DocumentAccessError(addr, sys.exc_info() ) if asIfFrom == None: asIfFrom = addr if openFormula != None: F = openFormula else: F = store.newFormula() if topLevel: newTopLevelFormula(F) import os if guess == "x-application/sparql": if diag.chatty_flag > 49: progress("Parsing as SPARQL") from sparql import sparql_parser import sparql2cwm convertor = sparql2cwm.FromSparql(store, F, why=why) import StringIO p = sparql_parser.N3Parser(StringIO.StringIO(buffer), sparql_parser.branches, convertor) F = p.parse(sparql_parser.start).close() elif guess == 'application/rdf+xml': if diag.chatty_flag > 49: progress("Parsing as RDF") # import sax2rdf, xml.sax._exceptions # p = sax2rdf.RDFXMLParser(store, F, thisDoc=asIfFrom, flags=flags) if flags == 'rdflib' or int(os.environ.get("CWM_RDFLIB", 0)): parser = 'rdflib' flags = '' else: parser = os.environ.get("CWM_RDF_PARSER", "sax2rdf") import rdfxml p = rdfxml.rdfxmlparser(store, F, thisDoc=asIfFrom, flags=flags, parser=parser, why=why) p.feed(buffer) F = p.close() else: assert guess == 'text/rdf+n3' if diag.chatty_flag > 49: progress("Parsing as N3") if os.environ.get("CWM_N3_PARSER", 0) == 'n3p': import n3p_tm import triple_maker tm = triple_maker.TripleMaker(formula=F, store=store) p = n3p_tm.n3p_tm(asIfFrom, tm) else: p = notation3.SinkParser(store, F, thisDoc=asIfFrom,flags=flags, why=why) try: p.startDoc() p.feed(buffer) p.endDoc() except: progress("Failed to parse %s" % uri or buffer) raise if not openFormula: F = F.close() return F def loadMany(store, uris, openFormula=None): """Get, parse and merge serveral documents, given a list of URIs. Guesses format if necessary. Returns top-level formula which is the parse result. Raises IOError, SyntaxError """ assert type(uris) is type([]) if openFormula == None: F = store.newFormula() else: F = openFormula f = F.uriref() for u in uris: F.reopen() # should not be necessary store.load(u, openFormula=F, remember=0) return F.close() # @@@@@@@@@@@@@ Ripped from python2.4/lib/urllib which is buggy # File "/devel/WWW/2000/10/swap/webAccess.py", line 104, in load # netStream = urlopenForRDF(addr, referer) # File "/devel/WWW/2000/10/swap/webAccess.py", line 72, in urlopenForRDF # return urllib.urlopen(addr) # File "/sw/lib/python2.4/urllib.py", line 77, in urlopen # return opener.open(url) # File "/sw/lib/python2.4/urllib.py", line 185, in open # return getattr(self, name)(url) # File "/sw/lib/python2.4/urllib.py", line 559, in open_data # f.fileno = None # needed for addinfourl #AttributeError: 'cStringIO.StringI' object has no attribute 'fileno' # $ cwm 'data:text/rdf+n3;charset=utf-8;base64,QHByZWZpeCBsb2c6IDxodHRwOi8vd3d3LnczLm9yZy8yMDAwLzEwL3N3YXAvbG9nIz4gLgp7fSA9PiB7OmEgOmIgOmN9IC4g' # Found the bug in python bug traker. # http://sourceforge.net/tracker/index.php?func=detail&aid=1365984&group_id=5470&atid=105470 # "Fixed in revision 41548 and 41549 (2.4). by birkenfeld" # It is in effect fixed in python 2.4.4 def open_data(url, data=None): """Use "data" URL.""" # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value import mimetools, time from StringIO import StringIO try: [type, data] = url.split(',', 1) except ValueError: raise IOError, ('data error', 'bad data URL') if not type: type = 'text/plain;charset=US-ASCII' semi = type.rfind(';') if semi >= 0 and '=' not in type[semi:]: encoding = type[semi+1:] type = type[:semi] else: encoding = '' msg = [] msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': import base64 data = base64.decodestring(data) else: data = unquote(data) msg.append('Content-length: %d' % len(data)) msg.append('') msg.append(data) msg = '\n'.join(msg) f = StringIO(msg) headers = mimetools.Message(f, 0) f.fileno = None # needed for addinfourl return urllib.addinfourl(f, headers, url) #@@@@@@@@@@ Junk - just to keep track iof the interface to sandros stuff and rdflib def getParser(format, inputURI, workingContext, flags): """Return something which can load from a URI in the given format, while writing to the given store. """ r = BecauseOfCommandLine(sys.argv[0]) # @@ add user, host, pid, date time? Privacy! if format == "rdf" : touch(_store) if "l" in flags["rdf"]: from rdflib2rdf import RDFXMLParser else: rdfParserName = os.environ.get("CWM_RDF_PARSER", "sax2rdf") if rdfParserName == "rdflib2rdf": from rdflib2rdf import RDFXMLParser elif rdfParserName == "sax2rdf": from sax2rdf import RDFXMLParser else: raise RuntimeError("Unknown RDF parser: " + rdfParserName) return RDFXMLParser(_store, workingContext, inputURI, flags=flags[format], why=r) elif format == "n3": touch(_store) return notation3.SinkParser(_store, openFormula=workingContext, thisDoc=inputURI, why=r) else: need(lxkb) touch(lxkb) return LX.language.getParser(language=format, sink=lxkb, flags=flags) class DocumentAccessError(IOError): def __init__(self, uri, info): self._uri = uri self._info = info def __str__(self): # See C:\Python16\Doc\ref\try.html or URI to that effect # reason = `self._info[0]` + " with args: " + `self._info[1]` reason = indentString(self._info[1].__str__()) return ("Unable to access document <%s>, because:\n%s" % ( self._uri, reason)) cwm-1.2.1/swap/toXML.py0000755015216600007660000011521410713412506013752 0ustar syosisyosi#!/usr/local/bin/python """ $Id: toXML.py,v 1.41 2007/10/15 14:55:55 syosi Exp $ This module implements basic sources and sinks for RDF data. It defines a stream interface for such data. It has a command line interface, can work as a web query engine, and has built in test(), all of which demosntrate how it is used. To make a new RDF processor, subclass RDFSink. See also: Notation 3 http://www.w3.org/DesignIssues/Notation3 Closed World Machine - and RDF Processor http;//www.w3.org/2000/10/swap/cwm To DO: See also "@@" in comments Internationlization: - Decode incoming N3 file as unicode - Encode outgoing file - unicode \u (??) escapes in parse - unicode \u (??) escapes in string output Note currently unicode strings work in this code but fail when they are output into the python debugger interactive window. ______________________________________________ Module originally by Dan Connolly. TimBL added RDF stream model. """ import string import codecs # python 2-ism; for writing utf-8 in RDF/xml output import urlparse import urllib import re import sys #import thing from uripath import refTo from diag import progress from random import choice, seed seed(23) from xmlC14n import Canonicalize import RDFSink from set_importer import Set from RDFSink import CONTEXT, PRED, SUBJ, OBJ, PARTS, ALL4 from RDFSink import FORMULA, LITERAL, XMLLITERAL, LITERAL_DT, LITERAL_LANG, ANONYMOUS, SYMBOL from RDFSink import Logic_NS, NODE_MERGE_URI from isXML import isXMLChar, NCNameChar, NCNameStartChar, setXMLVersion, getXMLVersion N3_forSome_URI = RDFSink.forSomeSym N3_forAll_URI = RDFSink.forAllSym # Magic resources we know about RDF_type_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" RDF_NS_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" DAML_NS=DPO_NS = "http://www.daml.org/2001/03/daml+oil#" # DAML plus oil DAML_sameAs_URI = DPO_NS+"sameAs" parsesTo_URI = Logic_NS + "parsesTo" RDF_spec = "http://www.w3.org/TR/REC-rdf-syntax/" ADDED_HASH = "#" # Stop where we use this in case we want to remove it! # This is the hash on namespace URIs # Should the internal representation of lists be with DAML:first and :rest? DAML_LISTS = 1 # Else don't do these - do the funny compact ones- not a good idea after all RDF_type = ( SYMBOL , RDF_type_URI ) DAML_sameAs = ( SYMBOL, DAML_sameAs_URI ) List_NS = RDF_NS_URI # We have to pick just one all the time # For lists: N3_first = (SYMBOL, List_NS + "first") N3_rest = (SYMBOL, List_NS + "rest") RDF_li = (SYMBOL, List_NS + "li") # N3_only = (SYMBOL, List_NS + "only") N3_nil = (SYMBOL, List_NS + "nil") N3_List = (SYMBOL, List_NS + "List") N3_Empty = (SYMBOL, List_NS + "Empty") XML_NS_URI = "http://www.w3.org/XML/1998/namespace" option_noregen = 0 # If set, do not regenerate genids on output ########################## RDF 1.0 Syntax generator global _namechars _namechars = string.lowercase + string.uppercase + string.digits + '_-' def dummyWrite(x): pass class ToRDF(RDFSink.RDFStructuredOutput): """keeps track of most recent subject, reuses it""" _valChars = string.lowercase + string.uppercase + string.digits + "_ !#$%&().,+*/" #@ Not actually complete, and can encode anyway def __init__(self, outFp, thisURI=None, base=None, flags=""): RDFSink.RDFSink.__init__(self) if outFp == None: self._xwr = XMLWriter(dummyWrite, self) else: dummyEnc, dummyDec, dummyReader, encWriter = codecs.lookup('utf-8') z = encWriter(outFp) zw = z.write self._xwr = XMLWriter(zw, self) self._subj = None self._base = base self._formula = None # Where do we get this from? The outermost formula if base == None: self._base = thisURI self._thisDoc = thisURI self._flags = flags self._nodeID = {} self._nextnodeID = 0 self._docOpen = 0 # Delay doc open self._subj = None self._xwr.endElement() # self._xwr.endDocument() def makeComment(self, str): if self._docOpen: self._xwr.makeComment(str) return toDo = self._toDo def toDoMore(): toDo() self._xwr.makeComment(str) self._toDo = toDoMore def referenceTo(self, uri): "Conditional relative URI" if "r" in self._flags or self._base == None: return uri return refTo(self._base, uri) def flushStart(self): if not self._docOpen: if getXMLVersion() != '1.0': self._xwr.makePI('xml version="%s"' % getXMLVersion()) self._toDo() if self.prefixes.get(RDF_NS_URI, ":::") == ":::": if self.namespaces.get("rdf", ":::") ==":::": self.bind("rdf", RDF_NS_URI) ## else: ## ns = findLegal(self.prefixes, RDF_NS_URI) ## self.bind(ns, RDF_NS_URI) # if self.prefixes.get(Logic_NS, ":::") == ":::": # if self.namespaces.get("log", ":::") ==":::": # self.bind("log", Logic_NS) ats = [] ps = self.prefixes.values() ps.sort() # Cannonicalize output somewhat if self.defaultNamespace and "d" not in self._flags: if "z" in self._flags: ats.append(('xmlns', self.referenceTo(self.defaultNamespace))) else: ats.append(('xmlns',self.defaultNamespace)) for pfx in ps: nsvalue = self.namespaces[pfx] if "z" in self._flags: nsvalue = self.referenceTo( nsvalue) ats.append(('xmlns:'+pfx, nsvalue)) self._xwr.startElement(RDF_NS_URI+'RDF', ats, self.prefixes) self._subj = None self._nextId = 0 self._docOpen = 1 def makeStatement(self, tuple, why=None, aIsPossible=0): context, pred, subj, obj = tuple # Context is ignored if self.stack[-1]: if pred == RDF_li: pass elif pred == N3_first: pred = RDF_li elif pred == RDF_type and obj == N3_List: return # We knew elif pred == RDF_type and obj == N3_Empty: return # not how we would have put it but never mind elif pred == N3_rest: return # Ignore rest else: raise RuntimeError ("Should only see %s and %s in list mode, for tuple %s and stack %s" %(N3_first, N3_rest, `tuple`, `self.stack`)) if subj == context: # and context == self._formula: if pred == (SYMBOL, N3_forAll_URI): progress("Ignoring universal quantification of ", obj) return elif pred == (SYMBOL, N3_forSome_URI): nid = self._nodeID.get(obj, None) if nid == None and not("b" in self._flags): self._nextnodeID += 1 nid = 'b'+`self._nextnodeID` self._nodeID[obj] = nid #progress("object is now", obj, nid) return if subj[0] not in (SYMBOL, ANONYMOUS, LITERAL, LITERAL_DT, LITERAL_LANG): progress("Warning: because subject is not symbol, bnode or literal, Ignoring ", tuple) return # progress("@@@ subject node is ", subj) self.flushStart() if self._formula == None: self._formula = context # Asssume first statement is in outermost context @@ predn = self.referenceTo( pred[1]) subjn = self.referenceTo( subj[1]) if pred == (SYMBOL, RDF_NS_URI+'Description'): raise ValueError('rdf:Description is not a valid predicate') if self._subj != subj: if self._subj: self._xwr.endElement() self._subj = subj if (pred == (SYMBOL, RDF_type_URI)# Special case starting with rdf:type as element name and obj[0] != LITERAL and "c" not in self._flags): # "c" flag suppresses class element syntax on RDF output # self._xwr.startElement(obj[1], [(RDF_NS_URI+" about", subjn),], self.prefixes) # return start_tag = obj[1] else: start_tag = RDF_NS_URI+'Description' # progress("@@ Start tag: %s" % start_tag) if subj[0] == SYMBOL or subj[0] == ANONYMOUS: nid = self._nodeID.get(subj, None) if nid == None: if subj[0] == ANONYMOUS: self._xwr.startElement(start_tag, [], self.prefixes) else: self._xwr.startElement(start_tag, [(RDF_NS_URI+" about", subjn),], self.prefixes) else: self._xwr.startElement(start_tag, [(RDF_NS_URI+" nodeID", nid),], self.prefixes) if start_tag != RDF_NS_URI+'Description': return elif subj[0] == LITERAL: raise ValueError( """Bad subject of statement: %s. RDF/XML cannot serialize a graph in which a subject is a literal.""" % subj[1]) # See http://lists.w3.org/Archives/Public/public-cwm-bugs/2004Aug/0014.html v = subj[1] attrs = [] # Literal if type(v) is type((1,1)): v, dt, lang = v if dt != None: attrs.append((RDF_NS_URI+'datatype', dt)) if lang != None: attrs.append((XML_NS_URI+' lang', lang)) self._xwr.startElement(RDF_NS_URI+'Description', [], self.prefixes) self._xwr.startElement(RDF_NS_URI+"is", attrs, self.prefixes) self._xwr.data(v) self._xwr.endElement() else: raise RuntimeError("Unexpected subject", `subj`) if obj[0] not in (XMLLITERAL, LITERAL, LITERAL_DT, LITERAL_LANG): nid = self._nodeID.get(obj, None) if nid == None: objn = self.referenceTo( obj[1]) # progress("@@@ objn=%s, obj[1]=%s" %(objn, obj[1])) nid2 = self._nodeID.get(pred, None) if nid2 is None: self._xwr.emptyElement(pred[1], [(RDF_NS_URI+' resource', objn)], self.prefixes) else: bNodePredicate() else: self._xwr.emptyElement(pred[1], [(RDF_NS_URI+' nodeID', nid)], self.prefixes) return attrs = [] # Literal v = obj[1] if obj[0] == XMLLITERAL: attrs.append((RDF_NS_URI+' parseType', 'Literal')) elif obj[0] == LITERAL_DT: v, dt = v if dt != None: attrs.append((RDF_NS_URI+' datatype', dt)) elif obj[0] == LITERAL_LANG: v, lang = v if lang != None: attrs.append((XML_NS_URI+' lang', lang)) nid = self._nodeID.get(pred, None) if nid is None: self._xwr.startElement(pred[1], attrs, self.prefixes) else: bNodePredicate() if obj[0] == XMLLITERAL: # XML literal dom = obj[1] self._xwr.passXML(''.join([Canonicalize(x) for x in dom.childNodes])) else: self._xwr.data(v) self._xwr.endElement() # Below is for writing an anonymous node which is the object of only one arc # This is the arc leading to it. # As object def startAnonymous(self, tuple): self.startWithParseType("Resource", tuple) def endAnonymous(self, subject, verb): # Remind me where we are self._xwr.endElement() self._subj = subject # @@@ This all needs to be thought about! # Below we do anonymous top level node - arrows only leave this circle # There is no list synmtax for subject in RDF # As subject def startAnonymousNode(self, subj, isList=0): # progress("@@@ Anonymous node is ", subj) self.flushStart() if self._subj: self._xwr.endElement() self._subj = None self._xwr.startElement(RDF_NS_URI+'Description', [], self.prefixes) self._subj = subj # The object is not the subject context def endAnonymousNode(self, subj=None): # Remove context return #If a new subject is started, they'll know to close this one self._xwr.endElement() self._subj = None # LISTS # # Below is for writing an anonymous node which is the object of only one arc # This is the arc leading to it. # As object def startListObject(self, tuple, isList =0): self._pred = RDF_li self.startWithParseType('Collection', tuple) self.stack.append(1) return def endListObject(self, subject, verb): # Remind me where we are self.stack.pop() self._xwr.endElement() self._subj = subject # @@@ This all needs to be thought about! return def startWithParseType(self, parseType, tuple): self.flushStart() context, pred, subj, obj = tuple if self._subj != subj: if self._subj: self._xwr.endElement() nid = self._nodeID.get(subj, None) if nid == None: subjn = self.referenceTo( subj[1]) attr = ((RDF_NS_URI+' about', subjn),) if subj[0] == ANONYMOUS: attr = [] self._xwr.startElement(RDF_NS_URI + 'Description', attr, self.prefixes) else: self._xwr.startElement(RDF_NS_URI + 'Description', ((RDF_NS_URI+' nodeID', nid),), self.prefixes) self._subj = subj nid = self._nodeID.get(pred, None) if nid is None: self._xwr.startElement(pred[1], [(RDF_NS_URI+' parseType',parseType)], self.prefixes) else: bNodePredicate() self._subj = obj # The object is now the current subject return # As subject: def startListSubject(self, subj): self.startAnonymousNode(self) # @@@@@@ set flaf to do first/rest decomp def endListSubject(self, subj): self.endAnonymousNode(subj) # Below we notate a nested formula def startFormulaSubject(self, context): # Doesn't work with RDF sorry ILLEGAL self.flushStart() if self._subj: self._xwr.endElement() self._subj = None self._xwr.startElement(RDF_NS_URI+'Description', [], self.prefixes) self._xwr.startElement(NODE_MERGE_URI, [(RDF_NS_URI+' parseType', "Quote")], self.prefixes) self._subj = None def endFormulaSubject(self, subj): # Remove context if self._subj: self._xwr.endElement() # End description if any self._subj = 0 self._xwr.endElement() # End quote self._subj = subj def startFormulaObject(self, tuple): self.flushStart() context, pred, subj, obj = tuple if self._subj != subj: if self._subj: self._xwr.endElement() nid = self._nodeID.get(subj, None) if nid == None: progress("@@@Start anonymous node but not nodeID?", subj) subjn = self.referenceTo( subj[1]) self._xwr.startElement(RDF_NS_URI + 'Description', ((RDF_NS_URI+' about', subjn),), self.prefixes) else: self._xwr.startElement(RDF_NS_URI + 'Description', ((RDF_NS_URI+' nodeID', nid),), self.prefixes) self._subj = subj # log_quote = self.prefixes[(SYMBOL, Logic_NS)] + ":Quote" # Qname yuk self._xwr.startElement(pred[1], [(RDF_NS_URI+' parseType', "Quote")], self.prefixes) # @@? Parsetype RDF? Formula? self._subj = None def endFormulaObject(self, pred, subj): # Remove context if self._subj: self._xwr.endElement() # if any self._subj = None self._xwr.endElement() # end quote self._subj = subj # restore context from start # print "Ending formula, pred=", pred, "\n subj=", subj # print "\nEnd bag object, pred=", `pred`[-12:] ########################################### XML Writer class XMLWriter: """ taken from Id: tsv2xml.py,v 1.1 2000/10/02 19:41:02 connolly Exp connolly Takes as argument a writer which does the (eg utf-8) encoding """ def __init__(self, encodingWriter, counter, squeaky=0, version='1.0'): # self._outFp = outFp self._encwr = encodingWriter self._elts = [] self.squeaky = squeaky # No, not squeaky clean output self.tab = 4 # Number of spaces to indent per level self.needClose = 0 # 1 Means we need a ">" but save till later self.noWS = 0 # 1 Means we cant use white space for prettiness self.currentNS = None # @@@ Hack self.counter = counter self.version = version #@@ on __del__, close all open elements? _namechars = string.lowercase + string.uppercase + string.digits + '_-' def newline(self, howmany=1): if self.noWS: self.noWS = 0 self.flushClose() return i = howmany if i<1: i=1 self._encwr("\n\n\n\n"[:i]) self.indent() def indent(self, extra=0): self._encwr(' ' * ((len(self._elts)+extra) * self.tab)) self.flushClose() def closeTag(self): if self.squeaky: self.needClose =1 else: self._encwr(">") def flushClose(self): if self.needClose: self._encwr(">") self.needClose = 0 def passXML(self, st): self.flushClose() self._encwr(st) def figurePrefix(self, uriref, rawAttrs, prefixes): i = len(uriref) while i>0: if isXMLChar(uriref[i-1], NCNameChar): # uriref[i-1] in self._namechars: i = i - 1 else: break while i") # @@ def makePI(self, str): self._encwr('') def startElement(self, n, attrs = [], prefixes={}): oldNS = self.currentNS ln, at2 = self.figurePrefix(n, attrs, prefixes) self._elts.append((ln, oldNS)) self.closeTag() def emptyElement(self, n, attrs=[], prefixes={}): oldNS = self.currentNS ln, at2 = self.figurePrefix(n, attrs, prefixes) self.currentNS = oldNS # Forget change - no nesting self._encwr("/") self.closeTag() def endElement(self): n, self.currentNS = self._elts.pop() self.newline() self._encwr("&]") # timbl removed \n as can be in data attrEsc = re.compile(r"[\r<>&'\"\n]") def data(self, str): #@@ throw an exception if the element stack is empty # o = self._outFp self.flushClose() # xmldata(o.write, str, self.dataEsc) xmldata(self._encwr, str, self.dataEsc) self.noWS = 1 # Suppress whitespace - we are in data def endDocument(self): while len(self._elts) > 0: self.endElement() self.flushClose() self._encwr("\n") ##NOTHING = -1 ##SUBJECT = 0 ##PREDICATE = 1 ##OBJECT = 2 ## ##FORMULA = 0 ##LIST = 1 ##ANONYMOUS = 2 ## ##NO = 0 ##STALE = 1 ##FRESH = 2 import triple_maker tm = triple_maker def swap(List, a, b): q = List[a] List[a] = List[b] List[b] = q def findLegal(dict, str): ns = Set(dict.values()) s = u'' k = len(str) while k and str[k - 1] not in string.ascii_letters: k = k - 1 i = k while i: if str[i - 1] not in string.ascii_letters: break i = i - 1 j = i # raise RuntimeError(str[:i]+'[i]'+str[i:k]+'[k]'+str[k:]) while j < k and (str[j:k] in ns or str[j:k][:3] == 'xml'): j = j + 1 if j == k: # we need to find a better string s = str[i:k] while s in ns or s[:3] == 'xml': s = choice(string.ascii_letters) + s[:-1] return s else: return str[j:k] class tmToRDF(RDFSink.RDFStructuredOutput): """Trying to do the same as above, using the TripleMaker interface """ def __init__(self, outFp, thisURI=None, base=None, flags=""): RDFSink.RDFSink.__init__(self) if outFp == None: self._xwr = XMLWriter(dummyWrite, self) else: dummyEnc, dummyDec, dummyReader, encWriter = codecs.lookup('utf-8') z = encWriter(outFp) zw = z.write self._xwr = XMLWriter(zw, self) self._subj = None self._base = base self._formula = None # Where do we get this from? The outermost formula if base == None: self._base = thisURI self._thisDoc = thisURI self._flags = flags self._nodeID = {} self._nextNodeID = 0 self.namedAnonID = 0 self._docOpen = 0 # Delay doc open 3: raise ValueError('Too many parts in statement: Try ending the statement') if node is not None: #print node, '+', self._triples, '++', self._parts if self._parts[-1] == tm.PREDICATE and self._predIsOfs[-1] == tm.STALE: self._predIsOfs[-1] = tm.NO if self._parts[-1] == tm.SUBJECT: subj = self._triples[-1][tm.SUBJECT] if subj is not None and node != subj: self._closeSubject() elif self._parts[-1] == tm.PREDICATE: if node == (SYMBOL, RDF_type_URI) and self._classes[-1] is None: #special thing for self._classes[-1] = "Wait" else: if self._classes[-1] is None: self._openSubject(self._triples[-1][tm.SUBJECT]) self._classes[-1] = "Never" #self._openPredicate(node) else: if self._classes[-1] == "Wait": self._classes[-1] = node self._openSubject(self._triples[-1][tm.SUBJECT]) else: if node[0] == LITERAL: self._openPredicate(self._triples[-1][tm.PREDICATE], args=(node[2],node[3])) self._writeLiteral(node) self._closePredicate() elif node[0] == SYMBOL or node[0] == ANONYMOUS: self._openPredicate(self._triples[-1][tm.PREDICATE], obj=node) if nameLess: node = "NameLess" try: self._triples[-1][self._parts[-1]] = node except: print self._parts, " - ", self._triples raise if self._modes[-1] == tm.ANONYMOUS and self._pathModes[-1] == True: self.endStatement() self.endAnonymous() if self._modes[-1] == tm.LIST and nameLess == 0: self._modes[-1] = tm.FORMULA self.beginAnonymous() self.lists[-1] += 1 self._modes[-1] = tm.ANONYMOUS self.addSymbol(List_NS + "first") self.addNode(node) self.endStatement() self.addNode(None) self.addSymbol(List_NS + "rest") self._modes[-1] = tm.LIST def nodeIDize(self, argument): q = argument[1] if (q[0] == ANONYMOUS or q[0] == SYMBOL) and q[1] in self._nodeID: #print '---', (RDF_NS_URI+' nodeID', self._nodeID[q[1]]) return (RDF_NS_URI+' nodeID', self._nodeID[q[1]]) #print '+++', (argument[0], q[1]) return (argument[0], self.referenceTo(q[1])) def _openSubject(self, subject): if subject != "NameLess": subj = subject[1] q = (self.nodeIDize((RDF_NS_URI+' about', subject)),) else: q = [] if self._classes[-1] is None: self._xwr.startElement(RDF_NS_URI + 'Description', q, self.prefixes) self._classes[-1] = subject else: self._xwr.startElement(self._classes[-1][1], q, self.prefixes) def _closeSubject(self): self._xwr.endElement() self._classes[-1] = None def _openPredicate(self, pred, args=None, obj=None, resource=None): if obj is None: if resource is not None: self._xwr.startElement(pred[1], [(RDF_NS_URI+' parseType','Resource')], self.prefixes) else: attrs = [] if args is not None: dt, lang = args if dt is not None: attrs.append((RDF_NS_URI+' datatype', dt)) if lang is not None: attrs.append((XML_NS_URI+' lang', lang)) #print pred[1], attrs self._xwr.startElement(pred[1], attrs, self.prefixes) else: #print '++', pred[1], ' ++' self._xwr.emptyElement(pred[1], [self.nodeIDize((RDF_NS_URI+' resource', obj))], self.prefixes) def _closePredicate(self): self._xwr.endElement() def _writeLiteral(self, lit): self._xwr.data(lit[1]) def IsOf(self): self._predIsOfs[-1] = tm.FRESH def checkIsOf(self): return self._predIsOfs[-1] def forewardPath(self): if self._modes[-1] == tm.LIST: a = self.lists[-1].pop() else: a = self._triples[-1][self._parts[-1]] self._parts[-1] = self._parts[-1] - 1 self.beginAnonymous() self.addNode(a) self._predIsOfs[-1] = tm.FRESH self._pathModes[-1] = True def backwardPath(self): a = self._triples[-1][self._parts[-1]] self._parts[-1] = self._parts[-1] - 1 self.beginAnonymous() self.addNode(a) self._pathModes[-1] = True def endStatement(self): if self._parts[-1] == tm.SUBJECT: pass elif False: if self._parts[-1] != tm.OBJECT: raise ValueError('try adding more to the statement' + `self._triples`) if self._pathModes[-1]: swap(self._triples[-1], tm.PREDICATE, tm.OBJECT) if self._predIsOfs[-1]: swap(self._triples[-1], tm.SUBJECT, tm.OBJECT) subj, pred, obj = self._triples[-1] if subj == '@this': if pred == self.forSome: formula.declareExistential(obj) elif pred == self.forAll: formula.declareUniversal(obj) else: raise ValueError("Internal error: unknown quntifier with '@this'") else: formula.add(subj, pred, obj) self._parts[-1] = tm.NOTHING if self._modes[-1] == tm.ANONYMOUS and self._pathModes[-1]: self._parts[-1] = tm.SUBJECT def addLiteral(self, lit, dt=None, lang=None): a = (LITERAL, lit, dt, lang) self.addNode(a) def addSymbol(self, sym): #print '////', sym a = (SYMBOL, sym) self.addNode(a) def beginFormula(self): raise ValueError("The XML serializer does not support nested graphs.") def endFormula(self): raise ValueError("The XML serializer does not support nested graphs.") def beginList(self): self.lists.append(0) self._modes.append(tm.LIST) def endList(self): self._modes[-1] = tm.ANONYMOUS self.addSymbol(RDF_NS_URI + 'nil') a = self.lists.pop() for x in range(a): if self._parts[-1] != tm.PREDICATE: self._modes[-1] = tm.ANONYMOUS self.endAnonymous() self._modes.pop() print '_______________', self._modes def addAnonymous(self, Id): #print '\\\\\\\\', Id a = (ANONYMOUS, Id) if Id not in self._nodeID: self._nodeID[Id] = 'b'+`self._nextNodeID` self._nextNodeID += 1 self.addNode(a) def beginAnonymous(self): self.namedAnonID += 1 a = (ANONYMOUS, `self.namedAnonID`) if self._parts[-1] == tm.NOTHING: self.addNode(a, nameLess = 1) elif self._parts[-1] == tm.PREDICATE: self.bNodes.append(a) self._openPredicate(self._triples[-1][tm.PREDICATE], resource=[]) self._modes.append(tm.ANONYMOUS) self._triples.append([a, None, None]) self._parts.append(tm.SUBJECT) self._predIsOfs.append(tm.NO) self._pathModes.append(False) else: self.addAnonymous(self.namedAnonID) def endAnonymous(self): if self._modes[-1] != tm.ANONYMOUS: self._parts[-1] = tm.SUBJECT #self.endStatement() return if self._parts[-1] != tm.NOTHING: self.endStatement() a = self.bNodes.pop() self._modes.pop() self._triples.pop() self._parts.pop() self._predIsOfs.pop() self._pathModes.pop() self._closePredicate() def declareExistential(self, sym): self.nodeID[(SYMBOL, sym)] = _nextNodeID _nextNodeID += 1 return formula = self.formulas[-1] a = formula.newSymbol(sym) formula.declareExistential(a) def declareUniversal(self, sym): return formula = self.formulas[-1] a = formula.newSymbol(sym) formula.declareUniversal(a) def addQuestionMarkedSymbol(self, sym): return formula = self.formulas[-2] a = formula.newSymbol(sym) formula.declareUniversal(a) self.addNode(a) def xmldata(write, str, markupChars): i = 0 while i < len(str): m = markupChars.search(str, i) if not m: t = str[i:] # for ch in str[i:]: progress( "Char ", ord(ch)) # progress("Writer is %s" %(`write`)) # progress("t = "+t.encode(u) write(t) break j = m.start() write(str[i:j]) write("&#%d;" % (ord(str[j]),)) i = j + 1 def bNodePredicate(): raise ValueError("""Serialization Error: It is not possible in RDF/XML to have a bNode in a predicate. See Try using n3 instead.""") #ends cwm-1.2.1/swap/xmlC14n.py0000644015216600007660000003204610634511760014177 0ustar syosisyosi#! /usr/bin/env python '''XML Canonicalization This module generates canonical XML of a document or element. http://www.w3.org/TR/2001/REC-xml-c14n-20010315 and includes a prototype of exclusive canonicalization http://www.w3.org/Signature/Drafts/xml-exc-c14n Requires PyXML 0.7.0 or later. Known issues if using Ft.Lib.pDomlette: 1. Unicode 2. does not white space normalize attributes of type NMTOKEN and ID? 3. seems to be include "\n" after importing external entities? Note, this version processes a DOM tree, and consequently it processes namespace nodes as attributes, not from a node's namespace axis. This permits simple document and element canonicalization without XPath. When XPath is used, the XPath result node list is passed and used to determine if the node is in the XPath result list, but little else. Authors: "Joseph M. Reagle Jr." "Rich Salz" $Date: 2007/06/14 14:55:56 $ by $Author: syosi $ ''' _copyright = '''Copyright 2001, Zolera Systems Inc. All Rights Reserved. Copyright 2001, MIT. All Rights Reserved. Distributed under the terms of: Python 2.0 License or later. http://www.python.org/2.0.1/license.html or W3C Software License http://www.w3.org/Consortium/Legal/copyright-software-19980720 ''' # from diag import progress, chatty_flag import string from xml.dom import Node try: from xml.ns import XMLNS except: class XMLNS: BASE = "http://www.w3.org/2000/xmlns/" XML = "http://www.w3.org/XML/1998/namespace" #try: # import cStringIO # StringIO = cStringIO #except ImportError: import StringIO _attrs = lambda E: (E.attributes and E.attributes.values()) or [] _children = lambda E: E.childNodes or [] _IN_XML_NS = lambda n: n.namespaceURI == XMLNS.XML _inclusive = lambda n: n.unsuppressedPrefixes == None # Does a document/PI has lesser/greater document order than the # first element? _LesserElement, _Element, _GreaterElement = range(3) def _sorter(n1,n2): '''_sorter(n1,n2) -> int Sorting predicate for non-NS attributes.''' i = cmp(n1.namespaceURI, n2.namespaceURI) if i: return i return cmp(n1.localName, n2.localName) def _sorter_ns(n1,n2): '''_sorter_ns((n,v),(n,v)) -> int "(an empty namespace URI is lexicographically least)."''' if n1[0] == 'xmlns': return -1 if n2[0] == 'xmlns': return 1 return cmp(n1[0], n2[0]) def _utilized(n, node, other_attrs, unsuppressedPrefixes): '''_utilized(n, node, other_attrs, unsuppressedPrefixes) -> boolean Return true if that nodespace is utilized within the node''' if n.startswith('xmlns:'): n = n[6:] elif n.startswith('xmlns'): n = n[5:] if (n=="" and node.prefix in ["#default", None]) or \ n == node.prefix or n in unsuppressedPrefixes: return 1 for attr in other_attrs: if n == attr.prefix: return 1 return 0 #_in_subset = lambda subset, node: not subset or node in subset _in_subset = lambda subset, node: subset is None or node in subset # rich's tweak class _implementation: '''Implementation class for C14N. This accompanies a node during it's processing and includes the parameters and processing state.''' # Handler for each node type; populated during module instantiation. handlers = {} def __init__(self, node, write, **kw): '''Create and run the implementation.''' self.write = write self.subset = kw.get('subset') self.comments = kw.get('comments', 0) self.unsuppressedPrefixes = kw.get('unsuppressedPrefixes') nsdict = kw.get('nsdict', { 'xml': XMLNS.XML, 'xmlns': XMLNS.BASE }) # Processing state. self.state = (nsdict, {'xml':''}, {}) #0422 if node.nodeType == Node.DOCUMENT_NODE: self._do_document(node) elif node.nodeType == Node.ELEMENT_NODE: self.documentOrder = _Element # At document element if not _inclusive(self): self._do_element(node) else: inherited = self._inherit_context(node) self._do_element(node, inherited) elif node.nodeType == Node.DOCUMENT_TYPE_NODE: pass elif node.nodeType == Node.TEXT_NODE: self._do_text(node) else: raise TypeError, str(node) def _inherit_context(self, node): '''_inherit_context(self, node) -> list Scan ancestors of attribute and namespace context. Used only for single element node canonicalization, not for subset canonicalization.''' # Collect the initial list of xml:foo attributes. xmlattrs = filter(_IN_XML_NS, _attrs(node)) # Walk up and get all xml:XXX attributes we inherit. inherited, parent = [], node.parentNode while parent and parent.nodeType == Node.ELEMENT_NODE: for a in filter(_IN_XML_NS, _attrs(parent)): n = a.localName if n not in xmlattrs: xmlattrs.append(n) inherited.append(a) parent = parent.parentNode return inherited def _do_document(self, node): '''_do_document(self, node) -> None Process a document node. documentOrder holds whether the document element has been encountered such that PIs/comments can be written as specified.''' self.documentOrder = _LesserElement for child in node.childNodes: if child.nodeType == Node.ELEMENT_NODE: self.documentOrder = _Element # At document element self._do_element(child) self.documentOrder = _GreaterElement # After document element elif child.nodeType == Node.PROCESSING_INSTRUCTION_NODE: self._do_pi(child) elif child.nodeType == Node.COMMENT_NODE: self._do_comment(child) elif child.nodeType == Node.DOCUMENT_TYPE_NODE: pass else: raise TypeError, str(child) handlers[Node.DOCUMENT_NODE] = _do_document def _do_text(self, node): '''_do_text(self, node) -> None Process a text or CDATA node. Render various special characters as their C14N entity representations.''' if not _in_subset(self.subset, node): return s = string.replace(node.data, "&", "&") s = string.replace(s, "<", "<") s = string.replace(s, ">", ">") s = string.replace(s, "\015", " ") if s: self.write(s) handlers[Node.TEXT_NODE] = _do_text handlers[Node.CDATA_SECTION_NODE] = _do_text def _do_pi(self, node): '''_do_pi(self, node) -> None Process a PI node. Render a leading or trailing #xA if the document order of the PI is greater or lesser (respectively) than the document element. ''' if not _in_subset(self.subset, node): return W = self.write if self.documentOrder == _GreaterElement: W('\n') W('') if self.documentOrder == _LesserElement: W('\n') handlers[Node.PROCESSING_INSTRUCTION_NODE] = _do_pi def _do_comment(self, node): '''_do_comment(self, node) -> None Process a comment node. Render a leading or trailing #xA if the document order of the comment is greater or lesser (respectively) than the document element. ''' if not _in_subset(self.subset, node): return if self.comments: W = self.write if self.documentOrder == _GreaterElement: W('\n') W('') if self.documentOrder == _LesserElement: W('\n') handlers[Node.COMMENT_NODE] = _do_comment def _do_attr(self, n, value): ''''_do_attr(self, node) -> None Process an attribute.''' W = self.write W(' ') W(n) W('="') s = string.replace(value, "&", "&") s = string.replace(s, "<", "<") s = string.replace(s, '"', '"') s = string.replace(s, '\011', ' ') s = string.replace(s, '\012', ' ') s = string.replace(s, '\015', ' ') W(s) W('"') def _do_element(self, node, initial_other_attrs = []): '''_do_element(self, node, initial_other_attrs = []) -> None Process an element (and its children).''' # Get state (from the stack) make local copies. # ns_parent -- NS declarations in parent # ns_rendered -- NS nodes rendered by ancestors # ns_local -- NS declarations relevant to this element # xml_attrs -- Attributes in XML namespace from parent # xml_attrs_local -- Local attributes in XML namespace. ns_parent, ns_rendered, xml_attrs = \ self.state[0], self.state[1].copy(), self.state[2].copy() #0422 ns_local = ns_parent.copy() xml_attrs_local = {} # progress("_do_element node.nodeName=", node.nodeName) # progress("_do_element node.namespaceURI", node.namespaceURI) # progress("_do_element node.tocml()", node.toxml()) # Divide attributes into NS, XML, and others. other_attrs = initial_other_attrs[:] in_subset = _in_subset(self.subset, node) for a in _attrs(node): # progress("\t_do_element a.nodeName=", a.nodeName) if a.namespaceURI == XMLNS.BASE: n = a.nodeName if n == "xmlns:": n = "xmlns" # DOM bug workaround ns_local[n] = a.nodeValue elif a.namespaceURI == XMLNS.XML: if _inclusive(self) or in_subset: xml_attrs_local[a.nodeName] = a #0426 else: other_attrs.append(a) #add local xml:foo attributes to ancestor's xml:foo attributes xml_attrs.update(xml_attrs_local) # Render the node W, name = self.write, None if in_subset: name = node.nodeName W('<') W(name) # Create list of NS attributes to render. ns_to_render = [] for n,v in ns_local.items(): # If default namespace is XMLNS.BASE or empty, # and if an ancestor was the same if n == "xmlns" and v in [ XMLNS.BASE, '' ] \ and ns_rendered.get('xmlns') in [ XMLNS.BASE, '', None ]: continue # "omit namespace node with local name xml, which defines # the xml prefix, if its string value is # http://www.w3.org/XML/1998/namespace." if n in ["xmlns:xml", "xml"] \ and v in [ 'http://www.w3.org/XML/1998/namespace' ]: continue # If not previously rendered # and it's inclusive or utilized if (n,v) not in ns_rendered.items() \ and (_inclusive(self) or \ _utilized(n, node, other_attrs, self.unsuppressedPrefixes)): ns_to_render.append((n, v)) # Sort and render the ns, marking what was rendered. ns_to_render.sort(_sorter_ns) for n,v in ns_to_render: self._do_attr(n, v) ns_rendered[n]=v #0417 # If exclusive or the parent is in the subset, add the local xml attributes # Else, add all local and ancestor xml attributes # Sort and render the attributes. if not _inclusive(self) or _in_subset(self.subset,node.parentNode): #0426 other_attrs.extend(xml_attrs_local.values()) else: other_attrs.extend(xml_attrs.values()) other_attrs.sort(_sorter) for a in other_attrs: self._do_attr(a.nodeName, a.value) W('>') # Push state, recurse, pop state. state, self.state = self.state, (ns_local, ns_rendered, xml_attrs) for c in _children(node): _implementation.handlers[c.nodeType](self, c) self.state = state if name: W('' % name) handlers[Node.ELEMENT_NODE] = _do_element def Canonicalize(node, output=None, **kw): '''Canonicalize(node, output=None, **kw) -> UTF-8 Canonicalize a DOM document/element node and all descendents. Return the text; if output is specified then output.write will be called to output the text and None will be returned Keyword parameters: nsdict: a dictionary of prefix:uri namespace entries assumed to exist in the surrounding context comments: keep comments if non-zero (default is 0) subset: Canonical XML subsetting resulting from XPath (default is []) unsuppressedPrefixes: do exclusive C14N, and this specifies the prefixes that should be inherited. ''' if output: apply(_implementation, (node, output.write), kw) else: s = StringIO.StringIO() apply(_implementation, (node, s.write), kw) return s.getvalue() cwm-1.2.1/swap/update.py0000644015216600007660000001600310655653251014233 0ustar syosisyosi""" Update for cwm architecture The update module provides for the deletion as well as the addition of information to a formula. This module assumes the llyn.py store. It connects intimiately with the query module. 2004-03-17 written as an extension of query.py """ from set_importer import Set, sorted import diag from diag import chatty_flag, tracking, progress from formula import Formula from query import Query, Rule, seqToString, _substitute def patch(workingContext, patchFormula): """A task of running a set of updates on a knowledge base This is simpler than an Inference task, in that a patch is only done once, patches cannot lead to new patches, etc. """ if diag.chatty_flag >20: progress("New Update task, patches from %s applied to %s" % (patchFormula, workingContext)) store = workingContext.store true = store.newFormula().close() # {} universals = Set() lhs_done = [] agenda = {} for pred in store.insertion, store.deletion: for s in patchFormula.statementsMatching(pred=pred): dict = agenda.get(s.subject(), None) if dict == None: dict = {store.insertion: [], store.deletion: []} agenda[s.subject()] = dict dict[pred].append(s.object()) for lhs, dict in sorted(agenda.items()): if diag.chatty_flag > 19: progress("Patches lhs= %s: %s" %(lhs, dict)) if isinstance(lhs, Formula): if lhs.universals() != Set(): raise RuntimeError("""Cannot query for universally quantified things. As of 2003/07/28 forAll x ...x cannot be on left hand side of rule. This/these were: %s\n""" % lhs.universals()) addenda, minuenda = dict[store.insertion], dict[store.deletion] while addenda or minuenda: if addenda: conclusion = addenda.pop() else: conclusion = true if minuenda: retraction = minuenda.pop() else: retraction = true unmatched = lhs.statements[:] templateExistentials = lhs.existentials().copy() _substitute({lhs: workingContext}, unmatched) # Change context column variablesMentioned = lhs.occurringIn(patchFormula.universals()) variablesUsed = conclusion.occurringIn(variablesMentioned) | \ retraction.occurringIn(variablesMentioned) for x in sorted(variablesMentioned): if x not in variablesUsed: templateExistentials.add(x) if diag.chatty_flag >20: progress("New Patch =========== applied to %s" %(workingContext) ) for s in lhs.statements: progress(" ", `s`) progress("+=>") for s in conclusion.statements: progress(" ", `s`) progress("-=>") for s in retraction.statements: progress(" ", `s`) progress("Universals declared in outer " + seqToString(patchFormula.universals())) progress(" mentioned in template " + seqToString(variablesMentioned)) progress(" also used in conclusion " + seqToString(variablesUsed)) progress("Existentials in template " + seqToString(templateExistentials)) q = UpdateQuery(store, unmatched = unmatched, template = lhs, variables = patchFormula.universals(), existentials =templateExistentials, workingContext = workingContext, conclusion = conclusion, retraction = retraction, rule = None) q.resolve() class UpdateQuery(Query): "Subclass of query for doing patches onto the KB: adding and removing bits. Aka KB Update" def __init__(self, store, unmatched, # List of statements we are trying to match CORRUPTED template, # formula variables, # List of variables to match and return CORRUPTED existentials, # List of variables to match to anything # Existentials or any kind of variable in subexpression workingContext, conclusion, # Things to be added retraction, # Things to be deleted rule): # The rule statement Query.__init__(self, store, unmatched=unmatched, template=template, variables=variables, existentials= existentials, workingContext= workingContext, conclusion=conclusion, targetContext = workingContext, rule=rule) self.retraction = retraction def conclude(self, bindings, evidence = [], extraBNodes=Set(), allBindings=None): """When a match found in a query, add conclusions to target formula, and also remove retractions. Returns the number of statements added.""" if diag.chatty_flag > 25: progress( "Insertions will now be made into %s. Bindings %s" % (self.workingContext, bindings)) result = Query.conclude(self, bindings, evidence) # delete statements if diag.chatty_flag > 25: progress( "Insertions made, deletions will now be made. Bindings %s" % bindings) for st in self.retraction: s, p, o = st.spo() subj = self.doSubst(s, bindings) pred = self.doSubst(p, bindings) obj = self.doSubst(o, bindings) ss = self.workingContext.statementsMatching( subj = subj, pred = pred, obj = obj) if len(ss) != 1: progress("""Error: %i matches removing statement {%s %s %s} bound as {%s %s %s} from %s:\n%s\n""" % (len(ss),s,p,o, subj.uriref(), pred.uriref(), obj.uriref(), self.workingContext, ss )) progress(self.workingContext.debugString()) raise RuntimeError( """Error: %i matches removing statement {%s %s %s} bound as {%s %s %s} from %s""" % (len(ss),s,p,o, `subj`, pred.uriref(), `obj`, self.workingContext)) if diag.chatty_flag > 25: progress("Deleting %s" % ss[0]) self.workingContext.removeStatement(ss[0]) self.justOne = 1 # drop out of here when done return 1 # Success -- behave as a test and drop out def doSubst(self, x, bindings): if x.generated() and x not in bindings: raise ValueError("""Retractions cannot have bnodes in them. Use explict variables which also occur on the LHS. Found bnode: %s, bindings are: %s""" % (x, bindings)) return bindings.get(x, x) # ends cwm-1.2.1/swap/cwm_xml.py0000644015216600007660000001640510655653245014430 0ustar syosisyosi"""XML built-ins for cwm """ from diag import progress, verbosity from term import LightBuiltIn, Function, ReverseFunction, MultipleFunction, \ HeavyBuiltIn from llyn import loadToStore # for caching in store's experience from sax2rdf import XMLtoDOM # for fn:doc #from Ft.Xml.XPath import Evaluate as evalXPath # http://packages.debian.org/unstable/python/python-xml ## ## The following code allows for the lazy importing of the ## evalXPath function. It is a hack def evalXPath(*args, **keywords): try: from xml.xpath import Evaluate as localEvalXPath except ImportError: progress("Try getting python-xml from http://downloads.sourceforge.net/pyxml/PyXML-0.8.4.tar.gz") localEvalXPath = progress globals()['evalXPath'] = localEvalXPath return localEvalXPath(*args, **keywords) XMLBI_NS_URI = "http://www.w3.org/2007/ont/xml#" __version__ = "0.1" # Node properties # see http://www.python.org/doc/current/lib/dom-node-objects.html class BI_nodeType(LightBuiltIn, Function): """An integer representing the node type """ def evaluateObject(self, subj_py): return subj_py.nodeType class BI_parentNode(LightBuiltIn, Function): """The parent of the current node, or None for the document node. The value is always a Node object or None. For Element nodes, this will be the parent element, except for the root element, in which case it will be the Document object. For Attr nodes, this is always None. """ def evaluateObject(self, subj_py): return subj_py.parentNode class BI_attributes(LightBuiltIn, Function): """A NamedNodeMap of attribute objects. Only elements have actual values for this. """ def evaluateObject(self, subj_py): return subj_py.attributes class BI_previousSibling(LightBuiltIn, Function): """The node that immediately precedes this one with the same parent. For instance the element with an end-tag that comes just before the self element's start-tag. Of course, XML documents are made up of more than just elements so the previous sibling could be text, a comment, or something else. If this node is the first child of the parent, this property will not exist. """ def evaluateObject(self, subj_py): return subj_py.previousSibling class BI_nextSibling(LightBuiltIn, Function): """The node that immediately follows this one with the same parent. See also previousSibling. If this is the last child of the parent, this property will not exist. """ def evaluateObject(self, subj_py): return subj_py.nextSibling class BI_childNodes(LightBuiltIn, Function): """A list of nodes contained within this node. """ def evaluateObject(self, subj_py): return subj_py.childNodes class BI_firstChild(LightBuiltIn, Function): """The first child of the node, if there are any. """ def evaluateObject(self, subj_py): return subj_py.firstChild class BI_lastChild(LightBuiltIn, Function): """The last child of the node, if there are any. """ def evaluateObject(self, subj_py): return subj_py.lastChild class BI_localName(LightBuiltIn, Function): """The part of the tagName following the colon if there is one, else the entire tagName """ def evaluateObject(self, subj_py): return subj_py.localName class BI_prefix(LightBuiltIn, Function): """The part of the tagName preceding the colon if there is one, else the empty string """ def evaluateObject(self, subj_py): return subj_py.prefix class BI_namespaceURI(LightBuiltIn, Function): """The namespace associated with the element name. """ def evaluateObject(self, subj_py): return subj_py.namespaceURI class BI_nodeName(LightBuiltIn, Function): """This has a different meaning for each node type; see the DOM specification for details. You can always get the information you would get here from another property such as the tagName property for elements or the name property for attributes. """ def evaluateObject(self, subj_py): return subj_py.nodeName class BI_nodeValue(LightBuiltIn, Function): """This has a different meaning for each node type; see the DOM specification for details. The situation is similar to that with nodeName """ def evaluateObject(self, subj_py): return subj_py.nodeValue class BI_hasAttributes(LightBuiltIn, Function): """True if the node has any attributes. """ def evaluateObject(self, subj_py): return subj_py.hasAttributes() class BI_hasChildNodes(LightBuiltIn, Function): """True if the node has any child nodes """ def evaluateObject(self, subj_py): return subj_py.hasChildNodes() class BI_isSameNode(LightBuiltIn): """Returns true if other refers to the same node as this node. This is especially useful for DOM implementations which use any sort of proxy architecture (because more than one object can refer to the same node). """ def evaluate(self, subj_py, obj_py): return subj_py.sSameNode(obj_py) class BI_xpath(LightBuiltIn, MultipleFunction): """Evaluate XPath expression and bind to each resulting node.""" def evaluateObject(self, subj_py): node, expr = subj_py out = evalXPath(expr, node) return [self.store.newXMLLiteral(n) for n in out] class BI_doc(HeavyBuiltIn, Function): """Load XML document from the web. subject is a string, per XQuery. see test/xml-syntax/fn_doc1.n3 see also llyn.BI_xmlTree, which seems to be dead code """ def evalObj(self, subj, queue, bindings, proof, query): progress("@@fn:doc", subj) # fn:doc takes a string, but the llyn cache keys of symbols sym = subj.store.newSymbol(subj.value()) try: lit = loadToStore(sym, ["application/xml", "text/xml"]) except IOError, e: progress("@@ioerror", e) return None # hmm... is built-in API evolving to support exceptions? dom = XMLtoDOM(lit.value()) # odd... why does BI_xmlTree use the pair API rather than newXMLLiteral? progress("@@fn:doc returning") return lit.store.newXMLLiteral(dom) # Register the string built-ins with the store def register(store): str = store.symbol(XMLBI_NS_URI[:-1]) str.internFrag("nodeType", BI_nodeType) str.internFrag("parentNode", BI_parentNode) str.internFrag("attributes", BI_attributes) str.internFrag("previousSibling", BI_previousSibling) str.internFrag("nextSibling", BI_nextSibling) str.internFrag("childNodes", BI_childNodes) str.internFrag("firstChild", BI_firstChild) str.internFrag("lastChild", BI_lastChild) str.internFrag("localName", BI_localName) str.internFrag("prefix", BI_prefix) str.internFrag("namespaceURI", BI_namespaceURI) str.internFrag("nodeName", BI_nodeName) str.internFrag("nodeValue", BI_nodeValue) str.internFrag("hasAttributes", BI_hasAttributes) str.internFrag("hasChildNodes", BI_hasChildNodes) str.internFrag("isSameNode", BI_isSameNode) str.internFrag("xpath", BI_xpath) # needs test, docs fn = store.symbol("http://www.w3.org/2006/xpath-functions") fn.internFrag("string", BI_nodeValue) # probably not an exact match fn.internFrag("doc", BI_doc) # ends cwm-1.2.1/swap/term.py0000755015216600007660000017624210717732522013735 0ustar syosisyosi#! /usr/bin/python """ $Id: term.py,v 1.79 2007/11/18 03:45:22 syosi Exp $ term This module defines objects correspodning to the basic terms in the RDF and N3 langauges: Symbols, Literals and Lists. (The N3 language goes on to include formuale, which are defined elsewhere) The code in this module deals with the represnetation of these terms and in debug form (__repr__) Interning of URIs and strings for storage in SWAP store. It also defines th utility Namespace module which makes using terms in practice both more convenient maybe even more efficient than carrying full URIs around. Includes: - template classes for builtins """ from __future__ import generators # for yield import string, sys, types from set_importer import Set, ImmutableSet import uripath # DanC's tested and correct one import md5, binascii # for building md5 URIs from uripath import refTo from RDFSink import runNamespace from local_decimal import Decimal # for xsd:decimal LITERAL_URI_prefix = "data:application/rdf+n3-literal;" from RDFSink import List_NS from RDFSink import CONTEXT, PRED, SUBJ, OBJ, PARTS, ALL4 from RDFSink import FORMULA, LITERAL, LITERAL_LANG, LITERAL_DT, ANONYMOUS, \ SYMBOL, RDF_type_URI from RDFSink import Logic_NS from OrderedSequence import merge, intersection, minus import diag from diag import progress from weakref import WeakValueDictionary import sys if sys.hexversion < 0x02030000: raise RuntimeError("Sorry, this software requires python2.3 or newer.") ######################################## Storage URI Handling # # In general a Symbol has a URI which may or may not have # a "#" and fragment identifier. This code keeps track of URIs # which are the same up to the hash, so as to make it easy to discover # for example whether a term is a local identifier within a document # which we know about. This is relevant to the URI-spec related processing # rather than the RDF-spec related processing. # # than just a URI. It has subclasses of Symbol and Fragment. # # (libwww equivalent HTParentAnchor and HTChildAnchor IIRC) # # Every resource has a symbol table of fragments. # A resource may (later) have a connection to a bunch of parsed stuff. # # We are nesting symbols two deep let's make a symbol table for each resource # # The statement store lists are to reduce the search time # for triples in some cases. Of course, indexes would be faster. # but we can figure out what to optimize later. The target for now # is being able to find synonyms and so translate documents. class Env(dict): """An env is an immutable dict you can hash it (if you want to) """ __slots__ = ['_hashval', '__weakref__', 'id'] def __init__(self, other=None, keywords={}): if other is None: dict.__init__(self) else: dict.__init__(self, other, **keywords) self.id = self for k, (a,b) in self.iteritems(): if isinstance(a, tuple): raise RuntimeError("%s : (%s, %s)" % (k,a,b)) def copy(self): return self ## I'm immutable! def update(self, d2): k = self.__class__(self, d2) raise RuntimeError("I'm immutable!, %s" % k) def update2(self, d2): k = self.__class__(self, d2) return k def asDict(self): retVal = {} for k in self: retVal[k] = self[k] return retVal def newBinding(self, var, val): retVal = Env(self, {var: val}) retVal.id = self.id return retVal bind = newBinding def __setitem__(self, item, val): raise TypeError def __getitem__(self, item): return dict.__getitem__(self, item)[0] def get(self, item, default=None): return dict.get(self, item, (default,))[0] def dereference(self, var): try: hash(var) except TypeError: return var return dict.get(self, var, (var, self.id)) def flatten(self, other): """Pull all of the bindings of other into a copy of self """ # from backward import progress if diag.chatty_flag > 85: progress(lambda : 'Env.flatten(%s,%s)' % (self, other)) retVal = dict(other) for key, (val, source) in self.items(): if key in other: if source == dict.__getitem__(other, key)[1] and val != other[key]: raise ValueError(self[key], other[key]) if source is other.id: retVal[key] = (other.substitution(val, self), self.id) else: retVal[key] = (val, source) retVal = self.__class__(retVal) retVal.id = self.id if diag.chatty_flag > 85: progress(lambda : '... returns %s' % retVal) return retVal def filter(self, varSet): retVal = [(a,b) for (a,b) in self.items() if a in varSet] retVal = self.__class__(retVal) retVal.id = self.id return retVal def substitution(self, node, *otherEnvs): if self not in otherEnvs: envs = (self,) + otherEnvs if node in self: k, s = self.dereference(node) for env in envs: if s is env.id: return env.substitution(k, *envs) elif isinstance(node, list): return [self.substitution(x, otherEnvs) for x in node] if isinstance(node, tuple): return tuple([self.substitution(x, otherEnvs) for x in node]) if isinstance(node, (formula.StoredStatement, term.Term)): return node.substitution(self) ## Wrong! return node def canBind(self, var, val): if var in self: return self[var] == val return True def __repr__(self): return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self)) def __hash__(self): try: return self._hashval except AttributeError: self._hashval = hash(ImmutableSet(self.items())) return self._hashval def pickEnv(choice, *envs): for env in envs: if choice is env.id: return env return [] ## Not here. class Term(object): """The Term object represents an RDF term. It is interned for speed of processing by the store. Every term has a pointer back to its store. """ def __init__(self, store): self.store = store def __repr__(self): """This method only used for debugging output - it can be ambiguous, as it is is deliberately short to make debug printout readable. output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName]. This could be beefed up to guarantee unambiguity. """ s = self.uriref() p = string.rfind(s, "#") if p<0: # No hash, use slash p=s.rfind("/", 0, len(s)-2) # Allow "/" namespaces as a second best, not a trailing one if (p>=0 and s[p+1:].find(".") <0 ): # Can't use prefix if localname includes "." prefix = self.store.prefixes.get(s[:p+1], None) # @@ #CONVENTION if prefix != None : return (prefix + ":" + s[p+1:]).encode('unicode_escape') if s.endswith("#_formula"): return "`"+s[-22:-9]+"`" # Hack - debug notation for formula if p >= 0: return s[p+1:].encode('unicode_escape') return s.encode('unicode_escape') def debugString(self, already=[]): return `self` # unless more eleborate in superclass def representation(self, base=None): """The string represnting this in N3 """ return "<" + self.uriref(base) + ">" def generated(self): """Boolean Is this thing a genid - is its name arbitrary? """ return 0 # unless overridden def compareAnyTerm(self, other): """Compare two langauge items This is a cannoncial ordering in that is designed to allow the same graph always to be printed in the same order. This makes the regression tests possible. The literals are deemed smaller than symbols, which are smaller than formulae. This puts the rules at the botom of a file where they tend to take a lot of space anyway. Formulae have to be compared as a function of their sorted contents. @@ Anonymous nodes have to, within a given Formula, be compared as a function of the sorted information about them in that context. This is not done yet """ if self is other: return 0 diff = cmp(self.classOrder(), other.classOrder()) if diff != 0: return diff return self.compareTerm(other) def asPair(self): """Representation in an earlier format, being phased out 2002/08 The first part of the pair is a constant number represnting the type see RDFSink.py. the second is the value -- uri for symbols, string for literals""" return (SYMBOL, self.uriref()) def substitution(self, bindings, why=None, cannon=False): "Return this or a version of me with subsitution made" return bindings.get(self, self) def substituteEquals(self, bindings, newRedirections): "Return this or a version of me with substitution made" return bindings.get(self, self) def occurringIn(self, vars): if self in vars: return Set([self]) return Set() def value(self): "As a python value - by default, none exists, use self" return self def doesNodeAppear(self, symbol): """Does that node appear within this one This non-overloaded function will simply return if I'm equal to him """ return self == symbol def unify(self, other, env1=Env(), env2=Env(), vars=Set(), universals=Set(), existentials=Set(), n1Source=32, n2Source=32): return unify(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source) ## def unify(self, other, vars=Set([]), existentials=Set([]), bindings={}): ## """Unify this which may contain variables with the other, ## which may contain existentials but not variables. ## ## vars are variables we want a binding for if matched ## existentials are things we don't need a binding returned for ## bindings are those bindings already made in this unification ## ## Return [] if impossible. ## return [({}, reason] if no new bindings ## Return [( {var1: val1, var2: val2,...}, reason), ...] if match ## """ ## assert type(bindings) is types.DictType ## if diag.chatty_flag > 97: ## progress("Unifying symbol %s with %s vars=%s, so far=%s"% ## (self, other,vars, bindings)) ## s = bindings.get(self, self) ## if s is other: ## return [ ({}, None)] ## if s in vars|existentials: ## if diag.chatty_flag > 80: ## progress("Unifying var or exi MATCHED %s to %s"%(s, other)) ## return [ ({s: other}, None) ] ## if diag.chatty_flag > 99: ## progress("Failed Unifying symbol %s with %s vars=%s, so far=%s"% ## (self, other, vars, bindings)) ## return [] def unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55): if self is other: yield (env1, env2) def freeVariables(self): return Set() class ErrorFlag(TypeError, Term): __init__ = TypeError.__init__ __repr__ = TypeError.__str__ __str__ = TypeError.__str__ # uriref = lambda s: ':' value = lambda s: s def classOrder(self): return 99 class Node(Term): """A node in the graph """ pass class LabelledNode(Node): "The labelled node is one which has a URI." def compareTerm(self, other): "Assume is also a LabelledNode - see function compareTerm in formula.py" _type = RDF_type_URI s = self.uriref() if self is self.store.type: return -1 o = other.uriref() if other is self.store.type: return 1 retVal = cmp(s, o) if retVal: return retVal progress( "Error with '%s' being the same as '%s'" %(s,o)) raise RuntimeError( """Internal error: URIref strings should not match if not same object, comparing %s and %s""" % (s, o)) def classOrder(self): return 6 class Symbol(LabelledNode): """ A Term which has no fragment """ def __init__(self, uri, store): Term.__init__(self, store) assert string.find(uri, "#") < 0, "no fragments allowed: %s" % uri assert ':' in uri, "must be absolute: %s" % uri self.uri = uri self.fragments = WeakValueDictionary() def uriref2(self, base): assert ':' in base, "base must be absolute: %s" % base return refTo(base, self.uri) def uriref(self): # assert ':' in self.uri, "oops! must be absolute: %s" % self.uri return self.uri def internFrag(self, fragid, thetype): # type was only Fragment before f = self.fragments.get(fragid, None) if f != None: if not isinstance(f, thetype): raise RuntimeError( "Oops.. %s exists already but not with type %s" %(f, thetype)) return f # (Could check that types match just to be sure) f = thetype(self, fragid) self.fragments[fragid] = f return f def __getitem__(self, lname): """get the lname Symbol in this namespace. lname -- an XML name (limited to URI characters) """ if lname.startswith("__"): # python internal raise AttributeError, lname return self.internFrag(lname, Fragment) def dereference(self, mode="", workingContext=None): """dereference an identifier, finding the semantics of its schema if any Returns None if it cannot be retreived. """ if hasattr(self, "_semantics"): F = self._semantics else: inputURI = self.uriref() if diag.chatty_flag > 20: progress("Web: Looking up %s" % self) if "E" not in mode: F = self.store.load(inputURI) else: try: F = self.store.load(inputURI) except: #except (IOError, SyntaxError, DocumentAccessError, # xml.sax._exceptions.SAXParseException): F = None if F != None: if "m" in mode: workingContext.reopen() if diag.chatty_flag > 45: progress("Web: dereferenced %s added to %s" %( self, workingContext)) workingContext.store.copyFormula(F, workingContext) if "x" in mode: # capture experience workingContext.add(r, self.store.semantics, F) if not hasattr(self, "_semantics"): setattr(self, "_semantics", F) if diag.chatty_flag > 25: progress("Web: Dereferencing %s gave %s" %(self, F)) return F class Fragment(LabelledNode): """ A Term which DOES have a fragment id in its URI """ def __init__(self, resource, fragid): Term.__init__(self, resource.store) self.resource = resource self.fragid = fragid def compareTerm(self, other): if not isinstance(other, Fragment): return LabelledNode.compareTerm(self, other) if self is self.resource.store.type: return -1 if other is self.resource.store.type: return 1 if self.resource is other.resource: return cmp(self.fragid, other.fragid) return self.resource.compareTerm(other.resource) def uriref(self): return self.resource.uri + "#" + self.fragid def uriref2(self, base): return self.resource.uriref2(base) + "#" + self.fragid def representation(self, base=None): """ Optimize output if prefixes available """ return "<" + self.uriref2(base) + ">" def generated(self): """ A generated identifier? This arises when a document is parsed and a arbitrary name is made up to represent a node with no known URI. It is useful to know that its ID has no use outside that context. """ return 0 # Use class Anonymous for generated IDs def dereference(self, mode="", workingContext=None): """dereference an identifyer, finding the semantics of its schema if any Returns None if it cannot be retreived. """ return self.resource.dereference(mode, workingContext) nextId = 0 class AnonymousNode(Node): """Has no real URI except when needed for output. Goal is to eliminate use of ths URI in the code. The URI is however useful as a diagnostic, so we carry it when it is given. It is NOT checked for uniqueness etc. This is a superclass of many things, including AnonymousExistential, which has a scope.""" def __init__(self, store, uri=None): global nextId try: if uri: assert isinstance(uri, tuple(types.StringTypes)) except: print uri print type(uri) print '---------=============------------' raise Term.__init__(self, store) self._diagnosticURI = uri nextId += 1 self.serial = nextId def compareTerm(self, other): "Assume is also a Formula - see function compareTerm below" if hasattr(self, 'uri'): selfSerial = self.uri else: selfSerial = self.serial if hasattr(other, 'uri'): otherSerial = other.uri else: otherSerial = other.serial retVal = cmp(selfSerial, otherSerial) if retVal: return retVal return cmp(self.serial, other.serial) def classOrder(self): """Anonymous ndoes are higher than symbols as the = smushing tries to minimize the order rank of the node which it adopts as the epresentative node of an equivalence class.""" return 9 def uriref(self): if self._diagnosticURI: return self._diagnosticURI return runNamespace() + "_g" + `self.serial` # return runNamespace() + "_b" + `id(self)` def generated(self): return 1 def asPair(self): return (ANONYMOUS, self.uriref()) def freeVariables(self): return Set([self]) class Universal(Term): __repr__ = object.__repr__ class Existential(Term): __repr__ = object.__repr__ class SkolemFunction(Existential): pass class AnonymousVariable(AnonymousNode): """An anonymous node which is existentially quantified in a given context. Also known as a Blank Node, or "bnode" in RDF parlance.""" def __init__(self, scope, uri=None): AnonymousNode.__init__(self, scope.store, uri) class AnonymousExistential(AnonymousVariable, Existential): """An anonymous node which is existentially quantified in a given context. Also known as a Blank Node, or "bnode" in RDF parlance.""" __repr__= AnonymousVariable.__repr__ class AnonymousUniversal(AnonymousVariable, Universal): """Nodes which are introduced as universally quantified variables with no quotable URI""" def __init__(self, scope, uri=None): if isinstance(uri, Term): if isinstance(uri, AnonymousUniversal): uri = uri.uri elif isinstance(uri, AnonymousNode): uri = None elif isinstance(uri, LabelledNode): uri = uri.uriref() self.scope = scope self.uri = uri AnonymousVariable.__init__(self, scope, uri) scope.declareUniversal(self, key=self.__class__) def asPair(self): if not self.uri: return AnonymousVariable.asPair(self) return (SYMBOL, self.uriref()) __repr__= AnonymousVariable.__repr__ ## def __repr__(self): ## return str(abs(id(self))) ########################################################################## # # L I S T S # # Lists are interned, so python object comparison works for log:equalTo. # For this reason, do NOT use a regular init, always use rest.prepend(first) # to generate a new list form an old, or nil.prepend(first) for a singleton, # or nil.newList(somePythonList) # This lists can only hold hashable objects - but we only use hashable objects # in statements. # These don't have much to be said for them, compared with python lists, # except that (a) they are hashable, and (b) if you do your procesing using # first and rest a lot, you don't generate n(n+1)/2 list elements when # traversing (which you probably don't anyway using slices) # # Many different implementations are of course possible. # _nextList = 0 class CompoundTerm(Term): """A compound term has occurrences of terms within it. Examples: List, Formula""" pass class N3Set(ImmutableSet, CompoundTerm): #, """There can only be one of every N3Set """ res = {} def __init__(self, stuff=[]): """something""" ImmutableSet.__init__(self, stuff) def __new__(cls, stuff=[]): new_set = ImmutableSet.__new__(cls, stuff) new_set.__init__(stuff) if new_set in cls.res: return cls.res[new_set] cls.res[new_set] = new_set return new_set ## def __setattr__(self, attr, value): ## print "%s=%s" % (`attr`, `value`) ## ImmutableSet.__setattr__(self, attr, value) def uriref(self): raise NotImplementedError def substitution(self, bindings, why=None, cannon=False): "Return this or a version of me with variable substitution made" if self.occurringIn(bindings.keys()) == Set(): return self # phew! return self.__class__([x.substitution(bindings, why=why, cannon=cannon) for x in self]) def substituteEquals(self, bindings, newBindings): "Return this or a version of me with substitution of equals made" if diag.chatty_flag > 100: progress("SubstituteEquals list %s with %s" % (self, bindings)) if self.occurringIn(bindings.keys()) == Set(): return self # phew! new = self.__class__([x.substitution(bindings, why=why) for x in self]) newBindings[self] = new return new def occurringIn(self, vars): union = Set.union return reduce(union, [x.occurringIn(vars) for x in self], Set()) def asSequence(self): return self def classOrder(self): return 10 def unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55): return unifySet(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source) def compareTerm(self, other): """This is annoying """ def my_max(the_set): Max = None for a in the_set: if Max == None or a.compareAnyTerm(Max) > 0: Max = a return Max s1 = self - other s2 = other - self max1 = my_max(s1) max2 = my_max(s2) if max1 is max2: return 0 if max1 is None: return -1 if max2 is None: return 1 return max1.compareAnyTerm(max2) def freeVariables(self): union = Set.union return reduce(union, [x.freeVariables() for x in self], Set()) class List(CompoundTerm): def __init__(self, store, first, rest): # Do not use directly global _nextList Term.__init__(self, store) self.first = first self.rest = rest self._prec = {} self._id = _nextList _nextList = _nextList + 1 def uriref(self): return runNamespace() + "li"+ `self._id` def prepend(self, first): x = self._prec.get(first, None) if x != None: return x x = NonEmptyList(self.store, first, self) self._prec[first] = x return x def __iter__(self): """The internal method which allows one to iterate over the statements as though a formula were a sequence. """ x = self while x is not self.store.nil: yield x.first x = x.rest def __len__(self): """The internal method which allows one to count the statements as though a formula were a sequence. """ x = self i = 0 while x is not self.store.nil: i = i + 1 x = x.rest return i def value(self): res = [] for x in self: res.append(x.value()) return res def substitution(self, bindings, why=None, cannon=False): "Return this or a version of me with variable substitution made" if self.occurringIn(bindings.keys()) == Set(): return self # phew! s = self.asSequence() s.reverse() tail = self.store.nil for x in s: tail = tail.prepend(x.substitution(bindings, why=why, cannon=cannon)) if diag.chatty_flag > 90: progress("Substition of variables %s in list %s" % (bindings, self)) progress("...yields NEW %s = %s" % (tail, tail.value())) return tail def substituteEquals(self, bindings, newBindings): "Return this or a version of me with substitution of equals made" if diag.chatty_flag > 100: progress("SubstituteEquals list %s with %s" % (self, bindings)) if self.occurringIn(bindings.keys()) == Set(): return self # phew! s = self.asSequence() s.reverse() tail = self.store.nil for x in s: tail = tail.prepend(x.substituteEquals(bindings, newBindings)) newBindings[self] = tail # record a new equality self.generated = lambda : True if diag.chatty_flag > 90: progress("SubstitueEquals list CHANGED %s -> %s" % (self, tail)) return tail def occurringIn(self, vars): "Which variables in the list occur in this list?" set = Set() x = self while not isinstance(x, EmptyList): y = x.first x = x.rest import types set = set | y.occurringIn(vars) if self in vars: set.add(self) return set def asSequence(self): "Convert to a python sequence - NOT recursive" res = [] x = self while x is not self.store.nil: res.append(x.first) x = x.rest return res def doesNodeAppear(self, symbol): """Does that particular node appear anywhere in this list This function is necessarily recursive, and is useful for the pretty printer. It will also be useful for the flattener, when we write it. """ for elt in self: val = 0 if isinstance(elt, CompoundTerm): val = val or elt.doesNodeAppear(symbol) elif elt == symbol: val = 1 else: pass if val == 1: print 'I won!' return 1 return 0 def freeVariables(self): union = Set.union return reduce(union, [x.freeVariables() for x in self], Set()) class NonEmptyList(List): def classOrder(self): return 3 def compareTerm(self, other): "Assume is also a NonEmptyList - see function compareTerm in formula.py" s = self o = other while 1: if isinstance(o, EmptyList): return -1 if isinstance(s, EmptyList): return 1 diff = s.first.compareAnyTerm(o.first) if diff != 0: return diff s = s.rest o = o.rest ## def unify(self, other, vars=Set([]), existentials=Set([]), bindings={}): ## """See Term.unify()""" ## if diag.chatty_flag > 90: ## progress("Unifying list %s with %s vars=%s, so far=%s"% ## (self.value(), other.value(),vars, bindings)) ## if not isinstance(other, NonEmptyList): return [] ## if other is self: return [ ({}, None)] ## ## # Using the sequence-like properties of lists: ## return unifySequence(self, other, vars, existentials, bindings) def unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55): return unifySequence(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source) def debugString(self, already=[]): s = `self`+" is (" for i in self: s = s + i.debugString(already) + " " return s + ")" # def __repr__(self): # return "(" + `self.first` + "...)" def __getitem__(self, i): p = self while 1: if i == 0: return p.first p = p.rest if not isinstance(p, NonEmptyList): raise ValueError("Index %i exceeds size of list %s" % (i, `self`)) i = i - 1 class EmptyList(List): def classOrder(self): return 2 def value(self): return [] def uriref(self): return List_NS + "nil" def substitution(self, bindings, why=None, cannon=False): "Return this or a version of me with substitution made" return self def substituteEquals(self, bindings, newBindings): "Return this or a version of me with substitution of equals made" return self def __repr__(self): return "()" def newList(self, value): x = self l = len(value) if l == 0: return x try: value[0] except TypeError: for a in value: x = x.prepend(a) else: while l > 0: l = l - 1 x = x.prepend(value[l]) return x ## def unify(self, other, vars=Set([]), existentials=Set([]), bindings={}): ## """Unify the substitution of this using bindings found so far ## with the other. This may contain variables, the other may contain ## existentials but not variables. ## Return [] if impossible. ## Return [({}, None)] if no new bindings ## Return [( {var1: val1, var2: val2, ...}, reason) ...] if match. ## bindings is a dictionary.""" ## assert type(bindings) is type({}) ## if self is other: return [({}, None)] ## return [] def occurringIn(self, vars): return Set() def __repr__(self): return "()" def __getitem__(self, i): raise ValueError("Index %i exceeds size of empty list %s" % (i, `self`)) class FragmentNil(EmptyList, Fragment): " This is unique in being both a symbol and a list" def __init__(self, resource, fragid): Fragment.__init__(self, resource, fragid) EmptyList.__init__(self, self.store, None, None) self._asList = self def unifySequence(self, other, vars=Set([]), existentials=Set([]), bindings={}, start=0): """Utility routine to unify 2 python sequences of things against each other Slight optimization to iterate instead of recurse when no binding happens. """ if diag.chatty_flag > 99: progress("Unifying sequence %s with %s" % (`self`, `other`)) i = start if len(self) != len(other): return [] while 1: nbs = unify(self[i], other[i], vars, existentials, bindings) if nbs == []: return [] # Match fail i = i +1 if i == len(self): return nbs if nbs != [({}, None)]: break # Multiple bundings try: for a,b in nbs: pass except TypeError: progress("Bad nbs, should be seq of pairs: >>>" + `nbs` + "<<<") raise res = [] for nb, reason in nbs: b2 = bindings.copy() b2.update(nb) done = Set(nb.keys()) nbs2 = unifySequence(self, other, vars.difference(done), existentials.difference(done), b2, start=i) # if nbs2 == []: return [] No, don't return ... may be others for nb2, reason2 in nbs2: nb3 = nb2.copy() nb3.update(nb) res.append((nb3, None)) return res def unifySet(self, other, vars=Set([]), existentials=Set([]), bindings={}): """Utility routine to unify 2 python sets of things against each other No optimization! This is of course the graph match function implemented with indexing, and built-in functions, in query.py. """ if diag.chatty_flag > 99: progress("Unifying set %s with %s" % (`self`, `other`)) if len(self) != len(other): return [] # Match fail if self == Set([]): return [ ({}, None) ] # Perfect match self2 = self.copy() # Don't mess with parameters s = self2.pop() # Pick one res = [] for o in other: nbs = unify(s, o, vars, existentials, bindings) if nbs == []: continue other2 = other.copy() other2.remove(o) for nb, reason in nbs: # For each way the object matched, b2 = bindings.copy() b2.update(nb) done = Set(nb.keys()) nbs2 = unifySet(self2, other2, # Try the rest of the set vars.difference(done), existentials.difference(done), b2) if nbs2 == []: continue # try next case for the object for nb2, reason2 in nbs2: nb3 = nb2.copy() nb3.update(nb) res.append((nb3, None)) # Add next total case return res def betterUnifySet(self, other, vars=Set([]), existentials=Set([]), bindings={}): """We need to be smarter about this there are the following catagories : atoms variable atoms lists of only lists and atoms (recursive) lists of only lists and atoms (recursive), some of which may be variables lists containing sets sets in about that order of difficulty. Can we use this? strategy: Usually, we will only have a set of triples (of ... ) remove all ground ones. Match those directly off the bat (note: a ground set is NOT good enough!) This is looking complex look at all simple ones, generating binding possibilities then deal with sets """ def all_list(l, vars): m = True n = True for k in l: if isinstance(k, list_type): m_, n_ = all_list(k, vars) m = m and m_ n = n and n_ if isinstance(k, set_type): return False, False if k in vars: n = False return m, n atoms = Set() trivials = Set() someSubstitutionNeeded = Set() hard = Set() for s in self: if isinstance(s, atom): atoms.add(s) elif isinstance(s, list_type): lists, grounded = all_list(s, vars) if lists and grounded: trivials.add(s) elif lists: someSubstitutionNeeded.add(s) else: hard.add(s) else: hard.add(s) #@@@todo atoms ## ## Now lists def matchSet(pattern, kb, vars=Set([]), bindings={}): """Utility routine to match 2 python sets of things. No optimization! This is of course the graph match function implemented with indexing, and built-in functions, in query.py. This only reuires the first to include the second. vars are things to be regarded as variables in the pattern. bindings map from pattern to kb. """ if diag.chatty_flag > 99: progress("Matching pattern %s against %s, vars=%s" % (`pattern`, `kb`, `vars`)) if len(pattern) > len(kb): return [] # Match fail @@@discuss corner cases if len(pattern) == 0: return [(bindings, None)] # Success pattern2 = pattern.copy() # Don't mess with parameters o = pattern2.pop() # Pick one res = [] for s in kb: # Really slow recursion unaided by indexes nbs = unify(o, s, vars, Set([]), bindings) if nbs == []: continue kb2 = kb.copy() kb2.remove(s) for nb, reason in nbs: b2 = bindings.copy() b2.update(nb) done = Set(nb.keys()) nbs2 = matchSet(pattern2, kb2, vars.difference(done), b2) if nbs2 == []: continue for nb2, reason2 in nbs2: nb3 = nb2.copy() nb3.update(nb) res.append((nb3, None)) return res # Failed to match the one we picked #### Everything that follows are the new unification routines class ListView(object): def __init__(self, list, start=0): self.list = list self.start = start def _car(self): return self.list[self.start] car = property(_car) def _cdr(self): return ListView(self.list, self.start+1) cdr = property(_cdr) def __len__(self): return len(self.list) - self.start def unify(self, other, vars=Set([]), existentials=Set([]), bindings={}): """Unify something whatever it is See Term.unify """ if diag.chatty_flag > 100: progress("Unifying %s with %s" %(self, other)) if isinstance(self, (Set, ImmutableSet)): return unifySet(self, other, vars, existentials, bindings) if type(self) is type([]): return unifySequence(self, other, vars, existentials, bindings) k = self.unify(other, vars, existentials, bindings) if k == 0: raise RuntimeError(other, other.__class__) return k def pickEnv(choice, *envs): for env in envs: if choice is env.id: return env return [] ## Not here. def dereference(node, env1, env2, source): s = pickEnv(source, env1, env2) while node in s: node, source = s.dereference(node) s = pickEnv(source, env1, env2) return node, source def unify(self, other, bindings=Env(), otherBindings=Env(), vars=Set([]), universals=Set([]), existentials=Set([]), n1Source=32, n2Source=32): if isinstance(self, list): self = tuple(self) if isinstance(other, list): other = tuple(other) env1 = bindings env2 = otherBindings if n1Source == 32: ## magic value: n1Source = env1.id if n2Source == 32: n2Source = env2.id if n1Source is env1.id: n1SourceString = 'env1.id' elif n1Source is env2.id: n1SourceString = 'env2.id' else: n1SourceString = 'unknown.id' if n2Source is env1.id: n2SourceString = 'env1.id' elif n2Source is env2.id: n2SourceString = 'env2.id' else: n2SourceString = 'unknown.id' if diag.chatty_flag > 500: progress("Running unify(vars=%s, n1=%s, env1=%s, n2=%s, env2=%s, n1Source=%s, n2Source=%s)" % (vars, self, env1, other, env2, n1SourceString, n2SourceString)) self, n1Source = dereference(self, env1, env2, n1Source) assert self not in env1 other, n2Source = dereference(other, env1, env2, n2Source) if self in vars and (pickEnv(n1Source, env1, env2) is not None): ## external vars if other in vars: ### all good if self == other and n1Source == n2Source: yield (env1, env2) else: ### bind one to the other. It really does not matter ### we need to be careful about envs envWithBinding = pickEnv(n1Source, env1, env2).bind(self,(other, n2Source)) if n1Source is env1.id: yield (envWithBinding, env2) elif n1Source is env2.id: yield (env1, envWithBinding) else: raise ValueError(id(n1Source), id(env1.id), id(env2.id)) else: ## only n1 is a variable if occurs_check(self, other, env2): ## This needs help ### we need to be careful about envs envWithBinding = pickEnv(n1Source, env1, env2).bind(self,(other, n2Source)) if n1Source is env1.id: yield (envWithBinding, env2) elif n1Source is env2.id: yield (env1, envWithBinding) else: raise ValueError elif other in vars and (pickEnv(n2Source, env1, env2) is not None): if occurs_check(other, self, env1): ## This needs help ### we need to be careful about envs envWithBinding = pickEnv(n2Source, env1, env2).bind(other,(self, n1Source)) if n2Source is env1.id: yield (envWithBinding, env2) elif n2Source is env2.id: yield (env1, envWithBinding) else: raise ValueError elif self is other: yield (env1, env2) ## life is good elif self in universals and other in universals: ### we need to be careful about envs newUniversal = Universal(self.store) envWithBinding = pickEnv(n1Source, env1, env2).bind(self,(newUniversal, -1)) if n1Source is env1.id: (env11, env21) = (envWithBinding, env2) elif n1Source is env2.id: (env11, env21) = (env1, envWithBinding) else: raise ValueError envWithBinding = pickEnv(n2Source, env11, env21).bind(other,(newUniversal, -1)) if n2Source is env1.id: yield (envWithBinding, env21) elif n2Source is env2.id: yield (env11, envWithBinding) else: raise ValueError elif self in existentials and other in existentials: ### we need to be careful about envs newExistential = Existential(self.store) envWithBinding = pickEnv(n1Source, env1, env2).bind(self,(newExistential, -1)) if n1Source is env1.id: (env11, env21) = (envWithBinding, env2) elif n1Source is env2.id: (env11, env21) = (env1, envWithBinding) else: raise ValueError envWithBinding = pickEnv(n2Source, env11, env21).bind(other,(newExistential, -1)) if n2Source is env1.id: yield (envWithBinding, env21) elif n2Source is env2.id: yield (env11, envWithBinding) else: raise ValueError elif isinstance(self, (Set, ImmutableSet)): for x in unifySet(self, other, env1, env2, vars, existentials, n1Source=n1Source, n2Source=n2Source): yield x elif type(self) is tuple: for x in unifySequence(self, other, env1, env2, vars, existentials, n1Source=n1Source, n2Source=n2Source): yield x elif hasattr(self, 'unifySecondary') and hasattr(other, 'unifySecondary'): if self.unifySecondary.im_func is other.unifySecondary.im_func: # A reasonable definition of same type for x in self.unifySecondary(other, env1, env2, vars, universals, existentials, n1Source=n1Source, n2Source=n2Source): yield x def unifySequence(self, other, bindings=Env(), otherBindings=Env(), vars=Set([]), universals=Set([]), existentials=Set([]), n1Source=32, n2Source=32): if not isinstance(self, ListView): self = ListView([x for x in self]) if not isinstance(other, ListView): other = ListView([x for x in other]) def car(x): return x.car def cdr(x): return x.cdr if len(self) == len(other): if self: for (env11, env21) in unify(car(self), car(other), bindings, otherBindings, vars, universals, existentials, n1Source, n2Source): for (env12, env22) in unifySequence(cdr(self), cdr(other), env11, env21, vars, universals, existentials, n1Source, n2Source): yield (env12, env22) else: yield (bindings, otherBindings) def unifySet(self, other, bindings=Env(), otherBindings=Env(), vars=Set([]), universals=Set([]), existentials=Set([]), n1Source=32, n2Source=32): if len(self) == len(other): if self: self = Set(self) me = self.pop() for k in other: other2 = Set(other) other2.remove(k) for (env11, env21) in unify(me, k, env1, env2, vars, universals, existentials, n1Source, n2Source): for (env12, env22) in unify(self, other2, env11, env21, vars, universals, existentials, n1Source, n2Source): yield(env12, env22) else: yield (env1, env2) def occurs_check(self, other, env2): return not other.occurringIn(set([self])) return True ### @@@ Need real check ########################################################################## # # L I T E R A L S def toBool(val, dt=None): if dt is None: return bool(val) xsd = dt.store.integer.resource if dt.resource is xsd: dt = dt.fragid if dt == 'boolean': if val == 'false' or val == 'False' or val == '0': return False if val == 'true' or val == 'True' or val == '1': return True raise ValueError('"%s" is not a valid boolean' % val) if dt in typeMap: return bool(typeMap[dt](val)) raise TypeError("%s type cannot be converted to boolean" % val) typeMap = { "decimal": Decimal, "integer": long, "nonPositiveInteger": long, "negativeInteger": long, "long": int, "int": int, "short": int, "byte": int, "nonNegativeInteger": long, "unsignedLong": int, "unsignedInt": int, "unsignedShort": int, "unsignedByte": int, "positiveInteger": long, "boolean": toBool, "double": float, "float": float, "duration": unicode, "dateTime": unicode, "time": unicode, "date": unicode, "gYearMonth": unicode, "gYear": unicode, "gMonthDay": unicode, "gDay": unicode, "gMonth": unicode, "anyURI": unicode, "QName": unicode, "NOTATION": unicode, "string": unicode, "normalizedunicodeing": unicode, "token": unicode, "language": unicode, "Name": unicode, "NCNAME": unicode, "ID": unicode, "IDREF": unicode, "IDREFS": unicode, "ENTITY": unicode, "ENTITIES": unicode, "NMTOKEN": unicode, "NMTOKENS": unicode} ## ## We don't support base64Binary or hexBinary ## class Literal(Term): """ A Literal is a representation of an RDF literal really, data:text/rdf+n3;%22hello%22 == "hello" but who wants to store it that way? Maybe we do... at least in theory and maybe practice but, for now, we keep them in separate subclases of Term. An RDF literal has a value - by default a string, and a datattype, and a language. """ def __init__(self, store, str, dt=None, lang=None): Term.__init__(self, store) self.string = str # n3 notation EXcluding the " " self.datatype = dt # assert dt is None or isinstance(dt, Fragment) self.lang=lang def __str__(self): return self.string def __int__(self): return int(self.string) def __float__(self): return float(self.string) def __decimal__(self): return Decimal(self.string) def occurringIn(self, vars): return Set() def __repr__(self): if len(self.string) < 8: return '"%s"' % self.string.encode('unicode_escape') return unicode('"' + self.string[0:4] + '...' + self.string[-4:] + '"').encode('unicode_escape')# return self.string def asPair(self): if self.datatype: return LITERAL_DT, (self.string, self.datatype.uriref()) if self.lang: return LITERAL_LANG, (self.string, self.lang) return (LITERAL, self.string) def classOrder(self): return 1 def compareTerm(self, other): "Assume is also a literal - see function compareTerm in formula.py" if self.datatype == other.datatype: diff = cmp(self.string, other.string) if diff != 0 : return diff return cmp(self.lang, other.lang) else: if self.datatype == None: return -1 if other.datatype == None: return 1 return self.datatype.compareAnyTerm(other.datatype) def asHashURI(self): """return a md5: URI for this literal. Hmm... encoding... assuming utf8? @@test this. Hmm... for a class of literals including this one, strictly speaking.""" x=md5.new() x.update(self.string) d=x.digest() b16=binascii.hexlify(d) return "md5:" + b16 def substitution(self, bindings, why=None, cannon=False): "Return this or a version of me with subsitution made" return self def substituteEquals(self, bindings, newBindings): "Return this or a version of me with subsitution made" return self def representation(self, base=None): return '"' + self.string + '"' # @@@ encode quotes; @@@@ strings containing \n def value(self): """Datatype conversion XSD to Python RDF primitive datatypes are XML schema datatypes, in the XSD namespace. see http://www.w3.org/TR/xmlschema-2 """ global typeMap if self.datatype == None: return self.string xsd = self.store.integer.resource if self.datatype.resource is xsd: try: return typeMap[self.datatype.fragid](self.string) except KeyError: raise UnknownType( "Attempt to run built-in on unsupported XSD datatype %s of value %s." % (`self.datatype`, self.string)) raise UnknownType("Attempt to run built-in on unknown datatype %s of value %s." % (`self.datatype`, self.string)) def uriref(self): # Unused at present but interesting! 2000/10/14 # used in test/sameTerm.n3 testing 2001/07/19 return self.asHashURI() #something of a kludge? #return LITERAL_URI_prefix + uri_encode(self.representation()) # tbl preferred from xmlC14n import Canonicalize # http://dev.w3.org/cvsweb/2001/xmlsec-python/c14n.py?rev=1.10 class XMLLiteral(Literal): """ A Literal is a representation of an RDF literal really, data:text/rdf+n3;%22hello%22 == "hello" but who wants to store it that way? Maybe we do... at least in theory and maybe practice but, for now, we keep them in separate subclases of Term. An RDF literal has a value - by default a string, and a datattype, and a language. """ def __init__(self, store, dom): Term.__init__(self, store) self.dom = dom # n3 notation EXcluding the " " self.string = None # Only made when needed but then cached self.datatype = store.symbol("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral") # assert dt is None or isinstance(dt, Fragment) self.lang=None def __str__(self): if not self.string: self.string = ''.join([Canonicalize(x, None, unsuppressedPrefixes=[]) for x in self.dom.childNodes]) return self.string def __int__(self): return int(self.__str__()) def __float__(self): return float(self.__str__()) def __decimal__(self): return Decimal(self.__str__()) def occurringIn(self, vars): return Set() def __repr__(self): self.__str__() return '"' + self.string[0:7] + '...' + self.string[-4:] + '"' # return self.string def asPair(self): return (XMLLITERAL, self.dom) def classOrder(self): return 1.5 def compareTerm(self, other): "Assume is also a literal - see function compareTerm in formula.py" if self.datatype == other.datatype: diff = cmp(unicode(self), unicode(other)) return diff return cmp(self.lang, other.lang) else: if self.datatype == None: return -1 if other.datatype == None: return 1 return self.datatype.compareAnyTerm(other.datatype) def asHashURI(self): """return a md5: URI for this literal. Hmm... encoding... assuming utf8? @@test this. Hmm... for a class of literals including this one, strictly speaking.""" x=md5.new() x.update(self.__str__()) d=x.digest() b16=binascii.hexlify(d) return "md5:" + b16 def substitution(self, bindings, why=None, cannon=False): "Return this or a version of me with subsitution made" return self def substituteEquals(self, bindings, newBindings): "Return this or a version of me with subsitution made" return self def representation(self, base=None): return '"' + str(self) + '"' # @@@ encode quotes; @@@@ strings containing \n def value(self): """Datatype conversion XSD to Python The internal reopresentation is the dom tree """ return self.dom def uriref(self): # Unused at present but interesting! 2000/10/14 # used in test/sameTerm.n3 testing 2001/07/19 return self.asHashURI() #something of a kludge? #return LITERAL_URI_prefix + uri_encode(self.representation()) # tbl preferred #class Integer(Literal): # """Unused""" # def __init__(self, store, str): # Term.__init__(self, store) # self.datatype = store.integer # self.lang=None # self._value = int(str) # # def __int__(self): # return self._value # # def __str__(self): # return str(self._value) # # def __repr__(self): # return str(self._value) # # def representation(self, base=None): # return str(self._value) # # def value(self): # return self._value #I think I'll replace this with urllib.quote ##def uri_encode(str): ## """ untested - this must be in a standard library somewhere ## """ ## result = "" ## i=0 ## while i<"', str[i]) <0 : # @@@ etc ## result.append("%%%2x" % (atoi(str[i]))) ## else: ## result.append(str[i]) ## return result from urllib import quote as uri_encode ################################################################################ # # Built-in master classes # # These are resources in the store which have processing capability. # Each one has to have its own class, and each inherits from various of the # generic classes below, according to its capabilities. # # First, the template classes: # class BuiltIn(Fragment): """This class is a supercalss to any builtin predicate in cwm. A binary operator can calculate truth value given 2 arguments""" def __new__(cls, *args, **keywords): self = Fragment.__new__(cls, *args, **keywords) BuiltIn.all.append(self) # to prevent the forgetting of builtins return self all = [] def __init__(self, resource, fragid): Fragment.__init__(self, resource, fragid) def eval(self, subj, obj, queue, bindings, proof, query): """This function which has access to the store, unless overridden, calls a simpler one which uses python conventions. To reduce confusion, the inital ones called with the internals available use abreviations "eval", "subj" etc while the python-style ones use evaluate, subject, etc.""" if hasattr(self, "evaluate"): if (not isinstance(subj, (Literal, CompoundTerm)) or not isinstance(obj, (Literal, CompoundTerm))): raise ArgumentNotLiteral(subj, obj) return self.evaluate(subj.value(), obj.value()) elif isinstance(self, Function): return Function.eval(self, subj, obj, queue, bindings, proof, query) elif isinstance(self, ReverseFunction): return ReverseFunction.eval(self, subj, obj, queue, bindings, proof, query) raise RuntimeError("Instance %s of built-in has no eval() or subsititue for it" %`self`) class GenericBuiltIn(BuiltIn): def __init__(self, resource, fragid): Fragment.__init__(self, resource, fragid) class ArgumentNotLiteral(TypeError): pass class UnknownType(ValueError): pass class LightBuiltIn(GenericBuiltIn): """A light built-in is fast and is calculated immediately before searching the store. Make your built-in a subclass of either this or HeavyBultIn to tell cwm when to run it. Going out onto the web or net counts as heavy.""" pass class RDFBuiltIn(LightBuiltIn): """An RDF built-in is a light built-in which is inherent in the RDF model. The only examples are (I think) rdf:first and rdf:rest which in the RDF model are arcs but in cwm have to be builtins as Lists a a first class data type. .""" pass class HeavyBuiltIn(GenericBuiltIn): """A heavy built-in is fast and is calculated late, after searching the store to see if the answer is already in it. Make your built-in a subclass of either this or LightBultIn to tell cwm when to run it. Going out onto the web or net counts as Heavy.""" pass # A function can calculate its object from a given subject. # Example: Joe mother Jane . class Function(BuiltIn): """A function is a builtin which can calculate its object given its subject. To get cwm to invoke it this way, your built-in must be a subclass of Function. I may make changes to clean up the parameters of these methods below some day. -tbl""" def __init__(self): pass def evalObj(self, subj, queue, bindings, proof, query): """This function which has access to the store, unless overridden, calls a simpler one which uses python conventions. To reduce confusion, the inital ones called with the internals available use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.""" if not isinstance(subj, (Literal, CompoundTerm)): raise ArgumentNotLiteral return self.store._fromPython(self.evaluateObject(subj.value())) # This version is used by functions by default: def eval(self, subj, obj, queue, bindings, proof, query): F = self.evalObj(subj, queue, bindings, proof, query) return F is obj class ReverseFunction(BuiltIn): """A reverse function is a builtin which can calculate its subject given its object. To get cwm to invoke it this way, your built-in must be a subclass of ReverseFunction. If a function (like log:uri for example) is a two-way (1:1) builtin, it should be declared a subclass of Function and ReverseFunction. Then, cwm will call it either way as needed in trying to resolve a query. """ def __init__(self): pass def eval(self, subj, obj, queue, bindings, proof, query): F = self.evalSubj(obj, queue, bindings, proof, query) return F is subj def evalSubj(self, obj, queue, bindings, proof, query): """This function which has access to the store, unless overridden, calls a simpler one which uses python conventions""" if not isinstance(obj, (Literal, CompoundTerm)): raise ArgumentNotLiteral(obj) return self.store._fromPython(self.evaluateSubject(obj.value())) class MultipleFunction(Function): """Multiple return values. The preconditions are the same as for Function, that the subject must be bound. The result is different, as multiple versions are returned. Example: member of list. """ def evalSubj(self, obj, queue, bindings, proof, query): """This function which has access to the store, unless overridden, calls a simpler one which uses python conventions. The python one returns a list of function values. This returns a 'new bindings' structure (nbs) which is a sequence of (bindings, reason) pairs.""" if not isinstance(obj, (Literal, CompoundTerm)): raise ArgumentNotLiteral(obj) return self.store._fromPython(self.evaluateSubject(subj.value())) # results = self.store._fromPython(self.evaluateSubject(obj.value())) # return [ ({subj: x}, None) for x in results] class MultipleReverseFunction(ReverseFunction): """Multiple return values""" def evalObj(self, subj, queue, bindings, proof, query): if not isinstance(subj, (Literal, CompoundTerm)): raise ArgumentNotLiteral(subj) return self.store._fromPython(self.evaluateObject(obj.value())) # results = self.store._fromPython(self.evaluateObject(obj.value())) # return [ ({subj: x}, None) for x in results] class FiniteProperty(GenericBuiltIn, Function, ReverseFunction): """A finite property has a finite set of pairs of (subj, object) values The built-in finite property can ennumerate them all if necessary. Argv is the only useful example I can think of right now. """ # def __init__(self, resource, fragid): # Fragment.__init__(self, resource, fragid) def enn(self): " Return list of pairs [(subj, obj)]" for s, o in self.ennumerate(): yield self.store._fromPython(s), self.store._fromPython(o) def ennumerate(self): raise RuntimeError("Not implemented fbuilt-in") def evalSubj(self, obj, queue, bindings, proof, query): """This is of course very inefficient except for really small ones like argv.""" for s, o in self.ennum(): if o is obj: return s return None def evalObj(self, subj, queue, bindings, proof, query): """This is of course very inefficient except for really small ones like argv.""" for s, o in self.ennum(): if s is subj: return o return None def eval(self, subj, obj, queue, bindings, proof, query): """This is of course very inefficient except for really small ones like argv.""" for s, o in self.ennum(): if s is subj: return o return (subj, obj) in self.ennum() # For examples of use, see, for example, cwm_*.py cwm-1.2.1/swap/importList.py0000644015216600007660000000126110640230455015106 0ustar syosisyosi#!/usr/bin/env python """importList.py Generate a list of files imported by the files given on the command line """ from modulefinder import ModuleFinder import os.path import os import sys import uripath def main(argv): path = sys.path[:] path[0] = os.path.dirname(argv[0]) mf = ModuleFinder(path) for f in argv: mf.run_script(f) paths = sorted(list(set([os.path.abspath(x.__file__) for x in mf.modules.values() if x.__file__]))) cwd = os.getcwd() paths = [x for x in paths if x.startswith(cwd)] m = len(cwd) + 1 paths = argv + [x[m:] for x in paths] print ' '.join(paths) if __name__ == '__main__': main(sys.argv) cwm-1.2.1/swap/RDFSink.py0000644015216600007660000003575710640075637014232 0ustar syosisyosi#!/usr/bin/python """RDFSink -- RDF parser/serializer/store interface This is a simple API for a push-stream of RDF data. It doesn't use a particular classof obejcts, but just uses python pairs. It is kinda crude but it does allow for example data to be squirted efficiently between modules which use different python classes for RDF. HISTORY This module was factored out of notation3.py REFERENCES Python Style Guide Author: Guido van Rossum http://www.python.org/doc/essays/styleguide.html """ __version__ = "$Id: RDFSink.py,v 1.36 2007/06/26 02:36:15 syosi Exp $" import uripath import time from warnings import warn from diag import progress # The statement is stored as a quad - affectionately known as a triple ;-) # offsets when a statement is stored as a Python tuple (c, p, s, o) CONTEXT = 0 PRED = 1 SUBJ = 2 OBJ = 3 PARTS = PRED, SUBJ, OBJ ALL4 = CONTEXT, PRED, SUBJ, OBJ # A sink takes quads where each item is a pair type, value # However, the recopmmended way is for the source to call the factory methods new* rather # than just make up pairs. SYMBOL = 0 # URI which or may not have a fragment. # (formerly: RESOURCE) FORMULA = 1 # A { } set of statements. (identifier is arbitrary) LITERAL = 2 # string, untyped RDF literal. x[1] is a string or unicode string LITERAL_DT = 21 # typed RDF literal x[1] is a pair (string, datatype URI) LITERAL_LANG = 22 # Language RDF literal x[1] is a pair (string, langauge) ANONYMOUS = 3 # As SYMBOL except actual symbol is arbitrary, can be regenerated XMLLITERAL = 25 # A DOM tree encases in a dummy document level # quanitifiers... @@it's misleading to treat these as predicates... Logic_NS = "http://www.w3.org/2000/10/swap/log#" # For some graphs you can express with NTriples, there is no RDF syntax. The # following allows an anonymous node to be merged with another node. # It really is the same node, at the ntriples level, do not confuse with daml:sameAs NODE_MERGE_URI = Logic_NS + "is" # Pseudo-property indicating node merging forSomeSym = Logic_NS + "forSome" forAllSym = Logic_NS + "forAll" RDF_type_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" RDF_NS_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" # DAML_NS=DPO_NS = "http://www.daml.org/2001/03/daml+oil#" # DAML plus oil OWL_NS = "http://www.w3.org/2002/07/owl#" DAML_sameAs_URI = OWL_NS+"sameAs" parsesTo_URI = Logic_NS + "parsesTo" RDF_spec = "http://www.w3.org/TR/REC-rdf-syntax/" #List_NS = DPO_NS # We have to pick just one all the time List_NS = RDF_NS_URI # From 20030808 _Old_Logic_NS = "http://www.w3.org/2000/10/swap/log.n3#" # For lists: N3_first = (SYMBOL, List_NS + "first") N3_rest = (SYMBOL, List_NS + "rest") N3_li = (SYMBOL, List_NS + "li") N3_nil = (SYMBOL, List_NS + "nil") N3_List = (SYMBOL, List_NS + "List") N3_Empty = (SYMBOL, List_NS + "Empty") # Standard python modules: from os import getpid from time import time from uripath import base, join # SWAP modules: from diag import verbosity, progress from os import environ runNamespaceValue = None def runNamespace(): "Return a URI suitable as a namespace for run-local objects" # @@@ include hostname (privacy?) (hash it?) global runNamespaceValue if runNamespaceValue == None: try: runNamespaceValue = environ["CWM_RUN_NS"] except KeyError: runNamespaceValue = uripath.join( uripath.base(), ".run-" + `time()` + "p"+ `getpid()` +"#") runNamespaceValue = join(base(), runNamespaceValue) # absolutize return runNamespaceValue nextu = 0 def uniqueURI(): "A unique URI" global nextu nextu += 1 return runNamespace() + "u_" + `nextu` class URISyntaxError(ValueError): """A parameter is passed to a routine that requires a URI reference""" pass class RDFSink: """interface to connect modules in RDF processing. OBSOLETE This is a superclass for other RDF processors which accept RDF events or indeed Swell events. It is superceded, effectively, by the class Formula, as a sink of data and a soiurce of new symbols. Keeps track of prefixes. This interface has the advantage that it does n ot have any dependencies on object types, it is really one-way (easily serialized as no return values). It has the disadvantages that - It uses the pseudoproperties log:forSome and log:forAll to make variables, which is a bit of a kludge. - It may involve on the receiver side the same thing being interned many times, which wastes time searching hash tables. The superclass handles common functions such as craeting new arbitray identifiers """ def __init__(self, genPrefix=None): """If you give it a URI prefix to use for generated IDs it will use one; otherwise, it will use the name of an imaginary temporary file in the current directory.""" self.prefixes = { } # Convention only - human friendly to # track these. self.namespaces = {} # reverse mapping of prefixes self.defaultNamespace = None self.usingRunNamespace = 0 self.declaredRunNamespace = 0 self._counts = {} # How many times each namespace is used self._genPrefix = genPrefix if genPrefix == None: self._genPrefix = runNamespace() + "_g" self.usingRunNamespace = 1 self._nextId = 0 self.stayOpen = 0 # Delay close because more data coming if >0 def startDoc(self): pass def endDoc(self, rootFormulaPair): """End a document Call this once only at the end of parsing so that the receiver can wrap things up, oprimize, intern, index and so on. The pair given is the (type, value) identifier of the root formula of the thing parsed.""" pass def reopen(self): """Un-End a document If you have added stuff to a document, thought you were done, and then want to add more, call this to get back into the sate that makeSatement is again acceptable. Remember to end the document again when done.""" pass def makeStatement(self, tuple, why=None): """add a statement to a stream/store. raises URISyntaxError on bad URIs tuple is a quad (context, predicate, subject, object) of things generated by calls to newLiteral etc why is reason for the statement. """ pass def intern(self, something): return something def newList(self, l, context): if l == []: return self.newSymbol('http://www.w3.org/1999/02/22-rdf-syntax-ns#nil') a = self.newBlankNode(context) first = self.newSymbol('http://www.w3.org/1999/02/22-rdf-syntax-ns#first') rest = self.newSymbol('http://www.w3.org/1999/02/22-rdf-syntax-ns#rest') self.makeStatement((context, first, a, l[0])) self.makeStatement((context, rest, a, self.newList(l[1:], context))) return a def countNamespace(self, namesp): "On output, count how many times each namespace is used" try: self._counts[namesp] += 1 except KeyError: self._counts[namesp] = 1 def namespaceCounts(self): return self._counts def bind(self, prefix, uri): """Pass on a binding hint for later use in output This really is just a hint. The parser calls bind to pass on the prefix which it came across, as this is a useful hint for a human readable prefix for output of the same namespace. Otherwise, output processors will have to invent or avoid useing namespaces, which will look ugly """ if ':' not in uri: # @@ should raise an exception, but sax callbacks crash. warn("@@URI must be absolute: %s" % uri) # If we don't have a prefix for this ns... if self.prefixes.get(uri, None) == None: if self.namespaces.get(prefix,None) == None: # For conventions self.prefixes[uri] = prefix self.namespaces[prefix] = uri if verbosity() > 29: progress("RDFSink.bind: prefix %s: to <%s>. "%(prefix, uri)) else: self.bind(prefix+"_", uri) # Recursion unnecessary def setDefaultNamespace(self, uri): """Pass on a binding hint for later use in output This really is just a hint. The parser calls this to pass on the default namespace which it came across, as this is a useful hint for a human readable prefix for output of the same namespace. Otherwise, output processors will have to invent or avoid useing namespaces, which will look ugly. """ self.defaultNamespace = uri def makeComment(self, str): """This passes on a comment line which of course has no semantics. This is only useful in direct piping of parsers to output, to preserve comments in the original file. """ pass def genId(self): subj = None while not subj: subj = self._genPrefix assert subj # don't mask bugs subj = subj + `self._nextId` self._nextId = self._nextId + 1 try: self.checkNewId(subj) # For a store, just in case, check really unique except ValueError: subj = None if self.usingRunNamespace and not self.declaredRunNamespace: self.declaredRunNamespace = 1 ns = self._genPrefix hash = ns.find("#") self.bind("run", ns[:hash+1]) return subj def setGenPrefix(self, genPrefix): if not self._genPrefix: self._genPrefix = genPrefix def newLiteral(self, str, dt=None, lang=None): if dt != None: return (LITERAL_DT, (str, dt)) # raise ValueError("This sink cannot accept datatyped values") if lang != None: return (LITERAL_LANG, (str, lang)) # raise ValueError("This sink cannot accept values with languages") return (LITERAL, str) def newXMLLiteral(self, doc): return (XMLLITERAL, doc) def newSymbol(self, uri): return (SYMBOL, uri) def newFormula(self, uri=None): if uri==None: return FORMULA, self.genId() else: return (FORMULA, uri) def newBlankNode(self, context, uri=None, why=None): return self.newExistential(context, uri, why=why) def checkNewId(self, uri): """The store can override this to raise an exception if the id is not in fact new. This is useful because it is usfeul to generate IDs with useful diagnostic ways but this lays them open to possibly clashing in pathalogical cases.""" return def newUniversal(self, context, uri=None, why=None): if uri==None: subj = ANONYMOUS, self.genId() # ANONYMOUS means "arbitrary symbol" else: subj=(SYMBOL, uri) self.makeStatement((context, (SYMBOL, forAllSym), #pred context, #subj subj), why=why) # obj return subj def newExistential(self, context, uri=None, why=None): if uri==None: subj = ANONYMOUS, self.genId() else: subj=(SYMBOL, uri) self.makeStatement((context, (SYMBOL, forSomeSym), #pred context, #subj subj), why=why) # obj return subj class RDFStructuredOutput(RDFSink): # The foillowing are only used for structured "pretty" output of structrued N3. # They roughly correspond to certain syntax forms in N3, but the whole area # is just a kludge for pretty output and not worth going into unless you need to. # These simple versions may be inherited, by the reifier for example def startAnonymous(self, triple, isList=0): return self.makeStatement(triple) def endAnonymous(self, subject, verb): # Remind me where we are pass def startAnonymousNode(self, subj): pass def endAnonymousNode(self, endAnonymousNode): # Remove default subject, restore to subj pass def startFormulaSubject(self, context): pass def endFormulaSubject(self, subj): # Remove context pass def startFormulaObject(self, triple): return self.makeStatement(triple) def endFormulaObject(self, pred, subj): # Remove context pass from diag import printState class TracingRDFSink: """An implementation of the RDFSink interface which helps me understand it, especially how it gets used by parsers vs. by an RDF store. [ -sandro ] Set .backing to be some other RDFSink if you want to get proper results while tracing. Try: bash-2.04$ python cwm.py test/rules12.n3 --language=trace bash-2.04$ python cwm.py --pipe test/rules12.n3 --language=trace bash-2.04$ python cwm.py test/rules12.n3 --bySubject --language=trace ... and see the different outputs """ # These ones get called normally on a Sink... def __init__(self, outURI, base=None, flags=None): printState() self.backing = None def makeComment(self, comment): printState() if self.backing: self.backing.makeComment(comment) def startDoc(self): printState() if self.backing: self.backing.startDoc() def setDefaultNamespace(self, ns): printState() if self.backing: self.backing.setDefaultNamespace(ns) def bind(self, prefix, uri): printState() if self.backing: self.backing.bind(prefix, uri) def makeStatement(self, tuple, why=None): printState() if self.backing: self.backing.makeStatement(tuple, why) def endDoc(self, rootFormulaPair="<>"): printState() if self.backing: self.backing.endDoc(rootFormulaPair) # These ones get called when there's nesting, pretty-printed... def startFormulaSubject(self, context): printState() if self.backing: self.backing.startFormulaSubject(context) def endFormulaSubject(self, subj): printState() if self.backing: self.backing.endFormulaSubject(subj) def startFormulaObject(self, triple): printState() if self.backing: self.backing.startFormulaObject(triple) def endFormulaObject(self, pred, subj): printState() if self.backing: self.backing.endFormulaObject(pred, subj) # These are called by "cwm --pipe", they *need* backing to work. def newFormula(self, uri=None): printState() return self.backing.newFormula(uri) def newSymbol(self, uri): printState() return self.backing.newSymbol(uri) def newLiteral(self, str, dt=None, lang=None): printState() return self.backing.newSymbol(str, dt, lang) # ends cwm-1.2.1/swap/formula.py0000755015216600007660000011127110731067743014424 0ustar syosisyosifrom __future__ import generators #! /usr/bin/python """ $Id: formula.py,v 1.63 2007/12/16 00:22:59 syosi Exp $ Formula See: http://www.w3.org/DesignIssues/Notation3 Interfaces ========== The store stores many formulae, where one formula is what in straight RDF implementations is known as a "triple store". So look at the Formula class for a triple store interface. See also for comparison, a python RDF API for the Redland library (in C): http://www.redland.opensource.ac.uk/docs/api/index.html and the redfoot/rdflib interface, a python RDF API: http://rdflib.net/latest/doc/triple_store.html """ __version__ = '$Id: formula.py,v 1.63 2007/12/16 00:22:59 syosi Exp $'[1:-1] import types import StringIO import sys # for outputstrings. shouldn't be here - DWC from set_importer import Set, ImmutableSet, sorted import notation3 # N3 parsers and generators, and RDF generator import diag # problems importing the tracking flag, must be explicit it seems diag.tracking from diag import progress, verbosity, tracking from term import matchSet, \ AnonymousNode , AnonymousExistential, AnonymousUniversal, \ Term, CompoundTerm, List, \ unifySequence, unify from RDFSink import Logic_NS from RDFSink import CONTEXT, PRED, SUBJ, OBJ from RDFSink import FORMULA, SYMBOL from why import Because, isTopLevel ###################################### Forumula # # An atomic forumla is three terms holds(s, p, o) # A formula is # - an atomic formula # - a conjuction of formulas # - exists(x) F where F is a formula # - forall(x) F where F is a formula # These are kept in a normal form: # exists e1,e2,e3... forall u1,u2u3, ... # holds(s, p, o) and holds(s2,p2,o2) and ... class Formula(AnonymousNode, CompoundTerm): """A formula of a set of RDF statements, triples. (The triples are actually instances of StoredStatement.) Other systems such as jena and redland use the term "Model" for Formula. For rdflib, this is known as a TripleStore. Cwm and N3 extend RDF to allow a literal formula as an item in a triple. A formula is either open or closed. Initially, it is open. In this state is may be modified - for example, triples may be added to it. When it is closed, note that a different interned version of itself may be returned. From then on it is a constant. Only closed formulae may be mentioned in statements in other formuale. There is a reopen() method but it is not recommended, and if desperate should only be used immediately after a close(). """ def __init__(self, store, uri=None): AnonymousNode.__init__(self, store, uri) self.canonical = None # Set to self if this has been canonicalized self.statements = [] self._existentialVariables = Set() self._universalVariables = Set() self.stayOpen = 0 # If set, works as a knowledegbase, never canonicalized. self._redirections = {} # Used for equalities def __repr__(self): if self.statements == []: return "{}" if len(self.statements) == 1: st = self.statements[0] return "{"+`st[SUBJ]`+" "+`st[PRED]`+" "+`st[OBJ]`+"}" s = Term.__repr__(self) return "{%i}" % len(self.statements) def classOrder(self): return 11 # Put at the end of a listing because it makes it easier to read def compareTerm(self, other): "Assume is also a Formula - see function compareTerm below" for f in self, other: if f.canonical is not f: progress("@@@@@ Comparing formula NOT canonical", `f`) s = self.statements o = other.statements ls = len(s) lo = len(o) if ls > lo: return 1 if ls < lo: return -1 for se, oe, in ((list(self.universals()), list(other.universals())), (list(self.existentials()), list(other.existentials())) ): lse = len(se) loe = len(oe) if lse > loe: return 1 if lse < loe: return -1 se.sort(Term.compareAnyTerm) oe.sort(Term.compareAnyTerm) for i in range(lse): diff = se[i].compareAnyTerm(oe[i]) if diff != 0: return diff # @@@@ No need - canonical formulae are always sorted s.sort() # forumulae are all the same o.sort() for i in range(ls): diff = cmp(s[i],o[i]) if diff != 0: return diff return 0 import why raise RuntimeError("%s\n%s" % (dict(why.proofsOf), self.debugString())) raise RuntimeError("Identical formulae not interned! Length %i: %s\n\t%s\n vs\t%s" % ( ls, `s`, self.debugString(), other.debugString())) def existentials(self): """Return a list of existential variables with this formula as scope. Implementation: we may move to an internal storage rather than these pseudo-statements""" return self._existentialVariables def universals(self): """Return a set of variables universally quantified with this formula as scope. Implementation: We may move to an internal storage rather than these statements.""" return self._universalVariables def variables(self): """Return a set of all variables quantified within this scope.""" return self.existentials() | self.universals() def size(self): """Return the number statements. Obsolete: use len(F).""" return len(self.statements) def __len__(self): """ How many statements? """ return len(self.statements) def __iter__(self): """The internal method which allows one to iterate over the statements as though a formula were a sequence. """ for s in self.statements: yield s def newSymbol(self, uri): """Create or reuse the internal representation of the RDF node whose uri is given The symbol is created in the same store as the formula.""" return self.store.newSymbol(uri) def newList(self, list): return self.store.nil.newList(list) def newLiteral(self, str, dt=None, lang=None): """Create or reuse the internal representation of the RDF literal whose string is given The literal is created in the same store as the formula.""" return self.store.newLiteral(str, dt, lang) def newXMLLiteral(self, doc): """Create or reuse the internal representation of the RDF literal whose string is given The literal is created in the same store as the formula.""" return self.store.newXMLLiteral(doc) def intern(self, value): return self.store.intern(value) def newBlankNode(self, uri=None, why=None): """Create a new unnamed node with this formula as context. The URI is typically omitted, and the system will make up an internal idnetifier. If given is used as the (arbitrary) internal identifier of the node.""" x = AnonymousExistential(self, uri) self._existentialVariables.add(x) return x def declareUniversal(self, v, key=None): if key is not AnonymousUniversal: raise RuntimeError("""We have now disallowed the calling of declareUniversal. For future reference, use newUniversal """) if verbosity() > 90: progress("Declare universal:", v) if v not in self._universalVariables: self._universalVariables.add(v) if self.occurringIn(Set([self.newSymbol(v.uriref())])): raise ValueError("Internal error: declareUniversal: %s?" % v) def declareExistential(self, v): if verbosity() > 90: progress("Declare existential:", v) if v not in self._existentialVariables: # Takes time self._existentialVariables.add(v) ## if self.occurringIn(Set([v])) and not v.generated(): ## raise ValueError("Are you trying to confuse me, declaring %s as an existential?" % v) # else: # raise RuntimeError("Redeclared %s in %s -- trying to erase that" %(v, self)) def newExistential(self, uri=None, why=None): """Create a named variable existentially qualified within this formula See also: existentials() and newBlankNode().""" if uri == None: raise RuntimeError("Please use newBlankNode with no URI") return self.newBlankNode() # Please ask for a bnode next time return self.store.newExistential(self, uri, why=why) def newUniversal(self, uri=None, why=None): """Create a named variable universally qualified within this formula See also: universals()""" x = AnonymousUniversal(self, uri) ## self._universalVariables.add(x) return x def newFormula(self, uri=None): """Create a new open, empty, formula in the same store as this one. The URI is typically omitted, and the system will make up an internal idnetifier. If given is used as the (arbitrary) internal identifier of the formula.""" return self.store.newFormula(uri) def statementsMatching(self, pred=None, subj=None, obj=None): """Return a READ-ONLY list of StoredStatement objects matching the parts given For example: for s in f.statementsMatching(pred=pantoneColor): print "We've got one which is ", `s[OBJ]` If none, returns [] """ for s in self.statements: if ((pred == None or pred is s.predicate()) and (subj == None or subj is s.subject()) and (obj == None or obj is s.object())): yield s def contains(self, pred=None, subj=None, obj=None): """Return boolean true iff formula contains statement(s) matching the parts given For example: if f.contains(pred=pantoneColor): print "We've got one statement about something being some color" """ for s in self.statements: if ((pred == None or pred is s.predicate()) and (subj == None or subj is s.subject()) and (obj == None or obj is s.object())): return 1 return 0 def any(self, subj=None, pred=None, obj=None): """Return None or the value filing the blank in the called parameters. Specifiy exactly two of the arguments. color = f.any(pred=pantoneColor, subj=myCar) somethingRed = f.any(pred=pantoneColor, obj=red) Note difference from the old store.any!! Note SPO order not PSO. To aboid confusion, use named parameters. """ for s in self.statements: if ((pred == None or pred is s.predicate()) and (subj == None or subj is s.subject()) and (obj == None or obj is s.object())): break else: return None if obj == None: return s.object() if subj == None: return s.subject() if pred == None: return s.predicate() raise ValueError("You must give one wildcard in (%s, %s, %s)" %(subj, pred, obj)) def the(self, subj=None, pred=None, obj=None): """Return None or the value filing the blank in the called parameters This is just like any() except it checks that there is only one answer in the store. It wise to use this when you expect only one. color = f.the(pred=pantoneColor, subj=myCar) redCar = f.the(pred=pantoneColor, obj=red) """ return self.any(subj, pred, obj) # @@check >1 def each(self, subj=None, pred=None, obj=None): """Return a list of values value filing the blank in the called parameters Examples: colors = f.each(pred=pantoneColor, subj=myCar) for redthing in f.each(pred=pantoneColor, obj=red): ... """ for s in self.statements: if ((pred == None or pred is s.predicate()) and (subj == None or subj is s.subject()) and (obj == None or obj is s.object())): if pred == None: yield s.predicate() elif subj == None: yield s.subject() elif obj == None: yield s.object() else: raise ValueError( "You must give one wildcard in (%s, %s, %s)" %(subj, pred, obj)) def searchable(self, subj=None, pred=None, obj=None): """A pair of the difficulty of searching and a statement iterator of found statements The difficulty is a store-portable measure of how long the store thinks (in arbitrary units) it will take to search. This will only be used for choisng which part of the query to search first. If it is 0 there is no solution to the query, we know now. In this implementation, we use the length of the sequence to be searched.""" difficulty = 1 for p in subj, pred, obj: if p == None: difficulty += 1 return difficulty, self.statementsMatching(subj, pred, obj) # use lazy eval here def substitution(self, bindings, why=None, cannon=False, keepOpen=False): "Return this or a version of me with subsitution made" assert isinstance(bindings, dict) store = self.store if self in bindings: return bindings[self] oc = self.occurringIn(bindings.keys()) if oc == Set(): return self # phew! y = store.newFormula() if verbosity() > 90: progress("substitution: formula"+`self`+" becomes new "+`y`, " because of ", oc) y.loadFormulaWithSubstitution(self, bindings, why=why) if keepOpen: return y return y.canonicalize(cannon=cannon) def loadFormulaWithSubstitution(self, old, bindings={}, why=None, cannon=False): """Load information from another formula, subsituting as we go returns number of statements added (roughly)""" total = 0 subWhy=Because('I said so #1', why) bindings2 = bindings.copy() bindings3 = {} for v in old.universals(): if v not in bindings: bindings3[v] = self.newUniversal(bindings.get(v, v)) for v in old.existentials(): self.declareExistential(bindings.get(v, v)) bindings2[old] = self realStatementList = [] for s in old.statements[:] : # Copy list! subj=s[SUBJ].substitution( bindings2, why=subWhy, cannon=cannon).substitution( bindings3, why=subWhy, cannon=cannon) ### Make sure we don't keep making copies of the same formula from running ## the same rule again and again if isTopLevel(self) and isinstance(subj, Formula) and not subj.reallyCanonical: subj = subj.reopen() subj = subj.canonicalize(cannon=True) if isinstance(subj, Formula): subj = subj.canonical if subj is not s[SUBJ]: bindings2[s[SUBJ]] = subj pred=s[PRED].substitution( bindings2, why=subWhy, cannon=cannon).substitution( bindings3, why=subWhy, cannon=cannon) if pred is not s[PRED]: bindings2[s[PRED]] = pred obj=s[OBJ].substitution( bindings2, why=subWhy, cannon=cannon).substitution( bindings3, why=subWhy, cannon=cannon) if isTopLevel(self) and isinstance(obj, Formula) and not obj.reallyCanonical: obj = obj.reopen() obj = obj.canonicalize(cannon=True) if isinstance(obj, Formula): obj = obj.canonical if obj is not s[OBJ]: ### Question to self: What is this doing? bindings2[s[OBJ]] = obj try: total += self.add(subj=subj, pred=pred, obj=obj, why=why) realStatementList.append((subj, pred, obj)) except AssertionError: print 'subj=%s' % subj.debugString() print 'oldSubj=%s' % (s[SUBJ].debugString(),) print 'subj.canonical=%s' % subj.canonical.debugString() raise if diag.chatty_flag > 80: def thing2string(x): if isinstance(x, (tuple, list)): return '[' + ', '.join([thing2string(y) for y in x]) + ']' if isinstance(x, List): return '(' + ' '.join([thing2string(y) for y in x]) + ')' else: return str(x) progress('We added the following triples: %s' % (''.join(['\n\t%s' % thing2string(x) for x in realStatementList]),)) return bindings3, total def subSet(self, statements, why=None): f = self.newFormula() for s in statements: c, p, s, o = s.quad f.add(s, p, o, why=why) assert c is self uu = f.occurringIn(self.universals()) ee = f.occurringIn(self.existentials()) bindings = {} f = self.newFormula() ## do it right this time, with vars for v in uu: # progress("&&&&& New universal is %s\n\t in %s" % (v.uriref(), f)) bindings[v] = f.newUniversal(v) # progress("&&&&& Universals are %s\n\t in %s" % (f.universals(), f)) for v in ee: f.declareExistential(v) for s in statements: c, p, s, o = s.quad f.add(s.substitution(bindings, why=why), p.substitution(bindings, why=why), o.substitution(bindings, why=why), why=why) return f.close() # probably slow - much slower than statement subclass of formula def substituteEquals(self, bindings, newBindings): """Return this or a version of me with subsitution made Subsitution of = for = does NOT happen inside a formula, as the formula is a form of quotation.""" return self def occurringIn(self, vars): "Which variables in the list occur in this?" set = Set() for s in self.statements: for p in PRED, SUBJ, OBJ: y = s[p] if y is self: pass else: set = set | y.occurringIn(vars) return set def renameVars(self): if self._renameVarsMaps: if self in self._renameVarsMaps[-1]: return self._renameVarsMaps[-1][self] # progress('Running renameVars of self=%s' % self.debugString()) m2 = {} for triple in self: for node in triple.spo(): if isinstance(node, Formula): if node not in m2: m2[node] = node.renameVars() m = {} n = {} F1 = self.newFormula() F1.loadFormulaWithSubstitution(self, m2, why=Because("Vars in subexpressions must be renamed")) for v in sorted(list(F1.existentials()), Term.compareAnyTerm): m[v] = F1.newBlankNode() for v in sorted(list(F1.universals()), Term.compareAnyTerm): n[v] = F1.newUniversal(v) e = F1.existentials() u = F1.universals() for var in m: e.remove(var) for var in n: u.remove(var) m.update(n) #progress('F1 is %s' % F1.debugString()) #progress('bindings are %s' % m) retVal = F1.substitution(m, why=Because("Vars must be renamed"), cannon=False, keepOpen=True) self._renameVarsMaps.append(0) retVal = retVal.canonicalize() self._renameVarsMaps.pop() if self._renameVarsMaps: self._renameVarsMaps[-1][self] = retVal self._renameVarsMaps[-1][retVal] = retVal assert retVal.canonical is retVal, retVal #progress('...got %s' % retVal.debugString()) return retVal ## def renameVars(self): ## return self def resetRenames(reset = True): if reset: if diag.chatty_flag > 20: progress("Resetting all renamed vars maps ---------------------------------") Formula._renameVarsMaps.append({}) else: Formula._renameVarsMaps.pop() resetRenames = staticmethod(resetRenames) _renameVarsMaps = [] ## def unify(self, other, vars=Set([]), existentials=Set([]), bindings={}): ## """See Term.unify() ## """ ## if diag.chatty_flag > 99: progress("Unifying formula %s with %s" % ## (`self`, `other`)) ## if diag.chatty_flag > 139: progress("Self is %s\n\nOther is %s" % ## (self.debugString(), other.debugString())) ## if not isinstance(other, Formula): return [] ## if self is other: return [({}, None)] ## if (len(self) != len(other) ## or len(self. _existentialVariables) != len(other._existentialVariables) ## or len(self. _universalVariables) != len(other._universalVariables) ## ): return [] ## ## ex = existentials | self.existentials() # @@ Add unis to make var names irrelevant? ## return unifySequence( ## [Set(self.statements), self.universals(), self.existentials()], ## [Set(other.statements), other.universals(), other.existentials()], ## vars | self.existentials() | self.universals(), ## existentials , bindings) def unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source): MyStatements = ImmutableSet(self.statements) OtherStatements = ImmutableSet(other.statements) for x in unify(MyStatements, OtherStatements, env1, env2, vars, universals | self.universals() | other.universals(), existentials | self.existentials() | other.existentials(), n1Source, n2Source): yield x def n3EntailedBy(pattern, kb, vars=Set([]), existentials=Set([]), bindings={}): """See Term.unify() and term.matchSet() KB is a stronger statement han other. Bindings map variables in pattern onto kb. Self n3-entails other. Criteria: Subset of self statements must match other statements. Self's exisetntials must be subset of other's Self's universals must be superset. """ if diag.chatty_flag > 99: progress("n3EntailedBy: %s entailed by %s ?" % (`pattern`, `kb`)) if diag.chatty_flag > 139: progress("Pattern is %s\n\nKB is %s" % (pattern.debugString(), kb.debugString())) assert isinstance(kb, Formula), kb if pattern is kb: return [({}, None)] nbs = matchSet(Set(pattern.statements), Set(kb.statements), vars | pattern.existentials(), # | pattern.universals(), bindings) if diag.chatty_flag > 99: progress("n3EntailedBy: match result: ", `nbs`) if nbs == []: return [] res = [] for nb, rea in nbs: # We have matched the statements, now the lists of vars. ke = Set([ nb.get(e,e) for e in kb.existentials()]) ke = pattern.occurringIn(ke) #Only ones mentioned count pe = Set([ nb.get(e,e) for e in pattern.existentials()]) if diag.chatty_flag > 99: progress("\tpe=%s; ke=%s" %(pe,ke)) if not ke.issubset(pe): return [] # KB must be stronger - less e's ku = Set([ nb.get(v,v) for v in kb.universals()]) pu = Set([ nb.get(v,v) for v in pattern.universals()]) if diag.chatty_flag > 99: progress("\tpu=%s; ku=%s" %(pu,ku)) if not pu.issubset(ku): return [] # KB stronger - more u's if diag.chatty_flag > 99: progress("n3EntailwsBy: success with ", `nb`) res.append((nb, None)) # That works return res def bind(self, prefix, uri): """Give a prefix and associated URI as a hint for output The store does not use prefixes internally, but keeping track of those usedd in the input data makes for more human-readable output. """ return self.store.bind(prefix, uri) def add(self, subj, pred, obj, why=None): """Add a triple to the formula. The formula must be open. subj, pred and obj must be objects as for example generated by Formula.newSymbol() and newLiteral(), or else literal values which can be interned. why may be a reason for use when a proof will be required. """ if self.canonical != None: raise RuntimeError("Attempt to add statement to canonical formula "+`self`) self.store.size += 1 s = StoredStatement((self, pred, subj, obj)) self.statements.append(s) return 1 # One statement has been added @@ ignore closure extras from closure # Obsolete this return value? @@@ def removeStatement(self, s): """Removes a statement The formula must be open. This implementation is alas slow, as removal of items from tha hash is slow. """ assert self.canonical == None, "Cannot remove statement from canonical "+`self` self.store.size = self.store.size-1 self.statements.remove(s) return def close(self): """No more to add. Please return interned value. NOTE You must now use the interned one, not the original!""" return self.canonicalize() def canonicalize(F): """If this formula already exists, return the master version. If not, record this one and return it. Call this when the formula is in its final form, with all its statements. Make sure no one else has a copy of the pointer to the smushed one. LIMITATION: The basic Formula class does NOT canonicalize. So it won't spot idenical formulae. The IndexedFormula will. """ store = F.store if F.canonical != None: if verbosity() > 70: progress("Canonicalize -- @@ already canonical:"+`F`) return F.canonical # @@@@@@@@ no canonicalization @@ warning F.canonical = F return F def n3String(self, base=None, flags=""): "Dump the formula to an absolute string in N3" buffer=StringIO.StringIO() _outSink = notation3.ToN3(buffer.write, quiet=1, base=base, flags=flags) self.store.dumpNested(self, _outSink) return buffer.getvalue().decode('utf_8') def ntString(self, base=None, flags="bravestpun"): "Dump the formula to an absolute string in N3" buffer=StringIO.StringIO() _outSink = notation3.ToN3(buffer.write, quiet=1, base=base, flags=flags) self.store.dumpBySubject(self, _outSink) return buffer.getvalue().decode('utf_8') def rdfString(self, base=None, flags=""): "Dump the formula to an absolute string in RDF/XML" buffer=StringIO.StringIO() import toXML _outURI = 'http://example.com/' _outSink = toXML.ToRDF(buffer, _outURI, base=base, flags=flags) self.store.dumpNested(self, _outSink) return buffer.getvalue() def outputStrings(self, channel=None, relation=None): """Fetch output strings from store, sort and output To output a string, associate (using the given relation) with a key such that the order of the keys is the order in which you want the corresponding strings output. @@ what is this doing here?? """ if channel == None: channel = sys.stdout if relation == None: relation = self.store.intern((SYMBOL, Logic_NS + "outputString")) list = self.statementsMatching(pred=relation) # List of things of (subj, obj) pairs pairs = [] for s in list: pairs.append((s[SUBJ], s[OBJ])) pairs.sort(comparePair) for key, str in pairs: channel.write(str.string.encode('utf-8')) def reopen(self): """Make a formula which was once closed oopen for input again. NOT Recommended. Dangers: this formula will be, because of interning, the same objet as a formula used elsewhere which happens to have the same content. You mess with this one, you mess with that one. Much better to keep teh formula open until you don't needed it open any more. The trouble is, the parsers close it at the moment automatically. To be fixed.""" return self.store.reopen(self) # def includes(f, g, _variables=[], bindings=[]): # """Does this formula include the information in the other? # # bindings is for use within a query. # """ # from swap.query import testIncludes # Nor a dependency we want to make from here # return testIncludes(f, g, _variables=_variables, bindings=bindings) def generated(self): """Yes, any identifier you see for this is arbitrary.""" return 1 # def asPair(self): # """Return an old representation. Obsolete""" # return (FORMULA, self.uriref()) def subjects(self, pred=None, obj=None): """Obsolete - use each(pred=..., obj=...)""" for s in self.statementsMatching(pred=pred, obj=obj)[:]: yield s[SUBJ] def predicates(self, subj=None, obj=None): """Obsolete - use each(subj=..., obj=...)""" for s in self.statementsMatching(subj=subj, obj=obj)[:]: yield s[PRED] def objects(self, pred=None, subj=None): """Obsolete - use each(subj=..., pred=...)""" for s in self.statementsMatching(pred=pred, subj=subj)[:]: yield s[OBJ] def doesNodeAppear(self, symbol): """Does that particular node appear anywhere in this formula This function is necessarily recursive, and is useful for the pretty printer It will also be useful for the flattener, when we write it. """ for quad in self.statements: for s in PRED, SUBJ, OBJ: val = 0 if isinstance(quad[s], CompoundTerm): val = val or quad[s].doesNodeAppear(symbol) elif quad[s] == symbol: val = 1 else: pass if val == 1: return 1 return 0 def freeVariables(self): retVal = Set() for statement in self: for node in statement.spo(): retVal.update(node.freeVariables()) retVal.difference_update(self.existentials()) retVal.difference_update(self.universals()) if self.canonical: self.freeVariablesCompute = self.freeVariables self.freeVariables = lambda : retVal.copy() return retVal.copy() ################################################################################# class StoredStatement: """A statememnt as an element of a formula """ def __init__(self, q): self.quad = q def __getitem__(self, i): # So that we can index the stored thing directly return self.quad[i] def __repr__(self): return "{"+`self[SUBJ]`+" "+`self[PRED]`+" "+`self[OBJ]`+"}" # The order of statements is only for canonical output # We cannot override __cmp__ or the object becomes unhashable, # and can't be put into a dictionary. def __cmp__(self, other): """Just compare SUBJ, Pred and OBJ, others the same Avoid loops by spotting reference to containing formula""" if self is other: return 0 if not isinstance(other, StoredStatement): return cmp(self.__class__, other.__class__) sc = self.quad[CONTEXT] oc = other.quad[CONTEXT] for p in [SUBJ, PRED, OBJ]: # Note NOT internal order s = self.quad[p] o = other.quad[p] if s is sc: if o is oc: continue else: return -1 # @this is smaller than other formulae else: if o is oc: return 1 if s is not o: return s.compareAnyTerm(o) return 0 def __hash__(self): return id(self) def comparePredObj(self, other): """Just compare P and OBJ, others the same""" if self is other: return 0 sc = self.quad[CONTEXT] oc = other.quad[CONTEXT] for p in [PRED, OBJ]: # Note NOT internal order s = self.quad[p] o = other.quad[p] if s is sc: if o is oc: continue else: return -1 # @this is smaller than other formulae else: if o is oc: return 1 if s is not o: return s.compareAnyTerm(o) return 0 def context(self): """Return the context of the statement""" return self.quad[CONTEXT] def predicate(self): """Return the predicate of the statement""" return self.quad[PRED] def subject(self): """Return the subject of the statement""" return self.quad[SUBJ] def object(self): """Return the object of the statement""" return self.quad[OBJ] def spo(self): return (self.quad[SUBJ], self.quad[PRED], self.quad[OBJ]) def __len__(self): return 1 def statements(self): return [self] def occurringIn(self, vars): "Which variables in the list occur in this?" set = Set() if verbosity() > 98: progress("----occuringIn: ", `self`) for p in PRED, SUBJ, OBJ: y = self[p] if y is self: pass else: set = set | y.occurringIn(vars) return set def existentials(self): return self.occuringIn(self.quad[CONTEXT].existentials()) def universals(self): return self.occuringIn(self.quad[CONTEXT].universals()) ## def unify(self, other, vars=Set([]), existentials=Set([]), bindings={}): ## """See Term.unify() ## """ ## if diag.chatty_flag > 99: progress("Unifying statement %s with %s" % ## (`self`, `other`)) ## if not isinstance(other, StoredStatement): raise TypeError ## return unifySequence([self[PRED], self[SUBJ], self[OBJ]], ## [other[PRED], other[SUBJ], other[OBJ]], ## vars, existentials, bindings) def unify(self, other, env1, env2, vars, universals, existentials, n1Source=32, n2Source=32): return unify(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source) def unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source): return unifySequence([self[PRED], self[SUBJ], self[OBJ]], [other[PRED], other[SUBJ], other[OBJ]], env1, env2, vars, universals, existentials, n1Source, n2Source) def asFormula(self, why=None): """The formula which contains only a statement like this. When we split the statement up, we lose information in any existentials which are shared with other statements. So we introduce a skolem constant to tie the statements together. We don't have access to any enclosing formula so we can't express its quantification. This @@ not ideal. This extends the StoredStatement class with functionality we only need with "why" module.""" store = self.quad[CONTEXT].store c, p, s, o = self.quad f = store.newFormula() # @@@CAN WE DO THIS BY CLEVER SUBCLASSING? statement subclass of f? f.add(s, p, o, why=why) uu = f.freeVariables().intersection(c.universals()) ee = f.occurringIn(c.existentials()) bindings = {} f = store.newFormula() ## do it right this time, with vars for v in uu: # progress("&&&&& New universal is %s\n\t in %s" % (v.uriref(), f)) bindings[v] = f.newUniversal(v) # progress("&&&&& Universals are %s\n\t in %s" % (f.universals(), f)) for v in ee: f.declareExistential(v) f.add(s.substitution(bindings, why=why), p.substitution(bindings, why=why), o.substitution(bindings, why=why), why=why) return f.close() # probably slow - much slower than statement subclass of formula #ends cwm-1.2.1/swap/cwm_os.py0000755015216600007660000000644210640075637014251 0ustar syosisyosi#! /usr/bin/python """ $Id: cwm_os.py,v 1.12 2007/06/26 02:36:15 syosi Exp $ Operating systems built-ins for cwm http://www.w3.org/2000/10/swap/string.py See cwm.py and the os module in python """ import os from term import LightBuiltIn, Function, ReverseFunction from diag import verbosity, progress import uripath OS_NS_URI = "http://www.w3.org/2000/10/swap/os#" ############################################################################################### # # O P E R A T I N G S Y T E M B U I L T - I N s # # # Light Built-in classes # Read Operating sytem environment lookup - read-only # # Not fatal if not defined class BI_environ(LightBuiltIn, Function): def evaluateObject(self, subj_py): if isString(subj_py): return os.environ.get(subj_py, None) progress("os:environ input is not a string: "+`subj_py`) class BI_baseAbsolute(LightBuiltIn, Function): """The baseAbsolute function generates an absolute URIref from a string, interpreting the string as a a relative URIref relative to the current process base URI (typically, current working directory). It is not a reverse function, because sereral different relativisations exist for the same absolute URI. See uripath.py.""" def evaluateObject(self, subj_py): if verbosity() > 80: progress("os:baseAbsolute input:"+`subj_py`) if isString(subj_py): return uripath.join(uripath.base(), subj_py) progress("Warning: os:baseAbsolute input is not a string: "+`subj_py`) class BI_baseRelative(LightBuiltIn, Function, ReverseFunction): """The baseRelative of a URI is its expression relation to the process base URI. It is 1:1, being an arbitrary cannonical form. It is a reverse function too, as you can always work the other way.""" def evaluateObject(self, subj_py): if verbosity() > 80: progress("os:baseRelative input:"+`subj_py`) if isString(subj_py): return uripath.refTo(uripath.base(), subj_py) progress("Warning: os:baseRelative input is not a string: "+`subj_py`) def evaluateSubject(self, subj_py): return BI_baseAbsolute.evaluateObject(self, subj_py) # Command line argument: read-only # The command lines are passed though cwm using "--with" and into the RDFStore when init'ed. # Not fatal if not defined class BI_argv(LightBuiltIn, Function): def evaluateObject(self, subj_py): if verbosity() > 80: progress("os:argv input:"+`subj_py`) if self.store.argv: # Not None or []. was also: isString(subj_py) and try: argnum = int(subj_py) -1 except ValueError: if verbosity() > 30: progress("os:argv input is not a number: "+`subj_py`) return None if argnum < len(self.store.argv): return self.store.argv[argnum] def isString(x): # in 2.2, evidently we can test for isinstance(types.StringTypes) return type(x) is type('') or type(x) is type(u'') # Register the string built-ins with the store def register(store): str = store.symbol(OS_NS_URI[:-1]) str.internFrag("environ", BI_environ) str.internFrag("baseRelative", BI_baseRelative) str.internFrag("baseAbsolute", BI_baseAbsolute) str.internFrag("argv", BI_argv) # ends cwm-1.2.1/swap/my_profiler.py0000644015216600007660000000121610463521652015274 0ustar syosisyosi"""Profile.py This will try to profile cwm. """ import hotshot, hotshot.stats from cwm import doCommand import os, sys def runProfile(logfile): profiler = hotshot.Profile(logfile) saveout = sys.stdout fsock = open('/dev/null', 'w') sys.stdout = fsock profiler.runcall(doCommand) sys.stdout = saveout fsock.close() profiler.close() stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('cumulative', 'time', 'calls') stats.print_stats(60) if __name__ == '__main__': try: os.remove('/tmp/profile.log') except OSError: pass runProfile('/tmp/profile.log') cwm-1.2.1/swap/cwm_string.py0000755015216600007660000002625110640075637015136 0ustar syosisyosi#! /usr/bin/python """ $Id: cwm_string.py,v 1.36 2007/06/26 02:36:15 syosi Exp $ String built-ins for cwm This started as http://www.w3.org/2000/10/swap/string.py See cwm.py """ import string import re from diag import verbosity, progress import urllib # for hasContent import md5, binascii # for building md5 URIs from term import LightBuiltIn, ReverseFunction, Function from local_decimal import Decimal LITERAL_URI_prefix = "data:text/rdf+n3;" STRING_NS_URI = "http://www.w3.org/2000/10/swap/string#" ############################################################################################### # # S T R I N G B U I L T - I N s # # This should be in a separate module, imported and called once by the user # to register the code with the store # # Light Built-in classes class BI_GreaterThan(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (subj.string > obj.string) class BI_NotGreaterThan(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (subj.string <= obj.string) class BI_LessThan(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (subj.string < obj.string) class BI_NotLessThan(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (subj.string >= obj.string) class BI_StartsWith(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return subj.string.startswith(obj.string) class BI_EndsWith(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return subj.string.endswith(obj.string) # Added, SBP 2001-11:- class BI_Contains(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return subj.string.find(obj.string) >= 0 class BI_ContainsIgnoringCase(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return subj.string.lower().find(obj.string.lower()) >= 0 class BI_ContainsRoughly(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return normalizeWhitespace(subj.string.lower()).find(normalizeWhitespace(obj.string.lower())) >= 0 class BI_DoesNotContain(LightBuiltIn): # Converse of the above def eval(self, subj, obj, queue, bindings, proof, query): return subj.string.find(obj.string) < 0 class BI_equalIgnoringCase(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (subj.string.lower() == obj.string.lower()) class BI_notEqualIgnoringCase(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (string.lower(subj.string) != string.lower(obj.string)) def normalizeWhitespace(s): "Normalize whitespace sequences in a string to single spaces" res = "" for ch in s: if ch in " \t\r\n": if res[-1:]!=" ": res = res + " " else: res = res + ch return res # String Constructors - more light built-ins make_string = unicode class BI_concat(LightBuiltIn, ReverseFunction): def evaluateSubject(self, obj_py): if verbosity() > 80: progress("Concat input:"+`obj_py`) str = "" for x in obj_py: if not isString(x): return None # Can't str = str + x return str class BI_concatenation(LightBuiltIn, Function): def evaluateObject(self, subj_py): if verbosity() > 80: progress("Concatenation input:"+`subj_py`) str = "" for x in subj_py: if not isString(x): if type(x) == type(long()) or isinstance(x, Decimal): x = make_string(x) else: x = `x` if verbosity() > 34: progress("Warning: Coercing to string for concat:"+`x`) # return None # Can't str = str + x return str class BI_scrape(LightBuiltIn, Function): """a built-in for scraping using regexps. takes a list of 2 strings; the first is the input data, and the second is a regex with one () group. Returns the data matched by the () group. see also: test/includes/scrape1.n3 Hmm... negative tests don't seem to work. """ def evaluateObject(self, subj_py): # raise Error store = self.store if verbosity() > 80: progress("scrape input:"+`subj_py`) str, pat = subj_py patc = re.compile(pat) m = patc.search(str) if m: if verbosity() > 80: progress("scrape matched:"+m.group(1)) return m.group(1) if verbosity() > 80: progress("scrape didn't match") class BI_search(LightBuiltIn, Function): """a more powerful built-in for scraping using regexps. takes a list of 2 strings; the first is the input data, and the second is a regex with one or more () group. Returns the list of data matched by the () groups. see also: test/includes/search.n3 """ def evaluateObject(self, subj_py): # raise Error store = self.store if verbosity() > 80: progress("search input:"+`subj_py`) str, pat = subj_py patc = re.compile(pat) m = patc.search(str) if m: if verbosity() > 80: progress("search matched:"+m.group(1)) return m.groups() if verbosity() > 80: progress("search didn't match") class BI_split(LightBuiltIn, Function): """split a string into a list of strings takes a list of 2 strings and an integer; the first is the input data, and the second is a regex see re.split in http://docs.python.org/lib/node46.html """ def evaluateObject(self, subj_py): store = self.store str, pat, q = subj_py patc = re.compile(pat) return patc.split(str, q) class BI_tokenize(LightBuiltIn, Function): """like split without the max arg """ def evaluateObject(self, subj_py): store = self.store str, pat = subj_py patc = re.compile(pat) return patc.split(str) class BI_normalize_space(LightBuiltIn, Function): """Returns the value of $arg with whitespace normalized by stripping leading and trailing whitespace and replacing sequences of one or more than one whitespace character with a single space, #x20 -- http://www.w3.org/2006/xpath-functions#normalize-space """ def evaluateObject(self, subj_py): store = self.store return ' '.join(subj_py.split()) class BI_stringToList(LightBuiltIn, Function, ReverseFunction): """You need nothing else. Makes a string a list of characters, and visa versa. """ def evaluateObject(self, subj_py): print "hello, I'm at it" try: return [a for a in subj_py] except TypeError: return None def evaluateSubject(self, obj_py): try: return "".join(obj_py) except TypeError: return None class BI_format(LightBuiltIn, Function): """a built-in for string formatting, ala python % or C's sprintf or common-lisp's format takes a list; the first item is the format string, and the rest are args. see also: test/@@ """ def evaluateObject(self, subj_py): return subj_py[0] % tuple(subj_py[1:]) class BI_matches(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (re.compile(obj.string).search(subj.string)) class BI_notMatches(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (not re.compile(obj.string).search(subj.string)) dataEsc = re.compile(r"[\r<>&]") # timbl removed \n as can be in data attrEsc = re.compile(r"[\r<>&'\"\n]") class BI_xmlEscapeData(LightBuiltIn, Function): """Take a unicode string and return it encoded so as to pass in an XML data You will need the BI_xmlEscapeAttribute on for attributes, escaping quotes.""" def evaluateObject(self, subj_py): return xmlEscape(subj_py, dataEsc) class BI_xmlEscapeAttribute(LightBuiltIn, Function): """Take a unicode string and return it encoded so as to pass in an XML data You may need stg different for attributes, escaping quotes.""" def evaluateObject(self, subj_py): return xmlEscape(subj_py, attrEsc) def xmlEscape(subj_py, markupChars): """Escape a string given a regex of the markup chars to be escaped from toXML.py """ i = 0 result = "" while i < len(subj_py): m = markupChars.search(subj_py, i) if not m: result = result + subj_py[i:] break j = m.start() result = result + subj_py[i:j] result = result + ("&#%d;" % (ord(subj_py[j]),)) i = j + 1 return result class BI_encodeForURI(LightBuiltIn, Function): """Take a unicode string and return it encoded so as to pass in an URI path segment. See http://www.w3.org/TR/2005/CR-xpath-functions-20051103/#func-encode-for-uri""" def evaluateObject(self, subj_py): return urllib.quote(subj_py, "#!~*'()") class BI_encodeForFragID(LightBuiltIn, Function): """Take a unicode string and return it encoded so as to pass in a URI grament identifier.""" def evaluateObject(self, subj_py): return urllib.quote(subj_py) class BI_resolve_uri(LightBuiltIn, Function): """see http://www.w3.org/2006/xpath-functions#resolve-uri""" def evaluateObject(self, subj_py): import uripath there, base = subj_py return uripath.join(base, there) # Register the string built-ins with the store def isString(x): # in 2.2, evidently we can test for isinstance(types.StringTypes) return type(x) is type('') or type(x) is type(u'') def register(store): str = store.symbol(STRING_NS_URI[:-1]) str.internFrag("greaterThan", BI_GreaterThan) str.internFrag("notGreaterThan", BI_NotGreaterThan) str.internFrag("lessThan", BI_LessThan) str.internFrag("notLessThan", BI_NotLessThan) str.internFrag("startsWith", BI_StartsWith) str.internFrag("endsWith", BI_EndsWith) str.internFrag("concat", BI_concat) str.internFrag("concatenation", BI_concatenation) str.internFrag("scrape", BI_scrape) str.internFrag("search", BI_search) str.internFrag("split", BI_split) str.internFrag("stringToList", BI_stringToList) str.internFrag("format", BI_format) str.internFrag("matches", BI_matches) str.internFrag("notMatches", BI_notMatches) str.internFrag("contains", BI_Contains) str.internFrag("containsIgnoringCase", BI_ContainsIgnoringCase) str.internFrag("containsRoughly", BI_ContainsRoughly) str.internFrag("doesNotContain", BI_DoesNotContain) str.internFrag("equalIgnoringCase", BI_equalIgnoringCase) str.internFrag("notEqualIgnoringCase", BI_notEqualIgnoringCase) str.internFrag("xmlEscapeAttribute", BI_xmlEscapeAttribute) str.internFrag("xmlEscapeData", BI_xmlEscapeData) str.internFrag("encodeForURI", BI_encodeForURI) str.internFrag("encodeForFragID", BI_encodeForFragID) fn = store.symbol("http://www.w3.org/2006/xpath-functions") fn.internFrag("resolve-uri", BI_resolve_uri) fn.internFrag("tokenize", BI_tokenize) fn.internFrag("normalize-space", BI_normalize_space) cwm-1.2.1/swap/cwm_list.py0000755015216600007660000000775310717717700014610 0ustar syosisyosi#! /usr/bin/python """ $Id: cwm_list.py,v 1.15 2007/11/18 02:13:20 syosi Exp $ List and set built-ins for cwm http://www.w3.org/2000/10/swap/cwm_list.py See cwm.py and the os module in python """ from term import LightBuiltIn, RDFBuiltIn, Function, ReverseFunction, \ MultipleFunction, MultipleReverseFunction, \ CompoundTerm, N3Set, List, EmptyList, NonEmptyList from set_importer import Set from diag import verbosity, progress import uripath from RDFSink import List_NS, Logic_NS ListOperationsNamespace = "http://www.w3.org/2000/10/swap/list#" #################################################################### # # List handling B U I L T - I N s # # # Light Built-in classes class BI_first(RDFBuiltIn, Function): def evalObj(self, subj, queue, bindings, proof, query): if not isinstance(subj, NonEmptyList): return None return subj.first class BI_rest(RDFBuiltIn, Function): def evalObj(self, subj, queue, bindings, proof, query): if not isinstance(subj, NonEmptyList): return None return subj.rest class BI_last(LightBuiltIn, Function): def evalObj(self, subj, queue, bindings, proof, query): if not isinstance(subj, NonEmptyList): return None x = subj while 1: last = x x = x.rest if isinstance(x, EmptyList): return last.first ##class BI_map(LightBuiltIn, Function): ## def evalObj(self,subj, queue, bindings, proof, query): ## print subj ## store = self.store ## genID = store.genId() ## print genID ## hash = genID.rfind("#") ## print genID[hash+1:] ## symbol = genID[:hash] ## mapped = store.symbol(symbol) ## class Map(LightBuiltIn, Function): ## def evalObj(self, subj, queue, bindings, proof, query): ## print 'hi' ## return subj ## ## mapped.internFrag(genID[hash+1:], Map) ## return store.symbol(genID) class BI_in(LightBuiltIn, MultipleReverseFunction): """Is the subject in the object? Returnes a sequence of values.""" def eval(self, subj, obj, queue, bindings, proof, query): if not isinstance(obj, CompoundTerm): return None return subj in obj def evalSubj(self, obj, queue, bindings, proof, query): if not isinstance(obj, NonEmptyList) and not isinstance(obj, N3Set): return None rea = None return [x for x in obj] # [({subj:x}, rea) for x in obj] class BI_member(LightBuiltIn, MultipleFunction): """Is the subject in the object? Returnes a sequence of values.""" def eval(self, subj, obj, queue, bindings, proof, query): if not isinstance(subj, CompoundTerm): return None return obj in subj def evalObj(self,subj, queue, bindings, proof, query): if not isinstance(subj, NonEmptyList) and not isinstance(subj, N3Set): return None rea = None return [x for x in subj] # [({obj:x}, rea) for x in subj] class BI_append(LightBuiltIn, Function): """Takes a list of lists, and appends them together. """ def evalObj(self, subj, queue, bindings, proof, query): if not isinstance(subj, NonEmptyList): return None r = [] for x in subj: if not isinstance(x, List): return None r.extend([a for a in x]) return self.store.newList(r) class BI_members(LightBuiltIn, Function): """Makes a set from a list """ def evaluateObject(self, subj): return Set(subj) # Register the string built-ins with the store def register(store): # Done explicitly in llyn # list = store.internURI(List_NS[:-1]) # list.internFrag("first", BI_first) # list.internFrag("rest", BI_rest) ns = store.symbol(ListOperationsNamespace[:-1]) ns.internFrag("in", BI_in) ns.internFrag("member", BI_member) ns.internFrag("last", BI_last) ns.internFrag("append", BI_append) ns.internFrag("members", BI_members) ## ns.internFrag("map", BI_map) # ends cwm-1.2.1/swap/llyn.py0000755015216600007660000023203210731063552013726 0ustar syosisyosi#! /usr/bin/python """ $Id: llyn.py,v 1.185 2007/12/11 21:18:08 syosi Exp $ RDF Store and Query engine Logic Lookup: Yet another Name (also, in Wales, a lake - a storage area at the centre of the valley?) This is an engine which knows a certian amount of stuff and can manipulate it. It is a (forward chaining) query engine, not an (backward chaining) inference engine: that is, it will apply all rules it can but won't figure out which ones to apply to prove something. It is not optimized particularly. Used by cwm - the closed world machine. See: http://www.w3.org/DesignIssues/Notation3 Interfaces ========== This store stores many formulae, where one formula is what in straight RDF implementations is known as a "triple store". So look at the Formula class for a triple store interface. See also for comparison, a python RDF API for the Redland library (in C): http://www.redland.opensource.ac.uk/docs/api/index.html and the redfoot/rdflib interface, a python RDF API: http://rdflib.net/latest/doc/triple_store.html Copyright () 2000-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. """ # emacsbug="""emacs got confused by long string above""" from __future__ import generators # see http://www.amk.ca/python/2.2/index.html#SECTION000500000000000000000 from set_importer import Set, ImmutableSet import types import string import re import StringIO import sys import time, xml from warnings import warn import urllib # for log:content import md5, binascii # for building md5 URIs import uripath from uripath import canonical from sax2rdf import XMLtoDOM import xml.dom.minidom from why import smushedFormula, Premise, newTopLevelFormula, isTopLevel import notation3 # N3 parsers and generators, and RDF generator from webAccess import webget import diag # problems importing the tracking flag, # and chatty_flag must be explicit it seems: use diag.tracking from diag import progress, verbosity, tracking from term import BuiltIn, LightBuiltIn, RDFBuiltIn, HeavyBuiltIn, Function, \ MultipleFunction, ReverseFunction, MultipleReverseFunction, \ Literal, XMLLiteral, Symbol, Fragment, FragmentNil, Term, LabelledNode, \ CompoundTerm, List, EmptyList, NonEmptyList, AnonymousNode, N3Set, \ UnknownType from formula import Formula, StoredStatement import reify from weakref import WeakValueDictionary from query import think, applyRules, testIncludes import webAccess from webAccess import DocumentAccessError from local_decimal import Decimal from RDFSink import Logic_NS, RDFSink, forSomeSym, forAllSym from RDFSink import CONTEXT, PRED, SUBJ, OBJ, PARTS, ALL4 from RDFSink import N3_nil, N3_first, N3_rest, OWL_NS, N3_Empty, N3_List, \ N3_li, List_NS from RDFSink import RDF_NS_URI from RDFSink import FORMULA, LITERAL, LITERAL_DT, LITERAL_LANG, ANONYMOUS, SYMBOL from pretty import Serializer LITERAL_URI_prefix = "data:application/rdf+n3-literal;" Delta_NS = "http://www.w3.org/2004/delta#" cvsRevision = "$Revision: 1.185 $" # Magic resources we know about from RDFSink import RDF_type_URI, DAML_sameAs_URI from why import Because, BecauseBuiltIn, BecauseOfRule, \ BecauseOfExperience, becauseSubexpression, BecauseMerge ,report STRING_NS_URI = "http://www.w3.org/2000/10/swap/string#" META_NS_URI = "http://www.w3.org/2000/10/swap/meta#" INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer" FLOAT_DATATYPE = "http://www.w3.org/2001/XMLSchema#double" DECIMAL_DATATYPE = "http://www.w3.org/2001/XMLSchema#decimal" BOOL_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean" #reason=Namespace("http://www.w3.org/2000/10/swap/reason#") META_mergedWith = META_NS_URI + "mergedWith" META_source = META_NS_URI + "source" META_run = META_NS_URI + "run" doMeta = 0 # wait until we have written the code! :-) class DataObject: """The info about a term in the context of a specific formula It is created by being passed the formula and the term, and is then accessed like a python dictionary of sequences of values. Example: F = myWorkingFormula x = F.theObject(pred=rdfType obj=fooCar) for y in x[color][label] """ def __init__(context, term): self.context = context self.term = term def __getItem__(pred): # Use . or [] ? values = context.objects(pred=pred, subj=self.term) for v in value: yield DataObject(self.context, v) def arg_hash(arg): if isinstance(arg, dict): g = [] for k, v in arg.items(): g.append((arg_hash(k), arg_hash(v))) return hash(tuple(g)) if isinstance(arg, (tuple, list)): g = [] for k in arg: g.append(arg_hash(k)) return hash(tuple(g)) if isinstance(arg, Set): g = [] for k in arg: g.append(arg_hash(k)) return hash(ImmutableSet(g)) return hash(arg) def memoize(f): mymap = {} def k(*args, **keywords): n = arg_hash((args, keywords)) if n not in mymap: mymap[n] = f(*args, **keywords) else: if diag.chatty_flag > 10: progress("momoizing helped!") return mymap[n] return k #### ### BCHAIN @@@ Is this the right way to do it? #### BACKWARD_CHAINING = False class VARHASH(object): def __repr__(self): return 'VAR' def __str__(self): return 'VAR' VARHASH = VARHASH() #### ### /BCHAIN #### ###################################### Forumula # class IndexedFormula(Formula): """A formula which has indexes to facilitate queries. A formula is either open or closed. Initially, it is open. In this state is may be modified - for example, triples may be added to it. When it is closed, note that a different interned version of itself may be returned. From then on it is a constant. Only closed formulae may be mentioned in statements in other formuale. There is a reopen() method but it is not recommended, and if desperate should only be used immediately after a close(). """ def __init__(self, store, uri=None): Formula.__init__(self, store, uri) # self._redirections = {} self.descendents = None # Placeholder for list of closure under subcontext # self.collector = None # Object collecting evidence, if any self._newRedirections = {} # not subsituted yet self._index = {} self._index[(None,None,None)] = self.statements self._closureMode = "" self._closureAgenda = [] self._closureAlready = [] self.reallyCanonical = False def statementsMatching(self, pred=None, subj=None, obj=None): """Return a READ-ONLY list of StoredStatement objects matching the parts given For example: for s in f.statementsMatching(pred=pantoneColor): print "We've got one which is ", `s[OBJ]` If none, returns [] """ return self._index.get((pred, subj, obj), []) def contains(self, pred=None, subj=None, obj=None): """Return boolean true iff formula contains statement(s) matching the parts given For example: if f.contains(pred=pantoneColor): print "We've got one statement about something being some color" """ x = self._index.get((pred, subj, obj), []) if x : return 1 return 0 def any(self, subj=None, pred=None, obj=None): """Return None or the value filing the blank in the called parameters. Specifiy exactly two of the arguments. color = f.any(pred=pantoneColor, subj=myCar) somethingRed = f.any(pred=pantoneColor, obj=red) Note difference from the old store.any!! Note SPO order not PSO. To aboid confusion, use named parameters. """ hits = self._index.get((pred, subj, obj), []) if not hits: return None s = hits[0] if pred is None: return s[PRED] if subj is None: return s[SUBJ] if obj is None: return s[OBJ] raise ParameterError("You must give one wildcard") def the(self, subj=None, pred=None, obj=None): """Return None or the value filing the blank in the called parameters This is just like any() except it checks that there is only one answer in the store. It wise to use this when you expect only one. color = f.the(pred=pantoneColor, subj=myCar) redCar = f.the(pred=pantoneColor, obj=red) """ hits = self._index.get((pred, subj, obj), []) if not hits: return None assert len(hits) == 1, """There should only be one match for (%s %s %s). Found: %s""" %(subj, pred, obj, self.each(subj, pred, obj)) s = hits[0] if pred is None: return s[PRED] if subj is None: return s[SUBJ] if obj is None: return s[OBJ] raise parameterError("You must give one wildcard using the()") def each(self, subj=None, pred=None, obj=None): """Return a list of values value filing the blank in the called parameters Examples: colors = f.each(pred=pantoneColor, subj=myCar) for redthing in f.each(pred=pantoneColor, obj=red): ... """ hits = self._index.get((pred, subj, obj), []) if hits == []: return [] if pred is None: wc = PRED elif subj is None: wc = SUBJ elif obj is None: wc = OBJ else: raise ParameterError("You must give one wildcard None for each()") res = [] for s in hits: res.append(s[wc]) # should use yeild @@ when we are ready return res def searchable(self, subj=None, pred=None, obj=None): """A pair of the difficulty of searching and a statement iterator of found statements The difficulty is a store-portable measure of how long the store thinks (in arbitrary units) it will take to search. This will only be used for choisng which part of the query to search first. If it is 0 there is no solution to the query, we know now. In this implementation, we use the length of the sequence to be searched.""" res = self._index.get((pred, subj, obj), []) # progress("searchable %s, %s" %(self.statements, (pred, subj, obj)) return len(res), res def add(self, subj, pred, obj, why=None): """Add a triple to the formula. The formula must be open. subj, pred and obj must be objects as for example generated by Formula.newSymbol() and newLiteral(), or else literal values which can be interned. why may be a reason for use when a proof will be required. """ if self.canonical != None: raise RuntimeError("Attempt to add statement to closed formula "+`self`) store = self.store if not isinstance(subj, Term): subj = store.intern(subj) if not isinstance(pred, Term): pred = store.intern(pred) if not isinstance(obj, Term): obj = store.intern(obj) newBindings = {} # Smushing of things which are equal into a single node # Even if we do not do this with owl:sameAs, we do with lists subj = subj.substituteEquals(self._redirections, newBindings) pred = pred.substituteEquals(self._redirections, newBindings) obj = obj.substituteEquals(self._redirections, newBindings) if diag.chatty_flag > 90: progress(u"Add statement (size before %i, %i statements) to %s:\n {%s %s %s}" % ( self.store.size, len(self.statements),`self`, `subj`, `pred`, `obj`) ) if self.statementsMatching(pred, subj, obj): if diag.chatty_flag > 97: progress("Add duplicate SUPPRESSED %s: {%s %s %s}" % ( self, subj, pred, obj) ) return 0 # Return no change in size of store assert not isinstance(pred, Formula) or pred.canonical is pred, "pred Should be closed"+`pred` assert (not isinstance(subj, Formula) or subj is self or subj.canonical is subj), "subj Should be closed or self"+`subj` assert not isinstance(obj, Formula) or obj.canonical is obj, "obj Should be closed"+`obj`+`obj.canonical` store.size = store.size+1 # rather nominal but should be monotonic if False and isTopLevel(self): if isinstance(subj, Formula) and not subj.reallyCanonical: raise RuntimeError(subj.debugString()) if isinstance(obj, Formula) and not obj.reallyCanonical: raise RuntimeError(obj.debugString()) # We collapse lists from the declared daml first,rest structure into List objects. # To do this, we need a bnode with (a) a first; (b) a rest, and (c) the rest being a list. # We trigger list collapse on any of these three becoming true. # @@@ we don't reverse this on remove statement. Remove statement is really not a user call. # (Not clear: how t smush symbols without smushing variables. Need separate python class # for variables I guess as everyone has been saying. # When that happens, expend smushing to symbols.) if pred is store.rest: if isinstance(obj, List) and subj in self._existentialVariables: ss = self.statementsMatching(pred=store.first, subj=subj) if ss: s = ss[0] self.removeStatement(s) first = s[OBJ] list = obj.prepend(first) self._noteNewList(subj, list, newBindings) self.substituteEqualsInPlace(newBindings, why=why) return 1 # Added a statement but ... it is hidden in lists elif pred is store.first and subj in self._existentialVariables: ss = self.statementsMatching(pred=store.rest, subj=subj) if ss: s = ss[0] rest = s[OBJ] if isinstance(rest, List): list = rest.prepend(obj) self.removeStatement(s) self._noteNewList(subj, list, newBindings) self.substituteEqualsInPlace(newBindings) return 1 if pred is store.owlOneOf: if isinstance(obj, List) and subj in self._existentialVariables: new_set = store.newSet(obj) self._noteNewSet(subj, new_set, newBindings) self.substituteEqualsInPlace(newBindings) return 1 if "e" in self._closureMode: if pred is store.sameAs: if subj is obj: return 0 # ignore a = a if obj in self.existentials() and subj not in self.existentials(): var, val = obj, subj elif ((subj in self.existentials() and obj not in self.existentials()) or (subj.generated() and not obj.generated()) or Term.compareAnyTerm(obj, subj) < 0): var, val = subj, obj else: var, val = obj, subj newBindings[var] = val if diag.chatty_flag > 90: progress("Equality: %s = %s" % (`var`, `val`)) self.substituteEqualsInPlace(newBindings) return 1 if "T" in self._closureMode: if pred is store.type and obj is store.Truth: assert isinstance(subj, Formula), "What are we doing concluding %s is true?" % subj subj.resetRenames(True) self.loadFormulaWithSubstitution(subj.renameVars()) subj.resetRenames(False) ######### if newBindings != {}: self.substituteEqualsInPlace(newBindings) ####### s = StoredStatement((self, pred, subj, obj)) if diag.tracking: if (why is None): raise RuntimeError( "Tracking reasons but no reason given for"+`s`) report(s, why) # Build 8 indexes. # This now takes a lot of the time in a typical cwm run! :-( # I honestly think the above line is a bit pessemistic. The below lines scale. # The above lines do not (removeStatement does not scale) if subj is self: # Catch variable declarations if pred is self.store.forAll: if obj not in self._universalVariables: if diag.chatty_flag > 50: progress("\tUniversal ", obj) self._universalVariables.add(obj) return 1 if pred is self.store.forSome: if obj not in self._existentialVariables: if diag.chatty_flag > 50: progress("\tExistential ", obj) self._existentialVariables.add(obj) return 1 raise ValueError("You cannot use 'this' except as subject of forAll or forSome") self.statements.append(s) list = self._index.get((None, None, obj), None) if list is None: self._index[(None, None, obj)]=[s] else: list.append(s) list = self._index.get((None, subj, None), None) if list is None: self._index[(None, subj, None)]=[s] else: list.append(s) list = self._index.get((None, subj, obj), None) if list is None: self._index[(None, subj, obj)]=[s] else: list.append(s) list = self._index.get((pred, None, None), None) if list is None: self._index[(pred, None, None)]=[s] else: list.append(s) rein = self.newSymbol('http://dig.csail.mit.edu/2005/09/rein/network#requester') list = self._index.get((pred, None, obj), None) if list is None: self._index[(pred, None, obj)]=[s] else: list.append(s) list = self._index.get((pred, subj, None), None) if list is None: self._index[(pred, subj, None)]=[s] else: list.append(s) list = self._index.get((pred, subj, obj), None) if list is None: self._index[(pred, subj, obj)]=[s] else: list.append(s) if self._closureMode != "": self.checkClosure(subj, pred, obj) try: if self.isWorkingContext and diag.chatty_flag > 20: progress("adding", (subj, pred, obj)) except: pass return 1 # One statement has been added @@ ignore closure extras from closure # Obsolete this return value? @@@ def removeStatement(self, s): """Removes a statement The formula must be open. This implementation is alas slow, as removal of items from tha hash is slow. The above statement is false. Removing items from a hash is easily over five times faster than removing them from a list. Also, truth mainainance is not done. You can't undeclare things equal. This is really a low-level method, used within add() and for cleaning up the store to save space in purge() etc. """ assert self.canonical is None, "Cannot remove statement from canonnical"+`self` self.store.size = self.store.size-1 if diag.chatty_flag > 97: progress("removing %s" % (s)) context, pred, subj, obj = s.quad self.statements.remove(s) self._index[(None, None, obj)].remove(s) self._index[(None, subj, None)].remove(s) self._index[(None, subj, obj)].remove(s) self._index[(pred, None, None)].remove(s) self._index[(pred, None, obj)].remove(s) self._index[(pred, subj, None)].remove(s) self._index[(pred, subj, obj)].remove(s) #raise RuntimeError("The triple is %s: %s %s %s"%(context, pred, subj, obj)) return def newCanonicalize(F): ## Horrible name! if self._hashval is not None: return from term import Existential, Universal statements = [] def convert(n): if isinstance(n, Universal): return Universal if isinstance(n, Existential): return Existential return n for statement in self.statements: statements.append(tuple([convert(x) for x in statement])) self._hashval = hash(ImmutableSet(statements)) def canonicalize(F, cannon=False): """If this formula already exists, return the master version. If not, record this one and return it. Call this when the formula is in its final form, with all its statements. Make sure no one else has a copy of the pointer to the smushed one. In canonical form, - the statments are ordered - the lists are all internalized as lists Store dependency: Uses store._formulaeOfLength """ if diag.chatty_flag > 70: progress('I got here') store = F.store if F.canonical != None: if diag.chatty_flag > 70: progress("End formula -- @@ already canonical:"+`F`) return F.canonical if F.stayOpen: if diag.chatty_flag > 70: progress("Canonicalizion ignored: @@ Knowledge base mode:"+`F`) return F F.store._equivalentFormulae.add(F) if (diag.tracking and isTopLevel(F)) or (F._renameVarsMaps and not cannon): ## we are sitting in renameVars --- don't bother F.canonical = F return F fl = F.statements l = len(fl), len(F.universals()), len(F.existentials()) possibles = store._formulaeOfLength.get(l, None) # Any of same length if possibles is None: store._formulaeOfLength[l] = [F] if diag.chatty_flag > 70: progress("End formula - first of length", l, F) F.canonical = F F.reallyCanonical = True return F if diag.chatty_flag > 70: progress('I got here, possibles = ', possibles) fl.sort() fe = F.existentials() #fe.sort(Term.compareAnyTerm) fu = F.universals () #fu.sort(Term.compareAnyTerm) for G in possibles: # progress("Just checking.\n", # "\n", "_"*80, "\n", F.debugString(), # "\n", "_"*80, "\n", G.debugString(), # ) gl = G.statements gkey = len(gl), len(G.universals()), len(G.existentials()) if gkey != l: raise RuntimeError("@@Key of %s is %s instead of %s" %(G, `gkey`, `l`)) gl.sort() for se, oe, in ((fe, G.existentials()), (fu, G.universals())): if se != oe: break for i in range(l[0]): for p in PRED, SUBJ, OBJ: if (fl[i][p] is not gl[i][p]): # progress("""Mismatch on part %i on statement %i. # Becaue %s is not %s""" # % (p, i, `fl[i][p].uriref()`, `gl[i][p].uriref()`), # ) # for x in (fl[i][p], gl[i][p]): # progress("Class %s, id=%i" %(x.__class__, id(x))) # # if Formula.unify(F,G): # progress("""Unifies but did not match on part %i on statement %i. # Because %s is not %s""" # % (p, i, `fl[i][p].uriref()`, `gl[i][p].uriref()`), # "\n", "_"*80, "\n", F.debugString(), # "\n", "_"*80, "\n", G.debugString() # ) # raise RuntimeError("foundOne") break # mismatch else: #match one statement continue break else: #match # if not Formula.unify(F,G): # raise RuntimeError("Look the same but don't unify") if tracking: smushedFormula(F,G) if diag.chatty_flag > 70: progress( "** End Formula: Smushed new formula %s giving old %s" % (F, G)) F.canonical = G del(F) # Make sure it ain't used again return G possibles.append(F) F.canonical = F F.reallyCanonical = True if diag.chatty_flag > 70: progress("End formula, a fresh one:"+`F`) ## for k in possibles: ## print 'one choice is' ## print k.n3String() ## print '--------\n--------' ## raise RuntimeError(F.n3String()) return F def reopen(self): """Make a formula which was once closed oopen for input again. NOT Recommended. Dangers: this formula will be, because of interning, the same objet as a formula used elsewhere which happens to have the same content. You mess with this one, you mess with that one. Much better to keep teh formula open until you don't needed it open any more. The trouble is, the parsers close it at the moment automatically. To be fixed.""" return self.store.reopen(self) def setClosureMode(self, x): self._closureMode = x def checkClosure(self, subj, pred, obj): """Check the closure of the formula given new contents The s p o flags cause llyn to follow those parts of the new statement. i asks it to follow owl:imports r ask it to follow doc:rules """ firstCall = (self._closureAgenda == []) if "s" in self._closureMode: self.checkClosureOfSymbol(subj) if "p" in self._closureMode: self.checkClosureOfSymbol(pred) if ("o" in self._closureMode or "t" in self._closureMode and pred is self.store.type): self.checkClosureOfSymbol(obj) if (("r" in self._closureMode and pred is self.store.docRules) or ("i" in self._closureMode and pred is self.store.imports)): # check subject? @@@ semantics? self.checkClosureDocument(obj) if firstCall: while self._closureAgenda != []: x = self._closureAgenda.pop() self._closureAlready.append(x) x.dereference("m" + self._closureMode, self) def checkClosureOfSymbol(self, y): if not isinstance(y, Fragment): return return self.checkClosureDocument(y.resource) def checkClosureDocument(self, x): if x != None and x not in self._closureAlready and x not in self._closureAgenda: self._closureAgenda.append(x) def outputStrings(self, channel=None, relation=None): """Fetch output strings from store, sort and output To output a string, associate (using the given relation) with a key such that the order of the keys is the order in which you want the corresponding strings output. """ if channel is None: channel = sys.stdout if relation is None: relation = self.store.intern((SYMBOL, Logic_NS + "outputString")) list = self.statementsMatching(pred=relation) # List of things of (subj, obj) pairs pairs = [] for s in list: pairs.append((s[SUBJ], s[OBJ])) pairs.sort(comparePair) for key, str in pairs: if not hasattr(str, "string"): print `str` channel.write(str.string.encode('utf-8')) def debugString(self, already=[]): """A simple dump of a formula in debug form. This formula is dumped, using ids for nested formula. Then, each nested formula mentioned is dumped.""" red = "" if self._redirections != {}: red = " redirections:" + `self._redirections` str = `self`+ red + unicode(id(self)) + " is {" for vv, ss in ((self.universals().copy(), "@forAll"),(self.existentials().copy(), "@forSome")): if vv != Set(): str = str + " " + ss + " " + `vv.pop()` for v in vv: str = str + ", " + `v` str = str + "." todo = [] for s in self.statements: subj, pred, obj = s.spo() str = str + "\n%28s %20s %20s ." % (`subj`, `pred`, `obj`) for p in PRED, SUBJ, OBJ: if (isinstance(s[p], CompoundTerm) and s[p] not in already and s[p] not in todo and s[p] is not self): todo.append(s[p]) str = str+ "}.\n" already = already + todo + [ self ] for f in todo: str = str + " " + f.debugString(already) return str def _noteNewList(self, bnode, list, newBindings): """Note that we have a new list. Check whether this new list (given as bnode) causes other things to become lists. Set up redirection so the list is used from now on instead of the bnode. Internal function. This function is extraordinarily slow, .08 seconds per call on reify/reify3.n3""" if diag.chatty_flag > 80: progress("New list was %s, now %s = %s"%(`bnode`, `list`, `list.value()`)) if isinstance(bnode, List): return ##@@@@@ why is this necessary? weid. newBindings[bnode] = list if diag.chatty_flag > 80: progress("...New list newBindings %s"%(`newBindings`)) self._existentialVariables.discard(bnode) possibles = self.statementsMatching(pred=self.store.rest, obj=bnode) # What has this as rest? for s in possibles[:]: L2 = s[SUBJ] ff = self.statementsMatching(pred=self.store.first, subj=L2) if ff != []: first = ff[0][OBJ] self.removeStatement(s) self.removeStatement(ff[0]) list2 = list.prepend(first) self._noteNewList(L2, list2, newBindings) possibleSets = self.statementsMatching(pred=self.store.owlOneOf, obj=bnode) if possibleSets: new_set = self.store.newSet(list) for s in possibleSets[:]: s2 = s[SUBJ] if s2 in self._existentialVariables: self.removeStatement(s) self._noteNewSet(s2, new_set, newBindings) return def _noteNewSet(self, bnode, set, newBindings): newBindings[bnode] = set if diag.chatty_flag > 80: progress("...New set newBindings %s"%(`newBindings`)) self._existentialVariables.discard(bnode) def substituteEqualsInPlace(self, redirections, why=None): """Slow ... does not use indexes""" bindings = redirections while bindings != {}: self._redirections.update(bindings) newBindings = {} for s in self.statements[:]: # take a copy! changed = 0 quad = [self, s[PRED], s[SUBJ], s[OBJ]] for p in PRED, SUBJ, OBJ: x = s[p] y = x.substituteEquals(bindings, newBindings) if y is not x: if diag.chatty_flag>90: progress("Substituted %s -> %s in place" %(x, y)) changed = 1 quad[p] = y if changed: self.removeStatement(s) self.add(subj=quad[SUBJ], pred=quad[PRED], obj=quad[OBJ], why=why) bindings = newBindings if diag.chatty_flag>70: progress("Substitions %s generated %s" %(bindings, newBindings)) return ## def unify(self, other, vars=Set([]), existentials=Set([]), bindings={}): def unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source): if self.canonical and other.canonical and self.store._equivalentFormulae.connected(self, other): yield (env1, env2) else: from query import n3Equivalent, testIncludes freeVars = self.freeVariables() ## We can't use these retVal = n3Equivalent(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source) # \ ## and n3Entails(self, other, vars=vars, existentials=existentials, bindings=bindings) for (env11, env12) in retVal: if env11 == env1 and env12 == env2: self.store._equivalentFormulae.merge(self, other) yield (env11, env12) ## unify = memoize(unify) def comparePair(self, other): "Used only in outputString" for i in 0,1: x = self[i].compareAnyTerm(other[i]) if x != 0: return x ############################################################################################### # # C W M - S P E C I A L B U I L T - I N s # ########################################################################### # Equivalence relations class BI_EqualTo(LightBuiltIn,Function, ReverseFunction): def eval(self, subj, obj, queue, bindings, proof, query): return (subj is obj) # Assumes interning def evalObj(self, subj, queue, bindings, proof, query): return subj def evalSubj(self, obj, queue, bindings, proof, query): return obj class BI_notEqualTo(LightBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): return (subj is not obj) # Assumes interning BI_SameAs = BI_EqualTo #### I hope this is never really added ##class BI_RunAsPython(LightBuiltIn, Function): ## def evaluateObject(self, subject): ## return eval(subject) # Functions class BI_uri(LightBuiltIn, Function, ReverseFunction): def evalObj(self, subj, queue, bindings, proof, query): type, value = subj.asPair() if type == SYMBOL: return self.store.intern((LITERAL, value)) def evaluateSubject(self, object): """Return the object which has this string as its URI #@@hm... check string for URI syntax? # or at least for non-uri chars, such as space? Note that relative URIs can be OK as the whole process has a base, which may be irrelevant. Eg see roadmap-test in retest.sh """ store = self.store if ':' not in object: progress("Warning: taking log:uri of non-abs: %s" % object) return None #except (TypeError, AttributeError): # return None return store.intern((SYMBOL, object)) class BI_dtlit(LightBuiltIn, Function): """built a datatype literal from a string and a uri""" def evaluateObject(self, subj_py): lex, dt = subj_py if dt is self.store.symbol("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral"): try: dom = XMLtoDOM(lex) except SyntaxError, e: raise UnknownType # really malformed literal return self.store.newXMLLiteral(dom) else: return self.store.newLiteral(lex, dt) class BI_rawUri(BI_uri): """This is like uri except that it allows you to get the internal identifiers for anonymous nodes and formuale etc.""" def evalObj(self, subj, queue, bindings, proof, query): type, value = subj.asPair() return self.store.intern((LITERAL, value)) class BI_rawType(LightBuiltIn, Function): """ The raw type is a type from the point of view of the langauge: is it a formula, list, and so on. Needed for test for formula in finding subformulae eg see test/includes/check.n3 """ def evalObj(self, subj, queue, bindings, proof, query): store = self.store if isinstance(subj, Literal): y = store.Literal elif isinstance(subj, Formula): y = store.Formula elif isinstance(subj, List): y = store.List elif isinstance(subj, N3Set): y = store.Set elif isinstance(subj, AnonymousNode): y = store.Blank else: y = store.Other # None? store.Other? if diag.chatty_flag > 91: progress("%s rawType %s." %(`subj`, y)) return y class BI_racine(LightBuiltIn, Function): # The resource whose URI is the same up to the "#" def evalObj(self, subj, queue, bindings, proof, query): if isinstance(subj, Fragment): return subj.resource else: return subj # Heavy Built-ins class BI_includes(HeavyBuiltIn): """Check that one formula does include the other. This limits the ability to bind a variable by searching inside another context. This is quite a limitation in some ways. @@ fix """ def eval(self, subj, obj, queue, bindings, proof, query): store = subj.store if isinstance(subj, Formula) and isinstance(obj, Formula): return testIncludes(subj, obj, bindings=bindings) # No (relevant) variables return 0 class BI_notIncludes(HeavyBuiltIn): """Check that one formula does not include the other. notIncludes is a heavy function not only because it may take more time than a simple search, but also because it must be performed after other work so that the variables within the object formula have all been subsituted. It makes no sense to ask a notIncludes question with variables, "Are there any ?x for which F does not include foo bar ?x" because of course there will always be an infinite number for any finite F. So notIncludes can only be used to check, when a specific case has been found, that it does not exist in the formula. This means we have to know that the variables do not occur in obj. As for the subject, it does make sense for the opposite reason. If F(x) includes G for all x, then G would have to be infinite. """ def eval(self, subj, obj, queue, bindings, proof, query): store = subj.store if isinstance(subj, Formula) and isinstance(obj, Formula): return not testIncludes(subj, obj, bindings=bindings, interpretBuiltins=0) # No (relevant) variables return 0 # Can't say it *doesn't* include it if it ain't a formula class BI_notIncludesWithBuiltins(HeavyBuiltIn): def eval(self, subj, obj, queue, bindings, proof, query): store = subj.store if isinstance(subj, Formula) and isinstance(obj, Formula): return not testIncludes(subj, obj, bindings=bindings, interpretBuiltins=1) # No (relevant) variables return 0 # Can't say it *doesn't* include it if it ain't a formula class BI_semantics(HeavyBuiltIn, Function): """ The semantics of a resource are its machine-readable meaning, as an N3 forumula. The URI is used to find a representation of the resource in bits which is then parsed according to its content type.""" def evalObj(self, subj, queue, bindings, proof, query): store = subj.store if isinstance(subj, Fragment): doc = subj.resource else: doc = subj F = store.any((store._experience, store.semantics, doc, None)) if F != None: if diag.chatty_flag > 10: progress("Already read and parsed "+`doc`+" to "+ `F`) return F if diag.chatty_flag > 10: progress("Reading and parsing " + doc.uriref()) inputURI = doc.uriref() # if diag.tracking: flags="B" # @@@@@@@@@@@ Yuk # else: flags="" F = self.store.load(inputURI, why=becauseSubexpression) if diag.chatty_flag>10: progress(" semantics: %s" % (F)) return F.canonicalize() class BI_semanticsWithImportsClosure(HeavyBuiltIn, Function): """ The semantics of a resource are its machine-readable meaning, as an N3 forumula. The URI is used to find a representation of the resource in bits which is then parsed according to its content type. Extension : It also loads all imported URIs""" def evalObj(self, subj, queue, bindings, proof, query): store = subj.store if isinstance(subj, Fragment): doc = subj.resource else: doc = subj F = store.any((store._experience, store.semanticsWithImportsClosure, doc, None)) if F != None: if diag.chatty_flag > 10: progress("Already read and parsed "+`doc`+" to "+ `F`) return F if diag.chatty_flag > 10: progress("Reading and parsing with closure " + doc.uriref()) inputURI = doc.uriref() F = store.newFormula() F.setClosureMode("i") F = store.load(uri=inputURI, openFormula=F) if diag.chatty_flag>10: progress("Reading and parsing with closure done. semantics: %s" % (F)) # if diag.tracking: # proof.append(F.collector) F = F.close() store.storeQuad((store._experience, store.semanticsWithImportsClosure, doc, F)) return F import httplib class BI_semanticsOrError(BI_semantics): """ Either get and parse to semantics or return an error message on any error """ def evalObj(self, subj, queue, bindings, proof, query): import xml.sax._exceptions # hmm... store = subj.store x = store.any((store._experience, store.semanticsOrError, subj, None)) if x != None: if diag.chatty_flag > 10: progress(`store._experience`+`store.semanticsOrError`+": Already found error for "+`subj`+" was: "+ `x`) return x try: return BI_semantics.evalObj(self, subj, queue, bindings, proof, query) except (IOError, SyntaxError, DocumentAccessError, xml.sax._exceptions.SAXParseException, httplib.BadStatusLine): message = sys.exc_info()[1].__str__() result = store.intern((LITERAL, message)) if diag.chatty_flag > 0: progress(`store.semanticsOrError`+": Error trying to access <" + `subj` + ">: "+ message) store.storeQuad((store._experience, store.semanticsOrError, subj, result)) return result def loadToStore(term, types): """load content from the web and keep it in the store's experience. return resulting literal term raises IOError the log:content built-in could keep an HTTP response object around a la tabulator too. yes. You learn a lot from a recode. """ if isinstance(term, Fragment): doc = term.resource # i.e. racine else: doc = term store = term.store #hmm... separate store from term? C = store.any((store._experience, store.content, doc, None)) if C != None: if diag.chatty_flag > 10: progress("already read " + `doc`) return C if diag.chatty_flag > 10: progress("Reading " + `doc`) inputURI = doc.uriref() netStream = webget(inputURI, types) #@@ get charset from headers str = netStream.read().decode('utf-8') C = store.intern((LITERAL, str)) store.storeQuad((store._experience, store.content, doc, C)) return C class BI_content(HeavyBuiltIn, Function): def evalObj(self, subj, queue, bindings, proof, query): try: return loadToStore(subj, []) except IOError: return None # hmm... is built-in API evolving to support exceptions? class BI_xmlTree(HeavyBuiltIn, Function): def evalObj(self, subj, queue, bindings, proof, query): x= BI_content.evalObj(self, subj, queue, bindings, proof, query) dom = XMLtoDOM(x.value()) return subj.store.intern((XMLLITERAL, dom)) class BI_parsedAsN3(HeavyBuiltIn, Function): def evalObj(self, subj, queue, bindings, proof, query): store = subj.store if isinstance(subj, Literal): F = store.any((store._experience, store.parsedAsN3, subj, None)) if F != None: return F if diag.chatty_flag > 10: progress("parsing " + subj.string[:30] + "...") inputURI = subj.asHashURI() # iffy/bogus... rather asDataURI? yes! but make more efficient p = notation3.SinkParser(store) p.startDoc() p.feed(subj.string.encode('utf-8')) #@@ catch parse errors F = p.endDoc() F = F.close() store._experience.add(subj=subj, pred=store.parsedAsN3, obj=F) return F class BI_conclusion(HeavyBuiltIn, Function): """ Deductive Closure Closure under Forward Inference, equivalent to cwm's --think function. This is a function, so the object is calculated from the subject. """ def evalObj(self, subj, queue, bindings, proof, query): store = subj.store if isinstance(subj, Formula): assert subj.canonical != None F = self.store.any((store._experience, store.cufi, subj, None)) # Cached value? if F != None: if diag.chatty_flag > 10: progress("Bultin: " + `subj`+ " cached log:conclusion " + `F`) return F F = self.store.newFormula() newTopLevelFormula(F) if diag.tracking: reason = Premise("Assumption of builtin", (subj, self)) # reason = BecauseMerge(F, subj) # F.collector = reason # proof.append(reason) else: reason = None if diag.chatty_flag > 10: progress("Bultin: " + `subj`+ " log:conclusion " + `F`) self.store.copyFormula(subj, F, why=reason) # leave open think(F) F = F.close() assert subj.canonical != None self.store.storeQuad((store._experience, store.cufi, subj, F), why=BecauseOfExperience("conclusion")) # Cache for later return F class BI_supports(HeavyBuiltIn): """A more managable version of log:conclusion The real version of this should appear in query.py """ def eval(self, subj, obj, queue, bindings, proof, query): pass class BI_filter(LightBuiltIn, Function): """Filtering of formulae """ def evalObj(self, subj, queue, bindings, proof, query): store = subj.store if not isinstance(subj, List): raise ValueError('I need a list of two formulae') list = [x for x in subj] if len(list) != 2: raise ValueError('I need a list of TWO formulae') if diag.chatty_flag > 30: progress("=== begin filter of:" + `list`) # list = [bindings.get(a,a) for a in list] base, filter = list F = self.store.newFormula() if diag.tracking: pass else: reason = None applyRules(base, filter, F) F = F.close() if diag.chatty_flag > 30: progress("=== end filter of:" + `list` + "we got: " + `F`) return F class BI_vars(LightBuiltIn, Function): """Get only the variables from a formula """ def evalObj(self, subj, queue, bindings, proof, query): F = self.store.newFormula() #F.existentials().update(subj.existentials()) F.universals().update(subj.universals()) return F.close() class BI_universalVariableName(RDFBuiltIn): #, MultipleFunction): """Is the object the name of a universal variable in the subject? Runs even without interpretBuitins being set. Used internally in query.py for testing for Can be used as a test, or returns a sequence of values.""" def eval(self, subj, obj, queue, bindings, proof, query): if not isinstance(subj, Formula): return None s = str(obj) if diag.chatty_flag > 180: progress(`subj.universals()`) return obj in subj.universals() for v in subj.universals(): if v.uriref() == s: return 1 return 0 def evalObj(self,subj, queue, bindings, proof, query): if not isinstance(subj, Formula): return None return [subj.newLiteral(x.uriref()) for x in subj.universals()] class BI_existentialVariableName(RDFBuiltIn): #, MultipleFunction): """Is the object the name of a existential variable in the subject? Can be used as a test, or returns a sequence of values. Currently gives BNode names too. Maybe we make sep function for that?""" def eval(self, subj, obj, queue, bindings, proof, query): if not isinstance(subj, Formula): return None s = str(obj) if obj not in subj.existentials() and diag.chatty_flag > 25: progress('Failed, which is odd. Subj="%s", Obj="%s"' % (subj.debugString(), obj.debugString())) return obj in subj.existentials() for v in subj.existentials(): if v.uriref() == s: return 1 return 0 def evalObj(self,subj, queue, bindings, proof, query): if not isinstance(subj, Formula): return None rea = None return [subj.newLiteral(x.uriref()) for x in subj.existentials()] class BI_enforceUniqueBinding(RDFBuiltIn): """Is the mapping from the variable in the subject to the name in the object unique? """ def eval(self, subj, obj, queue, bindings, proof, query): if not isinstance(subj, Formula): return None s = str(obj) if subj not in query.backwardMappings: query.backwardMappings[subj] = s return True return query.backwardMappings[subj] == s class BI_conjunction(LightBuiltIn, Function): # Light? well, I suppose so. """ The conjunction of a set of formulae is the set of statements which is just the union of the sets of statements modulo non-duplication of course.""" def evalObj(self, subj, queue, bindings, proof, query): subj_py = subj.value() if diag.chatty_flag > 50: progress("Conjunction input:"+`subj_py`) for x in subj_py: progress(" conjunction input formula %s has %i statements" % (x, x.size())) F = self.store.newFormula() if diag.tracking: reason = Because("I said so #4") #reason = BecauseMerge(F, subj_py) else: reason = None for x in subj_py: if not isinstance(x, Formula): return None # Can't if (x.canonical == None): # Not closed! !! F.canonical != None progress("Conjunction input NOT CLOSED:"+`x`) #@@@ self.store.copyFormula(x, F, why=reason) # No, that is if diag.chatty_flag > 74: progress(" Formula %s now has %i" % (`F`,len(F.statements))) return F.canonicalize() class BI_n3String(LightBuiltIn, Function): # Light? well, I suppose so. """ The n3 string for a formula is what you get when you express it in the N3 language without using any URIs. Note that there is no guarantee that two implementations will generate the same thing, but whatever they generate should parse back using parsedAsN3 to exaclty the same original formula. If we *did* have a canonical form it would be great for signature A canonical form is possisble but not simple.""" def evalObj(self, subj, queue, bindings, proof, query): if diag.chatty_flag > 50: progress("Generating N3 string for:"+`subj`) if isinstance(subj, Formula): return self.store.intern((LITERAL, subj.n3String())) class BI_reification(HeavyBuiltIn, Function, ReverseFunction): """ """ def evalSubj(self, obj, queue, bindings, proof, query): f = obj.store.newFormula() return reify.dereification(obj, f, obj.store) def evalObj(self, subj, queue, bindings, proof, query): f = subj.store.newFormula() q = subj.reification(f, {}, why=None) f=f.close() self.store.storeQuad((self.store._experience, self.store.type, f, 3), why=BecauseOfExperience("SomethingOrOther")) return q import weakref class Disjoint_set(object): class disjoint_set_node(object): def __init__(self, val): self.value = weakref.ref(val) self.parent = None self.rank = 0 def link(self, other): if other.parent or self.parent: raise RuntimeError if self.rank > other.rank: other.parent = self else: self.parent = other if self.rank == other.rank: other.rank += 1 def find_set(self): if self.parent is None: return self self.parent = self.parent.find_set() return self.parent def disjoint(self, other): return self() is not other() def connected(self, other): return self() is other() __call__ = find_set def __init__(self): self.map = weakref.WeakKeyDictionary() def add(self, f): self.map[f] = self.disjoint_set_node(f) def connected(self, f, g): return self.map[f].connected(self.map[g]) def merge(self, s1, s2): s1 = self.map[s1]() s2 = self.map[s2]() s1.link(s2) ################################################################################################ class RDFStore(RDFSink) : """ Absorbs RDF stream and saves in triple store """ def clear(self): "Remove all formulas from the store @@@ DOESN'T ACTUALLY DO IT/BROKEN" self.resources = WeakValueDictionary() # Hash table of URIs for interning things # self.formulae = [] # List of all formulae self._experience = None # A formula of all the things program run knows from direct experience self._formulaeOfLength = {} # A dictionary of all the constant formuale in the store, lookup by length key. self._formulaeOfLengthPerWorkingContext = {} self.size = 0 self._equivalentFormulae = Disjoint_set() def __init__(self, genPrefix=None, metaURI=None, argv=None, crypto=0): RDFSink.__init__(self, genPrefix=genPrefix) self.clear() self.argv = argv # List of command line arguments for N3 scripts run = uripath.join(uripath.base(), ".RUN/") + `time.time()` # Reserrved URI @@ if metaURI != None: meta = metaURI else: meta = run + "meta#formula" self.reset(meta) # Constants, as interned: self.forSome = self.symbol(forSomeSym) self.integer = self.symbol(INTEGER_DATATYPE) self.float = self.symbol(FLOAT_DATATYPE) self.boolean = self.symbol(BOOL_DATATYPE) self.decimal = self.symbol(DECIMAL_DATATYPE) self.forAll = self.symbol(forAllSym) self.implies = self.symbol(Logic_NS + "implies") self.insertion = self.symbol(Delta_NS + "insertion") self.deletion = self.symbol(Delta_NS + "deletion") self.means = self.symbol(Logic_NS + "means") self.asserts = self.symbol(Logic_NS + "asserts") # Register Light Builtins: log = self.symbol(Logic_NS[:-1]) # The resource without the hash # Functions: log.internFrag("racine", BI_racine) # Strip fragment identifier from string log.internFrag("dtlit", BI_dtlit) self.rawType = log.internFrag("rawType", BI_rawType) # syntactic type, oneOf: log.internFrag("rawUri", BI_rawUri) self.Literal = log.internFrag("Literal", Fragment) # syntactic type possible value - a class self.List = log.internFrag("List", Fragment) # syntactic type possible value - a class self.Set = log.internFrag("Set", Fragment) # syntactic type possible value - a class self.Formula = log.internFrag("Formula", Fragment) # syntactic type possible value - a class self.Blank = log.internFrag("Blank", Fragment) self.Other = log.internFrag("Other", Fragment) # syntactic type possible value - a class self.filter = log.internFrag("filter", BI_filter) # equivilent of --filter self.vars = log.internFrag("vars", BI_vars) # variables of formula self.universalVariableName = log.internFrag( "universalVariableName", BI_universalVariableName) self.existentialVariableName = log.internFrag( "existentialVariableName", BI_existentialVariableName) self.enforceUniqueBinding = log.internFrag( "enforceUniqueBinding", BI_enforceUniqueBinding) log.internFrag("conjunction", BI_conjunction) # Bidirectional things: log.internFrag("uri", BI_uri) log.internFrag("equalTo", BI_EqualTo) log.internFrag("notEqualTo", BI_notEqualTo) log.internFrag("reification", BI_reification) owl = self.symbol(OWL_NS[:-1]) self.sameAs = owl.internFrag("sameAs", BI_SameAs) # Heavy relational operators: self.includes = log.internFrag( "includes", BI_includes) self.supports = log.internFrag( "supports", BI_supports) # log.internFrag("directlyIncludes", BI_directlyIncludes) self.notIncludes = log.internFrag("notIncludes", BI_notIncludes) self.smartNotIncludes = log.internFrag("notIncludesWithBuiltins", BI_notIncludesWithBuiltins) # log.internFrag("notDirectlyIncludes", BI_notDirectlyIncludes) #Heavy functions: # log.internFrag("resolvesTo", BI_semantics) # obsolete self.semantics = log.internFrag("semantics", BI_semantics) self.cufi = log.internFrag("conclusion", BI_conclusion) self.semanticsOrError = log.internFrag("semanticsOrError", BI_semanticsOrError) self.semanticsWithImportsClosure = log.internFrag("semanticsWithImportsClosure", BI_semanticsWithImportsClosure) self.content = log.internFrag("content", BI_content) self.parsedAsN3 = log.internFrag("parsedAsN3", BI_parsedAsN3) self.n3ExprFor = log.internFrag("n3ExprFor", BI_parsedAsN3) ## Obsolete log.internFrag("n3String", BI_n3String) # Remote service flag in metadata: self.definitiveService = log.internFrag("definitiveService", Fragment) self.definitiveDocument = log.internFrag("definitiveDocument", Fragment) self.pointsAt = log.internFrag("pointsAt", Fragment) # This was EricP's # Constants: self.Truth = self.symbol(Logic_NS + "Truth") self.Falsehood = self.symbol(Logic_NS + "Falsehood") self.type = self.symbol(RDF_type_URI) self.Chaff = self.symbol(Logic_NS + "Chaff") self.docRules = self.symbol("http://www.w3.org/2000/10/swap/pim/doc#rules") self.imports = self.symbol("http://www.w3.org/2002/07/owl#imports") self.owlOneOf = self.symbol('http://www.w3.org/2002/07/owl#oneOf') # List stuff - beware of namespace changes! :-( from cwm_list import BI_first, BI_rest rdf = self.symbol(List_NS[:-1]) self.first = rdf.internFrag("first", BI_first) self.rest = rdf.internFrag("rest", BI_rest) self.nil = self.intern(N3_nil, FragmentNil) self.Empty = self.intern(N3_Empty) self.li = self.intern(N3_li) self.List = self.intern(N3_List) import cwm_string # String builtins import cwm_os # OS builtins import cwm_time # time and date builtins import cwm_math # Mathematics import cwm_trigo # Trignometry import cwm_times # time and date builtins import cwm_maths # Mathematics, perl/string style import cwm_list # List handling operations import cwm_set # Set operations import cwm_sparql # builtins for sparql import cwm_xml # XML Document Object Model operations cwm_string.register(self) cwm_math.register(self) cwm_trigo.register(self) cwm_maths.register(self) cwm_os.register(self) cwm_time.register(self) cwm_times.register(self) cwm_list.register(self) cwm_set.register(self) cwm_sparql.register(self) cwm_xml.register(self) import cwm_crypto # Cryptography if crypto: if cwm_crypto.USE_PKC == 0: raise RuntimeError("Try installing pycrypto, and make sure it is in you PYTHONPATH") else: cwm_crypto.USE_PKC = 0 cwm_crypto.register(self) # would like to anyway to catch bug if used but not available def newLiteral(self, str, dt=None, lang=None): "Interned version: generate new literal object as stored in this store" key = (str, dt, lang) result = self.resources.get(key, None) if result != None: return result # if dt is not None: dt = self.newSymbol(dt) assert dt is None or isinstance(dt, LabelledNode) if dt is not None and not isinstance(dt, Fragment): progress("Warning: <%s> is not a fragment!" % dt) result = Literal(self, str, dt, lang) self.resources[key] = result return result def newXMLLiteral(self, dom): # We do NOT intern these so they will NOT have 'is' same as '==' return XMLLiteral(self, dom) def newFormula(self, uri=None): return IndexedFormula(self, uri) def newSymbol(self, uri): return self.intern(RDFSink.newSymbol(self, uri)) def newSet(self, iterator=[], context=None): new_set = N3Set(iterator) Term.__init__(new_set, self) return new_set def newBlankNode(self, context, uri=None, why=None): """Create or reuse, in the default store, a new unnamed node within the given formula as context, and return it for future use""" return context.newBlankNode(uri=uri) def newExistential(self, context, uri=None, why=None): """Create or reuse, in the default store, a new named variable existentially qualified within the given formula as context, and return it for future use""" return self.intern(RDFSink.newExistential(self, context, uri, why=why)) def newUniversal(self, context, uri=None, why=None): """Create or reuse, in the default store, a named variable universally qualified within the given formula as context, and return it for future use""" return self.intern(RDFSink.newUniversal(self, context, uri, why=why)) ################### def reset(self, metaURI): # Set the metaURI self._experience = self.newFormula(metaURI + "_formula") assert isinstance(self._experience, Formula) def load(store, uri=None, openFormula=None, asIfFrom=None, contentType=None, remember=1, flags="", referer=None, why=None, topLevel=False): """Get and parse document. Guesses format if necessary. uri: if None, load from standard input. remember: if 1, store as metadata the relationship between this URI and this formula. Returns: top-level formula of the parsed document. Raises: IOError, SyntaxError, DocumentError This was and could be an independent function, as it is fairly independent of the store. However, it is natural to call it as a method on the store. And a proliferation of APIs confuses. """ baseURI = uripath.base() givenOpenFormula = openFormula if openFormula is None: openFormula = store.newFormula() if topLevel: newTopLevelFormula(openFormula) if uri != None and openFormula==None and remember: addr = uripath.join(baseURI, uri) # Make abs from relative source = store.newSymbol(addr) F = store._experience.the(source, store.semantics) if F != None: if diag.chatty_flag > 40: progress("Using cached semantics for",addr) return F F = webAccess.load(store, uri, openFormula, asIfFrom, contentType, flags, referer, why) store._experience.add( store.intern((SYMBOL, addr)), store.semantics, F, why=BecauseOfExperience("load document")) return F return webAccess.load(store, uri, openFormula, asIfFrom, contentType, flags, \ referer=referer, why=why) def loadMany(self, uris, openFormula=None, referer=None): """Get, parse and merge serveral documents, given a list of URIs. Guesses format if necessary. Returns top-level formula which is the parse result. Raises IOError, SyntaxError """ assert type(uris) is type([]) if openFormula is None: F = self.newFormula() else: F = openFormula f = F.uriref() for u in uris: F.reopen() # should not be necessary self.load(u, openFormula=F, remember=0, referer=referer) return F.close() def genId(self): """Generate a new identifier This uses the inherited class, but also checks that we haven't for some pathalogical reason ended up generating the same one as for example in another run of the same system. """ while 1: uriRefString = RDFSink.genId(self) hash = string.rfind(uriRefString, "#") if hash < 0 : # This is a resource with no fragment return uriRefString # ?! resid = uriRefString[:hash] r = self.resources.get(resid, None) if r is None: return uriRefString fragid = uriRefString[hash+1:] f = r.fragments.get(fragid, None) if f is None: return uriRefString if diag.chatty_flag > 70: progress("llyn.genid Rejecting Id already used: "+uriRefString) def checkNewId(self, urirefString): """Raise an exception if the id is not in fact new. This is useful because it is usfeul to generate IDs with useful diagnostic ways but this lays them open to possibly clashing in pathalogical cases.""" hash = string.rfind(urirefString, "#") if hash < 0 : # This is a resource with no fragment result = self.resources.get(urirefString, None) if result is None: return else: r = self.resources.get(urirefString[:hash], None) if r is None: return f = r.fragments.get(urirefString[hash+1:], None) if f is None: return raise ValueError("Ooops! Attempt to create new identifier hits on one already used: %s"%(urirefString)) return def internURI(self, str, why=None): warn("use symbol()", DeprecationWarning, stacklevel=3) return self.intern((SYMBOL,str), why) def symbol(self, str, why=None): """Intern a URI for a symvol, returning a symbol object""" return self.intern((SYMBOL,str), why) def _fromPython(self, x, queue=None): """Takem a python string, seq etc and represent as a llyn object""" if isinstance(x, tuple(types.StringTypes)): return self.newLiteral(x) elif type(x) is types.LongType or type(x) is types.IntType: return self.newLiteral(str(x), self.integer) elif isinstance(x, Decimal): return self.newLiteral(str(x), self.decimal) elif isinstance(x, bool): return self.newLiteral(x and 'true' or 'false', self.boolean) elif isinstance(x, xml.dom.minidom.Document): return self.newXMLLiteral(x) elif type(x) is types.FloatType: if `x`.lower() == "nan": # We can get these form eg 2.math:asin return None return self.newLiteral(`x`, self.float) elif isinstance(x, Set) or isinstance(x, ImmutableSet): return self.newSet([self._fromPython(y) for y in x]) elif isinstance(x, Term): return x elif hasattr(x,'__getitem__'): #type(x) == type([]): return self.nil.newList([self._fromPython(y) for y in x]) return x def intern(self, what, dt=None, lang=None, why=None, ): """find-or-create a Fragment or a Symbol or Literal or list as appropriate returns URISyntaxError if, for example, the URIref has two #'s. This is the way they are actually made. """ if isinstance(what, Term): return what # Already interned. @@Could mask bugs if type(what) is not types.TupleType: if isinstance(what, tuple(types.StringTypes)): return self.newLiteral(what, dt, lang) # progress("llyn1450 @@@ interning non-string", `what`) if type(what) is types.LongType: return self.newLiteral(str(what), self.integer) if type(what) is types.IntType: return self.newLiteral(`what`, self.integer) if type(what) is types.FloatType: return self.newLiteral(repr(what), self.float) if isinstance(what,Decimal): return self.newLiteral(str(what), self.decimal) if isinstance(what, bool): return self.newLiteral(what and 'true' or 'false', self.boolean) if type(what) is types.ListType: #types.SequenceType: return self.newList(what) raise RuntimeError("Eh? can't intern "+`what`+" of type: "+`what.__class__`) typ, urirefString = what if typ == LITERAL: return self.newLiteral(urirefString, dt, lang) if typ == LITERAL_DT: return self.newLiteral(urirefString[0], self.intern(SYMBOL, urirefString[1])) if typ == LITERAL_LANG: return self.newLiteral(urirefString[0], None, urirefString[1]) else: urirefString = canonical(urirefString) assert ':' in urirefString, "must be absolute: %s" % urirefString hash = string.rfind(urirefString, "#") if hash < 0 : # This is a resource with no fragment assert typ == SYMBOL, "If URI <%s>has no hash, must be symbol" % urirefString result = self.resources.get(urirefString, None) if result != None: return result result = Symbol(urirefString, self) self.resources[urirefString] = result else : # This has a fragment and a resource resid = urirefString[:hash] if string.find(resid, "#") >= 0: raise URISyntaxError("Hash in document ID - can be from parsing XML as N3! -"+resid) r = self.symbol(resid) if typ == SYMBOL: if urirefString == N3_nil[1]: # Hack - easier if we have a different classs result = r.internFrag(urirefString[hash+1:], FragmentNil) else: result = r.internFrag(urirefString[hash+1:], Fragment) elif typ == ANONYMOUS: result = r.internFrag(urirefString[hash+1:], AnonymousNode) elif typ == FORMULA: raise RuntimeError("obsolete") result = r.internFrag(urirefString[hash+1:], IndexedFormula) else: raise RuntimeError, "did not expect other type:"+`typ` return result def newList(self, value, context=None): return self.nil.newList(value) # def deleteFormula(self,F): # if diag.chatty_flag > 30: progress("Deleting formula %s %ic" % # ( `F`, len(F.statements))) # for s in F.statements[:]: # Take copy # self.removeStatement(s) def reopen(self, F): if F.canonical is None: if diag.chatty_flag > 50: progress("reopen formula -- @@ already open: "+`F`) return F # was open if diag.chatty_flag > 00: progress("warning - reopen formula:"+`F`) key = len(F.statements), len(F.universals()), len(F.existentials()) try: self._formulaeOfLength[key].remove(F) # Formulae of same length except (KeyError, ValueError): pass F.canonical = None return F def bind(self, prefix, uri): if prefix != "": # Ignore binding to empty prefix return RDFSink.bind(self, prefix, uri) # Otherwise, do as usual. def makeStatement(self, tuple, why=None): """Add a quad to the store, each part of the quad being in pair form.""" q = ( self.intern(tuple[CONTEXT]), self.intern(tuple[PRED]), self.intern(tuple[SUBJ]), self.intern(tuple[OBJ]) ) if q[PRED] is self.forSome and isinstance(q[OBJ], Formula): if diag.chatty_flag > 97: progress("Makestatement suppressed") return # This is implicit, and the same formula can be used un >1 place self.storeQuad(q, why) def makeComment(self, str): pass # Can't store comments def any(self, q): """Query the store for the first match. Quad contains one None as wildcard. Returns first value matching in that position. """ list = q[CONTEXT].statementsMatching(q[PRED], q[SUBJ], q[OBJ]) if list == []: return None for p in ALL4: if q[p] is None: return list[0].quad[p] def storeQuad(self, q, why=None): """ intern quads, in that dupliates are eliminated. subject, predicate and object are terms - or atomic values to be interned. Builds the indexes and does stuff for lists. Deprocated: use Formula.add() """ context, pred, subj, obj = q assert isinstance(context, Formula), "Should be a Formula: "+`context` return context.add(subj=subj, pred=pred, obj=obj, why=why) def startDoc(self): pass def endDoc(self, rootFormulaPair): return ########################################################################## # # Output methods: # def dumpChronological(self, context, sink): "Fast as possible. Only dumps data. No formulae or universals." pp = Serializer(context, sink) pp. dumpChronological() del(pp) def dumpBySubject(self, context, sink, sorting=1): """ Dump by order of subject except forSome's first for n3=a mode""" pp = Serializer(context, sink, sorting=sorting) pp. dumpBySubject() del(pp) def dumpNested(self, context, sink, flags=""): """ Iterates over all URIs ever seen looking for statements """ pp = Serializer(context, sink, flags=flags) pp. dumpNested() del(pp) ################################## Manipulation methods: # # Note when we move things, then the store may shrink as they may # move on top of existing entries and we don't allow duplicates. # # @@@@ Should automatically here rewrite any variable name clashes # for variable names which occur in the other but not as the saem sort of variable # Must be done by caller. def copyFormula(self, old, new, why=None): new.loadFormulaWithSubstitution(old, why=why) return ## bindings = {old: new} ## for v in old.universals(): ## new.declareUniversal(bindings.get(v,v)) ## for v in old.existentials(): ## new.declareExistential(bindings.get(v,v)) ## for s in old.statements[:] : # Copy list! ## q = s.quad ## for p in CONTEXT, PRED, SUBJ, OBJ: ## x = q[p] ## if x is old: ## q = q[:p] + (new,) + q[p+1:] ## self.storeQuad(q, why) def purge(self, context, boringClass=None): """Clean up intermediate results Statements in the given context that a term is a Chaff cause any mentions of that term to be removed from the context. """ if boringClass is None: boringClass = self.Chaff for subj in context.subjects(pred=self.type, obj=boringClass): self.purgeSymbol(context, subj) def purgeSymbol(self, context, subj): """Purge all triples in which a symbol occurs. """ total = 0 for t in context.statementsMatching(subj=subj)[:]: context.removeStatement(t) # SLOW total = total + 1 for t in context.statementsMatching(pred=subj)[:]: context.removeStatement(t) # SLOW total = total + 1 for t in context.statementsMatching(obj=subj)[:]: context.removeStatement(t) # SLOW total = total + 1 if diag.chatty_flag > 30: progress("Purged %i statements with %s" % (total,`subj`)) return total # def removeStatement(self, s): # "Remove statement from store" # return s[CONTEXT].removeStatement(s) def purgeExceptData(self, context): """Remove anything which can't be expressed in plain RDF""" uu = context.universals() for s in context.statements[:]: for p in PRED, SUBJ, OBJ: x = s[p] if x in uu or isinstance(x, Formula): context.removeStatement(s) break context._universalVariables.clear() # Cheat! @ use API class URISyntaxError(ValueError): """A parameter is passed to a routine that requires a URI reference""" pass def isString(x): # in 2.2, evidently we can test for isinstance(types.StringTypes) # --- but on some releases, we need to say tuple(types.StringTypes) return type(x) is type('') or type(x) is type(u'') ##################### Register this module from myStore import setStoreClass setStoreClass(RDFStore) #ends cwm-1.2.1/swap/pychinko/0000755015216600007660000000000010731073447014221 5ustar syosisyosicwm-1.2.1/swap/pychinko/prooftrace.py0000644015216600007660000000125210410547106016727 0ustar syosisyosi### ### Facilities for generating proofs ### from terms import Pattern, URI from helpers import removedups, sortVars, keysToList class ProofTrace: """I represent a trace of the patterns that matched (i.e. alpha nodes) that justify a certain inference.""" def __init__(self): self.trace = list() def __getitem__(self, index): return self.trace[index] def __len__(self): return len(self.trace) def addPremise(self, premise): self.trace.append(premise) def render(self): """I render the proof trace as a list""" counter = 1 for premise in self.trace: print "Premise " + str(counter) + ": " + premise counter += 1 cwm-1.2.1/swap/pychinko/nodes.py0000644015216600007660000010754510640072461015711 0ustar syosisyosifrom terms import URI, Variable, Fact, Exivar from helpers import removedups, getOccurences, keysToList, sortVars, Memory, convertBNodeToFact, isListVarNode, INCLUDES from prooftrace import ProofTrace from sets import Set from helpers import FIRST, REST, TYPE, INCLUDES, LOG_SEMANTICS as SEMANTICS, IMPLIES, NIL import time import copy import exception #from pychinko.N3Loader import formulas py_lists = dict() #add initial facts that match the lists at the very beginning - shouldnt screw up anything class AlphaNode: def __init__(self, pattern): self.pattern = pattern #print "pattern", pattern self.ind = Memory() ###ind=memory, or ind=index self.betaNodes = list() self.vars = [v for v in pattern if isinstance(v, Variable)] sortVars(self.vars) self.svars = list() self.dependents = list() self.dependsOn = list() def clear(self): self.ind = Memory() #####Make this a Pattern method -- multiple arity patterns def getvar(self, var, fact): """I return the value of var in fact according to our pattern.""" if var in self.pattern: pos = self.pattern.index(var) return fact[pos] else: raise exception.UnboundRuleVariable(var, self.pattern) def getbindings(self, row, useBuiltin=None): """I return a set of bindings for row, where row is a set of values from my AlphaMemory (note that rows that do not have constants, only variable values.)""" bindings = dict() key = removedups(self.svars + self.vars) for i, val in enumerate(key): bindings[val] = row[i] #print "key alpha:",key #print "row alpha:",row return bindings def getkey(self): return removedups(self.svars + self.vars) def getrest(self, fact, sharedVars): """I return the unshared variable values for a given fact according to our pattern. Note that right now we need to pass the *shared* variable list as a parameter, but in our Rete network we would just make that an attribute of every ANode in compilation.""" vals = list() for i, v in enumerate(self.pattern): if isinstance(v, Variable) and v not in sharedVars: vals.append(fact[i]) return vals def setupIndex(self): if not self.svars: self.svars = [self.vars[0]] # need to account for 0 var case # len(shared) <= len(self.vars) # We need to remove dups. # unshared and shared are *disjoint*, so only need to remove # dups in each self.unshared = list(removedups([v for v in self.vars if v not in self.svars])) ####Make this a Pattern method def match(self, fact): """Determines whether the fact matches the node's pattern""" bindings = dict() for p, f in zip(self.pattern, fact): if not isinstance(p, Variable): if p != f: return False elif p not in bindings: bindings[p] = f elif bindings[p] != f: return False return bindings def addAll(self, facts): for f in facts: self.add(f) def add(self, fact): bindings = self.match(fact) if bindings: #make sure key has shared vars first key = removedups(self.svars + self.vars) return self.index(self.ind, bindings, key, fact) else: return False def getJustification(fact): """I take a fact and return its justification set (another set of facts).""" if fact.s in self.ind: if fact.p in self.ind[fact.s]: val = self.ind[fact.s][fact.p] if fact.o in val[fact.o]: return val[fact.o] return None def exists(self, fact, bindings): """Check the index for the presence of the fact (as expressed as a set of bindings returned by match)""" key = self.svars + self.unshared return self.__exists(bindings, self.ind, key) def __exists(self, bindings, ind, key): # vars are in reverse shared/unshared sorted if key: # Still comparison work to be done cur = key.pop(0) if bindings[cur] in ind: return self.existshelp(bindings, ind[bindings[cur]], key) else: return False else: # We succeded in getting to the bottom of the index return True def clear(self): """I clear the memory of this AlphaNode. This is only called from unit tests.""" self.ind = Memory() def index(self, ind, bindings, key, factAdded=None): if key: # Still work to be done cur = bindings[key.pop(0)] #pop(0) pops the first item off if cur not in ind: # So we know the fact doesn't exist if key: ind[cur] = Memory() # just a dictionary -- intended for sorted join return self.index(ind[cur], bindings, key, factAdded) else: # At the bottom, and the fact still doesn't exist # Create justification set, used for proof tracing, and stick it # as the inner most value in the memory pt = ProofTrace() pt.addPremise(factAdded) ind[cur] = tuple(pt) return True #it was added else: if key: # Perhaps the fact does exist return self.index(ind[cur], bindings, key, factAdded) else: # It definitely exists. return False def __repr__(self): return """AlphaNode(%s)(Mem: %s)""" %(str(self.pattern), str(self.ind)) class BetaNode: """A Beta node is a *join* of two other nodes. The other nodes maybe any mix of alphas and betas. An alpha may be joined against itself. The Beta has a set of *shared variables*, that is, variables that appear in both nodes (there may be none).""" def __init__(self, lnode, rnode): from builtins import builtinp self.lnode = lnode self.rnode = rnode #####Make this opaque if isinstance(lnode, BetaNode): self.lvars = lnode.pattern elif isinstance(lnode, AlphaNode): self.lvars = lnode.vars self.rvars = rnode.vars # Detect builtins if isinstance(rnode, AlphaNode): if builtinp(self.rnode): self.svars = lnode.svars else: # store svars in lexical order self.svars = [v for v in self.lvars if v in self.rvars] else: self.svars = [v for v in self.lvars if v in self.rvars] sortVars(self.svars) #destructively sort vars self.parents = list() self.children = list() self.pattern = removedups(self.svars + self.lvars + self.rvars) # Redundant var, will be refactored out self.vars = self.pattern self.builtinInput = None self.ind = Memory() self.inferredFacts = Set() # a pointer to the rule node (which contains the rhs) self.rule = None ####This is 'match' and hence should be a pattern method def getbindings(self, row, useBuiltin=None): bindings = dict() #check for builtins if useBuiltin: key = useBuiltin.indexKey() else: if isinstance(self.lnode, AlphaNode): key = removedups(self.lnode.svars + self.lnode.vars + self.rnode.vars) elif isinstance(self.lnode, BetaNode): key = removedups(self.lnode.pattern + self.rnode.vars) for i, v in enumerate(key): bindings[v] = row[i] return bindings def getkey(self): if isinstance(self.lnode, AlphaNode): key = removedups(self.lnode.svars + self.lnode.vars + self.rnode.vars) elif isinstance(self.lnode, BetaNode): key = removedups(self.lnode.pattern + self.rnode.vars) return key def add(self, row, justification=None): # store results in regular order key = copy.copy(self.pattern) bindings = self.getbindings(row) if bindings: return self.index(self.ind, row, bindings, key, justification) return False def index(self, ind, row, bindings, key, justification=None): if key: # Still work to be done cur = bindings[key.pop(0)] #pop(0) pops the first item off if cur not in ind: # So we know the fact doesn't exist if key: ind[cur] = Memory() return self.index(ind[cur], row, bindings, key, justification) else: # At the bottom, and the factd still doesn't exist if justification: ind[cur] = tuple(justification) else: ind[cur] = tuple() return True #it was added else: if key: # Perhaps the fact does exist return self.index(ind[cur], row, bindings, key, justification) else: # It definitely exists. return False def hasBuiltins(self): from builtins import builtinp, funcBuiltinp """Return True if I have builtins connected to me, otherwise False. Also set a pointer to the builtins""" # If left and right are builtins, they will have the same input node (does this hold for func. builtins, too?) if builtinp(self.lnode): self.builtinInput = self.lnode.getInputNode() if builtinp(self.rnode): self.builtinInput = self.rnode.getInputNode() return bool(self.builtinInput) def bindPossibleVar(self, possVar, bindings): if isinstance(possVar, Variable): return bindings[possVar] else: return possVar def evalBuiltins(self, returnBindings=False): t = time.time() """I evaluate my attached builtins nodes.""" from builtins import builtinp, funcBuiltinp #Three cases to handle: left is a builtin and right is a plain anode, #left is a plain anode and right is a builtin, or both the left #and right are builtins evaldRows = list() builtinNodes = list() if builtinp(self.lnode): builtinNodes.append(self.lnode) if builtinp(self.rnode): builtinNodes.append(self.rnode) for bi in builtinNodes: inputNode = bi.getInputNode() builtinInput = keysToList(inputNode.ind) for row in builtinInput: row = row[0] #Needed since row[1] is the justification set #print row #print bi.pattern bindings = inputNode.getbindings(row, useBuiltin=bi) #need to check and substitute bi.pattern.s and bi.pattern.o for possible bindings here #check and substitute if subj or obj are lists, they also might have variables in the lists subjInput = convertBNodeToFact(bi.pattern.s) objInput = convertBNodeToFact(bi.pattern.o) if isinstance(bi.pattern.s, Variable): if bi.pattern.s in bindings: subjInput = convertBNodeToFact(bindings[bi.pattern.s]) if isinstance(bi.pattern.o, Variable): if bi.pattern.o in bindings: objInput = convertBNodeToFact(bindings[bi.pattern.o]) if subjInput in py_lists: subjInput = [self.bindPossibleVar(x, bindings) for x in py_lists[subjInput]] if objInput in py_lists: objInput = [self.bindPossibleVar(x, bindings) for x in py_lists[objInput]] # print "builtin", bi, subjInput, objInput result = bi.evaluate(subjInput, objInput) if result: #hack: append the bindings if it's log:includes if bi.pattern.p == INCLUDES: bindings[bi.pattern.s]= subjInput bindings[bi.pattern.o]= objInput row.append(subjInput) row.append(objInput) #a bit inefficient if returnBindings: evaldRows.append(bindings) else: evaldRows.append([row, []]) #Empty justification for now #add to memory -- ##NOTE: Need to add justification (proof tracing) for data resulting ##from builtins #print "row after bindings", row #if it's a functional builtin, it's different - need to return result and store in memory if funcBuiltinp(self.lnode) or funcBuiltinp(self.rnode): #have no idea why it works row.append(result) #print "row added in evalbuiltins:", row #add this fact self.add(row) #print "___row:", row else: #print "___row:", row self.add(row) #print "evaldRows:", evaldRows print "evalBultins time:", time.time() - t return evaldRows def getSharedVars(self, node1, node2): if isinstance(node1, BetaNode): lvars = node1.pattern else: lvars = node1.vars if isinstance(node2, BetaNode): rvars = node2.pattern else: rvars = node2.vars result = removedups([item for item in lvars \ if item in rvars]) return result #optimize join: put node with smaller memory to the left #question: how can we switch the nodes in the join in the most painless way possible? #goal is not to affect other code at all, do all of the stuff in the join/joinhelper fcn. def join(self, useBindings=False): """ print "\n\n" print "self key:", self.getkey() print "join left:", self.lnode.pattern #for row in keysToList(self.lnode.ind): # print "left row",row[0] print "memory size of left node:", len(keysToList(self.lnode.ind)) print "left key:", self.lnode.getkey() print "" print "join right:", self.rnode.pattern # for row in keysToList(self.rnode.ind): # print "right row",row[0] print "memory size of right node:", len(keysToList(self.rnode.ind)) print "right key:", self.rnode.getkey() switched = False t = time.time() if len(keysToList(self.rnode.ind)) < len(keysToList(self.lnode.ind)): print "switched" switched = True print "keysToList time:", time.time() - t """ from builtins import builtinp if self.lnode == self.rnode: from builtins import builtinp, funcBuiltinp if builtinp(self.lnode): self.builtinInput = self.lnode.getInputNode() #problem is, here builtin input is empty return self.evalBuiltins(returnBindings=useBindings) else: self.pattern = self.lnode.vars if self.lnode.ind: return keysToList(self.lnode.ind) else: return [] elif self.hasBuiltins(): return self.evalBuiltins(returnBindings=useBindings) else: #right node is always an alpha node, #left one is an alphanode in the first join, beta node aftewards #compare the memory of both nodes, we want the smaller one to the left # if isListVarNode(self.rnode): rows = keysToList(self.lnode.ind) for row in rows: row = row[0] #print "rows:", row #print "left node key:", self.lnode.getkey() #left node key does not correspond to the bindings #bindings = self.lnode.getbindings(row) #get the bindings according to its own key, above line didnt work bindings = dict() key = self.getkey() try: for i, v in enumerate(key): bindings[v] = row[i] except: print "bindings=%s" % bindings print "row=%s" % row print "v=%s" % v print "i=%s" % i raise #copy the values for the variable in pattern.o if self.rnode.pattern.o in bindings: #copy it back to the original node - easiest way is to add it as a fact #also add bindings for the bnodes in subj for var in self.rnode.vars: if isinstance(var, Exivar): self.rnode.add(Fact(convertBNodeToFact(var), self.rnode.pattern.p, bindings[self.rnode.pattern.o])) #print "fact added:",convertBNodeToFact(var), self.rnode.pattern.p, bindings[self.rnode.pattern.o] elif isinstance(self.rnode.pattern.s, Exivar): print "something wrong happened - %s was supposed to be bound", self.rnode.pattern.s if isinstance(self.lnode, AlphaNode): key = self.lnode.svars elif isinstance(self.lnode, BetaNode): if not Set(self.lnode.vars).intersection(Set(self.rnode.vars)): key = list() else: #regenerate key here? was using self.svars before but was buggy key = self.getSharedVars(self.lnode, self.rnode) joinResults = list() if not key: #no shared variables and no matched values, so store and return the union #of the two memories """if switched: leftMemory = keysToList(self.rnode.ind) rightMemory = keysToList(self.lnode.ind) else:""" leftMemory = keysToList(self.lnode.ind) rightMemory = keysToList(self.rnode.ind) for lm, ljust in leftMemory: for rm, rjust in rightMemory: """if switched: row = rm + lm else:""" row = lm + rm joinResults.append([row, []]) ####NOTE -- Need to add justification (proof tracing) for this case self.add(row, []) else: t = time.time() """if switched: joinResults = self.joinhelper(self.rnode.ind, self.lnode.ind, key, [], [], switched) else:""" joinResults = self.joinhelper(self.lnode.ind, self.rnode.ind, key, [], []) print "joinhelper time:", time.time() - t return joinResults def joinhelper(self, leftMemory, rightMemory, sharedVars, matchedValues, results, switched=False): #all shared variable values matched if sharedVars: bindings = dict() #do this until we run out of shared variables to compare for lmk in leftMemory: #print "lmk:", lmk if lmk in rightMemory: #match on shared variable, continue to next level #leftMemory and rightMemory are nested dictionaries self.joinhelper(leftMemory[lmk], rightMemory[lmk], sharedVars[1:], matchedValues + [lmk], results, switched) elif matchedValues: if leftMemory: for lm, ljust in keysToList(leftMemory): #Both memories are nonempty if rightMemory: for rm, rjust in keysToList(rightMemory): """if switched: row = matchedValues + rm + lm else:""" row = matchedValues + lm + rm results.append([row, []]) self.add(row, []) else: #Left memory is nonempty, right is empty row = matchedValues + lm results.append([row, []]) self.add(row, []) elif rightMemory: for rm, rjust in keysToList(rightMemory): #Left memory is empty, right is nonempty row = matchedValues + rm results.append([row, []]) self.add(row, []) return results def getvar(self, var, fact): """I return values for var from fact""" values = list() if var in self.pattern: pos = self.pattern.index(var) return fact[pos] else: raise exception.UnboundRuleVariable(var, self.pattern) #####Make it a method of RuleNode def matchingFacts(self, rhs, facts): """I generate a set of facts and justifications, of the form: [[fact1, fact, fact2], [just1, just2, just2]] according to the given rhs from 'facts'""" results = list() for fact, just in facts: newFact = list() for p in rhs: if isinstance(p, Variable): newFact.append(self.getvar(p, fact)) else: newFact.append(p) # print "The fact: ", Fact(*newFact), " is justified by: ", just results.append(Fact(*newFact)) return results def __repr__(self): return """BetaNode(%s)(left: %s, right: %s)""" %(self.pattern, self.lnode, self.rnode) class AlphaStore(object): def __init__(self): self.nodes = list() self.sharedIndex = dict() #records what variables each node contains self.py_lists = dict() # mapping from bnodes that are head of rdf lists to python lists def addNode(self, node): from builtins import builtinp if node not in self.nodes: self.nodes.append(node) # Only index the non-builtins for sorting (since we want to make sure # builtins appear at the end if not builtinp(node) and not isListVarNode(node): for v in node.vars: if v not in self.sharedIndex: self.sharedIndex[v] = [node] else: self.sharedIndex[v].append(node) def __getitem__(self, index): return self.nodes[index] def listToPython(self, id, alphaNodes, py_list): if not alphaNodes: return py_list node_first = [node for node in alphaNodes if convertBNodeToFact(node.pattern.s)==id and node.pattern.p==FIRST] #it's tricky here because the subj might be a variable if node_first: if isinstance(node_first[0].pattern.o, Exivar): return self.listToPython(convertBNodeToFact(node_first[0].pattern.o), alphaNodes, py_list) elif isinstance(node_first[0].pattern.o, Variable): py_list.append(node_first[0].pattern.o) # append variable node_rest = [node for node in alphaNodes if convertBNodeToFact(node.pattern.s)==id and node.pattern.p==REST] if node_rest: if node_rest[0].pattern.o == NIL: return py_list else: return self.listToPython(convertBNodeToFact(node_rest[0].pattern.o), alphaNodes, py_list) else: return py_list def generateDependencies(self): from builtins import funcBuiltinp for a in self.nodes: if funcBuiltinp(a): #means that object is a variable, look for dependencies on that var. for x in self.nodes: if x != a and a.pattern.o in [x.pattern.s, x.pattern.o]: a.dependents.append(x) #rdf:rest should always be before rdf:first elif a.pattern.p == REST: for x in self.nodes: if x.pattern.p == FIRST and x.pattern.s == a.pattern.s: a.dependents.append(x) for a in self.nodes: if funcBuiltinp(a): # (?x ?a) math:sum z. we want to have x and a bound before evaluating math:sum. #so, look for the variables in the list, and see where they occur in the nodes set, then add dependencies #first, generate the variables from the list vars = self.listToPython(convertBNodeToFact(a.pattern.s), self.nodes, []) #now add dependencies for x in self.nodes: if x.pattern.p==FIRST and x.pattern.o in vars: x.dependents.append(a) """ for a in self.nodes: if a.dependents: pass #print "a:", a #print "dependents:", a.dependents """ """ 1. Select a vertex that has in-degree zero. 2. Add the vertex to the sort. 3. Delete the vertex and all the edges emanating from it from the graph. """ def indegree(self, node, graph): #print "node", node for a in graph: if node in a.dependents: return 1 return 0 lastTopSort = -1000000000L def topSort(self, unsorted, sorted): ## k = len(unsorted) ## if k > self.lastTopSort: ## import traceback ## #traceback.print_stack() ## self.__class__.lastTopSort = k from builtins import funcBuiltinp ## if not unsorted: ## #for i in sorted: ## # print "s", i ## return sorted ## else: ## first = [x for x in unsorted if self.indegree(x,unsorted)==0 and not funcBuiltinp(x)] ## if first: ## sorted.append(first[0]) ## unsorted.remove(first[0]) ## #print len(unsorted) ## return self.topSort(unsorted, sorted) ## else: ## first = [x for x in unsorted if self.indegree(x,unsorted)==0] ## sorted.append(first[0]) ## unsorted.remove(first[0]) ## return self.topSort(unsorted, sorted) try: set except: from sets import Set as set unsorted = set(unsorted) inDegrees = {} for node in unsorted: inDegrees[node] = 0 for node in unsorted: for parent in node.dependents: if parent in inDegrees: inDegrees[parent] = inDegrees[parent] + 1 zeros = set() simpleZeros = set() for node in inDegrees: if inDegrees[node] == 0: if funcBuiltinp(node): zeros.add(node) else: simpleZeros.add(node) while zeros or simpleZeros: if simpleZeros: top = simpleZeros.pop() else: top = zeros.pop() sorted.append(top) for node in top.dependents: if node in inDegrees: inDegrees[node] = inDegrees[node] - 1 if inDegrees[node] == 0: if funcBuiltinp(node): zeros.add(node) else: simpleZeros.add(node) if inDegrees and max(inDegrees.values()) != 0: raise ValueError return sorted def sort(self): self.generateDependencies() from builtins import builtinp builtins = list() for node in self.nodes: if builtinp(node): builtins.append(node) builtins = removedups(builtins) # for nodes with pattern like (_:exivar FIRST ?x) we want to make sure ?x's are bound when joining, #so add them at the end (like builtins) listVarNodes = [node for node in self.nodes if node.pattern.p in [FIRST, REST, INCLUDES, TYPE, SEMANTICS]] listVarNodes = removedups(listVarNodes) nonBuiltins = [x for x in self.nodes if x not in builtins] nonBuiltins = [x for x in nonBuiltins if x not in listVarNodes] # Sort the non-builtin alphas so that nodes that share variables (if any) # are adjacent sortedNonBuiltins = list() for nb in nonBuiltins: for v in nb.vars: nodesThatShare = self.sharedIndex.get(v) if nodesThatShare: sortedNonBuiltins.extend(nodesThatShare) sortedNonBuiltins.append(nb) # If there were any nodes that shared variables, use the sorted list of nodes if sortedNonBuiltins: nonBuiltins = removedups(sortedNonBuiltins) #only sort builtins and list nodes (rdf:first, rest, etc.) #the other nodes should come first unsortedNodes = removedups(builtins + listVarNodes) # make full topological sort self.nodes = removedups(nonBuiltins + self.topSort(unsortedNodes, [])) """ print "nodes:" for i in self.nodes: print i print "\n" """ def display(self): for n in self.nodes: print n.pattern class BetaStore(object): def __init__(self): self.nodes = list() def addNode(self, node): if node not in self.nodes: self.nodes.append(node) def __getitem__(self, index): return self.nodes[index] class RuleNode(object): """I am a node for storing rules.""" def __init__(self, rule): #only store the right-hand side self.__rhs = rule.rhs self.__ts = rule.timestamp self.proofTrace = ProofTrace() def __repr__(self): return """RuleNode(%s)""" % (self.rhs) def getRhs(self): return self.__rhs def setRhs(self, val): self.__rhs = val def getTs(self): return self.__ts rhs = property(getRhs, setRhs, None, None) timestamp = property(getTs, None, None, None) def __eq__(self, other): return (self == other) def __hash__(self): return hash(tuple(self.rhs)) def __neq__(self, other): return not self.__eq__(self, other) class QueryRuleNode: """I provide an interface to all the rows in the BetaNode that I am connected to.""" def __init__(self): self.lhs = [] self.rhs = [] self.betaNode = None self.rows = Set() def getRows(self): """I return the rows of the BetaNode, one row at a time.""" rows = keysToList(self.betaNode.ind) for r in rows: yield r # class NodeStorage(object): # def __init__(self): # """I store all the (alpha or beta) nodes of a particular kind""" # self.store = Set() # def add(self, node): # self.store.add(node) # return self.store # def __repr__(self): # return """%s""" %(self.store) class AlphaIndex: """I index AlphaNodes by pattern. The pattern is abstract, e.g. all patterns of the form (variable predicate variable) will be grouped together.""" def __init__(self): self.ind = dict() def index(self, ind, node, varsk): if varsk: # Still work to be done cur = varsk.pop(0) #pop(0) pops the first item off if cur not in ind: # So we know the node doesn't exist if varsk: if isinstance(cur, Variable): #index variables as 'None' cur = None if cur in ind: ind[cur] = ind[cur] else: ind[cur] = {} return self.index(ind[cur], node, varsk) else: # At the bottom, and the node if isinstance(cur, Variable): cur = None if cur not in ind: ind[cur] = [node] else: if ind[cur]: # if the very same alpha node is not already there # then add it if node not in ind[cur]: ind[cur].append(node) else: return False else: ind[cur] = [node] return True else: if varsk: # Perhaps the node does exist if isinstance(cur, Variable): cur = None return self.index(ind[cur], node, varsk) else: # It definitely exists. return False def match(self, pattern): """I return a list of matching alpha nodes for a given pattern""" nodesMatched = list() key = [pattern.p, pattern.o, pattern.s] self.matchhelper(key, self.ind, nodesMatched) return nodesMatched def matchhelper(self, pattern, ind, nodesMatched): """I determine what alpha node(s) a certain pattern matches.""" if not pattern: nodesMatched.extend(ind) return nodesMatched p = pattern[0] if None in ind: self.matchhelper(pattern[1:], ind[None], nodesMatched) if p in ind: self.matchhelper(pattern[1:], ind[p], nodesMatched) def add(self, anode): #index by pattern, followed by object, followed by subj key = [anode.pattern.p, anode.pattern.o, anode.pattern.s] return self.index(self.ind, anode, key) class BetaIndex(list): pass cwm-1.2.1/swap/pychinko/__init__.py0000644015216600007660000000000210410547106016312 0ustar syosisyosi #cwm-1.2.1/swap/pychinko/terms.py0000644015216600007660000002074110410547106015721 0ustar syosisyosiimport time, sys from exceptions import StandardError #from rdflib.URIRef import URIRef #from rdflib.BNode import BNode #from rdflib import Namespace from types import IntType from swap.myStore import Namespace LOG = Namespace("http://www.w3.org/2000/10/swap/log#") class URIRef(unicode): def __new__(cls, value, base=None): if base is not None: value = urljoin(base, value, allow_fragments=1) #if normalize and value and value != normalize("NFC", value): # raise Error("value must be in NFC normalized form.") return unicode.__new__(cls,value) #XXX: This now accepts URIRef's too since that is what #XXX: rdflib.constants uses class URI(URIRef): def __init__(self, s): URIRef.__init__(self, unicode(s)) self.name = unicode(s) # unicode.__new__(cls,value) # def __cmp__(self, other): # return unicode(self) is unicode(other) def __repr__(self): return """%s""" % (self.name) class Formula: #todo finish here! def __init__(self, n3l=None): if n3l: self.patterns = list(n3l.patterns()) self.id = n3l.identifier self.rules = list(n3l.rules()) self.facts = list(n3l.facts()) else: self.patterns = list() # get new bnode value here tmp = BNode() self.id = tmp.n3() print "_________ID:", self.id self.rules = list() self.facts = list() # version of facts() and rules() butthis time input is a terms.formula, not rdflib.graph # these are used in log:conjunction def getFacts(self): for s, p, o in self.patterns: if p!= LOG.implies and not isinstance(s, Variable) and not isinstance(o, Variable): # and not isinstance(s, BNode) and not isinstance(o, BNode): yield Fact(s,p,o) def getRules(self): for s, p, o in self.patterns: if p == LOG.implies: lhs = list(s.patterns) rhs = list(o.patterns) yield Rule(lhs, rhs, (s, p, o)) def add(self, triple): self.patterns.append(triple) def __repr__(self): if self.patterns == []: return "{}" s = "Formula ID:%s" % self.id s += "\nFormula(%s)\n" % self.patterns return s class Variable(object): def __init__(self, s): """I am a variable. My only argument is a string identifier.""" self.name = unicode(s) def __repr__(self): return """?%s""" % (self.name) def __hash__(self): return hash(self.name) def __eq__(self, other): if isinstance(other, Variable): return self.name == other.name return False def __neq__(self, other): return not(self.__eq__(other)) class Exivar(Variable): """I am a space holder for an N3 existential variable.""" def __init__(self, s): Variable.__init__(self, s) def __str__(self): return "_:" + self.name class Univar(Variable): """I am a space holder for an N3 universal variable.""" def __init__(self, s): Variable.__init__(self, s) class Triple: label = "Triple" def __init__(self, s, p, o): """I am an RDF 3-tuple: (subject, predicate, object).""" self._s = s; self._o = o; self._p = p self.spo = [s, p, o] def getS(self): return self._s def getP(self): return self._p def getO(self): return self._o def getT(self): return tuple((self._s, self._p, self._o)) s = property(getS, None, None, "Subject") p = property(getP, None, None, "Predicate") o = property(getO, None, None, "Object") t = property(getT, None, None, "Triple") def index(self, var): return self.spo.index(var) def __getitem__(self, index): if type(index) is not IntType: raise TypeError, "index must be an integer." else: return self.spo[index] def __eq__(self, other): return not self.__ne__(other) def __ne__(self, other): if not isinstance(other, Triple): return True if self.s != other.s: return True elif self.p != other.p: return True elif self.o != other.o: return True else: return False def __repr__(self): return """%s%s""" % (self.label, self.t) class Fact(Triple): label = "Fact" ######Change this to a "Fact Factory!" def __init__(self, s, p, o): """I am a Fact. I take grounded subject, predicate, and object arguments.""" if isinstance(s, Variable) or isinstance(p, Variable) \ or isinstance(o, Variable) or isinstance(s, list) or isinstance(p, list) \ or isinstance(o, list): raise TypeError, "Facts are patterns with three grounded values." Triple.__init__(self, s, p, o) def __hash__(self): return hash((self._s, self._p, self._o)) def __repr__(self): return """Fact(%s, %s, %s)""" %(self.s, self.p, self.o) class Pattern(Triple): label = "Pattern" def __init__(self, s, p, o): """I am a Pattern. I take subject, predicate, object arguments""" self.spo = (s, p, o) Triple.__init__(self, s, p, o) def index(self, var): return list(self.spo).index(var) def __hash__(self): return hash((self._s, self._p, self._o)) def __len__(self): return len(self.spo) def noneBasedPattern(self): """I return a pattern that does not distinguish between variables; that is, I keep the constants as is and replace any variable with a 'None'""" nonePattern = list() for i in self.spo: if isinstance(i, Variable): nonePattern.append(None) else: nonePattern.append(i) return tuple(nonePattern) class Rule(object): label = "Rule" def __init__(self, lhs, rhs, (subj,pred,obj)): """I am a Rule. My arguments are left and right hand sides, which are arbitrary-lengthened lists of instances of Pattern.""" for i in lhs: if not isinstance(i, Pattern): raise TypeError, \ "The members of a Rule's LHS must be Patterns (see item: %s)." % (i) else: continue for i in rhs: if not isinstance(i, Pattern): raise TypeError, \ "The members of a Rule's RHS must be Patterns (see item: %s)." % (i) else: continue self.__lhs = lhs self.__rhs = rhs self.__ts = time.time() #I think this will break on Windows... self.__triple = (subj,pred,obj) #this is so we can identify the lhs and rhs easily def getRuleTriple(self): return self.__triple def getTs(self): return self.__ts def setTs(self, val): self.__ts = val def getLhs(self): return self.__lhs def setLhs(self, val): self.__lhs = val def getRhs(self): return self.__rhs def setRhs(self, val): self.__rhs = val timestamp = property(getTs, setTs, None, None) lhs = property(getLhs, setLhs, None, None) rhs = property(getRhs, setRhs, None, None) def __repr__(self): return """%s(%s =>\n\t%s :timestamp %s)""" % (self.label, self.lhs, self.rhs, self.timestamp) class BuiltinRule(Rule): def __init__(self, lhs, rhs, builtin): Rule.__init__(self, lhs, rhs) self.builtin = builtin class TokenConstructionError(StandardError): pass class Token(object): def __init__(self, tag, fact): if isinstance(tag, Tag): self.tag = tag else: raise TokenConstructorError self.fact = fact def __repr__(self): return """Token(%s, %s)""" % (self.tag, self.fact) def __eq__(self, other): if self.tag == other.tag: if self.fact == other.fact: return True return False return False #abstract base class class Tag(object): def __repr__(self): return """%s""" % (self.label) def __eq__(self, other): if type(self) == type(other): return True return False class Add(Tag): label = "+" class Delete(Tag): label = "-" def makeToken(t, l): if t == "+": tag = Add() elif t == "-": tag = Delete() else: raise TokenConstructionError return Token(tag, l) cwm-1.2.1/swap/pychinko/config.py0000644015216600007660000000050110410547106016024 0ustar syosisyosi#### #### point to yr local stuff #### import sys CWM = "\"C:\Documents and Settings\kolovski\My Documents\mindswap\Policy Aware Web\cwm-1.0.0\cwm.py\"" CWMSOURCE = "C:\Documents and Settings\kolovski\My Documents\mindswap\Policy Aware Web\www\2000\10\swap" # add cwm builtins source to path #sys.path += [CWMSOURCE] cwm-1.2.1/swap/pychinko/rete.py0000644015216600007660000002177210437347350015543 0ustar syosisyosi# # The Rete network # from nodes import AlphaIndex, BetaIndex, AlphaNode, BetaNode, RuleNode, AlphaStore, BetaStore, QueryRuleNode, py_lists from terms import Pattern, URI from helpers import removedups, sortVars, keysToList, listToPython from builtins import Builtin, CWMBuiltins, builtinp, getPatternType ### ### We make sure to build Rete network such that more "selective" ### JOINs appear first, e.g.: ### ### LHS: (?x p ?y) (?z p ?a) (?a p ?d) ### ### In this case, it would clearly be more efficient to build the network such that ### the first and second ANodes are (?z p ?a) (?a p ?d) since they are likely to be more ### selective than (?x p ?y) ### class Rete(object): def __init__(self): self.alphaNodeStore = AlphaStore() self.betaNodeStore = BetaStore() self.betaIndex = BetaIndex() self.alphaIndex = AlphaIndex() def printNetwork(self): for bnode in self.betaNodeStore: print bnode class RuleCompiler(object): def __init__(self): self.rete = Rete() def addRule(self, rule): alphaNodesOfRule = AlphaStore() for pattern in rule.lhs: anodePattern = Pattern(pattern.s, pattern.p, pattern.o) anode = self.makeAlphaNode(anodePattern) alphaNodesOfRule.addNode(anode) alphaNodesOfRule.sort() self.rete.alphaNodeStore.sort() alphaNodesOfRule = removedups(alphaNodesOfRule) l = len(alphaNodesOfRule) if l == 0: # probably malformed input raise Exception elif l == 1: # If the rule has one pattern, we create two identical anodes # for it so that we can have a BetaNode with a left and right input beta1 = self.makeBetaNode(alphaNodesOfRule[0], alphaNodesOfRule[0], futureJoins=False) alphaNodesOfRule[0].betaNodes = [beta1] beta1.rule = self.makeRuleNode(rule) beta1.rule.betaNode = beta1 elif l == 2: # here we build a one beta with the only two alphas as its inputs beta1 = self.makeBetaNode(alphaNodesOfRule[0], alphaNodesOfRule[1], futureJoins=False) # connect our AlphaNodes to the BetaNode alphaNodesOfRule[0].betaNodes = [beta1] alphaNodesOfRule[1].betaNodes = [beta1] beta1.rule = self.makeRuleNode(rule) beta1.rule.betaNode = beta1 self.rete.betaNodeStore.addNode(beta1) else: beta1 = self.makeBetaNode(alphaNodesOfRule[0], alphaNodesOfRule[1], futureJoins=True) alphaNodesOfRule[0].betaNodes = [beta1] alphaNodesOfRule[1].betaNodes = [beta1] self.rete.betaNodeStore.addNode(beta1) # we've consumed the first two alpha nodes alphaNodeList = alphaNodesOfRule[2:] self.makeBetaNetwork(rule, beta1, alphaNodeList) return self.rete, alphaNodesOfRule def compile(self, rules): for rule in rules: print "%s of %s" % (rules.index(rule), len(rules)) alphaNodesOfRule = AlphaStore() for pattern in rule.lhs: anodePattern = Pattern(pattern.s, pattern.p, pattern.o) anode = self.makeAlphaNode(anodePattern) alphaNodesOfRule.addNode(anode) alphaNodesOfRule.sort() self.rete.alphaNodeStore.sort() alphaNodesOfRule = removedups(alphaNodesOfRule) l = len(alphaNodesOfRule) if l == 0: # probably malformed input raise Exception elif l == 1: # If the rule has one pattern, we create two identical anodes # for it so that we can have a BetaNode with a left and right input beta1 = self.makeBetaNode(alphaNodesOfRule[0], alphaNodesOfRule[0], futureJoins=False) alphaNodesOfRule[0].betaNodes = [beta1] beta1.rule = self.makeRuleNode(rule) beta1.rule.betaNode = beta1 elif l == 2: # here we build a one beta with the only two alphas as its inputs beta1 = self.makeBetaNode(alphaNodesOfRule[0], alphaNodesOfRule[1], futureJoins=False) # connect our AlphaNodes to the BetaNode alphaNodesOfRule[0].betaNodes = [beta1] alphaNodesOfRule[1].betaNodes = [beta1] beta1.rule = self.makeRuleNode(rule) beta1.rule.betaNode = beta1 self.rete.betaNodeStore.addNode(beta1) else: beta1 = self.makeBetaNode(alphaNodesOfRule[0], alphaNodesOfRule[1], futureJoins=True) alphaNodesOfRule[0].betaNodes = [beta1] alphaNodesOfRule[1].betaNodes = [beta1] self.rete.betaNodeStore.addNode(beta1) # we've consumed the first two alpha nodes alphaNodeList = alphaNodesOfRule[2:] self.makeBetaNetwork(rule, beta1, alphaNodeList) return self.rete def makeBetaNetwork(self, rule, betaNode, alphaNodeList): """I have more than 2 alpha nodes and so I make a network""" length = len(alphaNodeList) if length == 0: betaNode.rule = self.makeRuleNode(rule) betaNode.rule.betaNode = betaNode else: alpha = alphaNodeList[0] betaChild = self.makeBetaNode(betaNode, alpha) # connect our newly created BetaNode to its parent BetaNode, # and connect the parent to its child betaChild.parents = [betaNode] betaNode.children = [betaChild] sharedJoinVars = self.getSharedVars(betaNode, alpha) sortVars(sharedJoinVars) if not builtinp(alpha): # adjust our beta node shared variables betaNode.svars = sharedJoinVars # Our betanode has children, and so set up our # pattern in an order that is conducive to the children JOINs betaNode.pattern = removedups(sharedJoinVars + betaNode.pattern) # connect our AlphaNode to its relevant BetaNode alpha.betaNodes = [betaChild] self.rete.betaNodeStore.addNode(betaNode) self.rete.betaNodeStore.addNode(betaChild) alphaNodeList = alphaNodeList[1:] return self.makeBetaNetwork(rule, betaChild, alphaNodeList) def getSharedVars(self, node1, node2): """I return a list of shared variables between two nodes""" lvars = list() rvars = list() # check for builtins - do not calculate the shared variables # between a builtin and a regular Beta Node, since the index order # does not change if isinstance(node1, BetaNode): lvars = node1.pattern else: lvars = node1.vars if isinstance(node2, BetaNode): rvars = node2.pattern else: rvars = node2.vars result = removedups([item for item in lvars \ if item in rvars]) return result def makeBetaNode(self, node1, node2, futureJoins=True): sharedVars = self.getSharedVars(node1, node2) # if our left input is an alpha node, then it has the same shared # variables as our right input if isinstance(node1, AlphaNode): node1.svars = sharedVars sortVars(node1.svars) node2.svars = sharedVars sortVars(node2.svars) # make new BetaNode b = BetaNode(node1, node2) # store the shared variables in our new BetaNode # the shared vars here will be reset if the beta node has beta children b.svars = sharedVars # just add the beta node to the index (which is a flat list), no indexing for now return b def makeAlphaNode(self, pattern): # check if it's a builtin, and if it is, instantiate it biType = getPatternType(URI(pattern.p)) if biType: a = biType(pattern) else: a = AlphaNode(pattern) self.rete.alphaIndex.add(a) self.rete.alphaNodeStore.addNode(a) return a def makeRuleNode(self, rule): """I make a new RuleNode (which will be linked to the last BetaNode)""" # if the right hand side is empty, treat it as a query rule node if not rule.rhs: return QueryRuleNode() # A dummy else: return RuleNode(rule) cwm-1.2.1/swap/pychinko/helpers.py0000644015216600007660000001537610410547106016241 0ustar syosisyosifrom terms import URI, Variable, Fact, Exivar from types import IntType, DictType from UserDict import UserDict #from rdflib.TripleStore import TripleStore import os try: import cPickle as pickle except ImportError: import pickle output = open('pychinko.output.n3', 'w') INCLUDES = "http://www.w3.org/2000/10/swap/log#includes" IMPLIES = "http://www.w3.org/2000/10/swap/log#implies" LOG_SEMANTICS = "http://www.w3.org/2000/10/swap/log#semantics" LOG_CONJUNCTION = "http://www.w3.org/2000/10/swap/log#conjunction" LOG_CONCLUSION = "http://www.w3.org/2000/10/swap/log#conclusion" FIRST = "http://www.w3.org/1999/02/22-rdf-syntax-ns#first" REST = "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest" NIL = "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil" TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" LIST = "http://www.w3.org/1999/02/22-rdf-syntax-ns#List" def handleURL(filename): if filename.startswith('http://'): filename = 'tests/rdfig/' + filename.split('/')[-1] return filename def bindingsp(object): """I check whether something is a binding returned by JOIN""" return isinstance(object, DictType) def countTriples(filename): """I return the number of triples in `filename'.""" print filename store = TripleStore() if filename.endswith('n3') or filename.endswith('ntriples'): # assume an ntriples file store.load(filename, format="nt") else: store.load(filename) return len(store) def convertBNodeToFact( node): if isinstance(node, Exivar): return node.name #elif isinstance(node, Variable): #return node.name else: return node def loadRete(flo): """I unpersist a rete object from a file-like object.""" u = pickle.Unpickler(flo) try: rete = u.load() except UnpicklingError: return False return rete def storeRete(flo): """I persist a rete object to a file-like object (flo).""" p = pickle.Pickler(flo) p.dump(self) return flo class Memory(dict): def __init__(self, dict=None): self.origInput = None def aNodeListToPython(id, alphaNodes, py_list): if not alphaNodes: return py_list node_first = [node for node in alphaNodes if convertBNodeToFact(node.pattern.s)==id and node.pattern.p==FIRST] """print "node_first:", node_first if node_first: print "type:", type(node_first[0].pattern.o) print "fact_first:", fact_first if fact_first: print "type:", type(fact_first[0].o)""" #it's tricky here because the subj might be a variable if node_first: py_list.append(node_first[0].pattern.o) # append variable node_rest = [node for node in alphaNodes if convertBNodeToFact(node.pattern.s)==id and node.pattern.p==REST] if node_rest: if node_rest[0].pattern.o == NIL: return py_list else: return aNodeListToPython(convertBNodeToFact(node_rest[0].pattern.o), alphaNodes, py_list) else: return py_list def factListToPython(id, facts, py_list): if not facts: return py_list fact_first = [fact for fact in facts if convertBNodeToFact(fact.s)==id and fact.p==FIRST] if fact_first: py_list.append(fact_first[0].o) # append fact fact_rest = [fact for fact in facts if convertBNodeToFact(fact.s)==id and fact.p==REST] if fact_rest: if fact_rest[0].o == NIL: return py_list else: return factListToPython(convertBNodeToFact(fact_rest[0].o), facts, py_list) else: return py_list #convert rdf list to python list and do NOT remove patterns associated with rdf_list def listToPython(id, alphaNodes, facts, py_list): if not alphaNodes: return py_list node_first = [node for node in alphaNodes if convertBNodeToFact(node.pattern.s)==id and node.pattern.p==FIRST] fact_first = [fact for fact in facts if convertBNodeToFact(fact.s)==id and fact.p==FIRST] """print "node_first:", node_first if node_first: print "type:", type(node_first[0].pattern.o) print "fact_first:", fact_first if fact_first: print "type:", type(fact_first[0].o)""" #it's tricky here because the subj might be a variable if node_first: if isinstance(node_first[0].pattern.o, Variable): py_list.append(node_first[0].pattern.o) # append variable else: py_list.append(fact_first[0].o) # append fact elif fact_first: py_list.append(fact_first[0].o) # append fact node_rest = [node for node in alphaNodes if convertBNodeToFact(node.pattern.s)==id and node.pattern.p==REST] if node_rest: if node_rest[0].pattern.o == NIL: return py_list else: return listToPython(convertBNodeToFact(node_rest[0].pattern.o), alphaNodes, facts, py_list) else: return py_list def isListVarNode(node): return isinstance(node.pattern.s, Exivar) and node.pattern.p == FIRST and isinstance(node.pattern.o, Variable) def cmpVar(x, y): if x.name < y.name: return -1 elif x.name == y.name: return 0 elif x.name > y.name: return 1 def sortVars(vars): """I am a destructive function.""" return vars.sort(cmpVar) def removedups(lst): nodups = list() for elt in lst: if not elt in nodups: nodups.append(elt) return nodups def getOccurences(var, lst): """Return all positions of var in list.""" loc = 0 occurs = list() for elt in lst: if var == elt: occurs.append(loc) loc += 1 return tuple(occurs) def keysToList(dictionary): """I return a list of all keys in a nested dictionary, with optional values `prefix' inserted in the beginning.""" result = [] justification = [] if not dictionary: return result keysToListHelper(dictionary, [], result, justification) return result ###NOTE--this function should be renamed ('memoryToList'?) def keysToListHelper(dictionary, prefix, result, justification): """I take a dictionary representing a memory and convert it to a list based format, i.e.: [[v1, v2, v3, v4], [Fact(a, b, c), Fact(d, e, f)] ...] where the first list corresponds to a row in the memory, and the second to a set of facts justifying them.""" if isinstance(dictionary, tuple) or not dictionary: # get the justification #for j in dictionary: # justification.append(j) result.append([prefix, []]) return for k in dictionary: if len(dictionary[k]) > 1 and (not isinstance(dictionary[k], tuple)): for k2 in dictionary[k]: keysToListHelper(dictionary[k][k2], prefix + [k] + [k2], result, justification) else: keysToListHelper(dictionary[k], prefix + [k], result, justification) if __name__ == "__main__": a = {'immanuel': {'alan': {}, 'foo': {}, 'grups': {}}, 'friedrich': {'drew': {}}, 'john': {'willard': {}}, 'willard': {'pat': {}}, 'richard': {'bertrand': {}}} print keysToList(a) cwm-1.2.1/swap/pychinko/exception.py0000644015216600007660000000252710410547106016567 0ustar syosisyosiclass UnboundRuleVariable(Exception): def __init__(self, var, pattern): Exception.__init__(self, """%s is not bound in %s""" % (var, pattern)) class UnknownN3Type(Exception): def __init__(self, type, value): Exception.__init__(self, """%s is not a known N3 type (value was %s)""" % (type, value)) class AssertError(Exception): """I am raised when the validation predicate 'assert' fails.""" def __init__(self, subj, pred, obj): Exception.__init__(self, """Fact(%s, %s, %s) is not in the fact base.""" % (subj, pred, obj)) class ReportError(Exception): """I am raised when the validation predicate 'report' fails.""" def __init__(self, subj, pred, obj): Exception.__init__(self, """Fact(%s, %s, %s) is in the fact base.""" % (subj, pred, obj)) class UnknownBuiltin(Exception): """I am raised when an unknown builtin is referenced.""" def __init__(self, builtin): Exception.__init__(self, "Unknown builtin '%s' referenced." % (builtin)) class UnknownFactsFile(Exception): """I am raised when an unknown facts file format is passed in.""" def __init__(self, filename): Exception.__init__(self, "Unknown facts file '%s'" % (filename)) cwm-1.2.1/swap/pychinko/conclusion.py0000644015216600007660000000320110410547106016733 0ustar syosisyosi#from pychinko.interpreter import Interpreter from terms import Formula, Pattern from sets import Set import sys import os import config # TODO: fix bug: pychinko doesnot work for trivial cases, when there are no variables """{{ } log:implies { a }. .""" class Conclusion(object): """An implementation of CWM's log:conclusion""" def __init__(self, pattern): pass """run the rete on this the subj formula and return the result in obj""" def evaluate(self, subj, obj): #this is trickier: #create a rete, run it until no more new facts are found #return back the formula print "here!" rules = subj.rules #there may be facts in the rules file facts = subj.facts interp = Interpreter(rules) #print "patterns:" # for i in subj.patterns: # print i for i in rules: print "rule:", i #print "Ground fact(s): ", len(facts) #print facts interp.addFacts(Set(facts), initialSet=True) interp.run() print "interpreter sucessfully ran" print len(interp.inferredFacts) #create a new formula with the new facts + the stuff in subj and return it f = Formula() # copy all of the patterns f.patterns.extend(subj.patterns) #add the new ones for i in interp.inferredFacts: f.patterns.append(Pattern(i.s, i.p, i.o)) f.rules = f.getRules() f.facts = f.getFacts() return f cwm-1.2.1/swap/pychinko/builtins.py0000644015216600007660000004607110410564401016421 0ustar syosisyosi #from pychinko.N3Loader import N3Loader from terms import URI, Variable, Formula, Fact, Univar, Exivar from helpers import removedups, keysToList, convertBNodeToFact, LOG_SEMANTICS, LOG_CONJUNCTION, LOG_CONCLUSION from urllib import pathname2url #from rdflib.BNode import BNode #from rdflib.Graph import Graph from copy import copy import nodes import sys import os import config # add cwm builtins source to path sys.path += [config.CWMSOURCE] #print sys.path from swap.llyn import RDFStore from swap.term import Function, ReverseFunction, Term, CompoundTerm from swap import cwm_string, cwm_list, cwm_math, cwm_os #from pychinko.validation import Assert, Report, ValidationBuiltin #from pychinko.N3Loader import formulas from conclusion import Conclusion store = RDFStore() def builtinp(node): return isinstance(node, Builtin) or \ isinstance(node, ALBuiltin) def funcBuiltinp(node): if isinstance(node, Builtin): return node.pattern.p==LOG_SEMANTICS or node.pattern.p==LOG_CONJUNCTION or \ node.pattern.p == LOG_CONCLUSION or (node.pattern.p in FuncBuiltins) class Resource(object): def __init__(self): self.store = None class CWMString(CompoundTerm): """I am a superfluous string holder used to pass in strings to CWM builtins""" def __init__(self, string, store): self.string = string self.store = store def value(self): return self.string class Builtin(nodes.AlphaNode): """Placeholder for a builtin""" def __init__(self, pattern): self.URI = pattern.p self.pattern = pattern self.py_list = list() # python representation of rdf lists used in builtins, #now this only represents cwmSubj, extend it for obj,too nodes.AlphaNode.__init__(self, pattern) def evaluate(self, subj, obj): #print self.URI if self.URI in CWMBuiltins or self.URI in FuncBuiltins: """cwmSubj = subj cwmObj = obj""" cwmSubj = CWMString(subj, store) cwmObj = CWMString(obj, store) """print "subj:",cwmSubj.value() print "obj:",cwmObj.value() print "isinstance:", isinstance(cwmSubj,Term)""" # create the appropriate CWM builtin if self.URI in CWMBuiltins: builtin = CWMBuiltins[self.URI](cwmSubj, cwmObj) else: builtin = FuncBuiltins[self.URI](cwmSubj, cwmObj) # unfortunately, the CWM builtin 'evaluate' function has the signature # (store, context, subj, subj_py, obj, obj_py) even though only 'subj' # and 'obj' are actually used in function body - so we must # pass in superfluous arguments #TODO: what kind of values to return here? convert to str or not? if isinstance(builtin, Function): return str(builtin.evalObj(cwmSubj, False, False, False, False)) elif isinstance(builtin, ReverseFunction): return str(builtin.evalSubj(cwmObj, False, False, False, False)) else: return builtin.eval(cwmSubj, cwmObj, False, False, False, False) elif self.URI in PychBuiltins: builtin = PychBuiltins[self.URI](self.pattern) return builtin.evaluate(subj, obj) else: raise exception.UnknownBuiltin(self, self.URI) def getInputNode(self): """I what node feeds input to me""" inputNode = None for b in self.betaNodes: #hack if funcBuiltinp(b.lnode) or funcBuiltinp(b.rnode): return b.lnode if builtinp(b.lnode) and not builtinp(b.rnode): inputNode = b.rnode elif builtinp(b.rnode) and not builtinp(b.lnode): inputNode = b.lnode elif builtinp(b.rnode) and builtinp(b.lnode): if b.parents: inputNode = b.parents[0] else: inputNode = self else: raise "No builtin to evaluate!" """ if isinstance(inputNode, pychinko.nodes.BetaNode) and inputNode.builtinInput: print "inputNode", inputNode.pattern print "bInput", inputNode.builtinInput inputNode.pattern = inputNode.builtinInput.pattern inputNode.ind = inputNode.ind """ return inputNode def indexKey(self): """I return the key according to which we build the bindings for the rows resulting builtin evaluation""" inputNode = self.getInputNode() if isinstance(inputNode, nodes.AlphaNode): return removedups(inputNode.svars + inputNode.vars) elif isinstance(inputNode, nodes.BetaNode): return inputNode.pattern def getbindings(self, row,useBuiltin=None): bindings = dict() key = self.indexKey() for i, v in enumerate(key): bindings[v] = row[i] return bindings class Semantics(object): """An implementation of CWM's log:semantics""" def __init__(self, pattern): pass """retrieve the document at subj, parse it into a formula and store it in obj code similar to setup_and_run in main.py, uses N3loader""" def evaluate(self, subj, obj): if not subj.startswith('http://'): subj = pathname2url(subj) p = N3Loader() p.parse(subj, format='n3') f = Formula(p) return f class Conjunction(object): """An implementation of CWM's log:conjunction""" def __init__(self, pattern): pass """Take a list of formulas as input in subject, merge them into a new formula and return the new one""" def evaluate(self, subj, obj): # need an N3 loader to get rules and facts first f = Formula() for conjunct in subj: f.patterns.extend(conjunct.patterns) f.rules = list(f.getRules()) f.facts = list(f.getFacts()) return f class notIncludes(object): """An implementation of CWM's log:notIncludes""" def __init__(self, pattern): pass def evaluate(self, subj, obj): inc = self.Includes() return not inc.evaluate(subj, obj) class Includes(object): """An implementation of CWM's log:includes""" def __init__(self, pattern=None): pass """ log:includes implemented as simple matching: - for every fact in obj, see whether it's contained in subj - currently have only universal vars - ?a :y :z log:includes :x :y :z - no bindings passed for first-cut implementation - are there any bindings needed as input?""" def evaluate(self, subj, obj): # print "Includes.." # print "subj: ", subj # print "obj: ", obj return self.testIncludes(subj.patterns, obj.patterns) """does lhs log:include rhs?""" def matchLiteral(self, lhs, rhs): if isinstance(rhs,Univar): print "cwm does not allow universals in object of log:includes", rhs return False elif isinstance(rhs,Exivar): return True elif isinstance(lhs, Univar): return True elif isinstance(lhs, Exivar): return False else: #no vars, just compare facts return rhs == lhs """ I match a triple with subject formula. The triple does not contain any nested graphs""" def matchTriple(self, sFormula, triple): #eliminate triples in sFormula that contain formulas themselves l = [ item for item in sFormula if not isinstance(item.s, Formula) and not isinstance(item.o, Formula) ] # match the triple l = [item for item in sFormula if self.matchLiteral(item.s, triple.s) and self.matchLiteral(item.p, triple.p) and self.matchLiteral(item.o, triple.o)] return len(l) > 0 """ first compare the top level statements, then the nested formulas recursively """ def testIncludes(self, sFormula, oFormula): for triple in oFormula: if not isinstance(triple.s, Formula) and not isinstance(triple.o, Formula): if not self.matchTriple(sFormula, triple): return False elif isinstance(triple.s, Formula) and isinstance(triple.o, Formula): # {} _ {} filtered = [item for item in sFormula if isinstance(item.s, Formula) and self.matchLiteral(item.p, triple.p)] filtered = [item for item in filtered if isinstance(item.o, Formula)] #go through the filtered triples and invoke testIncludes recursively #if there's at least one match return true matched = False for i in filtered: if (self.testIncludes(i.s.patterns, triple.s.patterns) and self.testIncludes(i.o.patterns, triple.o.patterns)): matched = True break if not matched: return False elif isinstance(triple.s, Formula): # {} _ _ filtered = [item for item in sFormula if isinstance(item.s, Formula) and self.matchLiteral(item.p, triple.p) and self.matchLiteral(item.o, triple.o)] matched = False for i in filtered: if self.testIncludes(i.s.patterns, triple.s.patterns): matched = True break if not matched: return False elif isinstance(triple.o, Formula): # _ _ {} filtered = [item for item in sFormula if isinstance(item.o, Formula) and self.matchLiteral(item.p, triple.p) and self.matchLiteral(item.s, triple.s)] matched = False for i in filtered: if self.testIncludes(i.o.patterns, triple.o.patterns): matched = True break if not matched: return False #print "returning true..." return True class PelletQuery(object): """Ship RDQL queries to Pellet and return the result""" def __init__(self, kb): self.kb = kb self.pellet = self.getPellet() self.runCmd = self.pellet + ' -classify N3 -realize -inputFormat N3 -inputFile ' + self.kb def getPellet(self): """I read Pellet's location from ../config/pellet.conf""" import ConfigParser config = ConfigParser.ConfigParser() config.readfp(open('config/pellet.conf')) for name, value in config.items("Pellet"): if name == 'pelletcmd': return value def queryString(self, query): """I ship an RDQL query contained in a string to Pellet and return the result""" queryfp = open('query', 'w') queryfp.write(query + '\n') queryfp.close() query = self.runCmd + ' -queryFile query' pelletfp = os.popen(query, 'r') print pelletfp.read() # Implementation of AL-log. # # Our rules are of the same form as before. To gain the ALC expressivity # of class instance testing, we define the builtin :instanceOf whose object # argument is a class name (a string.) # # We still need to figure out how to have class expressions, e.g. :instanceOf (C v D). class ALBuiltin(Builtin): def __init__(self, pattern): Builtin.__init__(self, pattern) def evaluate(self, subj, obj): if self.URI in PychBuiltins: print "Known builtin (%s)" %(self.URI) print "Subj: ", subj print "Obj: ", obj builtin = PychBuiltins[self.URI](self.pattern) return builtin.evaluate(subj, obj) else: print "Unknown builtin (%s)" %(self.URI) return None class instanceOf(ALBuiltin): def __init__(self, pattern): ALBuiltin.__init__(self, pattern) def evaluate(self, subj, obj): print "Evaling s->(%s) o->(%s)" %(subj, obj) pellet = PelletQuery("allogtests/allog-facts.n3") pellet.queryString("SELECT ?x, ?y\nWHERE (?x, , ?z)") # CWM has a store.internURI() method which already does this, but tapping into # will involve using their RDFStore (which can be rdflib, I believe) but it's # nontrivial so I'm recreating it here until full integration ## These are builtins that are called directly from the CWM source CWMBuiltins = { URI('http://www.w3.org/2000/10/swap/math#negation'): cwm_math.BI_negation, URI('http://www.w3.org/2000/10/swap/math#absoluteValue'): cwm_math.BI_absoluteValue, URI('http://www.w3.org/2000/10/swap/math#rounded'): cwm_math.BI_rounded, URI('http://www.w3.org/2000/10/swap/list#in'): cwm_list.BI_in, URI('http://www.w3.org/2000/10/swap/math#notGreaterThan'): cwm_math.BI_notGreaterThan, URI('http://www.w3.org/2000/10/swap/math#notLessThan'): cwm_math.BI_notLessThan, URI('http://www.w3.org/2000/10/swap/math#equalTo'): cwm_math.BI_equalTo, URI('http://www.w3.org/2000/10/swap/math#notEqualTo'): cwm_math.BI_notEqualTo, URI('http://www.w3.org/2000/10/swap/math#memberCount'): cwm_math.BI_memberCount, #cwm relational string builtins URI('http://www.w3.org/2000/10/swap/string#greaterThan'): cwm_string.BI_GreaterThan, URI('http://www.w3.org/2000/10/swap/string#lessThan'): cwm_string.BI_LessThan, URI('http://www.w3.org/2000/10/swap/math#greaterThan'): cwm_math.BI_greaterThan, URI('http://www.w3.org/2000/10/swap/math#lessThan'): cwm_math.BI_lessThan, URI('http://www.w3.org/2000/10/swap/string#contains'): cwm_string.BI_Contains, URI('http://www.w3.org/2000/10/swap/string#startsWith'): cwm_string.BI_StartsWith, URI('http://www.w3.org/2000/10/swap/string#endsWith'): cwm_string.BI_EndsWith, URI('http://www.w3.org/2000/10/swap/string#greaterThan'): cwm_string.BI_GreaterThan, URI('http://www.w3.org/2000/10/swap/string#notGreaterThan'): cwm_string.BI_NotGreaterThan, URI('http://www.w3.org/2000/10/swap/string#lessThan'): cwm_string.BI_LessThan, URI('http://www.w3.org/2000/10/swap/string#notLessThan'): cwm_string.BI_NotLessThan, URI('http://www.w3.org/2000/10/swap/string#notEqualIgnoringCase'): cwm_string.BI_notEqualIgnoringCase} PychBuiltins = { # URI('http://www.mindswap.org/~katz/pychinko/builtins#assert'): # Assert, # URI('http://www.mindswap.org/~katz/pychinko/builtins#report'): # Report, URI('http://www.mindswap.org/~katz/pychinko/builtins#instanceOf'): instanceOf, URI('http://www.w3.org/2000/10/swap/log#includes'): Includes, URI('http://www.w3.org/2000/10/swap/log#semantics'): Semantics, URI('http://www.w3.org/2000/10/swap/log#conjunction'): Conjunction, URI('http://www.w3.org/2000/10/swap/log#conclusion'): Conclusion } FuncBuiltins = {URI('http://www.w3.org/2000/10/swap/math#sum'): cwm_math.BI_sum, URI('http://www.w3.org/2000/10/swap/math#sum'): cwm_math.BI_sum, URI('http://www.w3.org/2000/10/swap/math#difference'): cwm_math.BI_difference, URI('http://www.w3.org/2000/10/swap/math#product'): cwm_math.BI_product, URI('http://www.w3.org/2000/10/swap/math#integerQuotient'): cwm_math.BI_integerQuotient, URI('http://www.w3.org/2000/10/swap/math#quotient'): cwm_math.BI_quotient, URI('http://www.w3.org/2000/10/swap/math#remainder'): cwm_math.BI_remainder, URI('http://www.w3.org/2000/10/swap/math#exponentiation'): cwm_math.BI_exponentiation, URI('http://www.w3.org/2000/10/swap/math#sumOf'): cwm_math.BI_sumOf, URI('http://www.w3.org/2000/10/swap/math#factors'): cwm_math.BI_factors, URI('http://www.w3.org/2000/10/swap/math#bit'): cwm_math.BI_bit, URI('http://www.w3.org/2000/10/swap/math#quotientOf'): cwm_math.BI_quotientOf, URI('http://www.w3.org/2000/10/swap/math#remainderOf'): cwm_math.BI_remainderOf, URI('http://www.w3.org/2000/10/swap/math#exponentiationOf'): cwm_math.BI_exponentiationOf, URI('http://www.w3.org/2000/10/swap/math#negation'): cwm_math.BI_negation, URI('http://www.w3.org/2000/10/swap/math#absoluteValue'): cwm_math.BI_absoluteValue, URI('http://www.w3.org/2000/10/swap/math#rounded'): cwm_math.BI_rounded, #string builtins URI('http://www.w3.org/2000/10/swap/string#concatenation'): cwm_string.BI_concatenation, } logimplies = (URI, 'http://www.w3.org/2000/10/swap/log#logimplies') def getPatternType(pred): if pred in PychBuiltins or pred in CWMBuiltins or pred in FuncBuiltins: return Builtin # elif pred in CWMBuiltins: # print "RETURNING ---> ", CWMBuiltins[pred] # return CWMBuiltins[pred] # else: # return None cwm-1.2.1/swap/pychinko/interpreter.py0000644015216600007660000002206110410547106017127 0ustar syosisyosiimport sys import rete from terms import Variable, Pattern, Rule, Fact, URI, makeToken, Exivar, Univar from nodes import AlphaIndex, BetaNode, QueryRuleNode, py_lists from sets import Set from helpers import removedups, TYPE, listToPython, aNodeListToPython, factListToPython, FIRST, REST, LIST, INCLUDES, convertBNodeToFact, isListVarNode #from pychinko import N3Loader import time class Interpreter: def __init__(self, rules=None): self.compiler = rete.RuleCompiler() self.rules = rules self.rete = self.compiler.compile(rules) self.totalFacts = Set() self.joinedBetaNodes = Set() self.inferredFacts = Set() self.fta = Set() #FactsToAdd self.rulesThatFired = Set() self.initialFacts = Set() def addRule(self, rule): #self.rules.add(rule) self.rete, alphaNodesOfRule = self.compiler.addRule(rule) #add facts only to the alphanodes of this rule self.addFactsForRule(self.totalFacts, alphaNodesOfRule) #this function propagates the totalFacts to the alphanodes of the rule def addFactsForRule(self, facts, alphaNodesRule): status = False t = time.time() listFacts = Set() if not alphaNodesRule: print "No alpha nodes in rule!" return False for f in facts: alphaMatches = self.rete.alphaIndex.match(f) for anode in alphaMatches: if anode in alphaNodesRule: if anode.add(f): status = True print "add facts for new rule time:", time.time() - t return status #bool(alphaMatches) #true if any alpha nodes matched #clean up this function, make it more flexible so when we add only 1 new fact we do not have to rerun the whole thing def addFacts(self, facts, initialSet=False): #facts = Set """Adds a set of facts to the AlphaNodes.""" if initialSet: self.initialFacts = Set(facts) else: pass #self.initialFacts = self.totalFacts #not an initial set, then initialFacts would be the old total facts if not self.rete.alphaIndex: print "No alpha nodes in store!" return False #add facts for every list-related pattern with bnodes for alphaNode in self.rete.alphaNodeStore: #if the alphanode includes bnodes (list related) then add a matching fact if (alphaNode.pattern.p in [FIRST, REST, INCLUDES]) or (alphaNode.pattern.p==TYPE and alphaNode.pattern.o==LIST): #add a fact subj = convertBNodeToFact(alphaNode.pattern.s) obj = convertBNodeToFact(alphaNode.pattern.o) if not isinstance(subj, Variable) and not isinstance(obj, Variable): #add it to the set of initial facts or the alphanode? #add the fact directly to the alphanode for now, dont have to do the matching #self.initialFacts.add(Fact(subj, alphaNode.pattern.p, obj)) #alphaNode.add(Fact(subj, alphaNode.pattern.p, obj)) #print "adding fact" #print subj, alphaNode.pattern.p, obj facts.add(Fact(subj, alphaNode.pattern.p, obj)) #following code is converting and adding python lists in dictionary py_lists #for the rules triples that are list related for alphaNode in self.rete.alphaNodeStore: #print alphaNode if (alphaNode.pattern.p == FIRST and not isinstance(alphaNode.pattern.s, Univar) ): #print "bnode:", convertBNodeToFact(alphaNode.pattern.s) py_list = aNodeListToPython(convertBNodeToFact(alphaNode.pattern.s), self.rete.alphaNodeStore.nodes, []) #py_list = listToPython(convertBNodeToFact(alphaNode.pattern.s), self.rete.alphaNodeStore.nodes, self.initialFacts.union(facts),[]) py_lists[convertBNodeToFact(alphaNode.pattern.s)] = py_list #print "py_lists:", py_lists status = False #this code does the same for the facts for f in self.initialFacts: if f.p==FIRST: py_list = factListToPython(convertBNodeToFact(f.s), self.initialFacts.union(facts),[]) py_lists[convertBNodeToFact(f.s)] = py_list #print "py_lists:", py_lists self.totalFacts.add(f) #add only to relevant alpha nodes alphaMatches = self.rete.alphaIndex.match(f) for anode in alphaMatches: if anode.add(f): status = True for f in facts.difference(self.initialFacts): #if this fact is of type list, add it to the dict if f.p==TYPE and f.o==LIST: py_list = factListToPython(convertBNodeToFact(f.s), self.initialFacts.union(facts),[]) py_lists[convertBNodeToFact(f.s)] = py_list #print "py_lists:", py_lists self.totalFacts.add(f) #add only to relevant alpha nodes alphaMatches = self.rete.alphaIndex.match(f) for anode in alphaMatches: #print "new fact added:", f #print "_to alpha node added:", anode.pattern #do not add the fact if the bnode does not match #this is to take care of: _:xsdiuh rdf:first ?y or _:sdfds rdf:rest _:dsfdsf if (anode.pattern.p in [REST, FIRST]) or (anode.pattern.p==TYPE and anode.pattern.o==LIST): if isinstance(anode.pattern.s, Exivar) and convertBNodeToFact(anode.pattern.s)==f.s: if anode.add(f): status = True else: if anode.add(f): status = True #if isinstance(anode.pattern.s, Exivar) and convertBNodeToFact(anode.pattern.s)==f.s: # if anode.add(f): # status = True #elif not isinstance(anode.pattern.s, Exivar): # if anode.add(f): # status = True return status #bool(alphaMatches) #true if any alpha nodes matched def run(self, alphaMatches = None): """I walk the Rete network and attempt to make the necessary JOINs.""" t = time.time() for alphaNode in self.rete.alphaNodeStore: for betaNode in alphaNode.betaNodes: if betaNode in self.joinedBetaNodes: continue self.fta = Set() #resets the list of inferred facts from JOINs self.processBetaNode(betaNode) #returns results via self.fta if self.fta: #facts that are in newFacts but not in inferred facts = "unique facts" # print "inferred facts:", self.fta self.fta = self.fta.difference(self.initialFacts) newInferredFacts = self.fta.difference(self.inferredFacts) if newInferredFacts: self.inferredFacts.union_update(newInferredFacts) #reapply the rules to the new facts. If unique facts is empty or #the new facts are a subset of the initial facts, we terminate. if self.addFacts(newInferredFacts): self.joinedBetaNodes = Set() self.run() # take the inferred facts, create an rdflib.graph and serialize it in rdf/xml #this is a rules in PIT extension #N3loader.convertBackToGraph(self.inferredFacts) print "interpreter run() time:", time.time() - t def processBetaNode(self, betaNode): """I process a beta node""" #t = time.time() inferences = betaNode.join() if inferences: self.joinedBetaNodes.add(betaNode) if betaNode.rule: #self.rulesThatFired.add(betaNode.rule) #######this test will be moved into `matchingFacts' for rhsPattern in betaNode.rule.rhs: results = betaNode.matchingFacts(rhsPattern, inferences) self.fta.union_update(Set(results)) else: for child in betaNode.children: #process children of BetaNode.. self.processBetaNode(child) #print "process betanode time:", time.time() - t cwm-1.2.1/swap/reify.py0000644015216600007660000003303210731063552014062 0ustar syosisyosi#!/usr/bin/python """ Functions to reify and dereify a graph. These functions should be perfect inverses of each other. The strategy used is different from that of the reifier in notation3.py, that tries to reify what it outputs. This simply puts the reification into the sink given, or a new one, depending on the function called. $Id: reify.py,v 1.19 2007/12/11 21:18:08 syosi Exp $ """ from term import BuiltIn, LightBuiltIn, LabelledNode, \ HeavyBuiltIn, Function, ReverseFunction, AnonymousNode, \ Literal, Symbol, Fragment, FragmentNil, Term,\ CompoundTerm, List, EmptyList, NonEmptyList, N3Set from formula import Formula, StoredStatement from RDFSink import CONTEXT, PRED, SUBJ, OBJ, PARTS, ALL4, RDF_type_URI import uripath import diag from mixin import Mixin from set_importer import Set reifyNS = 'http://www.w3.org/2004/06/rei#' REIFY_NS = reifyNS owlOneOf = 'http://www.w3.org/2002/07/owl#oneOf' class rTerm(Mixin, Term): def unflatten(self, sink, bNodes, why=None): return self class rLabelledNode(Mixin, LabelledNode): def reification(self, sink, bnodeMap={}, why=None): """Describe myself in RDF to the given context [ reify:uri "http://example.org/whatever"] """ #" b = sink.newBlankNode(why=why) uri = sink.newSymbol(REIFY_NS + "uri") sink.add(subj=b, pred=uri, obj=sink.newLiteral(self.uriref()), why=why) return b def flatten(self, sink, why=None): return self class rAnonymousNode(Mixin, AnonymousNode): def reification(self, sink, bnodeMap={}, why=None): """Describe myself in RDF to the given context [ reify:items ( [ reify:value "foo"] .... ) ] """ try: return bnodeMap[self] except KeyError: b = sink.newBlankNode() bnodeMap[self] = b q = sink.newSymbol(RDF_type_URI) r = sink.newSymbol(REIFY_NS+"BlankNode") sink.add(subj=b, pred=q, obj=r, why=why) return b def flatten(self, sink, why=None): sink.declareExistential(self) return self def unflatten(self, sink, bNodes, why=None): try: return bNodes[self] except KeyError: bNodes[self] = sink.newBlankNode() return bNodes[self] class rN3Set(Mixin, N3Set): def reification(self, sink, bnodeMap={}, why=None): """Describe myself in RDF to the given context [ reify:items ( [ reify:value "foo"] .... ) ] """ m = [x for x in self] m.sort(Term.compareAnyTerm) mm = [x.reification(sink, bnodeMap, why) for x in m] elements = sink.store.newSet(mm) b = sink.newBlankNode() sink.add(subj=b, pred=sink.newSymbol(REIFY_NS+"items"), obj=elements, why=why) return b def flatten(self, sink, why=None): newlist = sink.store.newSet([x.flatten(sink, why=why) for x in self]) return newlist def unflatten(self, sink, bNodes, why=None): newlist = sink.store.newSet([x.unflatten(sink, bNodes, why=why) for x in self]) return newlist class rList(Mixin, List): def reification(self, sink, bnodeMap={}, why=None): """Describe myself in RDF to the given context [ reify:items ( [ reify:value "foo"] .... ) ] """ elements = sink.newList([ x.reification(sink, bnodeMap, why) for x in self]) b = sink.newBlankNode() sink.add(subj=b, pred=sink.newSymbol(REIFY_NS+"items"), obj=elements, why=why) return b def flatten(self, sink, why=None): newlist = sink.newList([x.flatten(sink, why=why) for x in self]) return newlist def unflatten(self, sink, bNodes, why=None): newlist = sink.newList([x.unflatten(sink, bNodes, why=why) for x in self]) return newlist class rLiteral(Mixin, Literal): def reification(self, sink, bnodeMap={}, why=None): """Describe myself in RDF to the given context [ reify:value "un expression quelconque"@fr ] """ b = sink.newBlankNode(why=why) sink.add(subj=b, pred=sink.newSymbol(REIFY_NS+"value"), obj=self, why=why) return b def flatten(self, sink, why=None): return self class rFormula(Mixin, Formula): def reification(self, sink, bnodeMap={}, why=None): """Describe myself in RDF to the given context """ list = [].__class__ try: return bnodeMap[self] except KeyError: F = sink.newBlankNode() bnodeMap[self] = F rei = sink.newSymbol(reifyNS[:-1]) myMap = bnodeMap ooo = sink.newSymbol(owlOneOf) es = list(self.existentials()) es.sort(Term.compareAnyTerm) us = list(self.universals()) us.sort(Term.compareAnyTerm) for vars, vocab in ((es, rei["existentials"]), (us, rei["universals"])): if diag.chatty_flag > 54: progress("vars=", vars) progress("vars=", [v.uriref() for v in vars]) list = sink.store.nil.newList([x.reification(sink, myMap, why) for x in vars]) # sink.newLiteral(x.uriref()) klass = sink.newBlankNode() sink.add(klass, ooo, list) sink.add(F, vocab, klass, why) #The great list of statements statementList = [] for s in self.statements: subj = sink.newBlankNode() sink.add(subj, rei["subject"], s[SUBJ].reification(sink, myMap, why), why) sink.add(subj, rei["predicate"], s[PRED].reification(sink, myMap, why), why ) sink.add(subj, rei["object"], s[OBJ].reification(sink, myMap, why), why) statementList.append(subj) #The great class of statements StatementClass = sink.newBlankNode() realStatementList = sink.store.nil.newList(statementList) sink.add(StatementClass, ooo, realStatementList, why) #We now know something! sink.add(F, rei["statements"], StatementClass, why) return F def flatten(self, sink, why=None): return self.reification(sink, {}, why=why) def flatten(formula): """Flatten a formula This will minimally change a formula to make it valid RDF flattening a flattened formula should thus be the unity """ why = None store = formula.store valid_triples = formula.statements[:] for triple in valid_triples: for part in SUBJ, PRED, OBJ: try: triple[part] = triple[part].close() except AttributeError: pass invalid_triples = [] new_invalid_triples = [] shared_vars = Set() for triple in valid_triples: if triple.occurringIn(formula.universals()): new_invalid_triples.append(triple) shared_vars.update(triple.occurringIn(formula.existentials())) for triple in new_invalid_triples: try: valid_triples.remove(triple) except ValueError: pass while new_invalid_triples: invalid_triples.extend(new_invalid_triples) new_invalid_triples = [] for triple in valid_triples: if triple.occurringIn(shared_vars): new_invalid_triples.append(triple) shared_vars.update(triple.occurringIn(formula.existentials())) for triple in new_invalid_triples: try: valid_triples.remove(triple) except ValueError: pass still_needed_existentials = reduce(Set.union, [x.occurringIn(formula.existentials()) for x in valid_triples], Set()) returnFormula = formula.newFormula() tempBindings = {} bNodeBindings = {} for a in still_needed_existentials: bNodeBindings = returnFormula.newBlankNode(a) tempformula = formula.newFormula() for var in formula.universals(): tempBindings[var] = tempformula.newUniversal(var) for var in formula.existentials(): termBindings[var] = tempformula.newBlankNode(var) for triple in invalid_triples: tempformula.add(triple[SUBJ].substitution(tempBindings, why=why), triple[PRED].substitution(tempBindings, why=why), triple[OBJ].substitution(tempBindings, why=why)) #now for the stuff that isn't reified for triple in valid_triples: returnFormula.add(triple[SUBJ].substitution(bNodeBindings, why=why).flatten(returnFormula), triple[PRED].substitution(bNodeBindings, why=why).flatten(returnFormula), triple[OBJ].substitution(bNodeBindings, why=why).flatten(returnFormula)) if tempformula.statements != []: x = tempformula.reification(returnFormula) returnFormula.add(x, store.type, store.Truth) return returnFormula.close() def reify(formula): """Reify a formula Returns an RDF formula with the same semantics as the given formula """ a = formula.newFormula() x = formula.reification(a) a.add(x, a.store.type, a.store.Truth) a = a.close() return a def unflatten(formula, sink=None): """Undo the effects of the flatten function. Note that this still requires helper methods scattered throughout the Term heriarchy. Our life is made much more difficult by the necessity of removing all triples that have been dereified --- this required a modification to dereification() """ store = formula.store if sink == None: sink = formula.newFormula() bNodes = {} #to track bNodes that bacome formulae rei = formula.newSymbol(reifyNS[:-1]) formulaList = formula.each(pred=rei["statements"]) #on the next line, we are filtering Truths because those will be included later formulaList = [a for a in formulaList if formula.the(pred=store.type, obj=store.Truth) == None] skipNodeList=[] for a in formulaList: xList = [] bNodes[a] = dereification(a, formula, sink, xList=xList) skipNodeList.extend(xList[1:]) dereify(formula, sink, xList=skipNodeList) for triple in formula.statements: if triple[PRED] != rei["statements"] and \ triple[PRED] != rei["universals"] and \ triple[PRED] != rei["value"] and \ triple[PRED] != rei["existentials"] and \ triple[SUBJ] not in skipNodeList and \ triple[PRED] not in skipNodeList and \ triple[OBJ] not in skipNodeList: sink.add(triple[SUBJ].unflatten(sink, bNodes), triple[PRED].unflatten(sink, bNodes), triple[OBJ].unflatten(sink, bNodes)) return sink.close() #### Alternative method # Shortcuts are too messy and don't work with lists # def dereify(formula, sink=None, xList=[]): store = formula.store if sink == None: sink = formula.newFormula() weKnowList = formula.each(pred=store.type, obj=store.Truth) for weKnow in weKnowList: f = dereification(weKnow, formula, sink, xList=xList) sink.loadFormulaWithSubstitution(f) return sink def dereification(x, f, sink, bnodes={}, xList=[]): rei = f.newSymbol(reifyNS[:-1]) xList.append(x) if x == None: raise ValueError, "Can't dereify nothing. Suspect missing information in reified form." y = f.the(subj=x, pred=rei["uri"]) if y != None: return sink.newSymbol(y.value()) y = f.the(subj=x, pred=rei["value"]) if y != None: return y y = f.the(subj=x, pred=rei["items"]) if y != None: if isinstance(y, N3Set): yy = [z for z in y] yy.sort(Term.compareAnyTerm) return sink.store.newSet([dereification(z, f, sink, bnodes, xList) for z in yy]) return sink.newList([dereification(z, f, sink, bnodes, xList) for z in y]) y = f.the(subj=x, pred=rei["statements"]) if y != None: z = sink.newFormula() zbNodes = {} # Bnode map for this formula uset = f.the(subj=x, pred=rei["universals"]) xList.append(uset) ulist = uset #f.the(subj=uset, pred=f.newSymbol(owlOneOf)) xList.append(ulist) from diag import progress if diag.chatty_flag > 54: progress("universals = ",ulist) for v in ulist: z.declareUniversal(f.newSymbol(v.value())) uset = f.the(subj=x, pred=rei["existentials"]) xList.append(uset) ulist = uset #f.the(subj=uset, pred=f.newSymbol(owlOneOf)) xList.append(ulist) if diag.chatty_flag > 54: progress("existentials %s = %s"%(ulist, ulist.value())) for v in ulist: if diag.chatty_flag > 54: progress("Variable is ", v) z.declareExistential(f.newSymbol(v.value())) yy = y #f.the(subj=y, pred=f.newSymbol(owlOneOf)) xList.append(yy) if diag.chatty_flag > 54: progress("Statements: set=%s, list=%s = %s" %(y,yy, yy.value())) for stmt in yy: z.add(dereification(f.the(subj=stmt, pred=rei["subject"]), f, sink, zbNodes, xList), dereification(f.the(subj=stmt, pred=rei["predicate"]), f, sink, zbNodes, xList), dereification(f.the(subj=stmt, pred=rei["object"]), f, sink, zbNodes, xList)) return z.close() y = f.the(subj=x, pred=f.newSymbol(RDF_type_URI)) if y is not None: if x in bnodes: return bnodes[x] z = sink.newBlankNode() bnodes[x] = z return z raise ValueError, "Can't dereify %s - no clues I understand in %s" % (x, f) cwm-1.2.1/swap/set_importer.py0000644015216600007660000000677310462432117015472 0ustar syosisyosi""" A hack to import sets and frozensets, internally if possible """ realcmp = cmp try: my_sorted = sorted except NameError: def my_sorted(iterable, cmp=None, key=None, reverse=False): m = list(iterable) if cmp is None and (key is not None or reverse is not None): cmp = realcmp if key is not None: cmp2 = cmp def cmp(x,y): return cmp2(key(x), key(y)) if reverse is not None: cmp3 = cmp def cmp(x,y): return cmp3(y,x) m.sort(cmp) return m sorted = my_sorted try: Set = set except NameError: from sets import Set try: ImmutableSet = frozenset except NameError: from sets import ifilterfalse, BaseSet, ImmutableSet as notImmutableEnoughSet class ImmutableSet(notImmutableEnoughSet): def copy(self): return self.__class__(self) def union(self, other): ret = self._data.copy() if isinstance(other, BaseSet): ret.update(other._data) return self.__class__(ret) value = True if type(other) in (list, tuple, xrange): # Optimized: we know that __iter__() and next() can't # raise TypeError, so we can move 'try:' out of the loop. it = iter(other) while True: try: for element in it: ret[element] = value return self.__class__(ret) except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught ret[transform()] = value else: # Safe: only catch TypeError where intended for element in iterable: try: ret[element] = value except TypeError: transform = getattr(element, "__as_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught ret[transform()] = value return self.__class__(ret) def symmetric_difference(self, other): """Return the symmetric difference of two sets as a new set. (I.e. all elements that are in exactly one of the sets.) """ data = {} value = True selfdata = self._data try: otherdata = other._data except AttributeError: otherdata = Set(other)._data for elt in ifilterfalse(otherdata.has_key, selfdata): data[elt] = value for elt in ifilterfalse(selfdata.has_key, otherdata): data[elt] = value return self.__class__(data) def difference(self, other): """Return the difference of two sets as a new Set. (I.e. all elements that are in this set and not in the other.) """ data = {} try: otherdata = other._data except AttributeError: otherdata = Set(other)._data value = True for elt in ifilterfalse(otherdata.has_key, self): data[elt] = value return self.__class__(data) cwm-1.2.1/swap/cant.py0000644015216600007660000002626210640075637013706 0ustar syosisyosi#! /usr/bin/python """CAnonicalize N-Triples Options: --verbose -v Print what you are doing as you go --help -h Print this message and exit --from=uri -f uri Specify an input file (or web resource) --diff=uri -d uri Specify a difference file Can have any number of --from parameters, in which case files are merged. If none are given, /dev/stdin is used. If any diff files are given then the diff files are read merged separately and compared with the input files. the result is a list of differences instead of the canonicalizd graph. This is NOT a minimal diff. Exits with nonzero system status if graphs do not match. This is an independent n-triples cannonicalizer. It uses heuristics, and will not terminate on all graphs. It is designed for testing: the output and the reference output are both canonicalized and compared. It uses the very simple NTriples format. It is designed to be independent of the SWAP code so that it can be used to test the SWAP code. It doesn't boast any fancy algorithms - just tries to get the job done for the small files in the test datasets. The algorithm to generate a "signature" for each bnode. This is just found by looking in its immediate viscinity, treating any local bnode as a blank. Bnodes which have signatures unique within the graph can be allocated cannonical identifiers as a function of the ordering of the signatures. These are then treated as fixed nodes. If another pass is done of the new graph, the signatures are more distinct. This works for well-labelled graphs, and graphs which don't have large areas of interconnected bnodes or large duplicate areas. A particular failing is complete lack of treatment of symmetry between bnodes. References: .google graph isomorphism See also eg http://www.w3.org/2000/10/rdf-tests/rdfcore/utils/ntc/compare.cc NTriples: see http://www.w3.org/TR/rdf-testcases/#ntriples Not to mention, published this month by coincidence: Kelly, Brian, [Whitehead Institute] "Graph cannonicalization", Dr Dobb's Journal, May 2003. $Id: cant.py,v 1.15 2007/06/26 02:36:15 syosi Exp $ This is or was http://www.w3.org/2000/10/swap/cant.py W3C open source licence . 2004-02-31 Serious bug fixed. This is a test program, shoul dbe itself tested. Quis custodiet ipsos custodes? """ # canticle - Canonicalizer of NTriples Independent of Cwm , Llyn, Etc. ? import os import sys import urllib try: from swap import uripath # http://www.w3.org/2000/10/swap/ except ImportError: import uripath from sys import stderr, exit import uripath import getopt import re import types name = "[A-Za-z][A-Za-z0-9]*" #http://www.w3.org/TR/rdf-testcases/#ntriples nodeID = '_:' + name uriref = r'<[^>]*>' language = r'[a-z0-9]+(?:-[a-z0-9]+)?' string_pattern = r'".*"' # We know in ntriples that there can only be one string on the line langString = string_pattern + r'(?:@' + language + r')?' datatypeString = langString + '(?:\^\^' + uriref + r')?' #literal = langString + "|" + datatypeString object = r'(' + nodeID + "|" + datatypeString + "|" + uriref + r')' ws = r'[ \t]*' com = ws + r'(#.*)?[\r\n]*' comment = re.compile("^"+com+"$") statement = re.compile( ws + object + ws + object + ws + object + com) # #" def usage(): print __doc__ def loadFiles(testFiles): graph = [] WD = "file://" + os.getcwd() + "/" for fn in testFiles: if verbose: stderr.write("Loading data from %s\n" % fn) uri = uripath.join(WD, fn) inStream = urllib.urlopen(uri) while 1: line = inStream.readline() if line == "" : break # if verbose: stderr.write("%s\n" % line) m = comment.match(line) if m != None: continue m = statement.match(line) if m == None: stderr.write("Syntax error: "+line+"\n") if verbose: [stderr.write('%2x ' % ord(c)) for c in line] stderr.write('\n') exit(-1) triple = m.group(1), m.group(2), m.group(3) if verbose: stderr.write( "Triple: %s %s %s.\n" % (triple[0], triple[1], triple[2])) graph.append(triple) if verbose: stderr.write("\nThere are %i statements in graph\n" % (len(graph))) return graph def main(): testFiles = [] diffFiles = [] global ploughOn # even if error ploughOn = 0 global verbose verbose = 0 try: opts, args = getopt.getopt(sys.argv[1:], "hf:d:iv", ["help", "from=", "diff=", "to=", "ignoreErrors", "verbose"]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) output = None for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() if o in ("-v", "--verbose"): verbose = 1 if o in ("-i", "--ignoreErrors"): ploughOn = 1 if o in ("-f", "--from"): testFiles.append(a) if o in ("-d", "--diff", "--to"): diffFiles.append(a) if testFiles == []: testFiles = [ "/dev/stdin" ] graph = loadFiles(testFiles) graph = canonicalize(graph) if diffFiles != []: graph2 = loadFiles(diffFiles) graph2 = canonicalize(graph2) d = compareCanonicalGraphs(graph, graph2) if d != 0: sys.exit(d) else: serialize(graph) def compareCanonicalGraphs(g1, g2): inserted, deleted = [], [] g1.sort() g2.sort() i1, i2 = 0,0 while 1: if i1 == len(g1): inserted = inserted + g2[i2:] if verbose: stderr.write("All other %i triples were inserted.\n" % (len(g2)-i2)) break if i2 == len(g2): deleted = deleted + g1[i1:] if verbose: stderr.write("All other %i triples were deleted.\n" % (len(g1)-i1)) break d = cmp(g1[i1], g2[i2]) # 1-2 if d==0: if verbose: stderr.write("Common: %s %s %s.\n" % g2[i2]) i1 += 1 i2 += 1 elif d<0: if verbose: stderr.write("Deleted: %s %s %s.\n" % g1[i1]) deleted.append(g1[i1]) i1 += 1 else: if verbose: stderr.write("Inserted: %s %s %s.\n" % g2[i2]) inserted.append(g2[i2]) i2 += 1 for triple in deleted: print "- %s %s %s." % triple for triple in inserted: print "+ %s %s %s." % triple number = len(deleted) + len(inserted) if verbose: if number == 0: stderr.write("FILES MATCH.\n") else: stderr.write("FILES DIFFER. (%i statements by our count)\n"% number) return number def canonicalize(g): "Do our best with this algo" dups, graph, c = canon(g) while dups != 0: newDups, graph, c = canon(graph, c) if newDups == dups: exit(-2) # give up dups = newDups return graph def serialize(graph): graph.sort() if verbose: print "# Canonicalized:" for t in graph: for x in t: if x.startswith("__"): x = x[1:] print x, print "." def compareFirst(a,b): "Compare consistently nested lists of strings" d = cmp(`a[0]`, `b[0]`) if verbose: if d<0: stderr.write("Comparing: %s]\n LESS THAN %s\n" % (`a`,`b`)) elif d>0: stderr.write("Comparing: %s]\n LESS THAN %s\n" % (`b`,`a`)) else: stderr.write("Comparing: %s]\n EQUALS %s\n" % (`b`,`a`)) return d #@@@@@@@@@@@@ if a==None and b == None: return 0 if a == None: return -1 if b == None: return 1 if isinstance(a, types.IntType): if isinstance (b,types.IntType): return a-b else: return -1 # Ints are less than strings or lists if isinstance(a, types.StringTypes): if isinstance (b, types.IntType): return 1 if isinstance (b,types.StringTypes): if a < b: return -1 if a > b: return 1 return 0 else: return -1 # Strings are less than lists else: # a is list if isinstance (b,types.StringTypes): return 1 else: # list vs list # assert isinstance(a, types.ListType) or isinstance(a, TupleType) if len(a) < len(b): return -1 if len(a) > len(b): return 1 for i in range(len(a)): d = compare(a[i], b[i], level+1) if d != 0: return d return 0 def canon(graph, c0=0): """Try one pass at canonicalizing this using 1 step sigs. Return as a triple: - The new graph - The number of duplicate signatures in the bnodes - The index number for th enext constant to be generated.""" nextBnode = 0 bnodes = {} pattern = [] signature = [] canonical = {} for j in range(len(graph)): triple = graph[j] pat = [] for i in range(3): if triple[i].startswith("_:"): b = bnodes.get(triple[i], None) if b == None: b = nextBnode nextBnode = nextBnode + 1 bnodes[triple[i]] = b signature.append([]) pat.append(None) else: pat.append(triple[i]) pattern.append(pat) for i in range(3): if triple[i].startswith("_:"): b = bnodes[triple[i]] signature[b].append((i, pat)) if verbose: stderr.write("\n") n = nextBnode s = [] for i in range(n): signature[i].sort() # Signature is now intrinsic to the local environment of that bnode. if verbose: stderr.write( "Bnode %3i) %s\n\n" % (i, signature[i])) s.append((signature[i], i)) s.sort(compareFirst) dups = 0 c = c0 if verbose: stderr.write("\nIn order\n") for i in range(n): sig, original = s[i] if verbose: stderr.write("%3i) Orig: %i Sig:%s\n" %(i, original, sig)) if i != n-1 and s[i][0] == s[i+1][0]: if verbose: stderr.write( "@@@ %3i] %i and %i have same signature: \n\t%s\nand\t%s\n" % ( i, s[i][1], s[i+1][1], s[i][0], s[i+1][0])) dups = dups + 1 elif i != 0 and s[i][0] == s[i-1][0]: if verbose: stderr.write( "@@@ %3i] %i and %i have same signature: \n\t%s\nand\t%s\n" % ( i, s[i][1], s[i-1][1], s[i][0], s[i-1][0])) else: canonical[original] = c if verbose: stderr.write( "\tBnode#%i canonicalized to new fixed C%i\n" %(s[i][1], c)) c = c + 1 newGraph = [] for j in range(len(graph)): triple = graph[j] newTriple = [] for i in range(3): x = triple[i] if x.startswith("_:"): b = bnodes[x] c1 = canonical.get(b, None) if c1 != None: x = "__:c" + str(c1) # New name newTriple.append(x) newGraph.append((newTriple[0], newTriple[1], newTriple[2])) if verbose: stderr.write("Iteration complete with %i duplicate signatures\n\n" %dups) return dups, newGraph, c if __name__ == "__main__": main() # ends cwm-1.2.1/swap/check.py0000644015216600007660000007616510640075637014045 0ustar syosisyosi"""Check a proof This is a simple proof checker. It hasn't itself been proved, and there are probably lots of ways to fool it especially as a deliberate malicious attack. That is because there are simple things I may have forgotten to check. Command line options for debug: -v50 Set verbosity to 50 (range is 0 -100) -c50 Set verbosity for inference done by cwm code to 50 -p50 Set verobsity when parsing top 50 @@for more command line options, see main() in source """ __version__ = '$Id: check.py,v 1.59 2007/06/26 02:36:15 syosi Exp $'[1:-1] # mystore and term should be swappable with rdflib; shared interfaces from swap.myStore import load, Namespace, formula #@@get rid of the global store from swap.RDFSink import PRED, SUBJ, OBJ #@@ this is the old quad API; should go. from swap.set_importer import Set # which python version shall we support? from swap.term import List, Literal, CompoundTerm, BuiltIn, Function #@@ TODO: split built-ins out of swap.term. don't rely on interning at the interface from swap.llyn import Formula #@@ dependency should not be be necessary from swap.diag import verbosity, setVerbosity, progress from swap import diag from swap.query import testIncludes #see also http://en.wikipedia.org/wiki/Unification . Currently cwm's unification algorithm is spread all over the place. import swap.llyn # Chosen engine registers itself import sys # to get exception info for diagnostics reason = Namespace("http://www.w3.org/2000/10/swap/reason#") log = Namespace("http://www.w3.org/2000/10/swap/log#") rdf=Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") rei = Namespace("http://www.w3.org/2004/06/rei#") chatty = 0 debugLevelForInference = 000 debugLevelForParsing = 0 nameBlankNodes = 0 proofSteps = 0 knownReasons = Set([reason.Premise, reason.Parsing, reason.Inference, reason.Conjunction, reason.Fact, reason.Extraction, reason.CommandLine, reason.Conclusion]) class Policy(object): """a proof-checking policy""" def documentOK(self, u): raise RuntimeError("subclass must implement") def assumes(self, f): """Check whether a formula is an axiom. Hmm... move checkBuiltin here?""" raise RuntimeError("subclass must implement") class AllPremises(Policy): """A useful testing policy is to accept all premises and no sources. """ def __init__(self): return Policy.__init__(self, True) def assumes(self, f): return True def documentOK(self, f): return False class FormulaCache(object): def __init__(self): self._loaded = {} def get(self, uri): f = self._loaded.get(uri, None) if f == None: setVerbosity(debugLevelForParsing) f = load(uri, flags="B").close() # why B? -DWC setVerbosity(0) self._loaded[uri] = f assert f.canonical is f, `f.canonical` return f def topLevelLoad(uri=None, flags=''): graph = formula() graph.setClosureMode("e") # Implement sameAs by smushing graph = load(uri, flags=flags, openFormula=graph) bindings = {} for s in graph.statementsMatching(pred=reason.representedBy): val, _, key = s.spo() bindings[key] = val return graph.substitution(bindings) def n3Entails(f, g, skipIncludes=0, level=0): """Does f N3-entail g? First try indexed graph match algorithm, and if that fails, unification.""" v = verbosity() setVerbosity(debugLevelForInference) try: if f is g: fyi("Yahooo! ######### ") return 1 if not isinstance(f, Formula) or not isinstance(g, Formula): return 0 #if len(g) != 4: return True #I hope not.... f.resetRenames() try: if testIncludes(f,g): fyi(lambda : "Indexed query works looking in %s for %s" %(f,g), level) return 1 finally: f.resetRenames(False) return False return bool(g.n3EntailedBy(f)) fyi("Indexed query fails to find match, try unification", level) for s in g: context, pred, subj, obj = s.quad if skipIncludes and pred is context.store.includes: fyi("(log:includes found in antecedent, assumed good)", level) continue if f.statementsMatching(pred=pred, subj=subj, obj=obj) != []: fyi("Statement found in index: %s" % s, level) continue for t in f.statements: fyi("Trying unify statement %s" %(`t`), level=level+1, thresh=70) if (t[PRED].unify(pred) != [] and t[SUBJ].unify(subj) != [] and t[OBJ].unify(obj) != []): fyi("Statement unified: %s" % t, level) break else: setVerbosity(0) fyi("""n3Entailment failure.\nCan't find: %s=%s\nin formula: %s=%s\n""" % (g, g.n3String(), f, f.n3String()), level, thresh=1) fyi("""The triple which failed to match was %s""" % s, thresh=-1) return 0 return 1 finally: setVerbosity(v) class InvalidProof(Exception): def __init__(self, s, level=0): self._s = s if True or chatty > 0: progress(" "*(level*4), "Proof failed: ", s) def __str__(self): return self._s class PolicyViolation(InvalidProof): pass class LogicalFallacy(InvalidProof): pass class Checker(FormulaCache): def __init__(self, proof): """proof is the formula which contains the proof """ FormulaCache.__init__(self) self._checked = {} self._pf = proof # step numbers for report() method self._num = {} self._maxn = 0 def conjecture(self): """return the formula that is claimed to be proved and the main justification step. """ s = self._pf.the(pred=rdf.type, obj=reason.Proof) if not s: raise InvalidProof("no main :Proof step") f = self._pf.the(subj=s, pred=reason.gives) if not f: raise InvalidProof("main Proof step has no :gives") return f, s def result(self, r, policy, level=0): """Get the result of a proof step. r is the step to be checked; in the case of the root reason, proof.the(pred=rdf.type, obj=reason.Proof), as from `proofStep()` level is just the nesting level for diagnostic output Returns the formula proved raises InvalidProof (perhaps IOError, others) """ fyi("Starting valid on %s" % r, level=level, thresh=1000) f = self._checked.get(r, None) if f is not None: fyi("Cache hit: already checked reason for %s is %s."%(f, r), level, 80) return f global proofSteps proofSteps += 1 proof = self._pf f = proof.any(r, reason.gives) if f != None: assert isinstance(f, Formula), \ "%s gives: %s which should be Formula" % (`r`, f) fs = " proof of %s" % f else: fs = "" # fyi("Validating: Reason for %s is %s."%(f, r), level, 60) if r == None: if f is None: txt = 'None' else: txt = f.n3String() raise InvalidProof("No reason for "+`f` + " :\n\n"+ txt +"\n\n", level=level) classesOfReason = knownReasons.intersection(proof.each(subj=r, pred=rdf.type)) if len(classesOfReason) < 1: raise InvalidProof("%s does not have the type of any reason" % r) if len(classesOfReason) > 1: raise InvalidProof("%s has too many reasons, being %s" % (r, classesOfReason)) t = classesOfReason.pop() fyi("%s %s %s"%(t,r,fs), level=level, thresh=10) level = level + 1 if t is reason.Parsing: return self.checkParsing(r, f, policy, level) elif t is reason.Inference: g = checkGMP(r, f, self, policy, level) elif t is reason.Conjunction: g = checkConjunction(r, f, self, policy, level) elif t is reason.Fact: return checkBuiltin(r, f, self, policy, level) elif t is reason.Conclusion: return checkSupports(r, f, self, policy, level) elif t is reason.Extraction: return checkExtraction(r, f, self, policy, level) elif t is reason.CommandLine: raise RuntimeError("shouldn't get here: command line a not a proof step") elif t is reason.Premise: g = proof.the(r, reason.gives) if g is None: raise InvalidProof("No given input for %s" % r) fyi(lambda : "Premise is: %s" % g.n3String(), level, thresh=25) if not policy.assumes(g): raise PolicyViolation("I cannot assume %s" % g) # this is crying out for a unit test -DWC if g.occurringIn(g.existentials()) != g.existentials(): # Check integrity raise RuntimeError(g.debugString()) ## setVerbosity(1000) fyi("About to check if proved %s matches given %s" % (g, f), level=level, thresh=100) if f is not None and f.unify(g) == []: diag.chatty_flag=1000 f.unify(g) setVerbosity(0) raise LogicalFallacy("%s: Calculated formula: %s\ndoes not match given: %s" % (t, g.debugString(), f.debugString())) ## setVerbosity(0) self._checked[r] = g fyi(lambda : "\n\nRESULT of %s %s is:\n%s\n\n" %(t,r,g.n3String()), level, thresh=100) return g def checkParsing(self, r, f, policy, level): proof = self._pf res = proof.any(subj=r, pred=reason.source) if res == None: raise InvalidProof("No source given to parse", level=level) u = res.uriref() if not policy.documentOK(u): raise PolicyViolation("I cannot trust that source: %s" % u) v = verbosity() setVerbosity(debugLevelForParsing) try: g = self.get(u) except IOError: raise InvalidProof("Can't retreive/parse <%s> because:\n %s." %(u, sys.exc_info()[1].__str__()), 0) setVerbosity(v) if f != None: # Additional intermediate check not essential #@@ this code is untested, no? -DWC if f.unify(g) == []: raise InvalidProof("""Parsed data does not match that given.\n Parsed: <%s>\n\n Given: %s\n\n""" % (g,f) , level=level) self._checked[r] = g return g def report(self, out, f=None, step=None): try: return self._num[step] except KeyError: pass proof = self._pf if step is None: f, step = self.conjecture() if f is None: f = proof.the(subj=step, pred=reason.gives) t = knownReasons.intersection(proof.each(subj=step, pred=rdf.type)).pop() if f: # get rid of the prefix lines body = f.n3String().split("\n") while body[0].strip().startswith("@"): del body[0] body = " ".join(body) # put the lines back together body = " ".join(body.split()) # normalize whitespace else: body = "..." #hmm... if t is reason.Parsing: res = proof.any(subj=step, pred=reason.source) self._maxn += 1 num = self._maxn out.write("%d: %s\n [by parsing <%s>]\n\n" % (num, body, res)) elif t is reason.Inference: evidence = proof.the(subj=step, pred=reason.evidence) ej = [] for e in evidence: n = self.report(out, None, e) ej.append(n) rule = proof.the(subj=step, pred=reason.rule) rn = self.report(out, None, rule) bindings={} for b in proof.each(subj=step, pred=reason.binding): varq = proof.the(subj=b, pred=reason.variable) var = proof.any(subj=varq, pred=rei.nodeId) or \ proof.any(subj=varq, pred=rei.uri) # get VAR from "...foo.n3#VAR" varname = str(var).split("#")[1] termq = proof.the(subj=b, pred=reason.boundTo) if isinstance(termq, Literal) \ or isinstance(termq, Formula): bindings[varname] = `termq` else: term = proof.any(subj=termq, pred=rei.uri) if term: bindings[varname] = "<%s>" % term else: term = proof.any(subj=termq, pred=rei.nodeId) if term: bindings[varname] = "[...]" else: bindings[varname] = "?" fyi("what sort of term is this? %s, %s" % (termq, rn)) self._maxn += 1 num = self._maxn out.write("%d: %s\n [by rule from step %s applied to steps %s\n with bindings %s]\n\n" % (num, body, rn, ej, bindings)) elif t is reason.Conjunction: components = proof.each(subj=step, pred=reason.component) num = 1 js = [] for e in components: n = self.report(out, None, e) js.append(n) self._maxn += 1 num = self._maxn out.write("%d: %s\n [by conjoining steps %s]\n\n" % (num, body, js)) elif t is reason.Fact: pred, subj, obj = atomicFormulaTerms(f) self._maxn += 1 num = self._maxn out.write("%d: %s\n [by built-in Axiom %s]\n\n" % (num, body, pred)) elif t is reason.Conclusion: self._maxn += 1 num = self._maxn out.write("%d: %s\n [by conditional proof on @@]\n\n" % (num, body)) elif t is reason.Extraction: r2 = proof.the(step, reason.because) n = self.report(out, None, r2) self._maxn += 1 num = self._maxn out.write("%d: %s\n [by erasure from step %s]\n\n" % (num, body, n)) elif t is reason.Premise: self._maxn += 1 num = self._maxn out.write("@@num/name: %s [Premise]\n\n" % body) else: raise RuntimeError, t self._num[step] = num return num # # some of the check* routines below should probably be # methods on Checker too. # _TestCEstep = """ @prefix soc: . @prefix : . @prefix n3: . <#p1> a :Premise; :gives {soc:socrates a soc:Man . soc:socrates a soc:Mortal }. <#step1> a :Extraction; :because <#p1>; :gives { soc:socrates a soc:Man }. """ def checkExtraction(r, f, checker, policy, level=0): r"""check an Extraction step. >>> soc = Namespace("http://example/socrates#") >>> pf = _s2f(_TestCEstep, "http://example/socrates") >>> checkExtraction(soc.step1, ... pf.the(subj=soc.step1, pred=reason.gives), ... Checker(pf), AllPremises()) {soc:socrates type soc:Man} """ # """ emacs python mode needs help proof = checker._pf r2 = proof.the(r, reason.because) if r2 == None: raise InvalidProof("Extraction: no source formula given for %s." % (`r`), level) f2 = checker.result(r2, policy, level) if not isinstance(f2, Formula): raise InvalidProof("Extraction of %s gave something odd, %s" % (r2, f2), level) if not n3Entails(f2, f): raise LogicalFallacy("""Extraction %s=%s not included in formula %s=%s.""" # """ %(f, f.n3String(), f2, f2.n3String()), level=level) checker._checked[r] = f # hmm... why different between Extraction and GMP? return f def checkConjunction(r, f, checker, policy, level): proof = checker._pf components = proof.each(subj=r, pred=reason.component) fyi("Conjunction: %i components" % len(components), thresh=20) g = r.store.newFormula() for e in components: g1 = checker.result(e, policy, level) before = len(g) g.loadFormulaWithSubstitution(g1) fyi(lambda : "Conjunction: adding %i statements, was %i, total %i\nAdded: %s" % (len(g1), before, len(g), g1.n3String()), level, thresh=80) #@@ hmm... don't we check f against g? -DWC return g.close() _TestGMPStep = """ @prefix soc: . @prefix : . @prefix n3: . <#p1> a :Premise; :gives {soc:socrates a soc:Man . }. <#p2> a :Premise; :gives { @forAll soc:who . { soc:who a soc:Man . } => {soc:who a soc:Mortal } }. <#step1> a :Inference; :evidence ( <#p1> ); :rule <#p2>; :binding [ :variable [ n3:uri "http://example/socrates#who" ]; :boundTo [ n3:uri "http://example/socrates#socrates" ]; ]. """ # """ emacs python mode needs help def checkGMP(r, f, checker, policy, level=0): r"""check a generalized modus ponens step. >>> soc = Namespace("http://example/socrates#") >>> pf = _s2f(_TestGMPStep, "http://example/socrates") >>> f = checkGMP(soc.step1, None, Checker(pf), AllPremises()) >>> f.n3String().strip() u'@prefix : .\n \n :socrates a :Mortal .' """ # """ emacs python mode needs help proof = checker._pf evidence = proof.the(subj=r, pred=reason.evidence) existentials = Set() bindings = {} for b in proof.each(subj=r, pred=reason.binding): var_rei = proof.the(subj=b, pred=reason.variable) var = getSymbol(proof, var_rei) val_rei = proof.the(subj=b, pred=reason.boundTo) # @@@ Check that they really are variables in the rule! val = getTerm(proof, val_rei) bindings[var] = val if proof.contains(subj=val_rei, pred=proof.store.type, obj=reason.Existential): ## if val_rei in proof.existentials(): existentials.add(val) rule = proof.the(subj=r, pred=reason.rule) proofFormula = checker.result(rule, policy, level) for s in proofFormula.statements: #@@@@@@ why look here? if s[PRED] is log.implies: ruleStatement = s break else: raise InvalidProof("Rule has %s instead of log:implies as predicate.", level) for v in proofFormula.variables(): var = proof.newSymbol(v.uriref()) if var in bindings: val = bindings[var] del bindings[var] bindings[v] = val # Check the evidence is itself proved evidenceFormula = proof.newFormula() for e in evidence: f2 = checker.result(e, policy, level) f2.store.copyFormula(f2, evidenceFormula) evidenceFormula = evidenceFormula.close() # Check: Every antecedent statement must be included as evidence antecedent = proof.newFormula() for k in bindings.values(): if k in existentials: #k in evidenceFormula.existentials() or antecedent.declareExistential(k) antecedent.loadFormulaWithSubstitution(ruleStatement[SUBJ], bindings) antecedent = antecedent.close() #antecedent = ruleStatement[SUBJ].substitution(bindings) fyi(lambda : "Bindings: %s\nAntecedent after subst: %s" % ( bindings, antecedent.debugString()), level, 195) fyi("about to test if n3Entails(%s, %s)" % (evidenceFormula, antecedent), level, 1) fyi(lambda : "about to test if n3Entails(%s, %s)" % (evidenceFormula.n3String(), antecedent.n3String()), level, 80) if not n3Entails(evidenceFormula, antecedent, skipIncludes=1, level=level+1): raise LogicalFallacy("Can't find %s in evidence for\n" "Antecedent of rule: %s\n" "Evidence:%s\n" "Bindings:%s" %((s[SUBJ], s[PRED], s[OBJ]), antecedent.n3String(), evidenceFormula.n3String(), bindings), level=level) fyi("Rule %s conditions met" % ruleStatement, level=level) retVal = proof.newFormula() for k in ruleStatement[OBJ].occurringIn(Set(bindings)): v = bindings[k] if v in existentials: #k in evidenceFormula.existentials() or retVal.declareExistential(v) retVal.loadFormulaWithSubstitution(ruleStatement[OBJ], bindings) retVal = retVal.close() return retVal ### return ruleStatement[OBJ].substitution(bindings) def getSymbol(proof, x): "De-reify a symbol: get the informatuion identifying it from the proof" y = proof.the(subj=x, pred=rei.uri) if y != None: return proof.newSymbol(y.string) y = proof.the(subj=x, pred=rei.nodeId) if y != None: fyi("Warning: variable is identified by nodeId: <%s>" % y.string, level=0, thresh=20) return proof.newSymbol(y.string) raise RuntimeError("Can't de-reify %s" % x) def getTerm(proof, x): "De-reify a term: get the informatuion about it from the proof" if isinstance(x, (Literal, CompoundTerm)): return x val = proof.the(subj=x, pred=rei.value) if val != None: return proof.newLiteral(val.string, val_value.datatype, val.lang) return getSymbol(proof, x) _TestBuiltinStep = """ @keywords is, of, a. @prefix math: . @prefix list: . @prefix str: . @prefix : . <#step1> a :Fact, :Proof; :gives { %s }. """ def checkBuiltin(r, f, checker, policy, level=0): """Check a built-in step. @@hmm... integrate with Policy more? >>> soc = Namespace("http://example/socrates#") >>> pf = _s2f(_TestBuiltinStep % '"a" list:in ("b" "a" "c")', ... "http://example/socrates") >>> f = checkBuiltin(soc.step1, ... pf.the(subj=soc.step1, pred=reason.gives), ... Checker(pf), AllPremises()) >>> len(f) 1 >>> pf = _s2f(_TestBuiltinStep % '"abc" str:startsWith "a"', ... "http://example/socrates") >>> f = checkBuiltin(soc.step1, ... pf.the(subj=soc.step1, pred=reason.gives), ... Checker(pf), AllPremises()) >>> len(f) 1 >>> pf = _s2f(_TestBuiltinStep % '"abc" str:startsWith "b"', ... "http://example/socrates") >>> f = checkBuiltin(soc.step1, ... pf.the(subj=soc.step1, pred=reason.gives), ... Checker(pf), AllPremises()) Traceback (most recent call last): ... LogicalFallacy: Built-in fact does not give correct results: predicate: abc subject: str:startsWith object: b result: None """ # """ help emacs proof = checker._pf pred, subj, obj = atomicFormulaTerms(f) fyi("Built-in: testing fact {%s %s %s}" % (subj, pred, obj), level=level) if pred is log.includes: #log:includes is very special. Huh? Why? -DWC if n3Entails(subj, obj): checker._checked[r] = f return f else: raise LogicalFallacy("Include test failed.\n" "It seems {%s} log:includes {%s} is false""" % (subj.n3String(), obj.n3String())) if not isinstance(pred, BuiltIn): raise PolicyViolation("Claimed as fact, but predicate is %s not builtin" % pred, level) if pred.eval(subj, obj, None, None, None, None): checker._checked[r] = f return f if isinstance(pred, Function) and isinstance(obj, Formula): result = pred.evalObj(subj, None, None, None, None) fyi("Re-checking builtin %s result %s against quoted %s" %(pred, result, obj)) if n3Entails(obj, result): fyi("Ok for n3Entails(obj, result), checking reverse.") if n3Entails(result, obj): fyi("Re-checked OK builtin %s result %s against quoted %s" %(pred, result, obj)) checker._checked[r] = f return f else: fyi("Failed reverse n3Entails!\n\n\n") else: global debugLevelForInference # raise StopIteration fyi("Failed forward n3Entails!\n\n\n") debugLevelForInference = 1000 n3Entails(obj, result) debugLevelForInference = 0 else: result = None s, o, r = subj, obj, result if isinstance(subj, Formula): s = subj.n3String() if isinstance(obj, Formula): o = obj.n3String() if isinstance(result, Formula): r = obj.n3String() ## if n3Entails(result, obj) and not n3Entails(obj, result): a = 0 ## elif n3Entails(obj, result) and not n3Entails(result, obj): a = 1 ## else: a = 2 raise LogicalFallacy("Built-in fact does not give correct results: " "predicate: %s " "subject: %s " "object: %s " "result: %s" % (s, pred, o, r), level) def atomicFormulaTerms(f): """Check that a formula is atomic and return the p, s, o terms. >>> atomicFormulaTerms(_s2f("<#sky> <#color> <#blue>.", ... "http://example/stuff")) (color, sky, blue) """ # """ help emacs if len(f) <> 1: raise ValueError("expected atomic formula; got: %s." % f.statements) #warn("DanC wants to get rid of the StoredStatement interface.") c, p, s, o = f.statements[0].quad return p, s, o def checkSupports(r, f, checker, policy, level): proof = checker._pf pred, subj, obj = atomicFormulaTerms(f) fyi("Built-in: testing log:supports {%s %s %s}" % (subj, pred, obj), level=level) if pred is not log.supports: raise InvalidProof('Supports step is not a log:supports') #log:includes is very special r2 = proof.the(r, reason.because) if r2 is None: raise InvalidProof("Extraction: no source formula given for %s." % (`r`), level) fyi("Starting nested conclusion", level=level) f2 = checker.result(r2, Assumption(subj), level) if not isinstance(f2, Formula): raise InvalidProof("Extraction of %s gave something odd, %s" % (r2, f2), level) fyi("... ended nested conclusion. success!", level=level) if not n3Entails(f2, obj): raise LogicalFallacy("""Extraction %s not included in formula %s.""" %(obj.debugString(), f2.debugString()), level=level) checker._checked[r] = f return f class Assumption(Policy): def __init__(self, premise): self.premise = premise def documentOK(self, u): return False def assumes(self, f): return n3Entails(self.premise, f) # Main program def usage(): sys.stderr.write(__doc__) class ParsingOK(Policy): """When run from the command-line, the policy is that all Parsing's are OK. Hmm... shouldn't it be only those that are mentioned in the CommandLine step? """ def documentOK(self, u): return True def assumes(self, f): return False def main(argv): global chatty global debugLevelForInference global debugLevelForParsing global nameBlankNodes setVerbosity(0) policy=ParsingOK() try: opts, args = getopt.getopt(argv[1:], "hv:c:p:B:a", [ "help", "verbose=", "chatty=", "parsing=", "nameBlankNodes", "allPremises", "profile", "report"]) except getopt.GetoptError: sys.stderr.write("check.py: Command line syntax error.\n\n") usage() sys.exit(2) output = None report = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() if o in ("-v", "--verbose"): chatty = int(a) if o in ("-p", "--verboseParsing"): debugLevelForParsing = int(a) if o in ("-c", "--chatty"): debugLevelForInference = int(a) if o in ("-B", "--nameBlankNodes"): nameBlankNodes = 1 if o in ("-a", "--allPremises"): policy = AllPremises() if o in ("--profile"): pass if o in ("--report"): report = True if nameBlankNodes: flags="B" else: flags="" if args: fyi("Reading proof from "+args[0]) proof = topLevelLoad(args[0], flags=flags) else: fyi("Reading proof from standard input.", thresh=5) proof = topLevelLoad(flags=flags) # setVerbosity(60) fyi("Length of proof formula: "+`len(proof)`, thresh=5) try: c = Checker(proof) if report: c.report(sys.stdout) proved = c.result(c.conjecture()[1], policy=policy) fyi("Proof looks OK. %i Steps" % proofSteps, thresh=5) setVerbosity(0) print proved.n3String().encode('utf-8') except InvalidProof, e: progress("Proof invalid:", e) sys.exit(-1) ################################ # test harness and diagnostics def fyi(str, level=0, thresh=50): if chatty >= thresh: if isinstance(str, (lambda : True).__class__): str = str() progress(" "*(level*4), str) return None def _test(): import doctest chatty = 20 #@@ doctest.testmod() def _s2f(s, base): """make a formula from a string. Cribbed from llyn.BI_parsedAsN3 should be part of the myStore API, no? yes. TODO >>> _s2f("<#sky> <#color> <#blue>.", "http://example/socrates") {sky color blue} ^ that test output depends on the way formulas print themselves. """ # """ emacs python mode needs help import notation3 graph = formula() graph.setClosureMode("e") # Implement sameAs by smushing p = notation3.SinkParser(graph.store, openFormula=graph, baseURI=base, thisDoc="data:@@some-formula-string") p.startDoc() p.feed(s) f = p.endDoc() f.close() bindings = {} for s in f.statementsMatching(pred=reason.representedBy): val, _, key = s.spo() bindings[key] = val return f.substitution(bindings) ######## def _profile(argv): from tempfile import mktemp logfile = mktemp() import hotshot, hotshot.stats profiler = hotshot.Profile(logfile) saveout = sys.stdout fsock = open('/dev/null', 'w') sys.stdout = fsock profiler.runcall(main, argv) sys.stdout = saveout fsock.close() profiler.close() stats = hotshot.stats.load(logfile) stats.strip_dirs() stats.sort_stats('cumulative', 'time', 'calls') stats.print_stats(50) if __name__ == "__main__": # we're running as a script, not imported... import sys, getopt if '--test' in sys.argv: _test() elif '--profile' in sys.argv: _profile(sys.argv) else: main(sys.argv) #ends cwm-1.2.1/swap/cwm_trigo.py0000644015216600007660000001046210640075637014746 0ustar syosisyosi"""Trigonometrical Built-Ins for CWM Allows CWM to do do trigonometrical http://www.python.org/doc/2.3/lib/module-math.html This module is inspired by the math module. See http://www.w3.org/2000/10/swap/cwm_math.py cf. http://www.w3.org/2000/10/swap/cwm.py See http://ilrt.org/discovery/chatlogs/rdfig/2003-09-23.html#T22-37-54 http://rdfig.xmlhack.com/2003/09/23/2003-09-23.html#1064356689.846120 """ __author__ = 'Karl Dubost' __cvsid__ = '$Id: cwm_trigo.py,v 1.13 2007/06/26 02:36:15 syosi Exp $' __version__ = '$Revision: 1.13 $' __all__ = ["evaluateObject"] from math import sin, acos, asin, atan, atan2, cos, cosh, sinh, tan, tanh from term import LightBuiltIn, Function, ReverseFunction import types from diag import progress from cwm_math import * MATH_NS_URI = 'http://www.w3.org/2000/10/swap/math#' # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Trigonometrical Features # # # Light Built-in classes - these are all reverse functions # # Note that asin the arc sine i s just the reverse function of sin, # handled by sin being a reverse function as well as a function # cosine, hyperbolic or not # sine, hyperbolic or not # tangent, arc tangent, arc tangent (y/x) # class BI_atan2(LightBuiltIn, Function): def evaluateObject(self, subj_py): """atan2(y, x) Return the arc tangent (measured in radians) of y/x. Unlike atan(y/x), the signs of both x and y are considered. -- Karl""" if len(numeric(subj_py)) == 2: return atan2(numeric(subj_py[0]),numeric(subj_py[1])) else: return None class BI_cos(LightBuiltIn, Function, ReverseFunction): def evaluateObject(self, subj_py): """cos(x) Return the cosine of x (measured in radians).""" return cos(numeric(subj_py)) def evaluateSubject(self, x): try: return acos(numeric(x)) except ValueError: return None class BI_cosh(LightBuiltIn, Function): def evaluateObject(self, subj_py): """cosh(x) Return the hyperbolic cosine of x.""" return cosh(numeric(subj_py)) # def evaluateSubject(self, x): # return acosh(numeric(x)) class BI_degrees(LightBuiltIn, Function, ReverseFunction): """Angles are in radians. This property is the equivalent in degrees. It can be calculated either way.""" def evaluateObject(self, subj_py): """Angles are in radians. This property is the equivalent in degrees.""" return numeric(subj_py) * 180 / 3.14159265358979323846 def evaluateSubject(self, obj_py): """radians(x) -> converts angle x from degrees to radian""" return numeric(obj_py) * 3.14159265358979323846 / 180 class BI_sin(LightBuiltIn, Function, ReverseFunction): """sin(x) x.math:sin is the sine of x (x measured in radians).""" def evaluateObject(self, subj_py): return sin(numeric(subj_py)) def evaluateSubject(self, x): try: return asin(numeric(x)) except: return None class BI_sinh(LightBuiltIn, Function): def evaluateObject(self, subj_py): """sinh(x) Return the hyperbolic sine of x.""" return sinh(numeric(subj_py)) # def evaluateSubject(self, x): # return asinh(numeric(x)) class BI_tan(LightBuiltIn, Function, ReverseFunction): def evaluateObject(self, subj_py): """tan(x) Return the tangent of x (measured in radians).""" return tan(numeric(subj_py)) def evaluateSubject(self, x): """tan(x) Return the tangent of x (measured in radians).""" return atan(numeric(x)) class BI_tanh(LightBuiltIn, Function): """tanh(x) Return the hyperbolic tangent of x.""" def evaluateObject(self, subj_py): return tanh(numeric(subj_py)) # def evaluateSubject(self, x): # return atanh(numeric(x)) # Register the string built-ins with the store def register(store): str = store.symbol(MATH_NS_URI[:-1]) str.internFrag('cos', BI_cos) str.internFrag('cosh', BI_cosh) str.internFrag('degrees', BI_degrees) str.internFrag('sin', BI_sin) str.internFrag('sinh', BI_sinh) str.internFrag('tan', BI_tan) str.internFrag('tanh', BI_tanh) if __name__=="__main__": print __doc__.strip() cwm-1.2.1/grammar/0000755015216600007660000000000010731073447013051 5ustar syosisyosicwm-1.2.1/grammar/bnf2html.n30000644015216600007660000000540007747216442015035 0ustar syosisyosi# Convert BNF in RDF to HTML # @prefix rdf: . @prefix rdfs: . @prefix bnf: . @prefix rul: . @prefix : . @prefix h: . @prefix log: . @prefix string: . @keywords a, is, of. ("0" 0) log:outputString """ BNF

BNF

Productions are in normal type, linked to their definitions.
Regular expressions are in italics
Literal characters in quoted in bold
void means an empty production.

""". ("~~" 9) log:outputString """
""". # Find all possible sequences for each term # { ?x bnf:mustBeOneSequence ?y} => { ?x optionTail ?y; a Production}. { ?x bnf:matches [] } => { ?x a Production}. {?x optionTail [rdf:first ?y; rdf:rest ?z]} => { ?x bnf:canBeSequence ?y; optionTail ?z. ?y a Sequence}. # Label every trailing subseqeunce { ?seq a Sequence } => { ?seq a SequenceTail }. { ?seq a SequenceTail; rdf:rest ?s2 } => { ?s2 a SequenceTail }. # Literal are referenced but no labels for LHS @@ escaped { ?seq a SequenceTail; rdf:first ?x. ?x log:rawType log:Literal. ( "\"" ?x "\"" ) string:concatenation ?ref. } => { ?x reference ?ref }. ############ { ?x a Production. ?x log:uri ?u. (?u ".*#(.*)") string:scrape ?lab. } => { ?x bnf:label ?lab. }. { ?x a Production; bnf:label ?lab. ( "
" ?lab "" ) string:concatenation ?ref. ( "
" ?lab "
\n" ) string:concatenation ?start. } => { ?x reference ?ref. (?lab 0) log:outputString ?start. (?lab 9) log:outputString "\t
\n". }. ############ () seqlabel "void". bnf:eof reference "EOF". # Start it, skipping use of the seqlabel of (): { ?seq a SequenceTail; rdf:first ?x; rdf:rest (). ?x reference ?lab1. } => { ?seq seqlabel ?lab1 }. # This one takes forever: { ?seq a SequenceTail; rdf:first ?x; rdf:rest ?tail. ?x reference ?lab1. ?tail seqlabel ?lab2; rdf:rest []. # Non-null (?lab1 " " ?lab2) string:concatenation ?str } => { ?seq seqlabel ?str }. {?x bnf:label ?lab; bnf:canBeSequence [seqlabel ?seqlab]. ("\t\t

" ?seqlab "

\n" ) string:concatenation ?para } => {(?lab 5) log:outputString ?para}. { [] a Production; bnf:label ?lab; bnf:matches ?regexp. ( "\t

" ?regexp "

\n") string:concatenation ?regpara. }=>{ (?lab 6) log:outputString ?regpara. }. #end cwm-1.2.1/grammar/n3-rdf.n30000644015216600007660000001117310713412507014401 0ustar syosisyosi# Notation3 subset which is RDF without extension # BNF without tokenization # @prefix rdf: . @prefix rdfs: . @prefix bnf: . @prefix rul: . @prefix : . @prefix d3: . @prefix n3: . @prefix list: . @prefix string: . @keywords a, is, of. # Issues: # - string token regexp not right # - tokenizing rules in general # - @keywords affects tokenizing # - Use of dot for ! # - datatypes and/or* languages in literals (*choice - follow RDF) # tokenizing: # Absorb anything until end of regexp, then stil white space # period followed IMMEDIATELY by an opener or name char is taken as "!". # Except after a "." used instead of in those circumstances, # ws may be inserted between tokens. # WS MUST be inserted between tokens where ambiguity would arise. # (possible ending characters of one and beginning characters overlap) # <> bnf:syntaxFor [ bnf:internetMediaType ]. # __________________________________________________________________ # # The N3 Full Grammar n3-rdfDocument bnf:mustBeOneSequence( ( [ bnf:zeroOrMore declaration ] [ bnf:zeroOrMore existential ] statements_optional bnf:eof ) ). statements_optional bnf:mustBeOneSequence (() ( statement "." statements_optional )e ). statementlist bnf:mustBeOneSequence ( ( ) ( statement statementtail ) ). statementtail bnf:mustBeOneSequence ( ( ) ( "." statementlist ) ). existential bnf:mustBeOneSequence( ( "@forSome" [ bnf:commaSeparatedPeriodTerminatedListOf symbol ] )). symbol bnf:mustBeOneSequence ( (explicituri) (qname) ). declaration bnf:mustBeOneSequence( ( "@base" explicituri "." ) ( "@prefix" qname explicituri "." ) ( "@keywords" [ bnf:commaSeparatedPeriodTerminatedListOf barename ] ) ). statement bnf:mustBeOneSequence(( subject propertylist )). propertylist bnf:mustBeOneSequence ( ( ) ( verb object objecttail propertylisttail ) ). propertylisttail bnf:mustBeOneSequence ( ( ) ( ";" propertylist ) ). objecttail bnf:mustBeOneSequence ( ( ) ( "," object objecttail ) ). verb bnf:mustBeOneSequence ( ( prop ) ( "@has" prop ) # ( "@is" prop "@of" ) # would be complicated to allow - would need subjectlist. ( "@a" ) ( "=" ) ). prop bnf:mustBeOneSequence ((node)). subject bnf:mustBeOneSequence( ( node_subject "!" pathtail ) ( string "^" verb pathtail ) ( numericliteral "^" verb pathtail ) ). object bnf:mustBeOneSequence( ( node_object pathtail ) # @@@@@@@@ ). pathtail bnf:mustBeOneSequence( ( ) ( "!" verb pathtail ) ( "^" verb pathtail ) ). node_subject bnf:mustBeOneSequence ( ( symbol ) ( "[" propertylist "]" ) ( "(" objectlist ")" ) ). node_object bnf:mustBeOneSequence ( ( symbol ) ( numericliteral ) ( string ) ( "[" propertylist "]" ) ( "(" itemlist ")" ) ). objectlist bnf:mustBeOneSequence (() (object objectlist)). #______________________________________________________________________ # # TOKENS alphanumeric bnf:matches "[a-zA-Z][a-zA-Z0-9_]*"; bnf:canStartWith "a". numericliteral bnf:matches """[-+]?[0-9]+(\\.[0-9]+)?(e[-+]?[0-9]+)?"""; bnf:canStartWith "0", "-", "+". explicituri bnf:matches "<[^>].*>"; bnf:canStartWith "<". qname bnf:matches "(([a-zA-Z_][a-zA-Z0-9_]*)?:)?([a-zA-Z_][a-zA-Z0-9_]*)?"; bnf:canStartWith "a", "_". # @@ etc barename bnf:matches "[a-zA-Z_][a-zA-Z0-9_]*"; # subset of qname bnf:canStartWith "a", "_". # @@ etc langcode bnf:matches "[a-zA-Z0-9]+(-[a-zA-Z0-9]+)?"; bnf:canStartWith "a". string bnf:matches "(\"\"\"[^\"\\\\]*(?:(?:\\\\.|\"(?!\"\"))[^\"\\\\]*)*\"\"\")|(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")"; bnf:canStartWith "\"". #____________________________________________________ # Axioms reducing the shortcut BNF terms to bnf:musBeOneSequence. { ?x bnf:zeroOrMore ?y } => {?x bnf:mustBeOneSequence ( () (?y ?x) ) }. { ?x bnf:commaSeparatedPeriodTerminatedListOf ?y } => { ?x bnf:mustBeOneSequence ( ( "." ) ( "," ?y ?x ) ) }. # labelling of things which do not have explicit URIs: { ?x bnf:zeroOrMore [ bnf:label ?y]. ( ?y "_s" ) string:concatenation ?str } => { ?x bnf:label ?str }. { ?x bnf:commaSeparatedPeriodTerminatedListOf [ bnf:label ?y]. ( ?y "_csl" ) string:concatenation ?str } => { ?x bnf:label ?str }. #ends cwm-1.2.1/grammar/sparql.n30000644015216600007660000010134510274702204014611 0ustar syosisyosi#SPARQL in Notation3 # Context Free Grammar without tokenization # @prefix rdf: . @prefix rdfs: . @prefix cfg: . @prefix rul: . @prefix : . @prefix n3: . @prefix list: . @prefix string: . @keywords a, is, of. IT_BASE cfg:matches "BASE"; a cfg:Token . IT_PREFIX cfg:matches "PREFIX"; a cfg:Token . IT_SELECT cfg:matches "SELECT"; a cfg:Token . IT_DISTINCT cfg:matches "DISTINCT"; a cfg:Token . GT_TIMES cfg:matches "\\*"; a cfg:Token . IT_CONSTRUCT cfg:matches "CONSTRUCT"; a cfg:Token . IT_DESCRIBE cfg:matches "DESCRIBE"; a cfg:Token . IT_ASK cfg:matches "ASK"; a cfg:Token . IT_FROM cfg:matches "FROM"; a cfg:Token . IT_NAMED cfg:matches "NAMED"; a cfg:Token . IT_WHERE cfg:matches "WHERE"; a cfg:Token . IT_ORDER cfg:matches "ORDER"; a cfg:Token . IT_BY cfg:matches "BY"; a cfg:Token . IT_ASC cfg:matches "ASC"; a cfg:Token . IT_DESC cfg:matches "DESC"; a cfg:Token . IT_LIMIT cfg:matches "LIMIT"; a cfg:Token . IT_OFFSET cfg:matches "OFFSET"; a cfg:Token . IT_OPTIONAL cfg:matches "OPTIONAL"; a cfg:Token . IT_GRAPH cfg:matches "GRAPH"; a cfg:Token . IT_UNION cfg:matches "UNION"; a cfg:Token . IT_FILTER cfg:matches "FILTER"; a cfg:Token . GT_LBRACKET cfg:matches "\\["; a cfg:Token . GT_LPAREN cfg:matches "\\("; a cfg:Token . GT_RBRACKET cfg:matches "\\]"; a cfg:Token . GT_RPAREN cfg:matches "\\)"; a cfg:Token . GT_SEMI cfg:matches ";"; a cfg:Token . GT_COMMA cfg:matches ","; a cfg:Token . IT_a cfg:matches "a"; a cfg:Token . GT_OR cfg:matches "\\|\\|"; a cfg:Token . GT_AND cfg:matches "&&"; a cfg:Token . GT_EQUAL cfg:matches "="; a cfg:Token . GT_NEQUAL cfg:matches "!="; a cfg:Token . GT_LT cfg:matches "<"; a cfg:Token . GT_GT cfg:matches ">"; a cfg:Token . GT_LE cfg:matches "<="; a cfg:Token . GT_GE cfg:matches ">="; a cfg:Token . GT_PLUS cfg:matches "\\+"; a cfg:Token . GT_MINUS cfg:matches "-"; a cfg:Token . GT_DIVIDE cfg:matches "/"; a cfg:Token . GT_NOT cfg:matches "!"; a cfg:Token . IT_STR cfg:matches "STR"; a cfg:Token . IT_LANG cfg:matches "LANG"; a cfg:Token . IT_DATATYPE cfg:matches "DATATYPE"; a cfg:Token . IT_BOUND cfg:matches "BOUND"; a cfg:Token . IT_isURI cfg:matches "isURI"; a cfg:Token . IT_isBLANK cfg:matches "isBLANK"; a cfg:Token . IT_isLITERAL cfg:matches "isLITERAL"; a cfg:Token . IT_REGEX cfg:matches "REGEX"; a cfg:Token . GT_DTYPE cfg:matches "\\^\\^"; a cfg:Token . IT_true cfg:matches "true"; a cfg:Token . IT_false cfg:matches "false"; a cfg:Token . QuotedIRIref cfg:matches "<[^> ]*>"; a cfg:Token . LANGTAG cfg:matches "@[a-zA-Z]+(?:-[a-zA-Z0-9]+)*"; a cfg:Token . INTEGER cfg:matches "[0-9]+"; a cfg:Token . DECIMAL cfg:matches "(?:[0-9]+\\.[0-9]*)|(?:\\.[0-9]+)"; a cfg:Token . EXPONENT cfg:matches "[eE][\\+-]?[0-9]+"; a cfg:Token . FLOATING_POINT cfg:matches "(?:[0-9]+\\.[0-9]*(?:[eE][\\+-]?[0-9]+)?)|(?:(?:\\.[0-9]+(?:[eE][\\+-]?[0-9]+)?)|(?:[0-9]+(?:[eE][\\+-]?[0-9]+)))"; a cfg:Token . STRING_LITERAL1 cfg:matches "'(?:(?:[^'\\\\\\n\\r])|(?:(?:\\\\[^\\r\\n])))*'"; a cfg:Token . STRING_LITERAL2 cfg:matches "\"(?:(?:[^\"\\\\\\n\\r])|(?:(?:\\\\[^\\r\\n])))*\""; a cfg:Token . STRING_LITERAL_LONG1 cfg:matches "'''(?:(?:[^'\\\\])|(?:(?:(?:\\\\[^\\r\\n]))|(?:(?:(?:'[^']))|(?:(?:''[^'])))))*'''"; a cfg:Token . STRING_LITERAL_LONG2 cfg:matches "\"\"\"(?:(?:[^\"\\\\])|(?:(?:(?:\\\\[^\\r\\n]))|(?:(?:(?:\"[^\"]))|(?:(?:\"\"[^\"])))))*\"\"\""; a cfg:Token . NCCHAR1 cfg:matches "(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF])))))))))))))"; a cfg:Token . NCCHAR cfg:matches "(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF])))))))))))))))|(?:(?:_)|(?:(?:-)|(?:(?:\\.)|(?:(?:[0-9])|(?:(?:\u00B7)|(?:(?:[\u0300-\u036F])|(?:[\u203F-\u2040])))))))"; a cfg:Token . NCNAME_PREFIX cfg:matches "(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF]))))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF])))))))))))))))|(?:(?:_)|(?:(?:-)|(?:(?:\\.)|(?:(?:[0-9])|(?:(?:\u00B7)|(?:(?:[\u0300-\u036F])|(?:[\u203F-\u2040]))))))))*"; a cfg:Token . ###QNAME_NS cfg:matches "(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF]))))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF])))))))))))))))|(?:(?:_)|(?:(?:-)|(?:(?:\\.)|(?:(?:[0-9])|(?:(?:\u00B7)|(?:(?:[\u0300-\u036F])|(?:[\u203F-\u2040]))))))))*)?:"; QNAME_NS cfg:matches "(?:[A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF][_\\-\\.0-9A-Za-z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0300-\u036F\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF]*)?:"; a cfg:Token . NCNAME cfg:matches "(?:(?:_)|(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF]))))))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF])))))))))))))))|(?:(?:_)|(?:(?:-)|(?:(?:\\.)|(?:(?:[0-9])|(?:(?:\u00B7)|(?:(?:[\u0300-\u036F])|(?:[\u203F-\u2040]))))))))*"; a cfg:Token . ###BNODE_LABEL cfg:matches "_:(?:(?:(?:_)|(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF]))))))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF])))))))))))))))|(?:(?:_)|(?:(?:-)|(?:(?:\\.)|(?:(?:[0-9])|(?:(?:\u00B7)|(?:(?:[\u0300-\u036F])|(?:[\u203F-\u2040]))))))))*)"; BNODE_LABEL cfg:matches "_:[_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF][_\\-\\.0-9A-Za-z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0300-\u036F\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF]*"; a cfg:Token . ###QNAME cfg:matches "(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF]))))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF])))))))))))))))|(?:(?:_)|(?:(?:-)|(?:(?:\\.)|(?:(?:[0-9])|(?:(?:\u00B7)|(?:(?:[\u0300-\u036F])|(?:[\u203F-\u2040]))))))))*)?:(?:(?:(?:_)|(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF]))))))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF])))))))))))))))|(?:(?:_)|(?:(?:-)|(?:(?:\\.)|(?:(?:[0-9])|(?:(?:\u00B7)|(?:(?:[\u0300-\u036F])|(?:[\u203F-\u2040]))))))))*)?"; QNAME cfg:matches "(?:[A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF][_\\-\\.0-9A-Za-z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0300-\u036F\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF]*)?:(?:[_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF][_\\-\\.0-9A-Za-z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0300-\u036F\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF]*)?"; a cfg:Token . VARNAME cfg:matches "(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF]))))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF])))))))))))))))|(?:(?:_)|(?:(?:[0-9])|(?:(?:\u00B7)|(?:(?:[\u0300-\u036F])|(?:[\u203F-\u2040]))))))*"; ### VARNAME cfg:matches "[A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCFuFDF0-\uFFFD\U00010000-\U000EFFFF][_0-9A-Za-z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0300-\u036F\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCFuFDF0-\uFFFD\U00010000-\U000EFFFF]*"; a cfg:Token . ###VAR2 cfg:matches "\\$(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF]))))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF])))))))))))))))|(?:(?:_)|(?:(?:[0-9])|(?:(?:\u00B7)|(?:(?:[\u0300-\u036F])|(?:[\u203F-\u2040]))))))*)"; VAR2 cfg:matches "\\$[A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF][_0-9A-Za-z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0300-\u036F\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF]*"; a cfg:Token . ###VAR1 cfg:matches "\\?(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF]))))))))))))))(?:(?:(?:(?:[A-Z])|(?:(?:[a-z])|(?:(?:[\u00C0-\u00D6])|(?:(?:[\u00D8-\u00F6])|(?:(?:[\u00F8-\u02FF])|(?:(?:[\u0370-\u037D])|(?:(?:[\u037F-\u1FFF])|(?:(?:[\u200C-\u200D])|(?:(?:[\u2070-\u218F])|(?:(?:[\u2C00-\u2FEF])|(?:(?:[\u3001-\uD7FF])|(?:(?:[\uF900-\uFDCF])|(?:(?:[\uFDF0-\uFFFD])|(?:[\U00010000-\U000EFFFF])))))))))))))))|(?:(?:_)|(?:(?:[0-9])|(?:(?:\u00B7)|(?:(?:[\u0300-\u036F])|(?:[\u203F-\u2040]))))))*)"; VAR1 cfg:matches "\\?[A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF][_0-9A-Za-z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0300-\u036F\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF]*"; a cfg:Token . SPACE cfg:matches "(?:\\t)|(?:(?:\\n)|(?:(?:\\r)|(?:(?: )|(?:(?:\u00A0)|(?:(?:[\u2000-\u200B])|(?:(?:\u202F)|(?:(?:\u205F)|(?:\u3000))))))))"; a cfg:Token . cfg:PASSED_TOKENS cfg:matches "(?:(?:(?:\\t)|(?:(?:\\n)|(?:(?:\\r)|(?:(?:[ ])|(?:(?:\u00A0)|(?:(?:[\u2000-\u200B])|(?:(?:\u202F)|(?:(?:\u205F)|(?:\u3000)))))))))+)|(?:#[^\\n]*\\n)"; a cfg:Token . Dot cfg:matches "\\."; a cfg:Token . OpenCurly cfg:matches "\\{"; a cfg:Token . CloseCurly cfg:matches "\\}"; a cfg:Token . Query cfg:tokens ( IT_BASE IT_PREFIX IT_SELECT IT_DISTINCT GT_TIMES IT_CONSTRUCT IT_DESCRIBE IT_ASK IT_FROM IT_NAMED IT_WHERE IT_ORDER IT_BY IT_ASC IT_DESC IT_LIMIT IT_OFFSET IT_OPTIONAL IT_GRAPH IT_UNION IT_FILTER GT_LBRACKET GT_LPAREN GT_RBRACKET GT_RPAREN GT_SEMI GT_COMMA IT_a GT_OR GT_AND GT_EQUAL GT_NEQUAL GT_LT GT_GT GT_LE GT_GE GT_PLUS GT_MINUS GT_DIVIDE GT_NOT IT_STR IT_LANG IT_DATATYPE IT_BOUND IT_isURI IT_isBLANK IT_isLITERAL IT_REGEX GT_DTYPE IT_true IT_false QuotedIRIref QNAME_NS QNAME BNODE_LABEL VAR1 VAR2 LANGTAG INTEGER FLOATING_POINT STRING_LITERAL1 STRING_LITERAL2 STRING_LITERAL_LONG1 STRING_LITERAL_LONG2 Dot OpenCurly CloseCurly cfg:eof) . Query cfg:mustBeOneSequence ( ( Prolog _O_QSelectQuery_E__Or__QConstructQuery_E__Or__QDescribeQuery_E__Or__QAskQuery_E__C cfg:eof ) ) . _O_QSelectQuery_E__Or__QConstructQuery_E__Or__QDescribeQuery_E__Or__QAskQuery_E__C cfg:mustBeOneSequence ( ( SelectQuery ) ( ConstructQuery ) ( DescribeQuery ) ( AskQuery ) ) . Prolog cfg:mustBeOneSequence ( ( _QBaseDecl_E_Opt _QPrefixDecl_E_Star ) ) . _QBaseDecl_E_Opt cfg:mustBeOneSequence ( ( ) ( BaseDecl ) ) . _QPrefixDecl_E_Star cfg:mustBeOneSequence ( ( ) ( PrefixDecl _QPrefixDecl_E_Star ) ) . BaseDecl cfg:mustBeOneSequence ( ( IT_BASE QuotedIRIref ) ) . PrefixDecl cfg:mustBeOneSequence ( ( IT_PREFIX QNAME_NS QuotedIRIref ) ) . SelectQuery cfg:mustBeOneSequence ( ( IT_SELECT _QDISTINCT_E_Opt _O_QVar_E_Plus_Or__QTIMES_E__C _QDatasetClause_E_Star WhereClause SolutionModifier ) ) . _QDISTINCT_E_Opt cfg:mustBeOneSequence ( ( ) ( IT_DISTINCT ) ) . _QVar_E_Plus cfg:mustBeOneSequence ( ( ) ( Var _QVar_E_Plus ) ) . _O_QVar_E_Plus_Or__QTIMES_E__C cfg:mustBeOneSequence ( ( Var _QVar_E_Plus ) ( GT_TIMES ) ) . _QDatasetClause_E_Star cfg:mustBeOneSequence ( ( ) ( DatasetClause _QDatasetClause_E_Star ) ) . ConstructQuery cfg:mustBeOneSequence ( ( IT_CONSTRUCT ConstructTemplate _QDatasetClause_E_Star WhereClause SolutionModifier ) ) . DescribeQuery cfg:mustBeOneSequence ( ( IT_DESCRIBE _O_QVarOrIRIref_E_Plus_Or__QTIMES_E__C _QDatasetClause_E_Star _QWhereClause_E_Opt SolutionModifier ) ) . _QVarOrIRIref_E_Plus cfg:mustBeOneSequence ( ( ) ( VarOrIRIref _QVarOrIRIref_E_Plus ) ) . _O_QVarOrIRIref_E_Plus_Or__QTIMES_E__C cfg:mustBeOneSequence ( ( VarOrIRIref _QVarOrIRIref_E_Plus ) ( GT_TIMES ) ) . _QWhereClause_E_Opt cfg:mustBeOneSequence ( ( ) ( WhereClause ) ) . AskQuery cfg:mustBeOneSequence ( ( IT_ASK _QDatasetClause_E_Star WhereClause ) ) . DatasetClause cfg:mustBeOneSequence ( ( IT_FROM _O_QDefaultGraphClause_E__Or__QNamedGraphClause_E__C ) ) . _O_QDefaultGraphClause_E__Or__QNamedGraphClause_E__C cfg:mustBeOneSequence ( ( DefaultGraphClause ) ( NamedGraphClause ) ) . DefaultGraphClause cfg:mustBeOneSequence ( ( SourceSelector ) ) . NamedGraphClause cfg:mustBeOneSequence ( ( IT_NAMED SourceSelector ) ) . SourceSelector cfg:mustBeOneSequence ( ( IRIref ) ) . WhereClause cfg:mustBeOneSequence ( ( _QWHERE_E_Opt GroupGraphPattern ) ) . _QWHERE_E_Opt cfg:mustBeOneSequence ( ( ) ( IT_WHERE ) ) . SolutionModifier cfg:mustBeOneSequence ( ( _QOrderClause_E_Opt _QLimitClause_E_Opt _QOffsetClause_E_Opt ) ) . _QOrderClause_E_Opt cfg:mustBeOneSequence ( ( ) ( OrderClause ) ) . _QLimitClause_E_Opt cfg:mustBeOneSequence ( ( ) ( LimitClause ) ) . _QOffsetClause_E_Opt cfg:mustBeOneSequence ( ( ) ( OffsetClause ) ) . OrderClause cfg:mustBeOneSequence ( ( IT_ORDER IT_BY OrderCondition _QOrderCondition_E_Plus ) ) . _QOrderCondition_E_Plus cfg:mustBeOneSequence ( ( ) ( OrderCondition _QOrderCondition_E_Plus ) ) . OrderCondition cfg:mustBeOneSequence ( ( _O_QASC_E__Or__QDESC_E____QBrackettedExpression_E__C ) ( _O_QFunctionCall_E__Or__QVar_E__Or__QBrackettedExpression_E__C ) ) . _O_QASC_E__Or__QDESC_E__C cfg:mustBeOneSequence ( ( IT_ASC ) ( IT_DESC ) ) . _O_QASC_E__Or__QDESC_E____QBrackettedExpression_E__C cfg:mustBeOneSequence ( ( _O_QASC_E__Or__QDESC_E__C BrackettedExpression ) ) . _O_QFunctionCall_E__Or__QVar_E__Or__QBrackettedExpression_E__C cfg:mustBeOneSequence ( ( FunctionCall ) ( Var ) ( BrackettedExpression ) ) . LimitClause cfg:mustBeOneSequence ( ( IT_LIMIT INTEGER ) ) . OffsetClause cfg:mustBeOneSequence ( ( IT_OFFSET INTEGER ) ) . GroupGraphPattern cfg:mustBeOneSequence ( ( OpenCurly GraphPatternList CloseCurly ) ) . GraphPatternList cfg:mustBeOneSequence ( ( _Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt ) ) . _O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C cfg:mustBeOneSequence ( ( Triples1 GraphPatternListTail ) ( GraphPatternNotTriples GraphPatternNotTriplesTail ) ) . _Q_O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C_E_Opt cfg:mustBeOneSequence ( ( ) ( _O_QTriples1_E____QGraphPatternListTail_E__Or__QGraphPatternNotTriples_E____QGraphPatternNotTriplesTail_E__C ) ) . GraphPatternListTail cfg:mustBeOneSequence ( ( _Q_O_QDot_E____QGraphPatternList_E__C_E_Opt ) ( GraphPatternNotTriplesList ) ) . _O_QDot_E____QGraphPatternList_E__C cfg:mustBeOneSequence ( ( Dot GraphPatternList ) ) . _Q_O_QDot_E____QGraphPatternList_E__C_E_Opt cfg:mustBeOneSequence ( ( ) ( _O_QDot_E____QGraphPatternList_E__C ) ) . GraphPatternNotTriplesTail cfg:mustBeOneSequence ( ( _O_QDot_E_Opt___QGraphPatternList_E__C ) ) . _QDot_E_Opt cfg:mustBeOneSequence ( ( ) ( Dot ) ) . _O_QDot_E_Opt___QGraphPatternList_E__C cfg:mustBeOneSequence ( ( _QDot_E_Opt GraphPatternList ) ) . GraphPatternNotTriplesList cfg:mustBeOneSequence ( ( GraphPatternNotTriples GraphPatternNotTriplesTail ) ) . GraphPatternNotTriples cfg:mustBeOneSequence ( ( OptionalGraphPattern ) ( GroupOrUnionGraphPattern ) ( GraphGraphPattern ) ( Constraint ) ) . OptionalGraphPattern cfg:mustBeOneSequence ( ( IT_OPTIONAL GroupGraphPattern ) ) . GraphGraphPattern cfg:mustBeOneSequence ( ( IT_GRAPH VarOrBlankNodeOrIRIref GroupGraphPattern ) ) . GroupOrUnionGraphPattern cfg:mustBeOneSequence ( ( GroupGraphPattern _Q_O_QUNION_E____QGroupGraphPattern_E__C_E_Star ) ) . _O_QUNION_E____QGroupGraphPattern_E__C cfg:mustBeOneSequence ( ( IT_UNION GroupGraphPattern ) ) . _Q_O_QUNION_E____QGroupGraphPattern_E__C_E_Star cfg:mustBeOneSequence ( ( ) ( _O_QUNION_E____QGroupGraphPattern_E__C _Q_O_QUNION_E____QGroupGraphPattern_E__C_E_Star ) ) . Constraint cfg:mustBeOneSequence ( ( IT_FILTER _O_QBrackettedExpression_E__Or__QCallExpression_E__C ) ) . _O_QBrackettedExpression_E__Or__QCallExpression_E__C cfg:mustBeOneSequence ( ( BrackettedExpression ) ( CallExpression ) ) . ConstructTemplate cfg:mustBeOneSequence ( ( OpenCurly _QTriples_E_Opt CloseCurly ) ) . _QTriples_E_Opt cfg:mustBeOneSequence ( ( ) ( Triples ) ) . Triples cfg:mustBeOneSequence ( ( Triples1 _Q_O_QDot_E____QTriples_E_Opt_C_E_Opt ) ) . _QTriples_E_Opt cfg:mustBeOneSequence ( ( ) ( Triples ) ) . _O_QDot_E____QTriples_E_Opt_C cfg:mustBeOneSequence ( ( Dot _QTriples_E_Opt ) ) . _Q_O_QDot_E____QTriples_E_Opt_C_E_Opt cfg:mustBeOneSequence ( ( ) ( _O_QDot_E____QTriples_E_Opt_C ) ) . Triples1 cfg:mustBeOneSequence ( ( VarOrTerm PropertyListNotEmpty ) ( GT_LBRACKET Triples2 ) ( GT_LPAREN Triples3 ) ) . Triples2 cfg:mustBeOneSequence ( ( GT_RBRACKET PropertyListNotEmpty ) ( PropertyListNotEmpty GT_RBRACKET PropertyList ) ) . Triples3 cfg:mustBeOneSequence ( ( GT_RPAREN PropertyListNotEmpty ) ( GraphNode _QGraphNode_E_Plus GT_RPAREN PropertyList ) ) . _QGraphNode_E_Plus cfg:mustBeOneSequence ( ( ) ( GraphNode _QGraphNode_E_Plus ) ) . PropertyList cfg:mustBeOneSequence ( ( _QPropertyListNotEmpty_E_Opt ) ) . _QPropertyListNotEmpty_E_Opt cfg:mustBeOneSequence ( ( ) ( PropertyListNotEmpty ) ) . PropertyListNotEmpty cfg:mustBeOneSequence ( ( Verb ObjectList _Q_O_QSEMI_E____QPropertyList_E__C_E_Opt ) ) . _O_QSEMI_E____QPropertyList_E__C cfg:mustBeOneSequence ( ( GT_SEMI PropertyList ) ) . _Q_O_QSEMI_E____QPropertyList_E__C_E_Opt cfg:mustBeOneSequence ( ( ) ( _O_QSEMI_E____QPropertyList_E__C ) ) . ObjectList cfg:mustBeOneSequence ( ( Object _Q_O_QCOMMA_E____QObjectList_E__C_E_Opt ) ) . _O_QCOMMA_E____QObjectList_E__C cfg:mustBeOneSequence ( ( GT_COMMA ObjectList ) ) . _Q_O_QCOMMA_E____QObjectList_E__C_E_Opt cfg:mustBeOneSequence ( ( ) ( _O_QCOMMA_E____QObjectList_E__C ) ) . Verb cfg:mustBeOneSequence ( ( VarOrBlankNodeOrIRIref ) ( IT_a ) ) . Object cfg:mustBeOneSequence ( ( VarOrTerm ) ( TriplesNode ) ) . TriplesNode cfg:mustBeOneSequence ( ( Collection ) ( BlankNodePropertyList ) ) . BlankNodePropertyList cfg:mustBeOneSequence ( ( GT_LBRACKET PropertyList GT_RBRACKET ) ) . Collection cfg:mustBeOneSequence ( ( GT_LPAREN _QGraphNode_E_Star GT_RPAREN ) ) . _QGraphNode_E_Star cfg:mustBeOneSequence ( ( ) ( GraphNode _QGraphNode_E_Star ) ) . GraphNode cfg:mustBeOneSequence ( ( VarOrTerm ) ( TriplesNode ) ) . VarOrTerm cfg:mustBeOneSequence ( ( Var ) ( GraphTerm ) ) . VarOrIRIref cfg:mustBeOneSequence ( ( Var ) ( IRIref ) ) . VarOrBlankNodeOrIRIref cfg:mustBeOneSequence ( ( Var ) ( BlankNode ) ( IRIref ) ( NamelessBlank ) ) . Var cfg:mustBeOneSequence ( ( VAR1 ) ( VAR2 ) ) . GraphTerm cfg:mustBeOneSequence ( ( RDFTerm ) ) . Expression cfg:mustBeOneSequence ( ( ConditionalOrExpression ) ) . ConditionalOrExpression cfg:mustBeOneSequence ( ( ConditionalAndExpression _Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star ) ) . _O_QOR_E____QConditionalAndExpression_E__C cfg:mustBeOneSequence ( ( GT_OR ConditionalAndExpression ) ) . _Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star cfg:mustBeOneSequence ( ( ) ( _O_QOR_E____QConditionalAndExpression_E__C _Q_O_QOR_E____QConditionalAndExpression_E__C_E_Star ) ) . ConditionalAndExpression cfg:mustBeOneSequence ( ( ValueLogical _Q_O_QAND_E____QValueLogical_E__C_E_Star ) ) . _O_QAND_E____QValueLogical_E__C cfg:mustBeOneSequence ( ( GT_AND ValueLogical ) ) . _Q_O_QAND_E____QValueLogical_E__C_E_Star cfg:mustBeOneSequence ( ( ) ( _O_QAND_E____QValueLogical_E__C _Q_O_QAND_E____QValueLogical_E__C_E_Star ) ) . ValueLogical cfg:mustBeOneSequence ( ( RelationalExpression ) ) . RelationalExpression cfg:mustBeOneSequence ( ( NumericExpression _Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt ) ) . _O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C cfg:mustBeOneSequence ( ( GT_EQUAL NumericExpression ) ( GT_NEQUAL NumericExpression ) ( GT_LT NumericExpression ) ( GT_GT NumericExpression ) ( GT_LE NumericExpression ) ( GT_GE NumericExpression ) ) . _Q_O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C_E_Opt cfg:mustBeOneSequence ( ( ) ( _O_QEQUAL_E____QNumericExpression_E__Or__QNEQUAL_E____QNumericExpression_E__Or__QLT_E____QNumericExpression_E__Or__QGT_E____QNumericExpression_E__Or__QLE_E____QNumericExpression_E__Or__QGE_E____QNumericExpression_E__C ) ) . NumericExpression cfg:mustBeOneSequence ( ( AdditiveExpression ) ) . AdditiveExpression cfg:mustBeOneSequence ( ( MultiplicativeExpression _Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star ) ) . _O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C cfg:mustBeOneSequence ( ( GT_PLUS MultiplicativeExpression ) ( GT_MINUS MultiplicativeExpression ) ) . _Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star cfg:mustBeOneSequence ( ( ) ( _O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C _Q_O_QPLUS_E____QMultiplicativeExpression_E__Or__QMINUS_E____QMultiplicativeExpression_E__C_E_Star ) ) . MultiplicativeExpression cfg:mustBeOneSequence ( ( UnaryExpression _Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star ) ) . _O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C cfg:mustBeOneSequence ( ( GT_TIMES UnaryExpression ) ( GT_DIVIDE UnaryExpression ) ) . _Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star cfg:mustBeOneSequence ( ( ) ( _O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C _Q_O_QTIMES_E____QUnaryExpression_E__Or__QDIVIDE_E____QUnaryExpression_E__C_E_Star ) ) . UnaryExpression cfg:mustBeOneSequence ( ( GT_NOT PrimaryExpression ) ( GT_PLUS PrimaryExpression ) ( GT_MINUS PrimaryExpression ) ( PrimaryExpression ) ) . CallExpression cfg:mustBeOneSequence ( ( BuiltinCallExpression ) ( FunctionCall ) ) . BuiltinCallExpression cfg:mustBeOneSequence ( ( IT_STR GT_LPAREN Expression GT_RPAREN ) ( IT_LANG GT_LPAREN Expression GT_RPAREN ) ( IT_DATATYPE GT_LPAREN Expression GT_RPAREN ) ( IT_BOUND GT_LPAREN Var GT_RPAREN ) ( IT_isURI GT_LPAREN Expression GT_RPAREN ) ( IT_isBLANK GT_LPAREN Expression GT_RPAREN ) ( IT_isLITERAL GT_LPAREN Expression GT_RPAREN ) ( RegexExpression ) ) . RegexExpression cfg:mustBeOneSequence ( ( IT_REGEX GT_LPAREN Expression GT_COMMA Expression _Q_O_QCOMMA_E____QExpression_E__C_E_Opt GT_RPAREN ) ) . _O_QCOMMA_E____QExpression_E__C cfg:mustBeOneSequence ( ( GT_COMMA Expression ) ) . _Q_O_QCOMMA_E____QExpression_E__C_E_Opt cfg:mustBeOneSequence ( ( ) ( _O_QCOMMA_E____QExpression_E__C ) ) . FunctionCall cfg:mustBeOneSequence ( ( IRIref ArgList ) ) . ArgList cfg:mustBeOneSequence ( ( GT_LPAREN _Q_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C_E_Opt GT_RPAREN ) ) . _Q_O_QCOMMA_E____QExpression_E__C_E_Star cfg:mustBeOneSequence ( ( ) ( _O_QCOMMA_E____QExpression_E__C _Q_O_QCOMMA_E____QExpression_E__C_E_Star ) ) . _O_QExpression_E____QCOMMA_E____QExpression_E_Star_C cfg:mustBeOneSequence ( ( Expression _Q_O_QCOMMA_E____QExpression_E__C_E_Star ) ) . _Q_O_QExpression_E____QCOMMA_E____QExpression_E_Star_C_E_Opt cfg:mustBeOneSequence ( ( ) ( _O_QExpression_E____QCOMMA_E____QExpression_E_Star_C ) ) . BrackettedExpression cfg:mustBeOneSequence ( ( GT_LPAREN Expression GT_RPAREN ) ) . PrimaryExpression cfg:mustBeOneSequence ( ( BrackettedExpression ) ( BuiltinCallExpression ) ( Var ) ( RDFTermOrFunc ) ) . RDFTerm cfg:mustBeOneSequence ( ( IRIref ) ( RDFLiteral ) ( NumericLiteral ) ( BooleanLiteral ) ( BlankNode ) ) . RDFTermOrFunc cfg:mustBeOneSequence ( ( IRIrefOrFunc ) ( RDFLiteral ) ( NumericLiteral ) ( BooleanLiteral ) ( BlankNode ) ) . IRIrefOrFunc cfg:mustBeOneSequence ( ( IRIref _QArgList_E_Opt ) ) . _QArgList_E_Opt cfg:mustBeOneSequence ( ( ) ( ArgList ) ) . NumericLiteral cfg:mustBeOneSequence ( ( INTEGER ) ( FLOATING_POINT ) ) . RDFLiteral cfg:mustBeOneSequence ( ( String _Q_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C_E_Opt ) ) . _O_QDTYPE_E____QIRIref_E__C cfg:mustBeOneSequence ( ( GT_DTYPE IRIref ) ) . _O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C cfg:mustBeOneSequence ( ( LANGTAG ) ( _O_QDTYPE_E____QIRIref_E__C ) ) . _Q_O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C_E_Opt cfg:mustBeOneSequence ( ( ) ( _O_QLANGTAG_E__Or__QDTYPE_E____QIRIref_E__C ) ) . BooleanLiteral cfg:mustBeOneSequence ( ( IT_true ) ( IT_false ) ) . String cfg:mustBeOneSequence ( ( STRING_LITERAL1 ) ( STRING_LITERAL2 ) ( STRING_LITERAL_LONG1 ) ( STRING_LITERAL_LONG2 ) ) . IRIref cfg:mustBeOneSequence ( ( QuotedIRIref ) ( QName ) ) . QName cfg:mustBeOneSequence ( ( QNAME ) ( QNAME_NS ) ) . BlankNode cfg:mustBeOneSequence ( ( BNODE_LABEL ) ) . NamelessBlank cfg:mustBeOneSequence ( ( GT_LBRACKET GT_RBRACKET ) ) . #____________________________________________________ # Axioms reducing the shortcut CFG terms to cfg:musBeOneSequence. { ?x cfg:zeroOrMore ?y } => {?x cfg:mustBeOneSequence ( () (?y ?x) ) }. cwm-1.2.1/grammar/bnf.n30000644015216600007660000000663310374647201014066 0ustar syosisyosi# # Context-free grammar (CFG) vocabulary # @prefix rdf: . @prefix rdfs: . @prefix cfg: . @prefix : . @prefix n3: . @prefix list: . @prefix doc: . @prefix dc: . @keywords a, is, of. doc:rules ; dc:creator ; rdfs:comment """ This ontology contains terms for defining a context-free grammar. The basic property is mustBeOneSequence which is equivalent to the expression of a production in the original simple BNF. Rules can be used to convert into and out of shorthand forms such as optional, repeating and token-separated list forms. Terminals are described either as a string, which is represented by itself, or are defined by a regular expression using cfg:matches. """. #cfg:canBeSequence a rdf:Property; # rdfs:domain cfg:Term; rdfs:range cfg:SequenceOfProductions; # rdfs:comment #"""If you use cfg:canBeSequence to define a BNF vocabulary, then the reader #has to assume that all possible productions are in the BNF file (or, generally, #in the N3 formula) you are dealing with. #Other possible vocabularies would explicitly list the "canBeSequence as a set of #cfg:mustBeOneSequence" #""". # #cfg:canBe rdfs:domain cfg:Term; rdfs:range cfg:Production. cfg:mustBeOneSequence a rdf:Property; rdfs:label "productions"; rdfs:domain cfg:Production; rdfs:range cfg:ListOfSequencesOfProductions; rdfs:comment """This is the core property you need to define a BNF production. It defines the list of the only sequences to which a given term may expand. Each sequence is just a list of other productions in order. """. cfg:Token rdfs:subClassOf cfg:Production; rdfs:label "token"; rdfs:comment """A terminal, aka atomic, production, defined as string or regexp""". cfg:matches a rdf:Property; rdfs:label "matches"; rdfs:domain cfg:Token; rdfs:range cfg:RegularExpression; rdfs:comment """The given token is defined by the regular expression which a token must match""". cfg:canStartWith a rdf:Property; rdfs:domain cfg:Production; rdfs:label "can start with"; rdfs:comment """The production can only start with the given representative character. In the case that a token starts with always the same character, that is the one given. In th eevent that it can start with alpha character, 'a' is given; if it can start with a numeric, '0' is given as the value for this predicate. This predicate is used only when a predictive parser is possible and desired."""; rdfs:range cfg:String. # Sugar cfg:zeroOrMore rdfs:label "zero or more"; rdfs:domain cfg:Term; rdfs:range cfg:Production. cfg:commaSeparatedPeriodTerminatedListOf rdfs:label "comma-separated period-terminated list of"; rdfs:domain cfg:Production; rdfs:range cfg:Production. cfg:mustBe rdfs:domain cfg:Production; rdfs:range cfg:Production. # Meta cfg:syntaxFor a rdf:Property; rdfs:domain cfg:Production; rdfs:label "language"; rdfs:range cfg:Language. cfg:internetMediaType a rdf:Property; rdf:domain cfg:Language; rdfs:label "internet media type". #ends cwm-1.2.1/grammar/README.txt0000644015216600007660000000004710006245351014536 0ustar syosisyosihttp://www.faqs.org/rfcs/rfc2234.html cwm-1.2.1/grammar/Makefile0000644015216600007660000001026310544265224014511 0ustar syosisyosi# Build stuff up from the CFG SWAP=.. P=python C=$(SWAP)/cwm.py CG=PYTHONPATH=$(SWAP) python predictiveParser.py .SUFFIXES: .rdf .n3 all : n3-checked.txt n3-report.html n3.rdf \ n3rdf-report.html \ n3rules-report.html \ n3ql-report.html echo all done # N3 Full: .n3.rdf: python $(SWAP)/cwm.py --n3 $< --rdf > $@ n3-yacc.c : n3-selectors.n3-yacc.y yacc -o $@ n3-selectors.n3-yacc.y n3-selectors.n3-yacc.y : n3-selectors.n3 n3-checked.txt: n3-selectors.n3 $(CG) --grammar=n3-selectors.n3 \ --as=http://www.w3.org/2000/10/swap/grammar/n3#document \ --parse=n3.n3 && touch $@ n3-selectors.n3 : n3.n3 bnf-rules.n3 time $P $C n3.n3 bnf-rules.n3 --think --purge --data --quiet > $@ n3-i18n-selectors.n3 : n3-re.n3 bnf-rules.n3 time $P $C n3-re.n3 bnf-rules.n3 --think --purge --data --quiet > $@ n3-report.big: n3.n3 bnf2html.n3 time $P $C n3.n3 bnf2html.n3 --chatty=21 --think --data --quiet > $@ n3-report.html : n3-report.big time $P $C n3-report.big --strings > $@ n3.rdf : n3.n3 $C --n3 n3.n3 --rdf > $@ # N3-RDF n3rdf-checked.txt: n3rdf-selectors.n3 $(CG) n3rdf-selectors.n3 \ http://www.w3.org/2000/10/swap/grammar/n3rdf#document > $@ n3rdf-selectors.n3 : n3-rdf.n3 bnf-rules.n3 time $P $C n3-rdf.n3 bnf-rules.n3 --think --purge --data > $@ n3rdf-report.big: n3-rdf.n3 bnf2html.n3 time $P $C n3-rdf.n3 bnf2html.n3 --chatty=21 --think --data > $@ n3rdf-report.html : n3rdf-report.big time $P $C n3rdf-report.big --strings > $@ # N3-Rules n3rules-selectors.n3 : n3-rules.n3 bnf-rules.n3 time $P $C n3-rules.n3 bnf-rules.n3 --think --purge --data > $@ n3rules-report.big: n3-rules.n3 bnf2html.n3 time $P $C n3-rules.n3 bnf2html.n3 --chatty=21 --think --data > $@ n3rules-report.html : n3rules-report.big time $P $C n3rules-report.big --strings > $@ # N3-QL n3ql-checked.txt: n3ql-selectors.n3 $(CG) n3ql-selectors.n3 \ http://www.w3.org/2000/10/swap/grammar/n3ql#document > $@ n3ql-selectors.n3 : n3-ql.n3 bnf-rules.n3 time $P $C n3-ql.n3 bnf-rules.n3 --think --purge --data > $@ n3ql-report.big: n3-ql.n3 bnf2html.n3 time $P $C n3-ql.n3 bnf2html.n3 --chatty=21 --think --data > $@ n3ql-report.html : n3ql-report.big time $P $C n3ql-report.big --strings > $@ #___________________________________ Q=../../../../2001/sw/DataAccess/rq23 sparql.n3 : $Q/grammar.yy sed -f yy2n3.sed < $Q/grammar.yy > sparql.n3 sparql-utf16.n3 : sparql.n3 to-utf18.sed sed -f to-utf16.sed < sparql.n3 > sparql-utf16.n3 sparql-checked.txt: sparql-selectors.n3 $(CG) --grammar=sparql-selectors.n3 \ --as=http://www.w3.org/2000/10/swap/grammar/sparql#Query > $@ sparql-selectors.n3 : sparql.n3 bnf-rules.n3 shorthand-rules.n3 time $P $C sparql.n3 shorthand-rules.n3 bnf-rules.n3 --think --purge --data > $@ sparql-report.big: sparql.n3 bnf2html.n3 time $P $C sparql.n3 bnf2html.n3 --chatty=21 --think --data > $@ sparql-report.html : sparql-report.big time $P $C sparql-report.big --strings > $@ ebnf: notation3.rdf ebnf.rdf notation3.json turtle_syntax turtle_syntax: turtle.json turtle-bnf.n3 turtle.n3 turtle.bnf CHATTY=0 .SUFFIXES: .json .n3 .bnf LYNX=elinks turtle.bnf: turtle.html $(LYNX) -no-references -no-numbering -dump turtle.html >$@ turtle.json: turtle-bnf.n3 gramLL1.py PYTHONPATH=$(HOME)/lib/python:../.. $P gramLL1.py turtle-bnf.n3 'http://www.w3.org/2000/10/swap/grammar/turtle#language' >$@ turtle-bnf.n3: turtle.n3 ebnf2bnf.n3 $P $C turtle.n3 ebnf2bnf.n3 --chatty=$(CHATTY) \ --think --data >$@ turtle.n3: turtle.bnf ebnf2turtle.py $P ebnf2turtle.py $< ttl language 'http://www.w3.org/2000/10/swap/grammar/turtle#' >$@ notation3.json: notation3-bnf.n3 gramLL1.py PYTHONPATH=$(HOME)/lib/python:../.. $P gramLL1.py notation3-bnf.n3 'http://www.w3.org/2000/10/swap/grammar/notation3#language' >$@ notation3-ll1.n3: notation3.n3 ebnf2bnf.n3 first_follow.n3 $P $C notation3.n3 ebnf2bnf.n3 first_follow.n3 --chatty=$(CHATTY) \ --think --data >$@ notation3-bnf.n3: notation3.n3 ebnf2bnf.n3 first_follow.n3 $P $C notation3.n3 ebnf2bnf.n3 --chatty=$(CHATTY) \ --think --data >$@ notation3.n3: notation3.bnf ebnf2turtle.py $P ebnf2turtle.py $< n3 language 'http://www.w3.org/2000/10/swap/grammar/notation3#' >$@ ebnf.rdf: ebnf.n3 notation3.rdf: notation3.n3 #ends cwm-1.2.1/grammar/n3-rules.n30000644015216600007660000001141410713412507014756 0ustar syosisyosi# Notation3 constrained to be RDF + a horn rules language # # BNF without tokenization # @prefix rdf: . @prefix rdfs: . @prefix bnf: . @prefix rul: . @prefix : . @prefix n3r: . @prefix list: . @prefix string: . @keywords a, is, of. # Issues: # - see general ones in n3.n3 # - Defining safe rules <> bnf:syntaxFor [ bnf:internetMediaType ]. # <> rdfsem:semanticsFor "" ..... # __________________________________________________________________ # # The N3 Rukes Grammar n3document a rul:Used; bnf:mustBeOneSequence( ( [ bnf:zeroOrMore declaration ] [ bnf:zeroOrMore universal ] [ bnf:zeroOrMore existential ] statements_optional bnf:eof ) ). statements_optional bnf:mustBeOneSequence (() ( statement_or_rule "." statements_optional )e ). statement_or_rule bnf:mustBeOneSequence( (statement) (rule) ). # Formula does NOT need period on last statement formulacontent bnf:mustBeOneSequence (( [ bnf:zeroOrMore declaration ] [ bnf:zeroOrMore existential ] statementlist )). statementlist bnf:mustBeOneSequence ( ( ) ( statement statementtail ) ). statementtail bnf:mustBeOneSequence ( ( ) ( "." statementlist ) ). universal bnf:mustBeOneSequence ( ( "@forAll" [ bnf:commaSeparatedPeriodTerminatedListOf symbol ] )). existential bnf:mustBeOneSequence( ( "@forSome" [ bnf:commaSeparatedPeriodTerminatedListOf symbol ] )). symbol bnf:mustBeOneSequence ( (explicituri) (qname) ). declaration bnf:mustBeOneSequence( ( "@base" explicituri "." ) ( "@prefix" qname explicituri "." ) ( "@keywords" [ bnf:commaSeparatedPeriodTerminatedListOf barename ] ) ). statement bnf:mustBeOneSequence(( subject propertylist )). rule bnf:mustBeOneSequence ( ( "{" formulacontent "}" "=>" "{" formulacontent "}" ) ). rule_safe bnf:mustBeOneSequence ( ( "{" formulacontent "}" "=>" "{" formula_safe "}" ) ). propertylist bnf:mustBeOneSequence ( ( ) ( verb object objecttail propertylisttail ) ). propertylisttail bnf:mustBeOneSequence ( ( ) ( ";" propertylist ) ). objecttail bnf:mustBeOneSequence ( ( ) ( "," object objecttail ) ). verb bnf:mustBeOneSequence ( ( prop ) ( "@has" prop ) ( "@is" prop "@of" ) ( "@a" ) ( "=" ) ). prop bnf:mustBeOneSequence ((node)). subject bnf:mustBeOneSequence ((item)). object bnf:mustBeOneSequence ((item)). item bnf:mustBeOneSequence( (path) ). path bnf:mustBeOneSequence( ( node pathtail ) ). pathtail bnf:mustBeOneSequence( ( ) ( "!" path ) ( "^" path ) ). node bnf:mustBeOneSequence ( ( symbol ) ( variable ) ( numericliteral ) ( literal ) ( "[" propertylist "]" ) ( "(" itemlist ")" ) ). node_safe bnf:mustBeOneSequence ( ( symbol ) ( variable ) ( numericliteral ) ( literal ) ). itemlist bnf:mustBeOneSequence (() (item itemlist)). literal bnf:mustBeOneSequence(( string dtlang)). dtlang bnf:mustBeOneSequence( () ("@" langcode) ("^^" symbol)). #______________________________________________________________________ # # TOKENS alphanumeric bnf:matches "[a-zA-Z][a-zA-Z0-9_]*"; bnf:canStartWith "a". numericliteral bnf:matches """[-+]?[0-9]+(\\.[0-9]+)?(e[-+]?[0-9]+)?"""; bnf:canStartWith "0", "-", "+". explicituri bnf:matches "<[^>].*>"; bnf:canStartWith "<". qname bnf:matches "(([a-zA-Z_][a-zA-Z0-9_]*)?:)?([a-zA-Z_][a-zA-Z0-9_]*)?"; bnf:canStartWith "a", "_". # @@ etc barename bnf:matches "[a-zA-Z_][a-zA-Z0-9_]*"; # subset of qname bnf:canStartWith "a", "_". # @@ etc variable bnf:matches "\\?[a-zA-Z_][a-zA-Z0-9_]*"; # ? barename bnf:canStartWith "?". # langcode bnf:matches "[a-zA-Z0-9]+(-[a-zA-Z0-9]+)?"; bnf:canStartWith "a". string bnf:matches "(\"\"\"[^\"\\\\]*(?:(?:\\\\.|\"(?!\"\"))[^\"\\\\]*)*\"\"\")|(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")"; bnf:canStartWith "\"". #____________________________________________________ # Axioms reducing the shortcut BNF terms to bnf:musBeOneSequence. { ?x bnf:zeroOrMore ?y } => {?x bnf:mustBeOneSequence ( () (?y ?x) ) }. { ?x bnf:commaSeparatedPeriodTerminatedListOf ?y } => { ?x bnf:mustBeOneSequence ( ( "." ) ( "," ?y ?x ) ) }. # labelling of things which do not have explicit URIs: { ?x bnf:zeroOrMore [ bnf:label ?y]. ( ?y "_s" ) string:concatenation ?str } => { ?x bnf:label ?str }. { ?x bnf:commaSeparatedPeriodTerminatedListOf [ bnf:label ?y]. ( ?y "_csl" ) string:concatenation ?str } => { ?x bnf:label ?str }. #ends cwm-1.2.1/grammar/n3-yacc.c0000644015216600007660000004334110103472651014450 0ustar syosisyosi#include #ifndef lint #if 0 static char yysccsid[] = "@(#)yaccpar 1.9 (Berkeley) 02/21/93"; #else __IDSTRING(yyrcsid, "$NetBSD: skeleton.c,v 1.14 1997/10/20 03:41:16 lukem Exp $"); #endif #endif #include #define YYBYACC 1 #define YYMAJOR 1 #define YYMINOR 9 #define YYLEX yylex() #define YYEMPTY -1 #define yyclearin (yychar=(YYEMPTY)) #define yyerrok (yyerrflag=0) #define YYRECOVERING (yyerrflag!=0) #define YYPREFIX "yy" #define N3_QNAME 257 #define N3_EXPLICITURI 258 #define N3_VARIABLE 259 #define N3_NUMERICLITERAL 260 #define N3_STRING 261 #define N3_BARENAME 262 #define YYERRCODE 256 short yylhs[] = { -1, 0, 1, 1, 2, 2, 3, 3, 4, 4, 6, 6, 7, 8, 9, 10, 10, 11, 11, 12, 12, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 20, 20, 20, 20, 20, 20, 20, 21, 22, 22, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 26, 27, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34, 34, 35, 35, 5, }; short yylen[] = { 2, 5, 0, 2, 0, 2, 0, 2, 0, 3, 4, 2, 2, 2, 2, 1, 2, 1, 2, 1, 2, 1, 0, 4, 1, 3, 1, 1, 1, 3, 1, 3, 2, 1, 2, 3, 1, 1, 1, 1, 1, 0, 3, 0, 5, 1, 3, 1, 1, 1, 3, 3, 1, 0, 2, 2, 1, 4, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 2, 0, 2, 0, }; short yydefred[] = { 0, 0, 0, 0, 0, 0, 0, 0, 15, 11, 0, 0, 0, 3, 0, 24, 0, 16, 27, 26, 17, 12, 0, 0, 0, 0, 5, 10, 0, 28, 0, 18, 19, 13, 0, 47, 48, 0, 0, 0, 0, 52, 74, 0, 0, 45, 21, 0, 49, 7, 25, 0, 30, 0, 20, 0, 0, 58, 0, 0, 0, 0, 0, 36, 37, 38, 39, 0, 0, 56, 33, 0, 0, 1, 0, 14, 0, 0, 32, 29, 0, 70, 71, 62, 46, 0, 0, 34, 0, 50, 40, 0, 60, 51, 9, 54, 55, 31, 64, 0, 0, 35, 0, 0, 66, 0, 57, 0, 0, 23, 0, 68, 42, 0, 73, 0, 0, 44, }; short yydgoto[] = { 3, 4, 11, 24, 42, 73, 5, 12, 25, 43, 9, 21, 33, 44, 67, 17, 45, 31, 54, 46, 68, 91, 103, 109, 47, 78, 70, 59, 48, 72, 60, 86, 100, 106, 57, 111, }; short yysindex[] = { -206, -237, -46, 0, -242, -206, -232, -4, 0, 0, -44, -227, -242, 0, -3, 0, -233, 0, 0, 0, 0, 0, 4, -40, 74, -227, 0, 0, -4, 0, -198, 0, 0, 0, 9, 0, 0, -55, -206, 45, 74, 0, 0, 6, 45, 0, 0, -23, 0, 0, 0, 4, 0, -198, 0, -2, -198, 0, -206, -58, -242, 74, 74, 0, 0, 0, 0, -16, 74, 0, 0, 74, 29, 0, 74, 0, 74, 74, 0, 0, 9, 0, 0, 0, 0, -242, -227, 0, -191, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, -227, 74, 0, 74, 25, 0, 44, 0, 36, 45, 0, 74, 0, 0, 74, 0, 36, 25, 0, }; short yyrindex[] = { 1, 0, 0, 0, 11, 1, 0, 0, 0, 0, 0, 21, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -28, -10, 5, 58, 0, 0, 0, -42, 0, 0, 28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -10, 0, 63, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 58, 0, 0, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, -37, 0, 0, 0, 0, -31, 0, 0, 0, 0, 0, 0, 0, -37, -25, 0, 0, -29, 0, -20, 0, -31, 0, 0, -25, 0, 0, 0, 0, -31, -29, 0, }; short yygindex[] = { 0, 102, 96, 86, 42, 0, -24, -53, -62, -75, 0, 0, 0, 0, 73, 90, 26, 69, 43, 33, 17, -94, -69, 10, -17, 0, 14, 0, 0, 51, 70, 46, 30, 20, 0, 0, }; #define YYTABLESIZE 347 short yytable[] = { 8, 2, 20, 65, 22, 69, 32, 85, 107, 55, 76, 4, 69, 69, 58, 41, 69, 43, 69, 115, 6, 6, 69, 10, 99, 105, 14, 69, 41, 28, 61, 69, 85, 69, 58, 105, 22, 99, 112, 23, 16, 2, 15, 27, 69, 69, 116, 81, 30, 34, 29, 4, 74, 53, 65, 52, 51, 1, 2, 18, 19, 6, 41, 69, 43, 69, 69, 84, 53, 53, 93, 77, 53, 71, 53, 87, 88, 89, 101, 80, 102, 61, 82, 22, 108, 40, 65, 53, 65, 53, 110, 69, 2, 8, 41, 69, 43, 69, 22, 59, 67, 90, 4, 63, 71, 72, 64, 13, 26, 95, 96, 49, 6, 61, 40, 61, 94, 75, 50, 53, 79, 53, 92, 97, 2, 113, 117, 0, 83, 104, 114, 98, 0, 0, 4, 90, 39, 0, 0, 0, 0, 0, 0, 0, 6, 0, 90, 0, 0, 0, 0, 53, 0, 53, 63, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 0, 63, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 19, 0, 7, 18, 19, 56, 65, 65, 65, 65, 65, 0, 0, 0, 0, 69, 69, 69, 69, 69, 0, 0, 65, 0, 0, 69, 69, 69, 69, 69, 69, 69, 0, 61, 61, 61, 61, 61, 0, 0, 0, 61, 61, 0, 2, 2, 2, 2, 2, 61, 0, 0, 2, 2, 4, 4, 4, 4, 4, 0, 2, 0, 0, 4, 6, 6, 6, 6, 6, 0, 4, 53, 53, 53, 53, 53, 0, 0, 0, 0, 6, 53, 53, 0, 53, 53, 53, 53, 18, 19, 35, 36, 37, 0, 0, 0, 0, 0, 61, 62, 0, 63, 65, 66, 41, 0, 63, 63, 63, 63, 63, 0, 0, 0, 0, 63, 0, 18, 19, 35, 36, 37, 63, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 41, }; short yycheck[] = { 46, 0, 46, 40, 46, 33, 46, 60, 102, 64, 33, 0, 40, 41, 38, 46, 44, 46, 46, 113, 257, 0, 39, 265, 86, 100, 258, 44, 59, 262, 40, 59, 85, 61, 58, 110, 10, 99, 107, 266, 44, 40, 46, 46, 61, 62, 115, 49, 44, 23, 46, 40, 46, 44, 91, 46, 30, 263, 264, 257, 258, 40, 93, 91, 93, 93, 94, 125, 40, 41, 41, 94, 44, 40, 46, 61, 62, 93, 269, 53, 44, 91, 56, 125, 59, 40, 123, 59, 125, 61, 46, 108, 91, 0, 125, 123, 125, 125, 93, 41, 125, 68, 91, 40, 71, 125, 61, 5, 12, 76, 77, 25, 91, 123, 40, 125, 74, 44, 28, 91, 51, 93, 71, 80, 123, 108, 116, -1, 58, 99, 110, 85, -1, -1, 123, 102, 91, -1, -1, -1, -1, -1, -1, -1, 123, -1, 113, -1, -1, -1, -1, 123, -1, 125, 91, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 91, -1, -1, 123, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 123, -1, 125, -1, -1, -1, -1, -1, -1, -1, -1, 123, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 257, 258, -1, 262, 257, 258, 274, 257, 258, 259, 260, 261, -1, -1, -1, -1, 257, 258, 259, 260, 261, -1, -1, 273, -1, -1, 267, 268, 269, 270, 271, 272, 273, -1, 257, 258, 259, 260, 261, -1, -1, -1, 265, 266, -1, 257, 258, 259, 260, 261, 273, -1, -1, 265, 266, 257, 258, 259, 260, 261, -1, 273, -1, -1, 266, 257, 258, 259, 260, 261, -1, 273, 257, 258, 259, 260, 261, -1, -1, -1, -1, 273, 267, 268, -1, 270, 271, 272, 273, 257, 258, 259, 260, 261, -1, -1, -1, -1, -1, 267, 268, -1, 270, 271, 272, 273, -1, 257, 258, 259, 260, 261, -1, -1, -1, -1, 266, -1, 257, 258, 259, 260, 261, 273, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 273, }; #define YYFINAL 3 #ifndef YYDEBUG #define YYDEBUG 0 #endif #define YYMAXTOKEN 274 #if YYDEBUG char *yyname[] = { "end-of-file",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, "'!'",0,0,0,0,0,0,"'('","')'",0,0,"','",0,"'.'",0,0,"'1'",0,0,0,0,0,0,0,0,0, "';'",0,"'='",0,0,"'@'",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, "'['",0,"']'","'^'",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, "'{'",0,"'}'",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"N3_QNAME","N3_EXPLICITURI","N3_VARIABLE", "N3_NUMERICLITERAL","N3_STRING","N3_BARENAME","\"@prefix\"","\"@keywords\"", "\"@forAll\"","\"@forSome\"","\"@has\"","\"@is\"","\"@of\"","\"@a\"","\"=>\"", "\"<=\"","\"@this\"","\"^^\"", }; char *yyrule[] = { "$accept : n3_document", "n3_document : _g0 _g1 _g2 n3_statements_optional eof", "_g0 :", "_g0 : n3_declaration _g0", "_g1 :", "_g1 : n3_universal _g1", "_g2 :", "_g2 : n3_existential _g2", "n3_statements_optional :", "n3_statements_optional : n3_statement '.' n3_statements_optional", "n3_declaration : \"@prefix\" N3_QNAME N3_EXPLICITURI '.'", "n3_declaration : \"@keywords\" _g8", "n3_universal : \"@forAll\" _g6", "n3_existential : \"@forSome\" _g7", "n3_statement : n3_subject n3_propertylist", "_g8 : '.'", "_g8 : N3_BARENAME _g11", "_g6 : '.'", "_g6 : n3_symbol _g9", "_g7 : '.'", "_g7 : n3_symbol _g10", "n3_subject : n3_path", "n3_propertylist :", "n3_propertylist : n3_verb n3_object n3_objecttail n3_propertylisttail", "_g11 : '.'", "_g11 : ',' N3_BARENAME _g11", "n3_symbol : N3_EXPLICITURI", "n3_symbol : N3_QNAME", "_g9 : '.'", "_g9 : ',' n3_symbol _g9", "_g10 : '.'", "_g10 : ',' n3_symbol _g10", "n3_path : n3_node n3_pathtail", "n3_verb : n3_prop", "n3_verb : \"@has\" n3_prop", "n3_verb : \"@is\" n3_prop \"@of\"", "n3_verb : \"@a\"", "n3_verb : '='", "n3_verb : \"=>\"", "n3_verb : \"<=\"", "n3_object : n3_path", "n3_objecttail :", "n3_objecttail : ',' n3_object n3_objecttail", "n3_propertylisttail :", "n3_propertylisttail : ';' n3_verb n3_object n3_objecttail n3_propertylisttail", "n3_node : n3_symbol", "n3_node : '{' n3_formulacontent '}'", "n3_node : N3_VARIABLE", "n3_node : N3_NUMERICLITERAL", "n3_node : n3_literal", "n3_node : '[' n3_propertylist ']'", "n3_node : '(' n3_pathlist ')'", "n3_node : \"@this\"", "n3_pathtail :", "n3_pathtail : '!' n3_path", "n3_pathtail : '^' n3_path", "n3_prop : n3_node", "n3_formulacontent : _g3 _g4 _g5 n3_statementlist", "n3_literal : N3_STRING n3_dtlang", "n3_pathlist :", "n3_pathlist : n3_path n3_pathlist", "_g3 :", "_g3 : n3_declaration _g3", "_g4 :", "_g4 : n3_universal _g4", "_g5 :", "_g5 : n3_existential _g5", "n3_statementlist :", "n3_statementlist : n3_statement n3_statementtail", "n3_dtlang :", "n3_dtlang : '@' '1'", "n3_dtlang : \"^^\" n3_symbol", "n3_statementtail :", "n3_statementtail : '.' n3_statementlist", "eof :", }; #endif #ifndef YYSTYPE typedef int YYSTYPE; #endif #ifdef YYSTACKSIZE #undef YYMAXDEPTH #define YYMAXDEPTH YYSTACKSIZE #else #ifdef YYMAXDEPTH #define YYSTACKSIZE YYMAXDEPTH #else #define YYSTACKSIZE 10000 #define YYMAXDEPTH 10000 #endif #endif #define YYINITSTACKSIZE 200 int yydebug; int yynerrs; int yyerrflag; int yychar; short *yyssp; YYSTYPE *yyvsp; YYSTYPE yyval; YYSTYPE yylval; short *yyss; short *yysslim; YYSTYPE *yyvs; int yystacksize; /* allocate initial stack or double stack size, up to YYMAXDEPTH */ int yyparse __P((void)); static int yygrowstack __P((void)); static int yygrowstack() { int newsize, i; short *newss; YYSTYPE *newvs; if ((newsize = yystacksize) == 0) newsize = YYINITSTACKSIZE; else if (newsize >= YYMAXDEPTH) return -1; else if ((newsize *= 2) > YYMAXDEPTH) newsize = YYMAXDEPTH; i = yyssp - yyss; if ((newss = (short *)realloc(yyss, newsize * sizeof *newss)) == NULL) return -1; yyss = newss; yyssp = newss + i; if ((newvs = (YYSTYPE *)realloc(yyvs, newsize * sizeof *newvs)) == NULL) return -1; yyvs = newvs; yyvsp = newvs + i; yystacksize = newsize; yysslim = yyss + newsize - 1; return 0; } #define YYABORT goto yyabort #define YYREJECT goto yyabort #define YYACCEPT goto yyaccept #define YYERROR goto yyerrlab int yyparse() { int yym, yyn, yystate; #if YYDEBUG char *yys; if ((yys = getenv("YYDEBUG")) != NULL) { yyn = *yys; if (yyn >= '0' && yyn <= '9') yydebug = yyn - '0'; } #endif yynerrs = 0; yyerrflag = 0; yychar = (-1); if (yyss == NULL && yygrowstack()) goto yyoverflow; yyssp = yyss; yyvsp = yyvs; *yyssp = yystate = 0; yyloop: if ((yyn = yydefred[yystate]) != 0) goto yyreduce; if (yychar < 0) { if ((yychar = yylex()) < 0) yychar = 0; #if YYDEBUG if (yydebug) { yys = 0; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (!yys) yys = "illegal-symbol"; printf("%sdebug: state %d, reading %d (%s)\n", YYPREFIX, yystate, yychar, yys); } #endif } if ((yyn = yysindex[yystate]) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { #if YYDEBUG if (yydebug) printf("%sdebug: state %d, shifting to state %d\n", YYPREFIX, yystate, yytable[yyn]); #endif if (yyssp >= yysslim && yygrowstack()) { goto yyoverflow; } *++yyssp = yystate = yytable[yyn]; *++yyvsp = yylval; yychar = (-1); if (yyerrflag > 0) --yyerrflag; goto yyloop; } if ((yyn = yyrindex[yystate]) && (yyn += yychar) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yychar) { yyn = yytable[yyn]; goto yyreduce; } if (yyerrflag) goto yyinrecovery; goto yynewerror; yynewerror: yyerror("syntax error"); goto yyerrlab; yyerrlab: ++yynerrs; yyinrecovery: if (yyerrflag < 3) { yyerrflag = 3; for (;;) { if ((yyn = yysindex[*yyssp]) && (yyn += YYERRCODE) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) { #if YYDEBUG if (yydebug) printf("%sdebug: state %d, error recovery shifting\ to state %d\n", YYPREFIX, *yyssp, yytable[yyn]); #endif if (yyssp >= yysslim && yygrowstack()) { goto yyoverflow; } *++yyssp = yystate = yytable[yyn]; *++yyvsp = yylval; goto yyloop; } else { #if YYDEBUG if (yydebug) printf("%sdebug: error recovery discarding state %d\n", YYPREFIX, *yyssp); #endif if (yyssp <= yyss) goto yyabort; --yyssp; --yyvsp; } } } else { if (yychar == 0) goto yyabort; #if YYDEBUG if (yydebug) { yys = 0; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (!yys) yys = "illegal-symbol"; printf("%sdebug: state %d, error recovery discards token %d (%s)\n", YYPREFIX, yystate, yychar, yys); } #endif yychar = (-1); goto yyloop; } yyreduce: #if YYDEBUG if (yydebug) printf("%sdebug: state %d, reducing by rule %d (%s)\n", YYPREFIX, yystate, yyn, yyrule[yyn]); #endif yym = yylen[yyn]; yyval = yyvsp[1-yym]; switch (yyn) { } yyssp -= yym; yystate = *yyssp; yyvsp -= yym; yym = yylhs[yyn]; if (yystate == 0 && yym == 0) { #if YYDEBUG if (yydebug) printf("%sdebug: after reduction, shifting from state 0 to\ state %d\n", YYPREFIX, YYFINAL); #endif yystate = YYFINAL; *++yyssp = YYFINAL; *++yyvsp = yyval; if (yychar < 0) { if ((yychar = yylex()) < 0) yychar = 0; #if YYDEBUG if (yydebug) { yys = 0; if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; if (!yys) yys = "illegal-symbol"; printf("%sdebug: state %d, reading %d (%s)\n", YYPREFIX, YYFINAL, yychar, yys); } #endif } if (yychar == 0) goto yyaccept; goto yyloop; } if ((yyn = yygindex[yym]) && (yyn += yystate) >= 0 && yyn <= YYTABLESIZE && yycheck[yyn] == yystate) yystate = yytable[yyn]; else yystate = yydgoto[yym]; #if YYDEBUG if (yydebug) printf("%sdebug: after reduction, shifting from state %d \ to state %d\n", YYPREFIX, *yyssp, yystate); #endif if (yyssp >= yysslim && yygrowstack()) { goto yyoverflow; } *++yyssp = yystate; *++yyvsp = yyval; goto yyloop; yyoverflow: yyerror("yacc stack overflow"); yyabort: return (1); yyaccept: return (0); } cwm-1.2.1/grammar/n3-ql.n30000644015216600007660000001137710713412507014250 0ustar syosisyosi# Notation3 constrained to be RDF + a horn rules language # # BNF without tokenization # @prefix rdf: . @prefix rdfs: . @prefix bnf: . @prefix rul: . @prefix : . @prefix n3r: . @prefix list: . @prefix string: . @keywords a, is, of. # Issues: # - see general ones in n3.n3 # - Defining safe rules #<> bnf:syntaxFor [ bnf:internetMediaType # ]. # <> rdfsem:semanticsFor "" ..... # __________________________________________________________________ # # The N3 Full Grammar document a rul:Used; bnf:mustBeOneSequence( ( [ bnf:zeroOrMore declaration ] # [ bnf:zeroOrMore universal ] [ bnf:zeroOrMore existential ] statements_optional bnf:eof ) ). statements_optional bnf:mustBeOneSequence (() ( statement_or_rule "." statements_optional )). statement_or_rule bnf:mustBeOneSequence( (statement) (rule) ). # Formula does NOT need period on last statement formulacontent bnf:mustBeOneSequence (( [ bnf:zeroOrMore declaration ] [ bnf:zeroOrMore existential ] statementlist )). statementlist bnf:mustBeOneSequence ( ( ) ( statement statementtail ) ). statementtail bnf:mustBeOneSequence ( ( ) ( "." statementlist ) ). universal bnf:mustBeOneSequence ( ( "@forAll" [ bnf:commaSeparatedPeriodTerminatedListOf symbol ] )). existential bnf:mustBeOneSequence( ( "@forSome" [ bnf:commaSeparatedPeriodTerminatedListOf symbol ] )). symbol bnf:mustBeOneSequence ( (explicituri) (qname) ). declaration bnf:mustBeOneSequence( ( "@base" explicituri "." ) ( "@prefix" qname explicituri "." ) ( "@keywords" [ bnf:commaSeparatedPeriodTerminatedListOf barename ] ) ). statement bnf:mustBeOneSequence(( subject propertylist )). rule bnf:mustBeOneSequence ( ( "{" formulacontent "}" "=>" "{" formulacontent "}" ) ). rule_safe bnf:mustBeOneSequence ( ( "{" formulacontent "}" "=>" "{" formula_safe "}" ) ). propertylist bnf:mustBeOneSequence ( ( ) ( verb object objecttail propertylisttail ) ). propertylisttail bnf:mustBeOneSequence ( ( ) ( ";" propertylist ) ). objecttail bnf:mustBeOneSequence ( ( ) ( "," object objecttail ) ). verb bnf:mustBeOneSequence ( ( prop ) ( "@has" prop ) ( "@is" prop "@of" ) ( "@a" ) ( "=" ) ). prop bnf:mustBeOneSequence ((node)). subject bnf:mustBeOneSequence ((item)). object bnf:mustBeOneSequence ((item)). item bnf:mustBeOneSequence( (path) ). path bnf:mustBeOneSequence( ( node pathtail ) ). pathtail bnf:mustBeOneSequence( ( ) ( "!" path ) ( "^" path ) ). node bnf:mustBeOneSequence ( ( symbol ) ( variable ) ( numericliteral ) ( literal ) ( "[" propertylist "]" ) ( "(" itemlist ")" ) ). node_safe bnf:mustBeOneSequence ( ( symbol ) ( variable ) ( numericliteral ) ( literal ) ). itemlist bnf:mustBeOneSequence (() (item itemlist)). literal bnf:mustBeOneSequence(( string dtlang)). dtlang bnf:mustBeOneSequence( () ("@" langcode) ("^^" symbol)). #______________________________________________________________________ # # TOKENS alphanumeric bnf:matches "[a-zA-Z][a-zA-Z0-9_]*"; bnf:canStartWith "a". numericliteral bnf:matches """[-+]?[0-9]+(\\.[0-9]+)?(e[-+]?[0-9]+)?"""; bnf:canStartWith "0", "-", "+". explicituri bnf:matches "<[^>].*>"; bnf:canStartWith "<". qname bnf:matches "(([a-zA-Z_][a-zA-Z0-9_]*)?:)?([a-zA-Z_][a-zA-Z0-9_]*)?"; bnf:canStartWith "a", "_". # @@ etc barename bnf:matches "[a-zA-Z_][a-zA-Z0-9_]*"; # subset of qname bnf:canStartWith "a", "_". # @@ etc variable bnf:matches "\\?[a-zA-Z_][a-zA-Z0-9_]*"; # ? barename bnf:canStartWith "?". # langcode bnf:matches "[a-zA-Z0-9]+(-[a-zA-Z0-9]+)?"; bnf:canStartWith "a". string bnf:matches "(\"\"\"[^\"\\\\]*(?:(?:\\\\.|\"(?!\"\"))[^\"\\\\]*)*\"\"\")|(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")"; bnf:canStartWith "\"". #____________________________________________________ # Axioms reducing the shortcut BNF terms to bnf:musBeOneSequence. { ?x bnf:zeroOrMore ?y } => {?x bnf:mustBeOneSequence ( () (?y ?x) ) }. { ?x bnf:commaSeparatedPeriodTerminatedListOf ?y } => { ?x bnf:mustBeOneSequence ( ( "." ) ( "," ?y ?x ) ) }. # labelling of things which do not have explicit URIs: { ?x bnf:zeroOrMore [ bnf:label ?y]. ( ?y "_s" ) string:concatenation ?str } => { ?x bnf:label ?str }. { ?x bnf:commaSeparatedPeriodTerminatedListOf [ bnf:label ?y]. ( ?y "_csl" ) string:concatenation ?str } => { ?x bnf:label ?str }. #ends cwm-1.2.1/grammar/predictiveParser.py0000644015216600007660000004156610640075640016746 0ustar syosisyosi#! /usr/bin/python """Generic predictive parser for N3-like languages This is is a generic parser for a set of N3-like languages. It is directly driven by the context-free grammar (CFG) in RDF. It was made to mutually test the CFG against the test files. Options --parse=uri This is the document to be parsed. Optional. --as=uri This is the URI of the production as which the document is to be parsed. default: http://www.w3.org/2000/10/swap/grammar/n3#document --grammar=uri This is the RDF augmented grammar. Default is the as= production's URI with the hash stripped. --yacc=file If this is given a yacc format grammar will be generated and written to the given file. (Abbreviated options -p, -a, -g, -y) For example: cwm n3.n3 bnf-rules.n3 --think --purge --data > n3-selectors.n3 PYTHONPATH=$SWAP python predictiveParser.py --grammar=n3-selectors.n3 \ --as=http://www.w3.org/2000/10/swap/grammar/n3#document --parse=n3.n3 The parser is N3-specific only because of the built-in tokenizer. This program is or was http://www.w3.org/2000/10/swap/grammar/predictiveParser.py W3C open source licence. Enjoy. Tim BL """ __version__ = "$Id: predictiveParser.py,v 1.19 2007/06/26 02:36:16 syosi Exp $" # SWAP http://www.w3.org/2000/10/swap try: from swap import webAccess, uripath, llyn, myStore, term, diag from swap.myStore import load, Namespace from swap.term import Literal from swap.diag import progress, chatty_flag except ImportError: import webAccess, uripath, llyn, myStore, term, diag from myStore import load, Namespace from term import Literal from diag import progress, chatty_flag #diag.chatty_flag=0 # Standard python import sys, getopt from sys import exit, stderr from time import clock import re from codecs import utf_8_encode BNF = Namespace("http://www.w3.org/2000/10/swap/grammar/bnf#") RDF = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") REGEX = Namespace("http://www.w3.org/2000/10/swap/grammar/regex#") branchTable = {} tokenRegexps = {} def recordError(str): global errors errors.append(str) str2 = "##### ERROR: " + str return str2 def deColonise(s): t = "" for ch in s: if ch == ":": ch = "_" t = t + ch return t def toYacc(x, tokenRegexps): if isinstance(x, Literal): return "'" + str(x.value()) + "'" # @@@ Escaping if x in tokenRegexps: return deColonise(`x`).upper() return deColonise(`x`) def yaccConvert(yacc, top, tokenRegexps): "Convert the grammar to yacc format" global already, agenda, errors already = [] agenda = [] errors = [] for x in tokenRegexps: yacc.write("%%token %s\n" % toYacc(x, tokenRegexps)) yacc.write("\n") yacc.write("%%\n") yaccProduction(yacc, top, tokenRegexps) while agenda: x = agenda[0] agenda = agenda[1:] already.append(x) yaccProduction(yacc, x, tokenRegexps) yacc.write("eof: /* empty */; \n") yacc.write("%%\n") def yaccProduction(yacc, lhs, tokenRegexps): if lhs is BNF.void: if chatty_flag: progress( "\nvoid") return if lhs is BNF.eof: if chatty_flag: progress( "\nEOF") return if isinstance(lhs, Literal): literalTerminals[lhs.value()] = 1 # print "\nLiteral %s" %(lhs) return rhs = g.the(pred=BNF.matches, subj=lhs) if rhs != None: if chatty_flag: progress( "\nToken %s matches regexp %s" %(lhs, rhs)) # tokenRegexps[lhs] = re.compile(rhs.value()) return rhs = g.the(pred=BNF.mustBeOneSequence, subj=lhs) if rhs == None: progress( recordError("No definition of " + `lhs`)) raise ValueError("No definition of %s in\n %s" %(`lhs`, `g`)) options = rhs if chatty_flag: progress ("\nProduction %s :: %s ie %s" %(`lhs`, `options` , `options.value()`)) yacc.write("\n%s:" % toYacc(lhs, tokenRegexps)) branches = g.each(subj=lhs, pred=BNF.branch) first = 1 for branch in branches: if not first: yacc.write("\t|\t") first = 0 option = g.the(subj=branch, pred=BNF.sequence) if chatty_flag: progress( "\toption: "+`option.value()`) yacc.write("\t") if option.value() == [] and yacc: yacc.write(" /* empty */") for part in option: if part not in already and part not in agenda: agenda.append(part) yacc.write(" %s" % toYacc(part, tokenRegexps)) yacc.write("\n") yacc.write("\t;\n") ########################################## end of yacc converter literalTerminals = {} def doProduction(lhs): "Generate branch tables for one production" global branchTable if lhs is BNF.void: progress("\nvoid") return if lhs is BNF.eof: progress( "\nEOF") return if isinstance(lhs, Literal): literalTerminals[lhs.value()] = 1 return branchDict = {} rhs = g.the(pred=BNF.matches, subj=lhs) if rhs != None: if chatty_flag: progress( "\nToken %s matches regexp %s" %(lhs, rhs)) try: tokenRegexps[lhs] = re.compile(rhs.value(), re.U) except: print rhs.value().encode('utf-8') raise cc = g.each(subj=lhs, pred=BNF.canStartWith) if cc == []: progress (recordError( "No record of what token %s can start with" % `lhs`)) if chatty_flag: progress("\tCan start with: %s" % cc) return if g.contains(subj=lhs, pred=RDF.type, obj=REGEX.Regex): import regex rhs = regex.makeRegex(g, lhs) try: tokenRegexps[lhs] = re.compile(rhs, re.U) except: print rhs raise cc = g.each(subj=lhs, pred=BNF.canStartWith) if cc == []: progress (recordError( "No record of what token %s can start with" % `lhs`)) if chatty_flag: progress("\tCan start with: %s" % cc) return rhs = g.the(pred=BNF.mustBeOneSequence, subj=lhs) if rhs == None: progress (recordError("No definition of " + `lhs`)) return # raise RuntimeError("No definition of %s in\n %s" %(`lhs`, `g`)) options = rhs if chatty_flag: progress ( "\nProduction %s :: %s ie %s" %(`lhs`, `options` , `options.value()`)) succ = g.each(subj=lhs, pred=BNF.canPrecede) if chatty_flag: progress("\tCan precede ", succ) branches = g.each(subj=lhs, pred=BNF.branch) for branch in branches: option = g.the(subj=branch, pred=BNF.sequence) if chatty_flag: progress( "\toption: "+`option.value()`) for part in option: if part not in already and part not in agenda: agenda.append(part) y = `part` conditions = g.each(subj=branch, pred=BNF.condition) if conditions == []: progress( recordError(" NO SELECTOR for %s option %s ie %s" % (`lhs`, `option`, `option.value()` ))) if option.value == []: # Void case - the tricky one succ = g.each(subj=lhs, pred=BNF.canPrecede) for y in succ: if chatty_flag: progress("\t\t\tCan precede ", `y`) if chatty_flag: progress("\t\tConditions: %s" %(conditions)) for str1 in conditions: if str1 in branchDict: progress(recordError( "Conflict: %s is also the condition for %s" % ( str1, branchDict[str1].value()))) branchDict[str1.__str__()] = option # break for str1 in branchDict: for str2 in branchDict: s1 = unicode(str1) s2 = unicode(str2) # @@ check that selectors are distinct, not substrings if (s1.startswith(s2) or s2.startswith(s1)) and branchDict[str1] is not branchDict[str2]: progress("WARNING: for %s, %s indicates %s, but %s indicates %s" % ( lhs, s1, branchDict[str1], s2, branchDict[str2])) branchTable[lhs] = branchDict ######################### Parser based on the RDF Context-free grammar whiteSpace = re.compile(ur'[ \t]*((#[^\n]*)?\r?\n)?') singleCharacterSelectors = u"\t\r\n !\"#$%&'()*.,+/;<=>?[\\]^`{|}~" notQNameChars = singleCharacterSelectors + "@" # Assume anything else valid qname :-/ notNameChars = notQNameChars + ":" # Assume anything else valid name :-/ class PredictiveParser: """A parser for N3 or derived languages""" def __init__(parser, sink, top, branchTable, tokenRegexps, keywords = None): parser.sink = sink parser.top = top # Initial production for whole document parser.branchTable = branchTable parser.tokenRegexps = tokenRegexps parser.lineNumber = 1 parser.startOfLine = 0 # Offset in buffer parser.atMode = True if keywords: parser.keywords = keywords parser.atMode = False else: parser.keywords = [ "a", "is", "of", "this" ] #print parser.keywords parser.verb = 0 # Verbosity parser.keywordMode = 0 # In a keyword statement, adding keywords def countLines(parser, buffer, here): """Count lines since called last time Make sure we count all lines """ parser.lineNumber+= buffer[parser.startOfLine:here].count("\n") parser.startOfLine = here def token(parser, str, i): """The Tokenizer: returns (token type character, offset of token) Skips spaces. "0" means numeric "a" means alphanumeric """ while 1: m = whiteSpace.match(str, i) if m == None or m.end() == i: break i = m.end() parser.countLines(str, i) if i == len(str): return "", i # eof if parser.verb: progress( "%i) Looking at: ...%s$%s..." % ( parser.lineNumber, str[i-10:i],str[i:i+10])) for double in "=>", "<=", "^^": if double == str[i:i+2]: return double, i ch = str[i] if ch == ".": parser.keywordMode = 0 # hack if ch in singleCharacterSelectors: return ch, i if ch in "+-0123456789": return "0", i # Numeric j = i+1 if ch == "@": if i!=0 and whiteSpace.match(str[i-1]).end() == 0: return ch, i while str[j] not in notNameChars: j = j + 1 if str[i+1:j] == "keywords" : parser.keywords = [] # Special parser.keywordMode = 1 return str[i:j], i # keyword if ch == '"': #" return '"', i #" # Alphanumeric: keyword hacks while str[j] not in notQNameChars: j = j+1 word = str[i:j] if parser.keywordMode: parser.keywords.append(word) elif word in parser.keywords: if word == "keywords" : parser.keywords = [] # Special parser.keywordMode = 1 if parser.atMode: return "@" + word, i # implicit keyword return word, i return "a", i # qname, langcode, or barename def around(parser, str, here): "The line around the given point" sol = str.rfind("\n", 0, here) if sol <= 0: sol = 0 eol = str.find("\n", here) if eol <= 0: eol = len(str) return "On line %i at $ in: %s$%s" %(parser.lineNumber, str[sol:here], str[here:eol]) def parse(parser, str): tok, here = parser.token(str, 0) return parser.parseProduction(parser.top, str, tok, here) def parseProduction(parser, lhs, str, tok=None, here=0): "The parser itself." if tok == "": return tok, here # EOF lookupTable = parser.branchTable[lhs] rhs = lookupTable.get(tok, None) # Predict branch from token if rhs == None: progress("""Found %s when expecting some form of %s, \tsuch as %s\n\t%s""" % (tok, lhs, lookupTable.keys(), parser.around(str, here))) raise SyntaxError("""Found %s when expecting some form of %s, \tsuch as %s\n\t%s""" % (tok, lhs, lookupTable.keys(), parser.around(str, here))) if parser.verb: progress( "%i %s means expand %s as %s" %(parser.lineNumber,tok, lhs, rhs.value())) for term in rhs: if isinstance(term, Literal): # CFG Terminal lit = term.value() next = here + len(lit) if str[here:next] == lit: pass elif "@"+str[here:next-1] == lit: next = next-1 else: raise SyntaxError( "Found %s where %s expected\n\t %s" % (`str[here:next]`, lit, parser.around(str, here))) else: rexp = tokenRegexps.get(term, None) if rexp == None: # Not token tok, here = parser.parseProduction(term, str, tok, here) continue m = rexp.match(str, here) if m == None: progress("\n\n\nToken: should match %s\n\t %s" % (rexp.pattern, parser.around(str, here))) raise SyntaxError("Token: should match %s\n\t %s" % (rexp.pattern, parser.around(str, here))) if parser.verb: progress( "Token matched to <%s> as pattern <%s>" % (str[here:m.end()], rexp.pattern)) next = m.end() tok, here = parser.token(str, next) # Next token return tok, here ############################### def _test(): import doctest, predictiveParser doctest.testmod(uripath) def usage(): sys.stderr.write(__doc__) ############################### Program def main(): global already, agenda, errors parseAs = None grammarFile = None parseFile = None yaccFile = None global verbose global g verbose = 0 lumped = 1 try: opts, args = getopt.getopt(sys.argv[1:], "ha:v:p:g:y:", ["help", "as=", "verbose=", "parse=", "grammar=", "yacc="]) except getopt.GetoptError: usage() sys.exit(2) output = None for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() if o in ("-v", "--verbose"): verbose =int(a) diag.chatty_flag = int(a) if o in ("-a", "--as"): parseAs = uripath.join(uripath.base(), a) if o in ("-p", "--parse"): parseFile = uripath.join(uripath.base(), a) if o in ("-g", "--grammar"): grammarFile = uripath.join(uripath.base(), a) if o in ("-y", "--yacc"): yaccFile = uripath.join(uripath.base(), a)[5:] # strip off file: # if testFiles == []: testFiles = [ "/dev/stdin" ] if not parseAs: usage() sys.exit(2) parseAs = uripath.join(uripath.base(), parseAs) if not grammarFile: grammarFile = parseAs.split("#")[0] # strip off fragid else: grammarFile = uripath.join(uripath.base(), grammarFile) # The Grammar formula progress("Loading " + grammarFile) start = clock() g = load(grammarFile) taken = clock() - start + 1 progress("Loaded %i statements in %fs, ie %f/s." % (len(g), taken, len(g)/taken)) document = g.newSymbol(parseAs) already = [] agenda = [] errors = [] doProduction(document) while agenda: x = agenda[0] agenda = agenda[1:] already.append(x) doProduction(x) if errors != []: progress("###### FAILED with %i errors." % len(errors)) for s in errors: progress ("\t%s" % s) exit(-2) else: progress( "Ok for predictive parsing") #if parser.verb: progress "Branch table:", branchTable if verbose: progress( "Literal terminals: %s" % literalTerminals.keys()) progress("Token regular expressions:") for r in tokenRegexps: progress( "\t%s matches %s" %(r, tokenRegexps[r].pattern) ) if yaccFile: yacc=open(yaccFile, "w") yaccConvert(yacc, document, tokenRegexps) yacc.close() if parseFile == None: exit(0) ip = webAccess.urlopenForRDF(parseFile, None) str = ip.read().decode('utf_8') sink = g.newFormula() keywords = g.each(pred=BNF.keywords, subj=document) keywords = [a.value() for a in keywords] p = PredictiveParser(sink=sink, top=document, branchTable= branchTable, tokenRegexps= tokenRegexps, keywords = keywords) p.verb = verbose start = clock() p.parse(str) taken = clock() - start + 1 progress("Loaded %i chars in %fs, ie %f/s." % (len(str), taken, len(str)/taken)) progress("Parsed <%s> OK" % parseFile) sys.exit(0) # didn't crash ########################################################################### if __name__ == "__main__": main() #ends cwm-1.2.1/grammar/n3.n30000644015216600007660000002247010713412507013632 0ustar syosisyosi# Notation3 in Notation3 # Context Free Grammar without tokenization # @prefix rdf: . @prefix rdfs: . @prefix cfg: . @prefix rul: . @prefix : . @prefix n3: . @prefix list: . @prefix string: . @keywords a, is, of. # Issues: # - string token regexp not right FIXED # - tokenizing rules in general: whitespace are not defined in n3.n3 # and it would be nice for the *entire* syntax description to be in RDF. # - encoding really needs specifying # - @keywords affects tokenizing # - comments (tokenizer deals with) # - We assume ASCII, in fact should use not notNameChars for i18n # tokenizing: # Absorb anything until end of regexp, then stil white space # period followed IMMEDIATELY by an opener or name char is taken as "!". # Except after a "." used instead of in those circumstances, # ws may be inserted between tokens. # WS MUST be inserted between tokens where ambiguity would arise. # (possible ending characters of one and beginning characters overlap) # <> cfg:syntaxFor [ cfg:internetMediaType ]. # <> rdfsem:semanticsFor "" ..... # __________________________________________________________________ # # The N3 Full Grammar language a cfg:Language; cfg:document document; cfg:whiteSpace "@@@@@". document a rul:Used; cfg:mustBeOneSequence( ( # [ cfg:zeroOrMore declaration ] # [ cfg:zeroOrMore universal ] # [ cfg:zeroOrMore existential ] statements_optional cfg:eof ) ). statements_optional cfg:mustBeOneSequence (() ( statement "." statements_optional ) ). # Formula does NOT need period on last statement formulacontent cfg:mustBeOneSequence ( ( statementlist ) ). statementlist cfg:mustBeOneSequence ( ( ) ( statement statementtail ) ). statementtail cfg:mustBeOneSequence ( ( ) ( "." statementlist ) ). statement cfg:mustBeOneSequence ( (declaration) (universal) (existential) (simpleStatement) ). universal cfg:mustBeOneSequence ( ( "@forAll" [ cfg:commaSeparatedListOf symbol ] )). existential cfg:mustBeOneSequence( ( "@forSome" [ cfg:commaSeparatedListOf symbol ] )). declaration cfg:mustBeOneSequence( ( "@base" explicituri ) ( "@prefix" prefix explicituri ) ( "@keywords" [ cfg:commaSeparatedListOf barename ] ) ). simpleStatement cfg:mustBeOneSequence(( subject propertylist )). propertylist cfg:mustBeOneSequence ( ( ) ( verb object objecttail propertylisttail ) ). propertylisttail cfg:mustBeOneSequence ( ( ) ( ";" propertylist ) ). objecttail cfg:mustBeOneSequence ( ( ) ( "," object objecttail ) ). verb cfg:mustBeOneSequence ( ( expression ) ( "@has" expression ) ( "@is" expression "@of" ) ( "@a" ) ( "=" ) ( "=>" ) ( "<=" ) ). subject cfg:mustBeOneSequence ((expression)). object cfg:mustBeOneSequence ((expression)). expression cfg:mustBeOneSequence( ( pathitem pathtail ) ). pathtail cfg:mustBeOneSequence( ( ) ( "!" expression ) ( "^" expression ) ). pathitem cfg:mustBeOneSequence ( ( symbol ) ( "{" formulacontent "}" ) ( quickvariable ) ( numericliteral ) ( literal ) ( "[" propertylist "]" ) ( "(" pathlist ")" ) ( boolean ) # ( "@this" ) # Deprocated. Was allowed for this log:forAll x ). boolean cfg:mustBeOneSequence ( ( "@true" ) ( "@false" ) ) . pathlist cfg:mustBeOneSequence (() (expression pathlist)). symbol cfg:mustBeOneSequence ( (explicituri) (qname) ). numericliteral cfg:mustBeOneSequence ( ( integer ) ( double ) ( decimal ) ) . literal cfg:mustBeOneSequence(( string dtlang)). dtlang cfg:mustBeOneSequence( () ("@" langcode) ("^^" symbol)). #______________________________________________________________________ # # TERMINALS # # "canStartWith" actually gives "a" for the whole class of alpha characters # and "0" for any of the digits 0-9. This is used to build the branching # tables. # integer cfg:matches """[-+]?[0-9]+"""; cfg:canStartWith "0", "-", "+". double cfg:matches """[-+]?[0-9]+(\\.[0-9]+)?([eE][-+]?[0-9]+)"""; cfg:canStartWith "0", "-", "+". decimal cfg:matches """[-+]?[0-9]+(\\.[0-9]+)?"""; cfg:canStartWith "0", "-", "+". #numericliteral cfg:matches """[-+]?[0-9]+(\\.[0-9]+)?(e[-+]?[0-9]+)?"""; # cfg:canStartWith "0", "-", "+". explicituri cfg:matches "<[^>]*>"; cfg:canStartWith "<". prefix cfg:matches "([A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][\\-0-9A-Z_a-z\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*)?:"; cfg:canStartWith "a", "_", ":". # @@ etc unicode qname cfg:matches "(([A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][\\-0-9A-Z_a-z\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*)?:)?[A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][\\-0-9A-Z_a-z\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*"; cfg:canStartWith "a", "_", ":". # @@ etc unicode # ASCII version: #barename cfg:matches "[a-zA-Z_][a-zA-Z0-9_]*"; # subset of qname # cfg:canStartWith "a", "_". # @@ etc # This is the XML1.1 barename cfg:matches "[A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][\\-0-9A-Z_a-z\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*"; cfg:canStartWith "a", "_". # @@ etc . # as far as I can tell, the regexp should be # barename cfg:matches "[A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][\\-0-9A-Z_a-z\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*" . # quickvariable cfg:matches "\\?[A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff][\\-0-9A-Z_a-z\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd\U00010000-\U000effff]*"; # ? barename cfg:canStartWith "?". # # Maybe dtlang should just be part of string regexp? # Whitespace is not allowed # was: "[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)?"; langcode cfg:matches "[a-z]+(-[a-z0-9]+)*"; # http://www.w3.org/TR/rdf-testcases/#language cfg:canStartWith "a". # raw regexp single quoted would be "([^"]|(\\"))*" # See: # $ PYTHONPATH=$SWAP python # >>> import tokenize # >>> import notation3 # >>> print notation3.stringToN3(tokenize.Double3) # "[^\"\\\\]*(?:(?:\\\\.|\"(?!\"\"))[^\"\\\\]*)*\"\"\"" # >>> print notation3.stringToN3(tokenize.Double) # "[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"" # After that we have to prefix with one or three opening \" which # the python regexp doesn't have them. # # string3 cfg:matches "\"\"\"[^\"\\\\]*(?:(?:\\\\.|\"(?!\"\"))[^\"\\\\]*)*\"\"\"". # string1 cfg:matches "\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"". string cfg:matches "(\"\"\"[^\"\\\\]*(?:(?:\\\\.|\"(?!\"\"))[^\"\\\\]*)*\"\"\")|(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")"; cfg:canStartWith "\"". #____________________________________________________ # Axioms reducing the shortcut CFG terms to cfg:musBeOneSequence. { ?x cfg:zeroOrMore ?y } => {?x cfg:mustBeOneSequence ( () (?y ?x) ) }. { ?x cfg:commaSeparatedPeriodTerminatedListOf ?y } => { ?x cfg:mustBeOneSequence ( ( "." ) ( ?y [cfg:CSLTail ?y] ) ) }. { ?x cfg:CSLTail ?y } => { ?x cfg:mustBeOneSequence ( ( "." ) ( "," ?y ?x ) ) }. # Without the period { ?x cfg:commaSeparatedListOf ?y } => { ?x cfg:mustBeOneSequence ( ( ) ( ?y [cfg:CSLTail2 ?y] ) ) }. { ?x cfg:CSLTail2 ?y } => { ?x cfg:mustBeOneSequence ( ( ) ( "," ?y ?x ) ) }. # labelling of things which do not have explicit URIs: { ?x cfg:zeroOrMore [ cfg:label ?y]. ( ?y "_s" ) string:concatenation ?str } => { ?x cfg:label ?str }. { ?x cfg:commaSeparatedPeriodTerminatedListOf [ cfg:label ?y]. ( ?y "_csl" ) string:concatenation ?str } => { ?x cfg:label ?str }. { ?x cfg:CSLTail [ cfg:label ?y]. ( ?y "_necsl" ) string:concatenation ?str } => { ?x cfg:label ?str }. #ends cwm-1.2.1/grammar/bnf-rules.n30000644015216600007660000000641510303444673015214 0ustar syosisyosi# # Baccus - Naur Form (BNF) vocabulary # @prefix rdf: . @prefix rdfs: . @prefix bnf: . @prefix : . @prefix rul: . @prefix n3: . @prefix list: . @prefix doc: . @prefix log: . @prefix string: . @keywords a, is, of. #_____________________________________ # Shorthand expansion into BNF #{ ?x bnf:zeroOrMore ?y } => { # ?x bnf:mustBeOneSequence ( ## ( ) # ( ?y ?x ) # ) #}. # #{ ?x bnf:mustBe ?y } => {?x bnf:mustBeOneSequence ((?y))}. # # Axioms relating the definite (open world) form to the indefinte (closed world) #(better words?) form: # #{ ?x bnf:mustBe ?y } => { ?x bnf:mustBeOneSequence (( ?y )) }. # # Enumerate options: { ?x bnf:mustBeOneSequence ?y} => { ?x optionTail ?y }. {?x optionTail [rdf:first ?y; rdf:rest ?z]} => { ?x bnf:branch [ bnf:sequence ?y]; optionTail ?z. }. { ?x bnf:branch [bnf:sequence ?y] } => { ?y sequenceTail ?y }. sequenceTail a log:Chaff. optionTail a log:Chaff. { ?x sequenceTail [ rdf:rest ?z ] } => { ?x sequenceTail ?z }. # What productions can follow each other? # This is used for working out when to { ?x sequenceTail [ rdf:first ?y; rdf:rest [ rdf:first ?z ]] } => { ?y bnf:canPrecede ?z }. { ?x bnf:branch [ bnf:sequence [ list:last ?y]]. ?x bnf:canPrecede ?z} => { ?y bnf:canPrecede ?z }. { ?x bnf:canPrecede ?y. ?y bnf:branch [ bnf:sequence () ]. ?y bnf:canPrecede ?z. } => { ?x bnf:canPrecede ?z. }. bnf:eof bnf:canStartWith "@EOFDUMMY". # @@ kludge # Have to separate the next three rules or cwm seems to # get screwed up and assume there is no solution @@@ { ?x bnf:branch [bnf:sequence [ rdf:first ?y ]]. } => { ?x bnf:TEST ?y }. { ?x bnf:TEST ?y . ?y log:rawType log:Literal. } => { ?x bnf:canStartWithLiteral ?y }. { ?x bnf:canStartWithLiteral ?y . # (?y "(.).*") string:scrape ?c # Use whole string } => { ?y bnf:canStartWith ?y }. #______________________________________________________________ # Rules for determining branching # A branch has a sequence, which is the given BNF production, and # one or more conditions, which are the strings on which to consider # that branch. N3 is a langauge in whch the look-ahead often is only # one character, and may allways be a constsnt string rather than a # regexp (check). # A branchTail is a sequnece which a branch could start with { ?x bnf:branch ?b. ?b bnf:sequence ?s. } => { ?b bnf:branchTail ?s. }. { ?b bnf:branchTail ?s. ?s rdf:first [ bnf:branch [ bnf:sequence () ]]; rdf:rest ?t } => { ?b bnf:branchTail ?t. }. { ?x bnf:branch ?b. ?b bnf:branchTail ?s. ?s rdf:first [bnf:canStartWith ?y]. } => { ?x bnf:canStartWith ?y. ?b bnf:condition ?y. }. { ?x bnf:branch ?b; bnf:canPrecede ?z. ?z log:rawType log:Literal. ?b bnf:sequence (). } => { ?b bnf:condition ?z}. { ?x bnf:branch ?b; bnf:canPrecede [bnf:canStartWith ?z]. ?b bnf:sequence (). } => { ?b bnf:condition ?z}. #ends cwm-1.2.1/cwm_sparql.html0000644015216600007660000040532310717717525014476 0ustar syosisyosi Python: module cwm_sparql
 
 
cwm_sparql
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/cwm_sparql.py

Builtins for doing SPARQL queries in CWM
 
$Id: cwm_sparql.py,v 1.22 2007/11/18 02:01:56 syosi Exp $

 
Modules
       
diag
uripath

 
Classes
       
swap.term.Function(swap.term.BuiltIn)
BI_dtLit(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)
BI_equals(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)
BI_langLit(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)
BI_query(swap.term.LightBuiltIn, swap.term.Function)
BI_semantics(swap.term.HeavyBuiltIn, swap.term.Function)
BI_typeErrorReturner(swap.term.LightBuiltIn, swap.term.Function)
swap.term.HeavyBuiltIn(swap.term.GenericBuiltIn)
BI_lamePred(swap.term.HeavyBuiltIn, swap.term.MultipleReverseFunction)
BI_semantics(swap.term.HeavyBuiltIn, swap.term.Function)
swap.term.LightBuiltIn(swap.term.GenericBuiltIn)
BI_dtLit(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)
BI_equals(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)
BI_greaterThan
BI_langLit(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)
BI_lessThan
BI_notEquals
BI_notGreaterThan
BI_notLessThan
BI_query(swap.term.LightBuiltIn, swap.term.Function)
BI_truthValue
BI_typeErrorIsTrue
BI_typeErrorReturner(swap.term.LightBuiltIn, swap.term.Function)
swap.term.MultipleReverseFunction(swap.term.ReverseFunction)
BI_lamePred(swap.term.HeavyBuiltIn, swap.term.MultipleReverseFunction)
swap.term.ReverseFunction(swap.term.BuiltIn)
BI_dtLit(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)
BI_equals(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)
BI_langLit(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)

 
class BI_dtLit(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)
    
Method resolution order:
BI_dtLit
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.Function
swap.term.ReverseFunction
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from swap.term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_equals(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)
    
Method resolution order:
BI_equals
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.Function
swap.term.ReverseFunction
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_greaterThan(swap.term.LightBuiltIn)
    
Method resolution order:
BI_greaterThan
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
evaluate(self, subject, object)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from swap.term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_lamePred(swap.term.HeavyBuiltIn, swap.term.MultipleReverseFunction)
    
Method resolution order:
BI_lamePred
swap.term.HeavyBuiltIn
swap.term.GenericBuiltIn
swap.term.MultipleReverseFunction
swap.term.ReverseFunction
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from swap.term.MultipleReverseFunction:
evalObj(self, subj, queue, bindings, proof, query)

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_langLit(swap.term.LightBuiltIn, swap.term.Function, swap.term.ReverseFunction)
    
Method resolution order:
BI_langLit
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.Function
swap.term.ReverseFunction
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from swap.term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_lessThan(swap.term.LightBuiltIn)
    
Method resolution order:
BI_lessThan
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
evaluate(self, subject, object)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from swap.term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notEquals(swap.term.LightBuiltIn)
    
Method resolution order:
BI_notEquals
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notGreaterThan(swap.term.LightBuiltIn)
    
Method resolution order:
BI_notGreaterThan
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
evaluate(self, subject, object)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from swap.term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_notLessThan(swap.term.LightBuiltIn)
    
Method resolution order:
BI_notLessThan
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
evaluate(self, subject, object)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from swap.term.BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_query(swap.term.LightBuiltIn, swap.term.Function)
    
Method resolution order:
BI_query
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.Function
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from swap.term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_semantics(swap.term.HeavyBuiltIn, swap.term.Function)
    The semantics of a resource are its machine-readable meaning, as an
N3 forumula.  The URI is used to find a represnetation of the resource in bits
which is then parsed according to its content type.
 
 
Method resolution order:
BI_semantics
swap.term.HeavyBuiltIn
swap.term.GenericBuiltIn
swap.term.Function
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from swap.term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_truthValue(swap.term.LightBuiltIn)
    
Method resolution order:
BI_truthValue
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_typeErrorIsTrue(swap.term.LightBuiltIn)
    Subject is anything (must be bound. 1 works well)
Object is a formula containing the test as its only triple
 
 
Method resolution order:
BI_typeErrorIsTrue
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_typeErrorReturner(swap.term.LightBuiltIn, swap.term.Function)
    
Method resolution order:
BI_typeErrorReturner
swap.term.LightBuiltIn
swap.term.GenericBuiltIn
swap.term.Function
swap.term.BuiltIn
swap.term.Fragment
swap.term.LabelledNode
swap.term.Node
swap.term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from swap.term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from swap.term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from swap.term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from swap.term.BuiltIn:
all = []

Methods inherited from swap.term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from swap.term.LabelledNode:
classOrder(self)

Methods inherited from swap.term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from swap.term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
Functions
       
bnode_replace(self, string) method of __builtin__.dict instance
outputString(q, F)
register(store)
sparql_output(query, F)
sparql_queryString(source, queryString)

 
Data
        SPARQL_NS = 'http://www.w3.org/2000/10/swap/sparqlCwm'
typeMap = {'ENTITIES': <type 'unicode'>, 'ENTITY': <type 'unicode'>, 'ID': <type 'unicode'>, 'IDREF': <type 'unicode'>, 'IDREFS': <type 'unicode'>, 'NCNAME': <type 'unicode'>, 'NMTOKEN': <type 'unicode'>, 'NMTOKENS': <type 'unicode'>, 'NOTATION': <type 'unicode'>, 'Name': <type 'unicode'>, ...}
cwm-1.2.1/xml2infoset.html0000644015216600007660000004454207731146611014574 0ustar syosisyosi Python: module xml2infoset
 
 
xml2infoset
index
/devel/WWW/2000/10/swap/xml2infoset.py

#   A parser for XML built on the xmllib XML parser.
#   Hacked down from Dan Connolly's RDF parser which is much more complicated!
#   To do:
#         Option of ordered listing with daml list of children  and/or attrs!!
#         Option of replacing ln and ns with rdf:type ns#e_ln and ns#a_ln - see TAG issue (6?)
#         maybe think about some real connection to XPath or infoset models and vocabulary

 
Modules
            
notation3
string
urllib
urlparse
xmllib
 
Classes
            
xmllib.XMLParser
RDFXMLParser
 
class RDFXMLParser(xmllib.XMLParser)
       
   Methods defined here:
__init__(self, sink, thisURI, **kw)
_generate(self, str='')
The string is just a debugging hint really
close(self)
flush(self)
handle_cdata(self, data)
handle_comment(self, data)
handle_data(self, data)
handle_doctype(self, tag, pubid, syslit, data)
handle_proc(self, name, data)
handle_xml(self, encoding, standalone)
load(self, uri, _baseURI='')
pso(self, pred, subj, obj)
psv(self, pred, subj, obj)
syntax_error(self, message)
tag2uri(self, str)
 Generate URI from tagname
unknown_charref(self, ref)
unknown_endtag(self, tag)
unknown_entityref(self, ref)
unknown_starttag(self, tag, attrs)
 Handle start tag. We register none so all are unknown
uriref(self, str)
 Generate uri from uriref in this document

Data and non-method functions defined here:
__doc__ = None
__module__ = 'xml2infoset'
str(object) -> string
 
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.

Methods inherited from xmllib.XMLParser:
_XMLParser__fixclass = __fixclass(self, kl)
_XMLParser__fixdict = __fixdict(self, dict)
_XMLParser__fixelements = __fixelements(self)
feed(self, data)
# Interface -- feed some data to the parser.  Call this as
# often as you want, with as little or as much text as you
# want (may include '\n').  (This just saves the text, all the
# processing is done by goahead().)
finish_endtag(self, tag)
# Internal -- finish processing of end tag
finish_starttag(self, tagname, attrdict, method)
# Internal -- finish processing of start tag
goahead(self, end)
# Internal -- handle data as far as reasonable.  May leave state
# and data to be processed by a subsequent call.  If 'end' is
# true, force handling all data as if followed by EOF marker.
handle_charref(self, name)
# Example -- handle character reference, no need to override
handle_endtag(self, tag, method)
# Overridable -- handle end tag
handle_starttag(self, tag, method, attrs)
# Overridable -- handle start tag
parse_attributes(self, tag, i, j)
# Internal -- parse attributes between i and j
parse_cdata(self, i)
# Internal -- handle CDATA tag, return length or -1 if not terminated
parse_comment(self, i)
# Internal -- parse comment, return length or -1 if not terminated
parse_doctype(self, res)
# Internal -- handle DOCTYPE tag, return length or -1 if not terminated
parse_endtag(self, i)
# Internal -- parse endtag
parse_proc(self, i)
# Internal -- handle a processing instruction tag
parse_starttag(self, i)
# Internal -- handle starttag, return length or -1 if not terminated
reset(self)
# Interface -- reset this instance.  Loses all unprocessed data
setliteral(self, *args)
# For derived classes only -- enter literal mode (CDATA)
setnomoretags(self)
# For derived classes only -- enter literal mode (CDATA) till EOF
translate_references(self, data, all=1)
# Interface -- translate references

Data and non-method functions inherited from xmllib.XMLParser:
_XMLParser__accept_missing_endtag_name = 0
int(x[, base]) -> integer
 
Convert a string or number to an integer, if possible.  A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!)  When converting a string, use
the optional base.  It is an error to supply a base when converting a
non-string.
_XMLParser__accept_unquoted_attributes = 0
int(x[, base]) -> integer
 
Convert a string or number to an integer, if possible.  A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!)  When converting a string, use
the optional base.  It is an error to supply a base when converting a
non-string.
_XMLParser__accept_utf8 = 0
int(x[, base]) -> integer
 
Convert a string or number to an integer, if possible.  A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!)  When converting a string, use
the optional base.  It is an error to supply a base when converting a
non-string.
_XMLParser__map_case = 0
int(x[, base]) -> integer
 
Convert a string or number to an integer, if possible.  A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!)  When converting a string, use
the optional base.  It is an error to supply a base when converting a
non-string.
_XMLParser__xml_namespace_attributes = {'ns': None, 'prefix': None, 'src': None}
dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
    (key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
    d = {}
    for k, v in seq:
        d[k] = v
attributes = {}
dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
    (key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
    d = {}
    for k, v in seq:
        d[k] = v
elements = {}
dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
    (key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
    d = {}
    for k, v in seq:
        d[k] = v
entitydefs = {'amp': '&#38;', 'apos': '&#39;', 'gt': '&#62;', 'lt': '&#60;', 'quot': '&#34;'}
dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
    (key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
    d = {}
    for k, v in seq:
        d[k] = v
 
Functions
            
test(args=None)
 
Data
             DAML_ONT_NS = 'http://www.daml.org/2000/10/daml-ont#'
DPO_NS = 'http://www.daml.org/2001/03/daml+oil#'
LITERAL = 2
List_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
NS = 'http://www.w3.org/2000/10/swap/xml#'
RDF_IS = (0, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#is')
RDF_NS_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
RDF_Specification = 'http://www.w3.org/TR/REC-rdf-syntax/'
STATE_DESCRIPTION = 'Description (have subject)'
STATE_LIST = 'within list'
STATE_LITERAL = 'within literal'
STATE_NOT_RDF = 'not RDF'
STATE_NOVALUE = 'no value'
STATE_NO_SUBJECT = 'no context'
STATE_VALUE = 'plain value'
SYMBOL = 0
__file__ = './xml2infoset.py'
__name__ = 'xml2infoset'
chatty = 0
cwm-1.2.1/PKG-INFO0000644015216600007660000000035110731073450012511 0ustar syosisyosiMetadata-Version: 1.0 Name: cwm Version: 1.2.0 Summary: Semantic Web Area for Play Home-page: http://www.w3.org/2000/10/swap/ Author: Tim Berners-Lee Author-email: timbl@w3.org License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN cwm-1.2.1/term.html0000644015216600007660000100565010731070065013260 0ustar syosisyosi Python: module term
 
 
term
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/term.py

$Id: term.py,v 1.79 2007/11/18 03:45:22 syosi Exp $
 
term
 
This module defines objects correspodning to the basic terms in the RDF
and N3 langauges: Symbols, Literals and Lists.  (The N3 language goes on to
include formuale, which are defined elsewhere)
 
The code in this module deals with the represnetation of these terms and
in debug form (__repr__)
 
Interning of URIs and strings for storage in SWAP store.
 
It also defines th utility Namespace module which makes
using terms in practice both more convenient maybe even
more efficient than carrying full URIs around.
 
Includes:
 - template classes for builtins

 
Modules
       
binascii
diag
md5
string
sys
types
uripath

 
Classes
       
__builtin__.dict(__builtin__.object)
Env
__builtin__.frozenset(__builtin__.object)
N3Set(__builtin__.frozenset, CompoundTerm)
__builtin__.object
ListView
Term
CompoundTerm
List
EmptyList
FragmentNil(EmptyList, Fragment)
NonEmptyList
N3Set(__builtin__.frozenset, CompoundTerm)
ErrorFlag(exceptions.TypeError, Term)
Existential
SkolemFunction
Literal
XMLLiteral
Node
AnonymousNode
AnonymousVariable
AnonymousExistential(AnonymousVariable, Existential)
AnonymousUniversal(AnonymousVariable, Universal)
LabelledNode
Fragment
BuiltIn
Function
MultipleFunction
GenericBuiltIn
FiniteProperty(GenericBuiltIn, Function, ReverseFunction)
HeavyBuiltIn
LightBuiltIn
RDFBuiltIn
ReverseFunction
MultipleReverseFunction
Symbol
Universal
exceptions.TypeError(exceptions.StandardError)
ArgumentNotLiteral
ErrorFlag(exceptions.TypeError, Term)
exceptions.ValueError(exceptions.StandardError)
UnknownType

 
class AnonymousExistential(AnonymousVariable, Existential)
    An anonymous node which is existentially quantified in a given context.
Also known as a Blank Node, or "bnode" in RDF parlance.
 
 
Method resolution order:
AnonymousExistential
AnonymousVariable
AnonymousNode
Node
Existential
Term
__builtin__.object

Methods defined here:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.

Methods inherited from AnonymousVariable:
__init__(self, scope, uri=None)

Methods inherited from AnonymousNode:
asPair(self)
classOrder(self)
Anonymous ndoes are higher than symbols as the = smushing
tries to minimize the order rank of the node which it adopts
as the epresentative node of an equivalence class.
compareTerm(self, other)
Assume is also a Formula - see function compareTerm below
freeVariables(self)
generated(self)
uriref(self)

Methods inherited from Term:
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class AnonymousNode(Node)
    Has no real URI except when needed for output.
Goal is to eliminate use of ths URI in the code.
The URI is however useful as a diagnostic, so we carry it
when it is given.   It is NOT checked for uniqueness etc.
This is a superclass of many things, including AnonymousExistential,
which has a scope.
 
 
Method resolution order:
AnonymousNode
Node
Term
__builtin__.object

Methods defined here:
__init__(self, store, uri=None)
asPair(self)
classOrder(self)
Anonymous ndoes are higher than symbols as the = smushing
tries to minimize the order rank of the node which it adopts
as the epresentative node of an equivalence class.
compareTerm(self, other)
Assume is also a Formula - see function compareTerm below
freeVariables(self)
generated(self)
uriref(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class AnonymousUniversal(AnonymousVariable, Universal)
    Nodes which are introduced as universally quantified variables with
no quotable URI
 
 
Method resolution order:
AnonymousUniversal
AnonymousVariable
AnonymousNode
Node
Universal
Term
__builtin__.object

Methods defined here:
__init__(self, scope, uri=None)
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)

Methods inherited from AnonymousNode:
classOrder(self)
Anonymous ndoes are higher than symbols as the = smushing
tries to minimize the order rank of the node which it adopts
as the epresentative node of an equivalence class.
compareTerm(self, other)
Assume is also a Formula - see function compareTerm below
freeVariables(self)
generated(self)
uriref(self)

Methods inherited from Term:
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class AnonymousVariable(AnonymousNode)
    An anonymous node which is existentially quantified in a given context.
Also known as a Blank Node, or "bnode" in RDF parlance.
 
 
Method resolution order:
AnonymousVariable
AnonymousNode
Node
Term
__builtin__.object

Methods defined here:
__init__(self, scope, uri=None)

Methods inherited from AnonymousNode:
asPair(self)
classOrder(self)
Anonymous ndoes are higher than symbols as the = smushing
tries to minimize the order rank of the node which it adopts
as the epresentative node of an equivalence class.
compareTerm(self, other)
Assume is also a Formula - see function compareTerm below
freeVariables(self)
generated(self)
uriref(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class ArgumentNotLiteral(exceptions.TypeError)
    
Method resolution order:
ArgumentNotLiteral
exceptions.TypeError
exceptions.StandardError
exceptions.Exception

Methods inherited from exceptions.Exception:
__getitem__(...)
__init__(...)
__str__(...)

 
class BuiltIn(Fragment)
    This class is a supercalss to any builtin predicate in cwm.
 
A binary operator can calculate truth value given 2 arguments
 
 
Method resolution order:
BuiltIn
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods defined here:
__init__(self, resource, fragid)
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods defined here:
__new__(cls, *args, **keywords)

Data and other attributes defined here:
all = []

Methods inherited from Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class CompoundTerm(Term)
    A compound term has occurrences of terms within it.
Examples: List, Formula
 
 
Method resolution order:
CompoundTerm
Term
__builtin__.object

Methods inherited from Term:
__init__(self, store)
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class EmptyList(List)
    
Method resolution order:
EmptyList
List
CompoundTerm
Term
__builtin__.object

Methods defined here:
__getitem__(self, i)
__repr__(self)
classOrder(self)
newList(self, value)
occurringIn(self, vars)
substituteEquals(self, bindings, newBindings)
Return this or a version of me with substitution of equals made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with substitution made
uriref(self)
value(self)

Methods inherited from List:
__init__(self, store, first, rest)
__iter__(self)
The internal method which allows one to iterate over the statements
as though a formula were a sequence.
__len__(self)
The internal method which allows one to count the statements
as though a formula were a sequence.
asSequence(self)
Convert to a python sequence - NOT recursive
doesNodeAppear(self, symbol)
Does that particular node appear anywhere in this list
 
This function is necessarily recursive, and is useful for the pretty
printer. It will also be useful for the flattener, when we write it.
freeVariables(self)
prepend(self, first)

Methods inherited from Term:
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
representation(self, base=None)
The string represnting this in N3
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class Env(__builtin__.dict)
    An env is an immutable dict
 
you can hash it (if you want to)
 
 
Method resolution order:
Env
__builtin__.dict
__builtin__.object

Methods defined here:
__getitem__(self, item)
__hash__(self)
__init__(self, other=None, keywords={})
__repr__(self)
__setitem__(self, item, val)
asDict(self)
bind = newBinding(self, var, val)
canBind(self, var, val)
copy(self)
dereference(self, var)
filter(self, varSet)
flatten(self, other)
Pull all of the bindings of other into a copy of self
get(self, item, default=None)
newBinding(self, var, val)
substitution(self, node, *otherEnvs)
update(self, d2)
update2(self, d2)

Data and other attributes defined here:
__slots__ = ['_hashval', '__weakref__', 'id']
__weakref__ = <attribute '__weakref__' of 'Env' objects>
list of weak references to the object (if defined)
id = <member 'id' of 'Env' objects>

Methods inherited from __builtin__.dict:
__cmp__(...)
x.__cmp__(y) <==> cmp(x,y)
__contains__(...)
D.__contains__(k) -> True if D has a key k, else False
__delitem__(...)
x.__delitem__(y) <==> del x[y]
__eq__(...)
x.__eq__(y) <==> x==y
__ge__(...)
x.__ge__(y) <==> x>=y
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__gt__(...)
x.__gt__(y) <==> x>y
__iter__(...)
x.__iter__() <==> iter(x)
__le__(...)
x.__le__(y) <==> x<=y
__len__(...)
x.__len__() <==> len(x)
__lt__(...)
x.__lt__(y) <==> x<y
__ne__(...)
x.__ne__(y) <==> x!=y
clear(...)
D.clear() -> None.  Remove all items from D.
has_key(...)
D.has_key(k) -> True if D has a key k, else False
items(...)
D.items() -> list of D's (key, value) pairs, as 2-tuples
iteritems(...)
D.iteritems() -> an iterator over the (key, value) items of D
iterkeys(...)
D.iterkeys() -> an iterator over the keys of D
itervalues(...)
D.itervalues() -> an iterator over the values of D
keys(...)
D.keys() -> list of D's keys
pop(...)
D.pop(k[,d]) -> v, remove specified key and return the corresponding value
If key is not found, d is returned if given, otherwise KeyError is raised
popitem(...)
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty
setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
values(...)
D.values() -> list of D's values

Data and other attributes inherited from __builtin__.dict:
__new__ = <built-in method __new__ of type object>
T.__new__(S, ...) -> a new object with type S, a subtype of T
fromkeys = <built-in method fromkeys of type object>
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.

 
class ErrorFlag(exceptions.TypeError, Term)
    
Method resolution order:
ErrorFlag
exceptions.TypeError
exceptions.StandardError
exceptions.Exception
Term
__builtin__.object

Methods defined here:
__init__(...)
__repr__ = __str__(...)
__str__(...)
classOrder(self)
value lambda s

Methods inherited from exceptions.Exception:
__getitem__(...)

Methods inherited from Term:
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class Existential(Term)
    
Method resolution order:
Existential
Term
__builtin__.object

Methods inherited from Term:
__init__(self, store)
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class FiniteProperty(GenericBuiltIn, Function, ReverseFunction)
    A finite property has a finite set of pairs of (subj, object) values
 
The built-in finite property can ennumerate them all if necessary.
Argv is the only useful example I can think of right now.
 
 
Method resolution order:
FiniteProperty
GenericBuiltIn
Function
ReverseFunction
BuiltIn
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods defined here:
enn(self)
Return list of pairs [(subj, obj)]
ennumerate(self)
eval(self, subj, obj, queue, bindings, proof, query)
This is of course   very inefficient except for really small ones like argv.
evalObj(self, subj, queue, bindings, proof, query)
This is of course   very inefficient except for really small ones like argv.
evalSubj(self, obj, queue, bindings, proof, query)
This is of course   very inefficient except for really small ones like argv.

Methods inherited from GenericBuiltIn:
__init__(self, resource, fragid)

Static methods inherited from BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from BuiltIn:
all = []

Methods inherited from Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class Fragment(LabelledNode)
    Term which DOES have a fragment id in its URI
 
 
Method resolution order:
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods defined here:
__init__(self, resource, fragid)
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class FragmentNil(EmptyList, Fragment)
    This is unique in being both a symbol and a list
 
 
Method resolution order:
FragmentNil
EmptyList
List
CompoundTerm
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods defined here:
__init__(self, resource, fragid)

Methods inherited from EmptyList:
__getitem__(self, i)
__repr__(self)
classOrder(self)
newList(self, value)
occurringIn(self, vars)
substituteEquals(self, bindings, newBindings)
Return this or a version of me with substitution of equals made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with substitution made
uriref(self)
value(self)

Methods inherited from List:
__iter__(self)
The internal method which allows one to iterate over the statements
as though a formula were a sequence.
__len__(self)
The internal method which allows one to count the statements
as though a formula were a sequence.
asSequence(self)
Convert to a python sequence - NOT recursive
doesNodeAppear(self, symbol)
Does that particular node appear anywhere in this list
 
This function is necessarily recursive, and is useful for the pretty
printer. It will also be useful for the flattener, when we write it.
freeVariables(self)
prepend(self, first)

Methods inherited from Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref2(self, base)

Methods inherited from Term:
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class Function(BuiltIn)
    A function is a builtin which can calculate its object given its subject.
 
To get cwm to invoke it this way, your built-in must be a subclass of Function.
I may make changes to clean up the parameters of these methods below some day. -tbl
 
 
Method resolution order:
Function
BuiltIn
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods defined here:
__init__(self)
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from BuiltIn:
all = []

Methods inherited from Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class GenericBuiltIn(BuiltIn)
    
Method resolution order:
GenericBuiltIn
BuiltIn
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods defined here:
__init__(self, resource, fragid)

Methods inherited from BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from BuiltIn:
all = []

Methods inherited from Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class HeavyBuiltIn(GenericBuiltIn)
    A heavy built-in is fast and is calculated late, after searching the store
to see if the answer is already in it.
 
Make your built-in a subclass of either this or LightBultIn to tell cwm when to
run it.  Going out onto the web or net counts as Heavy.
 
 
Method resolution order:
HeavyBuiltIn
GenericBuiltIn
BuiltIn
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods inherited from GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from BuiltIn:
all = []

Methods inherited from Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class LabelledNode(Node)
    The labelled node is one which has a URI.
 
 
Method resolution order:
LabelledNode
Node
Term
__builtin__.object

Methods defined here:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from Term:
__init__(self, store)
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class LightBuiltIn(GenericBuiltIn)
    A light built-in is fast and is calculated immediately before searching the store.
 
Make your built-in a subclass of either this or HeavyBultIn to tell cwm when to
run it.  Going out onto the web or net counts as heavy.
 
 
Method resolution order:
LightBuiltIn
GenericBuiltIn
BuiltIn
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods inherited from GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from BuiltIn:
all = []

Methods inherited from Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class List(CompoundTerm)
    
Method resolution order:
List
CompoundTerm
Term
__builtin__.object

Methods defined here:
__init__(self, store, first, rest)
__iter__(self)
The internal method which allows one to iterate over the statements
as though a formula were a sequence.
__len__(self)
The internal method which allows one to count the statements
as though a formula were a sequence.
asSequence(self)
Convert to a python sequence - NOT recursive
doesNodeAppear(self, symbol)
Does that particular node appear anywhere in this list
 
This function is necessarily recursive, and is useful for the pretty
printer. It will also be useful for the flattener, when we write it.
freeVariables(self)
occurringIn(self, vars)
Which variables in the list occur in this list?
prepend(self, first)
substituteEquals(self, bindings, newBindings)
Return this or a version of me with substitution of equals made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with variable substitution made
uriref(self)
value(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
representation(self, base=None)
The string represnting this in N3
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class ListView(__builtin__.object)
    #### Everything that follows are the new unification routines
 
  Methods defined here:
__init__(self, list, start=0)
__len__(self)

Properties defined here:
car
get = _car(self)
cdr
get = _cdr(self)

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'ListView' objects>
list of weak references to the object (if defined)

 
class Literal(Term)
    Literal is a representation of an RDF literal
 
really, data:text/rdf+n3;%22hello%22 == "hello" but who
wants to store it that way?  Maybe we do... at least in theory and maybe
practice but, for now, we keep them in separate subclases of Term.
An RDF literal has a value - by default a string, and a datattype, and a
language.
 
 
Method resolution order:
Literal
Term
__builtin__.object

Methods defined here:
__decimal__(self)
__float__(self)
__init__(self, store, str, dt=None, lang=None)
__int__(self)
__repr__(self)
__str__(self)
asHashURI(self)
return a md5: URI for this literal.
Hmm... encoding... assuming utf8? @@test this.
Hmm... for a class of literals including this one,
strictly speaking.
asPair(self)
classOrder(self)
compareTerm(self, other)
Assume is also a literal - see function compareTerm in formula.py
occurringIn(self, vars)
representation(self, base=None)
substituteEquals(self, bindings, newBindings)
Return this or a version of me with subsitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
uriref(self)
value(self)
Datatype conversion XSD to Python
 
RDF primitive datatypes are XML schema datatypes, in the XSD namespace.
see http://www.w3.org/TR/xmlschema-2

Methods inherited from Term:
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class MultipleFunction(Function)
    Multiple return values.
The preconditions are the same as for Function, that the subject must be bound.
The result is different, as multiple versions are returned. Example: member of list.
 
 
Method resolution order:
MultipleFunction
Function
BuiltIn
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods defined here:
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
The python one returns a list of function values.
This returns a 'new bindings' structure (nbs) which is a sequence of
(bindings, reason) pairs.

Methods inherited from Function:
__init__(self)
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from BuiltIn:
all = []

Methods inherited from Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class MultipleReverseFunction(ReverseFunction)
    Multiple return values
 
 
Method resolution order:
MultipleReverseFunction
ReverseFunction
BuiltIn
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from ReverseFunction:
__init__(self)
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from BuiltIn:
all = []

Methods inherited from Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class N3Set(__builtin__.frozenset, CompoundTerm)
    There can only be one of every N3Set
 
 
Method resolution order:
N3Set
__builtin__.frozenset
CompoundTerm
Term
__builtin__.object

Methods defined here:
__init__(self, stuff=[])
something
asSequence(self)
classOrder(self)
compareTerm(self, other)
This is annoying
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newBindings)
Return this or a version of me with substitution of equals made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with variable substitution made
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
uriref(self)

Static methods defined here:
__new__(cls, stuff=[])

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
res = {}

Methods inherited from __builtin__.frozenset:
__and__(...)
x.__and__(y) <==> x&y
__cmp__(...)
x.__cmp__(y) <==> cmp(x,y)
__contains__(...)
x.__contains__(y) <==> y in x.
__eq__(...)
x.__eq__(y) <==> x==y
__ge__(...)
x.__ge__(y) <==> x>=y
__getattribute__(...)
x.__getattribute__('name') <==> x.name
__gt__(...)
x.__gt__(y) <==> x>y
__hash__(...)
x.__hash__() <==> hash(x)
__iter__(...)
x.__iter__() <==> iter(x)
__le__(...)
x.__le__(y) <==> x<=y
__len__(...)
x.__len__() <==> len(x)
__lt__(...)
x.__lt__(y) <==> x<y
__ne__(...)
x.__ne__(y) <==> x!=y
__or__(...)
x.__or__(y) <==> x|y
__rand__(...)
x.__rand__(y) <==> y&x
__reduce__(...)
Return state information for pickling.
__repr__(...)
x.__repr__() <==> repr(x)
__ror__(...)
x.__ror__(y) <==> y|x
__rsub__(...)
x.__rsub__(y) <==> y-x
__rxor__(...)
x.__rxor__(y) <==> y^x
__sub__(...)
x.__sub__(y) <==> x-y
__xor__(...)
x.__xor__(y) <==> x^y
copy(...)
Return a shallow copy of a set.
difference(...)
Return the difference of two sets as a new set.
 
(i.e. all elements that are in this set but not the other.)
intersection(...)
Return the intersection of two sets as a new set.
 
(i.e. all elements that are in both sets.)
issubset(...)
Report whether another set contains this set.
issuperset(...)
Report whether this set contains another set.
symmetric_difference(...)
Return the symmetric difference of two sets as a new set.
 
(i.e. all elements that are in exactly one of the sets.)
union(...)
Return the union of two sets as a new set.
 
(i.e. all elements that are in either set.)

Methods inherited from Term:
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
representation(self, base=None)
The string represnting this in N3
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class Node(Term)
    A node in the graph
 
 
Method resolution order:
Node
Term
__builtin__.object

Methods inherited from Term:
__init__(self, store)
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class NonEmptyList(List)
    
Method resolution order:
NonEmptyList
List
CompoundTerm
Term
__builtin__.object

Methods defined here:
__getitem__(self, i)
classOrder(self)
compareTerm(self, other)
Assume is also a NonEmptyList - see function compareTerm in formula.py
debugString(self, already=[])
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)

Methods inherited from List:
__init__(self, store, first, rest)
__iter__(self)
The internal method which allows one to iterate over the statements
as though a formula were a sequence.
__len__(self)
The internal method which allows one to count the statements
as though a formula were a sequence.
asSequence(self)
Convert to a python sequence - NOT recursive
doesNodeAppear(self, symbol)
Does that particular node appear anywhere in this list
 
This function is necessarily recursive, and is useful for the pretty
printer. It will also be useful for the flattener, when we write it.
freeVariables(self)
occurringIn(self, vars)
Which variables in the list occur in this list?
prepend(self, first)
substituteEquals(self, bindings, newBindings)
Return this or a version of me with substitution of equals made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with variable substitution made
uriref(self)
value(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
representation(self, base=None)
The string represnting this in N3
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class RDFBuiltIn(LightBuiltIn)
    An RDF built-in is a light built-in which is inherent in the RDF model.
    
    The only examples are (I think) rdf:first and rdf:rest which in the RDF model
    are arcs but in cwm have to be builtins as Lists a a first class data type.
.
 
 
Method resolution order:
RDFBuiltIn
LightBuiltIn
GenericBuiltIn
BuiltIn
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods inherited from GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from BuiltIn:
eval(self, subj, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use
evaluate, subject, etc.

Static methods inherited from BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from BuiltIn:
all = []

Methods inherited from Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class ReverseFunction(BuiltIn)
    A reverse function is a builtin which can calculate its subject given its object.
 
To get cwm to invoke it this way, your built-in must be a subclass of ReverseFunction.
If a function (like log:uri for example) is a two-way  (1:1) builtin, it should be declared
a subclass of Function and ReverseFunction. Then, cwm will call it either way as needed
in trying to resolve a query.
 
 
Method resolution order:
ReverseFunction
BuiltIn
Fragment
LabelledNode
Node
Term
__builtin__.object

Methods defined here:
__init__(self)
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions

Static methods inherited from BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from BuiltIn:
all = []

Methods inherited from Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class SkolemFunction(Existential)
    
Method resolution order:
SkolemFunction
Existential
Term
__builtin__.object

Methods inherited from Term:
__init__(self, store)
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class Symbol(LabelledNode)
    Term which has no fragment
 
 
Method resolution order:
Symbol
LabelledNode
Node
Term
__builtin__.object

Methods defined here:
__getitem__(self, lname)
get the lname Symbol in this namespace.
 
lname -- an XML name (limited to URI characters)
__init__(self, uri, store)
dereference(self, mode='', workingContext=None)
dereference an identifier, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
internFrag(self, fragid, thetype)
uriref(self)
uriref2(self, base)

Methods inherited from LabelledNode:
classOrder(self)
compareTerm(self, other)
Assume is also a LabelledNode - see function compareTerm in formula.py

Methods inherited from Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class Term(__builtin__.object)
    The Term object represents an RDF term.
 
It is interned for speed of processing by the store.
Every term has a pointer back to its store.
 
  Methods defined here:
__init__(self, store)
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes defined here:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class Universal(Term)
    
Method resolution order:
Universal
Term
__builtin__.object

Methods inherited from Term:
__init__(self, store)
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
occurringIn(self, vars)
representation(self, base=None)
The string represnting this in N3
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class UnknownType(exceptions.ValueError)
    
Method resolution order:
UnknownType
exceptions.ValueError
exceptions.StandardError
exceptions.Exception

Methods inherited from exceptions.Exception:
__getitem__(...)
__init__(...)
__str__(...)

 
class XMLLiteral(Literal)
    Literal is a representation of an RDF literal
 
really, data:text/rdf+n3;%22hello%22 == "hello" but who
wants to store it that way?  Maybe we do... at least in theory and maybe
practice but, for now, we keep them in separate subclases of Term.
An RDF literal has a value - by default a string, and a datattype, and a
language.
 
 
Method resolution order:
XMLLiteral
Literal
Term
__builtin__.object

Methods defined here:
__decimal__(self)
__float__(self)
__init__(self, store, dom)
__int__(self)
__repr__(self)
__str__(self)
asHashURI(self)
return a md5: URI for this literal.
Hmm... encoding... assuming utf8? @@test this.
Hmm... for a class of literals including this one,
strictly speaking.
asPair(self)
classOrder(self)
compareTerm(self, other)
Assume is also a literal - see function compareTerm in formula.py
occurringIn(self, vars)
representation(self, base=None)
substituteEquals(self, bindings, newBindings)
Return this or a version of me with subsitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
uriref(self)
value(self)
Datatype conversion XSD to Python
 
The internal reopresentation is the dom tree

Methods inherited from Term:
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
generated(self)
Boolean Is this thing a genid - is its name arbitrary?
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)

Data and other attributes inherited from Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
Functions
       
betterUnifySet(self, other, vars=set([]), existentials=set([]), bindings={})
We need to be smarter about this
 
there are the following catagories :
    atoms
    variable atoms
    lists of only lists and atoms (recursive)
    lists of only lists and atoms (recursive), some of which may be variables
    lists containing sets
    sets
 
in about that order of difficulty. Can we use this?
strategy: Usually, we will only have a set of triples (of ... )
    remove all ground ones. Match those directly off the bat (note: a ground set is NOT good enough!)
        This is looking complex
    look at all simple ones, generating binding possibilities
    then deal with sets
dereference(node, env1, env2, source)
matchSet(pattern, kb, vars=set([]), bindings={})
Utility routine to match 2 python sets of things.
No optimization!  This is of course the graph match function 
implemented with indexing, and built-in functions, in query.py.
This only reuires the first to include the second.
 
vars are things to be regarded as variables in the pattern.
bindings map from pattern to kb.
occurs_check(self, other, env2)
pickEnv(choice, *envs)
toBool(val, dt=None)
unify(self, other, bindings=Env({}), otherBindings=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySequence(self, other, bindings=Env({}), otherBindings=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySet(self, other, bindings=Env({}), otherBindings=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)

 
Data
        ALL4 = (0, 1, 2, 3)
ANONYMOUS = 3
CONTEXT = 0
FORMULA = 1
LITERAL = 2
LITERAL_DT = 21
LITERAL_LANG = 22
LITERAL_URI_prefix = 'data:application/rdf+n3-literal;'
List_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
Logic_NS = 'http://www.w3.org/2000/10/swap/log#'
OBJ = 3
PARTS = (1, 2, 3)
PRED = 1
RDF_type_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
SUBJ = 2
SYMBOL = 0
generators = _Feature((2, 2, 0, 'alpha', 1), (2, 3, 0, 'final', 0), 4096)
nextId = 0
typeMap = {'ENTITIES': <type 'unicode'>, 'ENTITY': <type 'unicode'>, 'ID': <type 'unicode'>, 'IDREF': <type 'unicode'>, 'IDREFS': <type 'unicode'>, 'NCNAME': <type 'unicode'>, 'NMTOKEN': <type 'unicode'>, 'NMTOKENS': <type 'unicode'>, 'NOTATION': <type 'unicode'>, 'Name': <type 'unicode'>, ...}
cwm-1.2.1/cwm_list.html0000644015216600007660000020424410717732074014142 0ustar syosisyosi Python: module cwm_list
 
 
cwm_list
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/cwm_list.py

$Id: cwm_list.html,v 1.9 2007/11/18 03:40:44 syosi Exp $
 
List and set built-ins for cwm
http://www.w3.org/2000/10/swap/cwm_list.py
 
See cwm.py and the os module in python

 
Modules
       
uripath

 
Classes
       
term.Function(term.BuiltIn)
BI_append(term.LightBuiltIn, term.Function)
BI_first(term.RDFBuiltIn, term.Function)
BI_last(term.LightBuiltIn, term.Function)
BI_members(term.LightBuiltIn, term.Function)
BI_rest(term.RDFBuiltIn, term.Function)
term.LightBuiltIn(term.GenericBuiltIn)
BI_append(term.LightBuiltIn, term.Function)
BI_in(term.LightBuiltIn, term.MultipleReverseFunction)
BI_last(term.LightBuiltIn, term.Function)
BI_member(term.LightBuiltIn, term.MultipleFunction)
BI_members(term.LightBuiltIn, term.Function)
term.MultipleFunction(term.Function)
BI_member(term.LightBuiltIn, term.MultipleFunction)
term.MultipleReverseFunction(term.ReverseFunction)
BI_in(term.LightBuiltIn, term.MultipleReverseFunction)
term.RDFBuiltIn(term.LightBuiltIn)
BI_first(term.RDFBuiltIn, term.Function)
BI_rest(term.RDFBuiltIn, term.Function)

 
class BI_append(term.LightBuiltIn, term.Function)
    Takes a list of lists, and appends them together.
 
 
Method resolution order:
BI_append
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_first(term.RDFBuiltIn, term.Function)
    
Method resolution order:
BI_first
term.RDFBuiltIn
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_in(term.LightBuiltIn, term.MultipleReverseFunction)
    Is the subject in the object?
Returnes a sequence of values.
 
 
Method resolution order:
BI_in
term.LightBuiltIn
term.GenericBuiltIn
term.MultipleReverseFunction
term.ReverseFunction
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)
evalSubj(self, obj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.MultipleReverseFunction:
evalObj(self, subj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_last(term.LightBuiltIn, term.Function)
    
Method resolution order:
BI_last
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_member(term.LightBuiltIn, term.MultipleFunction)
    Is the subject in the object?
Returnes a sequence of values.
 
 
Method resolution order:
BI_member
term.LightBuiltIn
term.GenericBuiltIn
term.MultipleFunction
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.MultipleFunction:
evalSubj(self, obj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
The python one returns a list of function values.
This returns a 'new bindings' structure (nbs) which is a sequence of
(bindings, reason) pairs.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_members(term.LightBuiltIn, term.Function)
    Makes a set from a list
 
 
Method resolution order:
BI_members
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evaluateObject(self, subj)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)
evalObj(self, subj, queue, bindings, proof, query)
This function which has access to the store, unless overridden,
calls a simpler one which uses python conventions.
 
To reduce confusion, the inital ones called with the internals available
use abreviations "eval", "subj" etc while the python-style ones use "evaluate", "subject", etc.

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class BI_rest(term.RDFBuiltIn, term.Function)
    
Method resolution order:
BI_rest
term.RDFBuiltIn
term.LightBuiltIn
term.GenericBuiltIn
term.Function
term.BuiltIn
term.Fragment
term.LabelledNode
term.Node
term.Term
__builtin__.object

Methods defined here:
evalObj(self, subj, queue, bindings, proof, query)

Methods inherited from term.GenericBuiltIn:
__init__(self, resource, fragid)

Methods inherited from term.Function:
eval(self, subj, obj, queue, bindings, proof, query)

Static methods inherited from term.BuiltIn:
__new__(cls, *args, **keywords)

Data and other attributes inherited from term.BuiltIn:
all = []

Methods inherited from term.Fragment:
compareTerm(self, other)
dereference(self, mode='', workingContext=None)
dereference an identifyer, finding the semantics of its schema if any
 
Returns None if it cannot be retreived.
generated(self)
A generated identifier?
This arises when a document is parsed and a arbitrary
name is made up to represent a node with no known URI.
It is useful to know that its ID has no use outside that
context.
representation(self, base=None)
Optimize output if prefixes available
uriref(self)
uriref2(self, base)

Methods inherited from term.LabelledNode:
classOrder(self)

Methods inherited from term.Term:
__repr__(self)
This method only used for debugging output - it can be ambiguous,
as it is is deliberately short to make debug printout readable.
 
output as XML qnames [http://www.w3.org/TR/REC-xml-names/#NT-QName].
This could be beefed up to guarantee unambiguity.
asPair(self)
Representation in an earlier format, being phased out 2002/08
 
The first part of the pair is a constant number represnting the type
see RDFSink.py.  the second is the value -- uri for symbols,
string for literals
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
doesNodeAppear(self, symbol)
Does that node appear within this one
 
This non-overloaded function will simply return if I'm equal to him
freeVariables(self)
occurringIn(self, vars)
substituteEquals(self, bindings, newRedirections)
Return this or a version of me with substitution made
substitution(self, bindings, why=None, cannon=False)
Return this or a version of me with subsitution made
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source=55, n2Source=55)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
Functions
       
register(store)

 
Data
        ListOperationsNamespace = 'http://www.w3.org/2000/10/swap/list#'
List_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
Logic_NS = 'http://www.w3.org/2000/10/swap/log#'
cwm-1.2.1/why.html0000644015216600007660000007312310731070070013113 0ustar syosisyosi Python: module why
 
 
why
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/why.py

$Id: why.py,v 1.53 2007/06/27 17:58:39 syosi Exp $
 
A class for storing the reason why something is known.
The dontAsk constant reason is used as a reason for the explanations themselves-
 we could make it more complicated here for the recursively minded but i don't
 see the need at the moment.
 
Assumes wwe are using the process-global store -- uses Namespace() @@@

 
Modules
       
binascii
diag
md5
string
sys
uripath
urllib
weakref

 
Classes
       
Reason
Because
BecauseOfCommandLine
BecauseOfData
BecauseOfExperience
BecauseBuiltIn
BecauseIncludes
BecauseSupports
BecauseOfRule
BecauseSubexpression
KBReasonTracker
BecauseMerge
Premise

 
class Because(Reason)
    For the reason given on the string.
This is a kinda end of the road reason.
 
A nested reason can also be given.
 
  Methods defined here:
__init__(self, str, because=None)
explain(self, ko, flags)
Describe this reason to an RDF store
Returns the value of this reason as interned in the store.

Methods inherited from Reason:
meIn(self, ko)
The representation of this object in the formula ko

 
class BecauseBuiltIn(Reason)
    Because the built-in function given concluded so.
A nested reason for running the function must be given
 
  Methods defined here:
__init__(self, context, subj, pred, obj)
explain(self, ko, flags)
This is just a plain fact - or was at the time.

Methods inherited from Reason:
meIn(self, ko)
The representation of this object in the formula ko

 
class BecauseIncludes(BecauseBuiltIn)
    Because of the speific built-in log:includes
 
 
Method resolution order:
BecauseIncludes
BecauseBuiltIn
Reason

Methods inherited from BecauseBuiltIn:
__init__(self, context, subj, pred, obj)
explain(self, ko, flags)
This is just a plain fact - or was at the time.

Methods inherited from Reason:
meIn(self, ko)
The representation of this object in the formula ko

 
class BecauseMerge(KBReasonTracker)
    Because this formula is a merging of others
 
 
Method resolution order:
BecauseMerge
KBReasonTracker
Reason

Methods defined here:
__init__(self, f, set)
explain(self, ko, flags)
newStatement(self, s, why)

Methods inherited from KBReasonTracker:
explanation(self, ko=None, flags='')
Produce a justification for this formula into the output formula
 
Creates an output formula if necessary.
returns it.
(This is different from reason.explain(ko) which returns the reason)

Methods inherited from Reason:
meIn(self, ko)
The representation of this object in the formula ko

 
class BecauseOfCommandLine(Because)
    Because of the command line given in the string
 
 
Method resolution order:
BecauseOfCommandLine
Because
Reason

Methods defined here:
explain(self, ko, flags)
Describe this reason to an RDF store
Returns the value of this reason as interned in the store.

Methods inherited from Because:
__init__(self, str, because=None)

Methods inherited from Reason:
meIn(self, ko)
The representation of this object in the formula ko

 
class BecauseOfData(Because)
    Directly from data in the resource whose URI is the string.
 
A nested reason can also be given, for why this resource was parsed.
 
 
Method resolution order:
BecauseOfData
Because
Reason

Methods defined here:
__init__(self, source, because=None)
explain(self, ko, flags)
Describe this reason to an RDF store
Returns the value of this reason as interned in the store.

Methods inherited from Reason:
meIn(self, ko)
The representation of this object in the formula ko

 
class BecauseOfExperience(Because)
    Becase of the experience of this agent, as described in the string
 
 
Method resolution order:
BecauseOfExperience
Because
Reason

Methods inherited from Because:
__init__(self, str, because=None)
explain(self, ko, flags)
Describe this reason to an RDF store
Returns the value of this reason as interned in the store.

Methods inherited from Reason:
meIn(self, ko)
The representation of this object in the formula ko

 
class BecauseOfRule(Reason)
     Methods defined here:
__init__(self, rule, bindings, knownExistentials, evidence, kb, because=None)
explain(self, ko, flags)
Describe this reason to an RDF store
Returns the value of this reason as interned in the store.

Methods inherited from Reason:
meIn(self, ko)
The representation of this object in the formula ko

 
class BecauseSubexpression(Reason)
    This was generated as part of a calculatio of a subexpression.
 
It is is not necessarily believed
 
  Methods defined here:
explain(self, ko, flags)
Describe this reason to an RDF store
Returns the value of this reason as interned in the store.

Methods inherited from Reason:
__init__(self)
meIn(self, ko)
The representation of this object in the formula ko

 
class BecauseSupports(BecauseBuiltIn)
    Because of the very special build-in log:supports
 
 
Method resolution order:
BecauseSupports
BecauseBuiltIn
Reason

Methods defined here:
__init__(self, context, subj, conclusion, pred, obj, reason)
__repr__(self)
explain(self, ko, flags)
This is just a plain fact - or was at the time.

Methods inherited from Reason:
meIn(self, ko)
The representation of this object in the formula ko

 
class KBReasonTracker(Reason)
    A reason tracker tracks the reasons for the statements in its formula.
 
Beware that when a new formula is
interned, the proofsOf dict must be informed that its identity has changed.
The ForumulaReason is informed of each statement added to the knowlege
base.
 
A knowledge base (open formula) is made from the addition of forumlae,
which result from, for example parsing a document or doing inference.
Within such added formulae, there are variables, including bnodes, which
have a cetain scope.  It is impossible to consider the process
as being one of simply adding statements, as the cross-reference of
the vaiables within the add formuls mst be preserved. 
Variable renaming may occur as thr formula is added. 
 
When we track these operations for generating a proof, a proof reason
such as an BecauseOfRule or BecauseOfData corresponds to an added formula.
The KBReasonTracker tracks which statements in a  formula came from which
addion operations.
 
  Methods defined here:
__init__(self, formula=None)
explain(self, ko, flags)
explanation(self, ko=None, flags='')
Produce a justification for this formula into the output formula
 
Creates an output formula if necessary.
returns it.
(This is different from reason.explain(ko) which returns the reason)
newStatement(self, s, why)

Methods inherited from Reason:
meIn(self, ko)
The representation of this object in the formula ko

 
class Premise(Reason)
    For the reason given on the string.
This is a kinda end of the road reason.
It contais the info which was literally supplied as a premise.
 
A nested reason can also be given.
Because a premise has to be taken for granted, the tracker
has to tell a Premis what statements it has.
 
  Methods defined here:
__init__(self, str, because=None)
explain(self, ko, flags)
Describe this reason to an RDF store
Returns the value of this reason as interned in the store.

Methods inherited from Reason:
meIn(self, ko)
The representation of this object in the formula ko

 
class Reason
    The Reason class holds a reason for having some information.
Well, its subclasses actually do hold data.  This class should not be used
itself to make instances.  Reasons may be given to any functions which put
data into stores, is tracking or proof/explanation generation may be
required
 
  Methods defined here:
__init__(self)
explain(self, ko, flags)
Describe this reason to an RDF store
Returns the value of this object as interned in the store.
meIn(self, ko)
The representation of this object in the formula ko

 
Functions
       
describeStatement(s_l, ko, flags)
Describe the statement into the output formula ko
explainFormula(f, flags='')
Return the explanation formula for f
explainStatement(s, ko, ss=None, flags='')
explainStatements(s_l, ko, ss=None, flags='')
formulaStandIn(self, ko, f, flags) method of __builtin__.dict instance
getStatementReason(s)
isTopLevel(f)
newTopLevelFormula(f)
report(statement, why)
Report a new statement to the reason tracking software
 
This module stores the reasons.  The store should call this
method to report new data. See the KBReasonTracker class
 
Most formulas don't need collectors. Let's see if we can change that.
smushedFormula(F, G)
The formula F has been replaced by G
 
Because this module tracks formula in stores, if ever the address
of a formula is changed, that is (currently) when it is 
canonicalized, then the fact must be reported here.
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
subFormulaStandIn(self, ko, f, flags) method of __builtin__.dict instance

 
Data
        MAX_INLINE_SIZE = 10
REIFY_NS = 'http://www.w3.org/2004/06/rei#'
becauseSubexpression = <why.BecauseSubexpression instance>
dontAsk = <why.Because instance>
flagHelp = '\nn use iNdirect formulas when they get...ays give the :gives clause, even when not needed\n'
log = <myStore.Namespace object>
proofsOf = <WeakKeyDictionary at 1076571532>
rdf = <myStore.Namespace object>
reason = <myStore.Namespace object>
cwm-1.2.1/LICENSE.n30000644015216600007660000000077607506364620012763 0ustar syosisyosi# This licence is used for files in this distribution. @prefix doc:. @prefix s: . <> a doc:OpenSourceLicense; doc:subLicense ; s:comment """Share and Enjoy. Open Source license: Copyright (c) 2000,1,2 W3C (MIT, INRIA, Keio) Copyright other contributers mentioned in individual files. http://www.w3.org/Consortium/Legal/copyright-software-19980720""". # endscwm-1.2.1/README~0000644015216600007660000001247410732327261012506 0ustar syosisyosi$Id: README,v 1.11 2005/11/21 22:19:31 vkolovsk Exp $ Cwm is a general-purpose data processor for the semantic web, somewhat like sed, awk, etc. for text files or XSLT for XML. It is a forward chaining reasoner which can be used for querying, checking, transforming and filtering information. Its core language is RDF, extended to include rules, and it uses RDF/XML or RDF/N3 (see Notation3 Primer) serializations as required. To find out more about Cwm, visit http://www.w3.org/2000/10/swap/doc/cwm == Getting Started == Unpack this tarball in a useful place. cd to that directory and type: cd test; make at the command line. It should spend a while testing to make sure the program is working. The test files should give you a good idea of commands to get Cwm to work. If you run ./setup.py install, it will install cwm. Other possibilities are evident from running ./setup.py --help-commands If a test fails: There are three possiblilities: 1. Your Python setup is borked / sufficiently different from the one used in development. This is a distinct possiblility. It is also possibly a bug in our code, if your we should in fact be supporting you platform. 2. You tarball was corrupted / not generated properly. This is also a distinct possiblility. The latter case is a bug. 3. We knowingly published a version of Cwm that failed our own tests. This is highly unlikely. == What's New In this Release (1.2.0) == For a complete list of changes, look at doc/changes.html Release 1.2.0 == Proof updates Putting --why at the end of a command line will generate a proof, and has had much debugging. == General bugfixes. Release 1.1.0 (never released) ==Performance Improvements * Cwm now uses Python Sets instead of lists to store many things * Speed improvements to some tests are orders of magnitude * Output is not as stable as it once was ==Python 2.3 or later now required Used for Sets ==Experimental SPARQL Server support Cwm can now run as a SPARQL server. This includes: * A preview cwm --sparqlServer, which runs a server on port 8000 * cwm --sparql=, which behaves like --query= * builtins for doing sparql queries from within n3. ==RDF/XML serialization fixes A few strange bugs in rdf:xml serialization, many related to the rdf: prefix or xml: prefix, have been fixed ==delta exit statuses delta now returns with similar exit statuses as the diff utility for plaintext files. An exit status of 0 means no differences between the from and to graphs were found. An exit status of 1 means some differences were found. An exit status of 2 means differences were not computed for some reason. Release 1.0.0 ==General bugfixes Fixes in decimal support A bug introduced into 0.8.0 where cwm crashed if no input files were specified has been fixed ==delta and cwm --patch diff.py is renamed delta.py to avoid confusion with diff(1). delta.py now will make a difference file even in cases where nodes cannot be be uniquely identified (from [inverse] function properties) but can be uniquely identified in the context of the graph. So, delta.py can generate weak deltas rather than strong ones under these circumstances. Bug fix to cwm's --patch function. ==RDF/XML support changes cwm's rdf/xml output will now output any file that can be outputted in xml 1.0. Failing that, it will output it in xml 1.1. Failing that, it will throw an exception. The previous behavior of generating empty tags was a bug. Cwm will throw an excpetion if told to output rdf/xml for a file that uses literals as subjects Tests have been added for rdflib. It is now supported to a degree. Cwm now successfully fails to parse all but four of the rdf negative parser tests ==Performance improvements Performance work has resulted in some tasks taking 1/10 the time that they used to. Much more work is planned in this regard. ==Packaging Cwm now uses python's distutils for distribution. This allows for installation of cwm. As an added bonus, there are now rpm's, windows installers . ==Flatten support --flatten and --unflatten have been rewritten, replacing the old --flat. Flatten minimally reifies an n3 file to make it an rdf graph. Note that the graph may still fail to serialize as rdf, due to literals as subjects ==Other A crude hack in WebAccess.py allows a local file system to be used instead of a given website. The intent is to clean this up in the future. There has been much work on a grammar for n3. grammar/n3.n3 is the grammar, grammar/predictiveParser.n3 can understand it. == Submitting Bugs == Cwm is very much a work in progress and has many bugs. Some of them we already know about. Cwm bugs are tracked on the public Cwm bug mail list, http://lists.w3.org/Archives/Public/public-cwm-bugs/ . Submit any bugs you find there, assuming they have not already been submitted. Reply to a previous bug report if you have something to add. == License == cwm is open source. Share and Enjoy. For details, see the attached files, LICENSE.n3 and LICENSE == Contributors == Tim Berners-Lee Dan Connolly Sean Palmer Mark Nottingham Eric Prud'hommeaux Sandro Hawke Dan Brickley Karl Dubost Yosi Scharf Development of cwm is supported in part by funding from US Defense Advanced Research Projects Agency (DARPA) and Air Force Research Laboratory, Air Force Materiel Command, USAF, under agreement number F30602-00-2-0593, "Semantic Web Development". cwm-1.2.1/cant.py0000644015216600007660000000000010640075637016405 1cwm-1.2.1/swap/cant.pyustar syosisyosicwm-1.2.1/check.py0000644015216600007660000000000010640075637016665 1cwm-1.2.1/swap/check.pyustar syosisyosicwm-1.2.1/formula.html0000644015216600007660000010074410731070065013755 0ustar syosisyosi Python: module formula
 
 
formula (version Id: formula.py,v 1.63 2007/12/16 00:22:59 syosi Exp )
index
/home/syosi/cvs-trunk/WWW/2000/10/swap/formula.py

 
Modules
       
StringIO
diag
notation3
sys
types

 
Classes
       
StoredStatement
term.AnonymousNode(term.Node)
Formula(term.AnonymousNode, term.CompoundTerm)
term.CompoundTerm(term.Term)
Formula(term.AnonymousNode, term.CompoundTerm)

 
class Formula(term.AnonymousNode, term.CompoundTerm)
    A formula of a set of RDF statements, triples.
 
(The triples are actually instances of StoredStatement.)
Other systems such as jena and redland use the term "Model" for Formula.
For rdflib, this is known as a TripleStore.
Cwm and N3 extend RDF to allow a literal formula as an item in a triple.
 
A formula is either open or closed.  Initially, it is open. In this
state is may be modified - for example, triples may be added to it.
When it is closed, note that a different interned version of itself
may be returned. From then on it is a constant.
 
Only closed formulae may be mentioned in statements in other formuale.
 
There is a reopen() method but it is not recommended, and if desperate should
only be used immediately after a close().
 
 
Method resolution order:
Formula
term.AnonymousNode
term.Node
term.CompoundTerm
term.Term
__builtin__.object

Methods defined here:
__init__(self, store, uri=None)
__iter__(self)
The internal method which allows one to iterate over the statements
as though a formula were a sequence.
__len__(self)
How many statements?
__repr__(self)
add(self, subj, pred, obj, why=None)
Add a triple to the formula.
 
The formula must be open.
subj, pred and obj must be objects as for example generated 
by Formula.newSymbol() and newLiteral(), or else literal
values which can be interned.
why     may be a reason for use when a proof will be required.
any(self, subj=None, pred=None, obj=None)
Return None or the value filing the blank in the called parameters.
 
Specifiy exactly two of the arguments.
color = f.any(pred=pantoneColor, subj=myCar)
somethingRed = f.any(pred=pantoneColor, obj=red)
 
Note difference from the old store.any!!
Note SPO order not PSO.
To aboid confusion, use named parameters.
bind(self, prefix, uri)
Give a prefix and associated URI as a hint for output
 
The store does not use prefixes internally, but keeping track
of those usedd in the input data makes for more human-readable output.
canonicalize(F)
If this formula already exists, return the master version.
If not, record this one and return it.
Call this when the formula is in its final form, with all its statements.
Make sure no one else has a copy of the pointer to the smushed one.
 
LIMITATION: The basic Formula class does NOT canonicalize. So
it won't spot idenical formulae. The IndexedFormula will.
classOrder(self)
close(self)
No more to add. Please return interned value.
NOTE You must now use the interned one, not the original!
compareTerm(self, other)
Assume is also a Formula - see function compareTerm below
contains(self, pred=None, subj=None, obj=None)
Return boolean true iff formula contains statement(s) matching the parts given
 
For example:
if f.contains(pred=pantoneColor):
    print "We've got one statement about something being some color"
declareExistential(self, v)
declareUniversal(self, v, key=None)
doesNodeAppear(self, symbol)
Does that particular node appear anywhere in this formula
 
This function is necessarily recursive, and is useful for the pretty printer
It will also be useful for the flattener, when we write it.
each(self, subj=None, pred=None, obj=None)
Return a list of values value filing the blank in the called parameters
 
Examples:
colors = f.each(pred=pantoneColor, subj=myCar)
 
for redthing in f.each(pred=pantoneColor, obj=red): ...
existentials(self)
Return a list of existential variables with this formula as scope.
 
Implementation:
we may move to an internal storage rather than these pseudo-statements
freeVariables(self)
generated(self)
Yes, any identifier you see for this is arbitrary.
intern(self, value)
loadFormulaWithSubstitution(self, old, bindings={}, why=None, cannon=False)
Load information from another formula, subsituting as we go
returns number of statements added (roughly)
n3EntailedBy(pattern, kb, vars=set([]), existentials=set([]), bindings={})
See Term.unify() and term.matchSet()
 
KB is a stronger statement han other.
Bindings map variables in pattern onto kb.
Self n3-entails other.
Criteria:  Subset of self statements must match other statements.
  Self's exisetntials must be subset of other's
  Self's universals must be superset.
n3String(self, base=None, flags='')
Dump the formula to an absolute string in N3
newBlankNode(self, uri=None, why=None)
Create a new unnamed node with this formula as context.
 
The URI is typically omitted, and the system will make up an internal idnetifier.
If given is used as the (arbitrary) internal identifier of the node.
newExistential(self, uri=None, why=None)
Create a named variable existentially qualified within this formula
 
See also: existentials()  and newBlankNode().
newFormula(self, uri=None)
Create a new open, empty, formula in the same store as this one.
 
The URI is typically omitted, and the system will make up an internal idnetifier.
If given is used as the (arbitrary) internal identifier of the formula.
newList(self, list)
newLiteral(self, str, dt=None, lang=None)
Create or reuse the internal representation of the RDF literal whose string is given
 
The literal is created in the same store as the formula.
newSymbol(self, uri)
Create or reuse the internal representation of the RDF node whose uri is given
 
The symbol is created in the same store as the formula.
newUniversal(self, uri=None, why=None)
Create a named variable universally qualified within this formula
 
See also: universals()
newXMLLiteral(self, doc)
Create or reuse the internal representation of the RDF literal whose string is given
 
The literal is created in the same store as the formula.
ntString(self, base=None, flags='bravestpun')
Dump the formula to an absolute string in N3
objects(self, pred=None, subj=None)
Obsolete - use each(subj=..., pred=...)
occurringIn(self, vars)
Which variables in the list occur in this?
outputStrings(self, channel=None, relation=None)
Fetch output strings from store, sort and output
 
To output a string, associate (using the given relation) with a key
such that the order of the keys is the order in which you want the corresponding
strings output.
 
@@ what is this doing here??
predicates(self, subj=None, obj=None)
Obsolete - use each(subj=..., obj=...)
rdfString(self, base=None, flags='')
Dump the formula to an absolute string in RDF/XML
removeStatement(self, s)
Removes a statement The formula must be open.
 
This implementation is alas slow, as removal of items from tha hash is slow.
renameVars(self)
reopen(self)
Make a formula which was once closed oopen for input again.
 
NOT Recommended.  Dangers: this formula will be, because of interning,
the same objet as a formula used elsewhere which happens to have the same content.
You mess with this one, you mess with that one.
Much better to keep teh formula open until you don't needed it open any more.
The trouble is, the parsers close it at the moment automatically. To be fixed.
searchable(self, subj=None, pred=None, obj=None)
A pair of the difficulty of searching and a statement iterator of found statements
 
The difficulty is a store-portable measure of how long the store
thinks (in arbitrary units) it will take to search.
This will only be used for choisng which part of the query to search first.
If it is 0 there is no solution to the query, we know now.
 
In this implementation, we use the length of the sequence to be searched.
size(self)
Return the number statements.
Obsolete: use len(F).
statementsMatching(self, pred=None, subj=None, obj=None)
Return a READ-ONLY list of StoredStatement objects matching the parts given
 
For example:
for s in f.statementsMatching(pred=pantoneColor):
    print "We've got one which is ", `s[OBJ]`
    
If none, returns []
subSet(self, statements, why=None)
subjects(self, pred=None, obj=None)
Obsolete - use each(pred=..., obj=...)
substituteEquals(self, bindings, newBindings)
Return this or a version of me with subsitution made
 
Subsitution of = for = does NOT happen inside a formula,
as the formula is a form of quotation.
substitution(self, bindings, why=None, cannon=False, keepOpen=False)
Return this or a version of me with subsitution made
the(self, subj=None, pred=None, obj=None)
Return None or the value filing the blank in the called parameters
 
This is just like any() except it checks that there is only
one answer in the store. It wise to use this when you expect only one.
 
color = f.the(pred=pantoneColor, subj=myCar)
redCar = f.the(pred=pantoneColor, obj=red)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source)
universals(self)
Return a set of variables universally quantified with this formula as scope.
 
Implementation:
We may move to an internal storage rather than these statements.
variables(self)
Return a set of all variables quantified within this scope.

Static methods defined here:
resetRenames(reset=True)

Methods inherited from term.AnonymousNode:
asPair(self)
uriref(self)

Methods inherited from term.Term:
compareAnyTerm(self, other)
Compare two langauge items
This is a cannoncial ordering in that is designed to allow
the same graph always to be printed in the same order.
This makes the regression tests possible.
The literals are deemed smaller than symbols, which are smaller
than formulae.  This puts the rules at the botom of a file where
they tend to take a lot of space anyway.
Formulae have to be compared as a function of their sorted contents.
 
@@ Anonymous nodes have to, within a given Formula, be compared as
a function of the sorted information about them in that context.
This is not done yet
debugString(self, already=[])
representation(self, base=None)
The string represnting this in N3
unify(self, other, env1=Env({}), env2=Env({}), vars=set([]), universals=set([]), existentials=set([]), n1Source=32, n2Source=32)
value(self)
As a python value - by default, none exists, use self

Data and other attributes inherited from term.Term:
__dict__ = <dictproxy object>
dictionary for instance variables (if defined)
__weakref__ = <attribute '__weakref__' of 'Term' objects>
list of weak references to the object (if defined)

 
class StoredStatement
    A statememnt as an element of a formula
 
  Methods defined here:
__cmp__(self, other)
Just compare SUBJ, Pred and OBJ, others the same
Avoid loops by spotting reference to containing formula
__getitem__(self, i)
__hash__(self)
__init__(self, q)
__len__(self)
__repr__(self)
asFormula(self, why=None)
The formula which contains only a statement like this.
 
When we split the statement up, we lose information in any existentials which are
shared with other statements. So we introduce a skolem constant to tie the
statements together.  We don't have access to any enclosing formula 
so we can't express its quantification.  This @@ not ideal.
 
This extends the StoredStatement class with functionality we only need with "why" module.
comparePredObj(self, other)
Just compare P and OBJ, others the same
context(self)
Return the context of the statement
existentials(self)
object(self)
Return the object of the statement
occurringIn(self, vars)
Which variables in the list occur in this?
predicate(self)
Return the predicate of the statement
spo(self)
statements(self)
subject(self)
Return the subject of the statement
unify(self, other, env1, env2, vars, universals, existentials, n1Source=32, n2Source=32)
unifySecondary(self, other, env1, env2, vars, universals, existentials, n1Source, n2Source)
universals(self)

 
Functions
       
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

 
Data
        CONTEXT = 0
FORMULA = 1
Logic_NS = 'http://www.w3.org/2000/10/swap/log#'
OBJ = 3
PRED = 1
SUBJ = 2
SYMBOL = 0
__version__ = 'Id: formula.py,v 1.63 2007/12/16 00:22:59 syosi Exp '
generators = _Feature((2, 2, 0, 'alpha', 1), (2, 3, 0, 'final', 0), 4096)
tracking = 0
cwm-1.2.1/setup.py~0000755015216600007660000000324010731067743013337 0ustar syosisyosi#!/usr/bin/env python # borrowing liberally from Eikeon's setup.py for rdflib # an attempt at a setup.py installer for Cwm/SWAP # version: $Id: setup.py,v 1.23 2007/12/16 00:22:59 syosi Exp $ # by Dan Brickley # # STATUS: this file now works # much of what danbri typed I honestly do not know what it is trying to do. I suspect the answer is # ``not much'' # # DO NOT run this file directly! Use make dist_tarball instead. # # notes: # http://esw.w3.org/t/view/ESW/CwmTips from distutils.sysconfig import get_python_lib from os import rename from os.path import join, exists from time import time lib_dir = get_python_lib() swap_dir = join(lib_dir, "swap") print "swap dir: "+swap_dir ##if exists(swap_dir): ## backup = "%s-%s" % (swap_dir, int(time())) ## print "Renaming previously installed swap to: \n %s" % backup ## rename(swap_dir, backup) # Install SWAP from distutils.core import setup #from swap import __version__ __version__='1.2.0' setup( name = 'cwm', version = __version__, description = "Semantic Web Area for Play", author = "TimBL, Dan Connolly and contributors", author_email = "timbl@w3.org", maintainer = "Tim Berners-Lee", maintainer_email = "timbl@w3.org", url = "http://www.w3.org/2000/10/swap/", package_dir = {'swap': 'swap'}, packages = ['swap'], # py_modules = ['cwm', 'delta', 'cant'], scripts = ['cwm', 'delta', 'cant.py'], ) # todo, figure out which other modules are in public APIs # --danbri #,'swap.cwm','swap.RDFSink','swap.llyn'], # 'swap.RDFSink', # 'swap.llyn'], # packages = ['swap.cwm', # 'swap.RDFSink', # 'swap.llyn'], # package_dir = {'': 'swap'},

$Id: cwm_os.html,v 1.7 2007/06/27 17:58:39 syosi Exp $
 
Operating systems built-ins for cwm
http://www.w3.org/2000/10/swap/string.py
 
See cwm.py and the os module in python