コード例 #1
0
ファイル: N3Reader.cs プロジェクト: ArsenShnurkov/beagle-1
		private Resource ReadResource2(ParseContext context, bool allowDirective, out bool reverse, out bool forgetBNode) {
			reverse = false;
			forgetBNode = false;
			
			Location loc = context.Location;
			
			object tok = ReadToken(context.source, context);
			if (tok is Literal)
				return (Literal)tok;
			
			string str = (string)tok;
			if (str == "")
				return null;
				
			// Directives
			
			if (str == "@prefix") {
				if (allowDirective)
					return PrefixResource;
				else
					OnError("The directive '" + str + "' is not allowed here", loc);
			}

			if (str == "@keywords") {
				if (allowDirective)
					return KeywordsResource;
				else
					OnError("The directive '" + str + "' is not allowed here", loc);
			}

			if (str == "@base") {
				if (allowDirective)
					return BaseResource;
				else
					OnError("The directive '" + str + "' is not allowed here", loc);
			}
			
			// @ Keywords

			if (context.UsingKeywords && context.Keywords.Contains(str))
				str = "@" + str;
			if (!context.UsingKeywords &&
				( str == "a" || str == "has" || str == "is"))
				str = "@" + str;
			
			// Standard Keywords
			// TODO: Turn these off with @keywords
			
			if (str == "@a")
				return entRDFTYPE;
				
			if (str == "=")
				return entDAMLEQUIV;
			if (str == "=>")
				return entLOGIMPLIES;
			if (str == "<=") {
				reverse = true;
				return entLOGIMPLIES;
			}
			if (str == "=:>") // SPECIAL EXTENSION!
				return entGRAPHCONTAINS;

			if (str == "@has") // ignore this token
				return ReadResource2(context, false, out reverse, out forgetBNode);
			
			if (str == "@is") {
				// Reverse predicate
				bool reversetemp;
				Resource pred = ReadResource2(context, false, out reversetemp, out forgetBNode);
				reverse = true;
				
				string of = ReadToken(context.source, context) as string;
				if (of == null) OnError("End of stream while expecting 'of'", loc);
				if (of == "@of"
					|| (!context.UsingKeywords && of == "of")
					|| (context.UsingKeywords && context.Keywords.Contains("of") && of == "of"))
					return pred;
				OnError("Expecting token 'of' but found '" + of + "'", loc);
				return null; // unreachable
			}
			
			if (str.StartsWith("@"))
				OnError("The " + str + " directive is not supported", loc);

			// URI
			
			if (str.StartsWith("<") && str.EndsWith(">")) {
				string uri = GetAbsoluteUri(BaseUri, str.Substring(1, str.Length-2));
				string urierror = Entity.ValidateUri(uri);
				if (urierror != null)
					OnWarning(urierror, loc);
				return GetResource(context, uri);
			}
			
			// VARIABLE
			
			if (str[0] == '?') {
				string name = str.Substring(1);
				Entity varb = (Entity)context.variables[name];
				if (varb == null) {
					varb = new Variable(name);
					AddVariable((Variable)varb);
					context.variables[name] = varb;
				}
				return varb;
			}
			
			// QNAME

			if (str.IndexOf(":") != -1)
				return ResolveQName(str, context, loc);
				
			// ANONYMOUS
			
			if (str == "[") {
				Entity ret = new BNode();
				ReadWhitespace(context.source);
				if (context.source.Peek() != ']') {
					char bracket = ReadPredicates(ret, context);
					if (bracket == '.')
						bracket = ReadPunc(context.source);
					if (bracket != ']')
						OnError("Expected a close bracket but found '" + bracket + "'", loc);
				} else {
					context.source.Read();
				}
				forgetBNode = true;
				return ret;
			}
			
			// LIST
			
			if (str == "(") {
				// A list
				Entity head = null, ent = null;
				while (true) {
					bool rev2, fb2;
					Resource res = ReadResource(context, false, out rev2, out fb2);
					if (res == null)
						break;
					
					if (ent == null) {
						ent = new BNode();
						head = ent;
					} else {
						Entity sub = new BNode();
						Add(context.store, new Statement(ent, entRDFREST, sub, context.meta), loc);
						ent = sub;
					}
					
					Add(context.store, new Statement(ent, entRDFFIRST, res, context.meta), loc);
					if (fb2) DoForget(res, context);
				}
				if (head == null) // No list items.
					head = entRDFNIL; // according to Turtle spec
				else
					Add(context.store, new Statement(ent, entRDFREST, entRDFNIL, context.meta), loc);
				
				return head;
			}
			
			if (str == ")")
				return null; // Should I use a more precise end-of-list return value?
			
			// FORMULA
			
			if (str == "{") {
				// ParseContext is a struct, so this gives us a clone.
				ParseContext newcontext = context;
				
				// The formula is denoted by a blank node, unless we set
				// the override meta flag above.
				if (context.overrideMeta == null)
					newcontext.meta = new BNode();
				else
					newcontext.meta = context.overrideMeta;
				
				// According to the spec, _:xxx anonymous nodes are
				// local to the formula.  But ?$variables (which aren't
				// mentioned in the spec) are treated as global names.
				newcontext.anonymous = new Hashtable();
				
				while (NextPunc(context.source) != '}' && ReadStatement(newcontext)) { }
				ReadWhitespace(context.source);
				if (context.source.Peek() == '}') context.source.Read();
				
				return newcontext.meta;
			}
			
			// NUMERIC LITERAL
			
			// In Turtle, numbers are restricted to [0-9]+, and are datatyped xsd:integer.
			double numval;
			#if !SILVERLIGHT
			if (double.TryParse(str, System.Globalization.NumberStyles.Any, null, out numval)) {
			#else
			bool ok = true;
			numval = 0;
			try {
				numval = double.Parse(str);
			} catch (Exception) {
				ok = false;
			}
			if (ok) {
			#endif
				if (numval >= long.MinValue && numval <= long.MaxValue && numval == (double)(long)numval)
					return new Literal(((long)numval).ToString(), null, NS.XMLSCHEMA + "integer");
				else
					return new Literal(numval.ToString(), null, NS.XMLSCHEMA + "double");
			}
			
			//BOOLEAN LITERAL
			
			if (str == "true" || str == "false") {
			  return new Literal(str,null,NS.XMLSCHEMA+"boolean");
			}
			
			// If @keywords is used, alphanumerics that aren't keywords
			// are local names in the default namespace.
			if (context.UsingKeywords && char.IsLetter(str[0])) {
				if (BaseUri == null)
					OnError("The document contains an unqualified name but no BaseUri was specified: \"" + str + "\"", loc);
				return GetResource(context, BaseUri + str);
			}
			
			// NOTHING MATCHED
			
			OnError("Invalid token: " + str, loc);
			return null;
		}
		
		private void Add(StatementSink store, Statement statement, Location position) {
			store.Add(statement);
		}
コード例 #2
0
		public override void Run(SelectableSource source, QueryResultSink resultsink) {
			if (!(query is SelectQuery))
				throw new InvalidOperationException("Only SELECT queries are supported by this method (" + query.GetType() + ").");

			// Perform the query
			SelectQuery squery = (SelectQuery)query;
			
			RdfSourceWrapper sourcewrapper = new RdfSourceWrapper(source, QueryMeta, this);

			MyLogicFactory logic = new MyLogicFactory();
			foreach (RdfFunction f in extFunctions)
				logic.registerExternalFunction(
					new URIWrapper(f.Uri),
					new ExtFuncWrapper(sourcewrapper, f));

			squery.bindLogic(logic);
			
			RdfBindingSet results;
			try {
				results = squery.execute(sourcewrapper);
			} catch (java.lang.Exception e) {
				throw new QueryExecutionException("Error executing query: " + e.Message, e);
			}
			
			// Prepare binding objects
			java.util.List vars = results.getVariables();
			VariableBinding[] bindings = new VariableBinding[vars.size()];
			SparqlVariable[] svars = new SparqlVariable[vars.size()];
			SemWebVariable[] vars2 = new SemWebVariable[vars.size()];
			for (int i = 0; i < bindings.Length; i++) {
				svars[i] = (SparqlVariable)vars.get(i);
				vars2[i] = new SemWebVariable(svars[i].getName());
				bindings[i] = new VariableBinding(vars2[i], null);
			}
			
			// Initialize the result sink
			resultsink.Init(bindings, false, false); // set distinct and ordered
			
			// Set the comments
			resultsink.AddComments(queryString + "\n");
			resultsink.AddComments(sourcewrapper.GetLog());

			// Iterate the bindings
			java.util.Iterator iter = results.iterator();
			long ctr = -1, ctr2 = 0;
			while (iter.hasNext()) {
				RdfBindingRow row = (RdfBindingRow)iter.next();

				// Since SPARQL processing may be lazy-delayed,
				// add any new comments that might have been logged.
				resultsink.AddComments(sourcewrapper.GetLog());

				ctr++;
			
				if (ctr < ReturnStart && ReturnStart != -1) continue;

				for (int i = 0; i < bindings.Length; i++) {
					Resource r = sourcewrapper.ToResource(row.getValue(svars[i]));
					r = sourcewrapper.Persist(r);
					bindings[i] = new VariableBinding(bindings[i].Variable, r);
				}

				resultsink.AddComments(sourcewrapper.GetLog());
				
				resultsink.Add(bindings);

				ctr2++;
				if (ctr2 >= ReturnLimit && ReturnLimit != -1) break;
			}
			
			resultsink.AddComments(sourcewrapper.GetLog());
			
			// Close the result sink.
			resultsink.Finished();
		}
コード例 #3
0
        public void InteropSemWebNativeStore()
        {
            //Get the Talis Connection
            TalisPlatformConnector talis = new TalisPlatformConnector("rvesse-dev1", "rvesse", "4kn478wj");
            Assert.IsNotNull(talis);

            //Create a Talis Triple Store
            TalisTripleStore store = new TalisTripleStore(talis);

            //Create the Native Store Source
            NativeStoreSource source = new NativeStoreSource(store);

            Console.WriteLine("All Statements in the Store");
            source.Select(new SemWebConsolePrinter());
            Console.WriteLine();

            Console.Write("Does a FordFiesta exist in the Store? ");
            Console.WriteLine(source.Contains(new Entity("http://example.org/vehicles/FordFiesta")));
            Console.WriteLine();

            Console.Write("Does a Monkey exist in the Store? ");
            Console.WriteLine(source.Contains(new Entity("http://example.org/Monkey")));
            Console.WriteLine();

            Console.Write("Do any Cars exist in the Store? ");
            Statement cars = new Statement(null, new Entity(RdfSpecsHelper.RdfType), new Entity("http://example.org/vehicles/Car"));
            Console.WriteLine(source.Contains(cars));
            Console.WriteLine();

            Console.Write("Do any Gorillas exist in the Store?");
            Statement gorillas = new Statement(null, new Entity(RdfSpecsHelper.RdfType), new Entity("http://example.org/Gorilla"));
            Console.WriteLine(source.Contains(gorillas));
            Console.WriteLine();

            Console.WriteLine("What Cars exists in the Store?");
            source.Select(new Statement(null, new Entity(RdfSpecsHelper.RdfType), new Entity("http://example.org/vehicles/Car")), new SemWebConsolePrinter());
            Console.WriteLine();

            Console.WriteLine("Cars are their Speeds from the Store?");
            Variable car = new Variable("car");
            Statement[] pattern = new Statement[] 
            {
                new Statement(car, new Entity(RdfSpecsHelper.RdfType), new Entity("http://example.org/vehicles/Car")),
                new Statement(car, new Entity("http://example.org/vehicles/Speed"), new Variable("speed"))
            };
            source.Query(pattern, new QueryOptions(), new SemWebResultsConsolePrinter());
            Console.WriteLine();
        }
コード例 #4
0
		private Resource ReadResource2(ParseContext context, out bool reverse) {
			reverse = false;
			
			Location loc = context.Location;
			
			object tok = ReadToken(context.source, context);
			if (tok is Literal)
				return (Literal)tok;
			
			string str = (string)tok;
			if (str == "")
				return null;
			
			// @ Keywords

			if (str == "@prefix")
				return PrefixResource;

			if (str == "@keywords")
				return KeywordsResource;
			
			if (context.UsingKeywords && context.Keywords.Contains(str))
				str = "@" + str;
			if (!context.UsingKeywords &&
				( str == "a" || str == "has" || str == "is"))
				str = "@" + str;
			
			// Standard Keywords
			// TODO: Turn these off with @keywords
			
			if (str == "@a")
				return entRDFTYPE;
				
			if (str == "=")
				return entDAMLEQUIV;
			if (str == "=>")
				return entLOGIMPLIES;
			if (str == "<=") {
				reverse = true;
				return entLOGIMPLIES;
			}				

			if (str == "@has") // ignore this token
				return ReadResource2(context, out reverse);
			
			if (str == "@is") {
				// Reverse predicate
				bool reversetemp;
				Resource pred = ReadResource2(context, out reversetemp);
				reverse = true;
				
				string of = ReadToken(context.source, context) as string;
				if (of == null) OnError("End of stream while expecting 'of'", loc);
				if (of == "@of"
					|| (!context.UsingKeywords && of == "of")
					|| (context.UsingKeywords && context.Keywords.Contains("of") && of == "of"))
					return pred;
				OnError("Expecting token 'of' but found '" + of + "'", loc);
				return null; // unreachable
			}
			
			if (str.StartsWith("@"))
				OnError("The " + str + " directive is not supported", loc);

			// URI
			
			if (str.StartsWith("<") && str.EndsWith(">")) {
				string uri = GetAbsoluteUri(BaseUri, str.Substring(1, str.Length-2));
				return GetResource(context, uri);
			}
			
			// VARIABLE
			
			if (str[0] == '?') {
				string name = str.Substring(1);
				Entity var = (Entity)context.variables[name];
				if (var == null) {
					var = new Variable(name);
					AddVariable((Variable)var);
					context.variables[name] = var;
				}
				return var;
			}
			
			// QNAME

			if (str.IndexOf(":") != -1)
				return ResolveQName(str, context, loc);
				
			// ANONYMOUS
			
			if (str == "[") {
				Entity ret = new BNode();
				ReadWhitespace(context.source);
				if (context.source.Peek() != ']') {
					char bracket = ReadPredicates(ret, context);
					if (bracket == '.')
						bracket = ReadPunc(context.source);
					if (bracket != ']')
						OnError("Expected a close bracket but found '" + bracket + "'", loc);
				} else {
					context.source.Read();
				}
				return ret;
			}
			
			// LIST
			
			if (str == "(") {
				// A list
				Entity ent = null;
				while (true) {
					bool rev2;
					Resource res = ReadResource(context, out rev2);
					if (res == null)
						break;
					
					if (ent == null) {
						ent = new BNode();
					} else {
						Entity sub = new BNode();
						Add(context.store, new Statement(ent, entRDFREST, sub, context.meta), loc);
						ent = sub;
					}
					
					Add(context.store, new Statement(ent, entRDFFIRST, res, context.meta), loc);
				}
				if (ent == null) // No list items.
					ent = entRDFNIL; // according to Turtle spec
				else
					Add(context.store, new Statement(ent, entRDFREST, entRDFNIL, context.meta), loc);
				return ent;
			}
			
			if (str == ")")
				return null; // Should I use a more precise end-of-list return value?
			
			// FORMULA
			
			if (str == "{") {
				// ParseContext is a struct, so this gives us a clone.
				ParseContext newcontext = context;
				
				// The formula is denoted by a blank node
				newcontext.meta = new BNode();
				
				// According to the spec, _:xxx anonymous nodes are
				// local to the formula.  But ?$variables (which aren't
				// mentioned in the spec) are treated as global names.
				newcontext.anonymous = new Hashtable();
				
				while (NextPunc(context.source) != '}' && ReadStatement(newcontext)) { }
				ReadWhitespace(context.source);
				if (context.source.Peek() == '}') context.source.Read();
				
				return newcontext.meta;
			}
			
			// NUMERIC LITERAL
			
			// In Turtle, numbers are restricted to [0-9]+, and are datatyped xsd:integer.
			double numval;
			if (double.TryParse(str, System.Globalization.NumberStyles.Any, null, out numval))
				return new Literal(numval.ToString());
			
			// If @keywords is used, alphanumerics that aren't keywords
			// are local names in the default namespace.
			if (context.UsingKeywords && char.IsLetter(str[0])) {
				if (BaseUri == null)
					OnError("The document contains an unqualified name but no BaseUri was specified: \"" + str + "\"", loc);
				return GetResource(context, BaseUri + str);
			}
			
			// NOTHING MATCHED
			
			OnError("Invalid token: " + str, loc);
			return null;
		}
コード例 #5
0
			public override void Init(Variable[] variables) {
				for (int i = 0; i < variables.Length; i++) {
					if (variables[i].LocalName == "subject") si = i;
					if (variables[i].LocalName == "predicate") pi = i;
					if (variables[i].LocalName == "object") oi = i;
				}
			}
コード例 #6
0
        public void InteropSemWebGraphQuery() 
        {
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            GraphSource source = new GraphSource(g);

            Console.WriteLine("Query for Cars and their Speeds");
            Console.WriteLine();
            SemWeb.Query.SparqlXmlQuerySink sink = new SemWeb.Query.SparqlXmlQuerySink(Console.Out);
            Variable car = new Variable("car");
            Statement[] graphPattern = new Statement[] 
            {
                new Statement(car, new Entity(RdfSpecsHelper.RdfType), new Entity("http://example.org/vehicles/Car")),
                new Statement(car, new Entity("http://example.org/vehicles/Speed"), new Variable("speed"))
            };

            source.Query(graphPattern, new SemWeb.Query.QueryOptions(), sink);

            Console.WriteLine("Query for the 1st Car and it's Speed");
            Console.WriteLine();
            sink = new SemWeb.Query.SparqlXmlQuerySink(Console.Out);
            graphPattern = new Statement[] 
            {
                new Statement(car, new Entity(RdfSpecsHelper.RdfType), new Entity("http://example.org/vehicles/Car")),
                new Statement(car, new Entity("http://example.org/vehicles/Speed"), new Variable("speed"))
            };
            SemWeb.Query.QueryOptions options = new SemWeb.Query.QueryOptions();
            options.Limit = 1;
            source.Query(graphPattern, options, sink);
        }
コード例 #7
0
ファイル: Euler.cs プロジェクト: shariqatariq/profiles-rns
        private static ArrayList prove(Hashtable cases, SelectableSource world, Statement[] goal, int maxNumberOfSteps)
        {
            // This is the main routine from euler.js.

            // cases: Resource (predicate) => IList of Sequent

            if (world != null) // cache our queries to the world, if a world is provided
                world = new SemWeb.Stores.CachedSource(world);

            StatementMap cached_subproofs = new StatementMap();

            // Create the queue and add the first item.
            ArrayList queue = new ArrayList();
            {
                QueueItem start = new QueueItem();
                start.env = new Hashtable();
                start.rule = new Sequent(Statement.All, goal, null);
                start.src = null;
                start.ind = 0;
                start.parent = null;
                start.ground = new ArrayList();
                queue.Add(start);
                if (Debug) Console.Error.WriteLine("Euler: Queue: " + start);
            }

            // The evidence array holds the results of this proof.
            ArrayList evidence = new ArrayList();

            // Track how many steps we take to not go over the limit.
            int step = 0;

            // Process the queue until it's empty or we reach our step limit.
            while (queue.Count > 0) {
                // deal with the QueueItem at the top of the queue
                QueueItem c = (QueueItem)queue[queue.Count-1];
                queue.RemoveAt(queue.Count-1);
                ArrayList g = new ArrayList(c.ground);

                // have we done too much?
                step++;
                if (maxNumberOfSteps != -1 && step >= maxNumberOfSteps) {
                    if (Debug) Console.Error.WriteLine("Euler: Maximum number of steps exceeded.  Giving up.");
                    return null;
                }

                // if each statement in the body of the sequent has been proved
                if (c.ind == c.rule.body.Length) {
                    // if this is the top-level sequent being proved; we've found a complete evidence for the goal
                    if (c.parent == null) {
                        EvidenceItem ev = new EvidenceItem();
                        ev.head = new Statement[c.rule.body.Length];
                        bool canRepresentHead = true;
                        for (int i = 0; i < c.rule.body.Length; i++) {
                            ev.head[i] = evaluate(c.rule.body[i], c.env);
                            if (ev.head[i].AnyNull) // can't represent it: literal in subject position, for instance
                                canRepresentHead = false;
                        }

                        ev.body = c.ground;
                        ev.env = c.env;

                        if (Debug) Console.Error.WriteLine("Euler: Found Evidence: " + ev);

                        if (!canRepresentHead)
                            continue;

                        evidence.Add(ev);

                    // this is a subproof of something; whatever it is a subgroup for can
                    // be incremented
                    } else {
                        // if the rule had no body, it was just an axiom and we represent that with Ground
                        if (c.rule.body.Length != 0) g.Add(new Ground(c.rule, c.env));

                        // advance the parent being proved and put the advanced
                        // parent into the queue; unify the parent variable assignments
                        // with this one's
                        QueueItem r = new QueueItem();
                        r.rule = c.parent.rule;
                        r.src = c.parent.src;
                        r.ind = c.parent.ind;
                        r.parent = c.parent.parent;
                        r.env = (Hashtable)c.parent.env.Clone();
                        r.ground = g;
                        unify(c.rule.head, c.env, r.rule.body[r.ind], r.env, true);
                        r.ind++;
                        queue.Add(r);
                        if (Debug) Console.Error.WriteLine("Euler: Queue Advancement: " + r);

                        // The number of live children for this parent is decremented since we are
                        // done with this subproof, but we store the result for later.
                        if (c.parent.solutions == null)
                            c.parent.solutions = new StatementList();
                        c.parent.solutions.Add(evaluate(r.rule.body[r.ind-1], r.env));
                        decrementLife(c.parent, cached_subproofs);
                    }

                // this sequent still has parts of the body left to be proved; try to
                // find evidence for the next statement in the body, and if we find
                // evidence, queue up that evidence
                } else {
                    // this is the next part of the body that we need to try to prove
                    Statement t = c.rule.body[c.ind];

                    // Try to process this predicate with a user-provided custom
                    // function that resolves things like mathematical relations.
                    // euler.js provides similar functionality, but the system
                    // of user predicates is completely different here.
                    RdfRelation b = FindUserPredicate(t.Predicate);
                    if (b != null) {
                        Resource[] args;
                        Variable[] unifyResult;
                        Resource value = evaluate(t.Object, c.env);

                        if (!c.rule.callArgs.ContainsKey(t.Subject)) {
                            // The array of arguments to this relation is just the subject of the triple itself
                            args = new Resource[] { evaluate(t.Subject, c.env) };
                            unifyResult = new Variable[1];
                            if (t.Subject is Variable) unifyResult[0] = (Variable)t.Subject;

                        } else {
                            // The array of arguments to this relation comes from a pre-grouped arg list.
                            args = (Resource[])((ICloneable)c.rule.callArgs[t.Subject]).Clone();
                            unifyResult = new Variable[args.Length];

                            for (int i = 0; i < args.Length; i++) {
                                if (args[i] is Variable) {
                                    unifyResult[i] = (Variable)args[i];
                                    args[i] = evaluate(args[i], c.env);
                                }
                            }
                        }

                        // Run the user relation on the array of arguments (subject) and on the object.
                        if (b.Evaluate(args, ref value)) {
                            // If it succeeds, we press on.

                            // The user predicate may update the 'value' variable and the argument
                            // list array, and so we want to unify any variables in the subject
                            // or object of this user predicate with the values given to us
                            // by the user predicate.
                            Hashtable newenv = (Hashtable)c.env.Clone();
                            if (t.Object is Variable) unify(value, null, t.Object, newenv, true);
                            for (int i = 0; i < args.Length; i++)
                                if (unifyResult[i] != null)
                                    unify(args[i], null, unifyResult[i], newenv, true);

                            Statement grnd = evaluate(t, newenv);
                            if (grnd != Statement.All) // sometimes not representable, like if literal as subject
                                g.Add(new Ground(new Sequent(grnd, new Statement[0], null), new Hashtable()));

                            QueueItem r = new QueueItem();
                            r.rule = c.rule;
                            r.src = c.src;
                            r.ind = c.ind;
                            r.parent = c.parent;
                            r.env = newenv;
                            r.ground = g;
                            r.ind++;
                            queue.Add(r);

                            // Note: Since we are putting something back in for c, we don't touch the life counter on the parent.

                        } else {
                            // If the predicate fails, decrement the life of the parent.
                            if (c.parent != null)
                                decrementLife(c.parent, cached_subproofs);
                        }
                        continue;
                    }

                    // t can be proved either by the use of a rule
                    // or if t literally exists in the world

                    Statement t_resolved = evaluate(t, c.env);

                    // If resolving this statement requires putting a literal in subject or predicate position, we
                    // can't prove it.
                    if (t_resolved == Statement.All) {
                        if (c.parent != null)
                            decrementLife(c.parent, cached_subproofs);
                        continue;
                    }

                    ArrayList tcases = new ArrayList();

                    // See if we have already tried to prove this.
                    if (cached_subproofs.ContainsKey(t_resolved)) {
                        StatementList cached_solutions = (StatementList)cached_subproofs[t_resolved];
                        if (cached_solutions == null) {
                            if (Debug) Console.Error.WriteLine("Euler: Dropping queue item because we have already failed to prove it: " + t_resolved);
                        } else {
                            foreach (Statement s in cached_solutions) {
                                if (Debug) Console.Error.WriteLine("Euler: Using Cached Axiom:  " + s);
                                Sequent seq = new Sequent(s);
                                tcases.Add(seq);
                            }
                        }
                    } else {
                        // get all of the rules that apply to the predicate in question
                        if (t_resolved.Predicate != null && cases.ContainsKey(t_resolved.Predicate))
                            tcases.AddRange((IList)cases[t_resolved.Predicate]);

                        if (cases.ContainsKey("WILDCARD"))
                            tcases.AddRange((IList)cases["WILDCARD"]);

                        // if t has no unbound variables and we've matched something from
                        // the axioms, don't bother looking at the world, and don't bother
                        // proving it any other way than by the axiom.
                        bool lookAtWorld = true;
                        foreach (Sequent seq in tcases) {
                            if (seq.body.Length == 0 && seq.head == t_resolved) {
                                lookAtWorld = false;
                                tcases.Clear();
                                tcases.Add(seq);
                                break;
                            }
                        }

                        // if there is a seprate world, get all of the world
                        // statements that witness t
                        if (world != null && lookAtWorld) {
                            MemoryStore w = new MemoryStore();

                            if (Debug) Console.Error.WriteLine("Running " + c);
                            if (Debug) Console.Error.WriteLine("Euler: Ask World: " + t_resolved);
                            world.Select(t_resolved, w);
                            foreach (Statement s in w) {
                                if (Debug) Console.Error.WriteLine("Euler: World Select Response:  " + s);
                                Sequent seq = new Sequent(s);
                                tcases.Add(seq);
                            }
                        }
                    }

                    // If there is no evidence or potential evidence (i.e. rules)
                    // for t, then we will dump this QueueItem by not queuing any
                    // subproofs.

                    // Otherwise we try each piece of evidence in turn.
                    foreach (Sequent rl in tcases) {
                        ArrayList g2 = (ArrayList)c.ground.Clone();
                        if (rl.body.Length == 0) g2.Add(new Ground(rl, new Hashtable()));

                        QueueItem r = new QueueItem();
                        r.rule = rl;
                        r.src = rl;
                        r.ind = 0;
                        r.parent = c;
                        r.env = new Hashtable();
                        r.ground = g2;

                        if (unify(t, c.env, rl.head, r.env, true)) {
                            QueueItem ep = c;  // euler path
                         	while ((ep = ep.parent) != null)
                          		if (ep.src == c.src && unify(ep.rule.head, ep.env, c.rule.head, c.env, false))
                          			break;
                         	if (ep == null) {
                                // It is better for caching subproofs to work an entire proof out before
                                // going on, which means we want to put the new queue item at the
                                // top of the stack.
                         		queue.Add(r);
                                c.liveChildren++;
                         		if (Debug) Console.Error.WriteLine("Euler: Queue from Axiom: " + r);
                         	}
                        }
                    }

                    // If we did not add anything back into the queue for this item, then
                    // we decrement the life of the parent.
                    if (c.liveChildren == 0 && c.parent != null)
                        decrementLife(c.parent, cached_subproofs);
                }
            }

            return evidence;
        }
コード例 #8
0
 /// <summary>
 /// Writes the specified variable to the output writer.
 /// </summary>
 /// <param name="variable">The variable.</param>
 protected virtual void WriteVariable(Variable variable)
 {
     Write("?");
     WriteEscaped(variable.LocalName ?? ("var" + Math.Abs(variable.GetHashCode())));
 }
コード例 #9
0
 public override void Init(Variable[] variables)
 {
     output.WriteLine("<table>");
     output.WriteLine("<tr>");
     foreach (Variable var in variables) {
         if (var.LocalName == null) continue;
         output.WriteLine("<th>" + var.LocalName + "</th>");
     }
     output.WriteLine("</tr>");
 }
コード例 #10
0
ファイル: Euler.cs プロジェクト: shariqatariq/profiles-rns
        public override void Query(Statement[] graph, SemWeb.Query.QueryOptions options, SelectableSource targetModel, SemWeb.Query.QueryResultSink sink)
        {
            QueryCheckArg(graph);

            // Try to do the inferencing.
            ArrayList evidence = prove(rules, targetModel, graph, -1);
            if (evidence == null)
                return; // not provable (in max number of steps, if that were given)

            // Then send the possible bindings to the QueryResultSink.

            // Map variables to indexes.
            Hashtable vars = new Hashtable();
            foreach (Statement s in graph) {
                if (s.Subject is Variable && !vars.ContainsKey(s.Subject)) vars[s.Subject] = vars.Count;
                if (s.Predicate is Variable && !vars.ContainsKey(s.Predicate)) vars[s.Predicate] = vars.Count;
                if (s.Object is Variable && !vars.ContainsKey(s.Object)) vars[s.Object] = vars.Count;
            }

            // Prepare the bindings array.
            Variable[] varOrder = new Variable[vars.Count];
            foreach (Variable v in vars.Keys)
                varOrder[(int)vars[v]] = v;

            // Initialize the sink.
            sink.Init(varOrder);

            // Send a binding set for each piece of evidence.
            foreach (EvidenceItem ei in evidence) {
                // Write a comment to the results with the actual proof. (nifty actually)
                sink.AddComments(ei.ToProof().ToString());

                // Create the binding array and send it on
                Resource[] variableBindings = new Resource[varOrder.Length];
                foreach (Variable v in vars.Keys)
                    if (ei.env.ContainsKey(v))
                        variableBindings[(int)vars[v]] = (Resource)ei.env[v];
                sink.Add(new SemWeb.Query.VariableBindings(varOrder, variableBindings));
            }

            // Close the sink.
            sink.Finished();
        }
コード例 #11
0
 public override void Init(Variable[] variables)
 {
     bool first = true;
     foreach (Variable var in variables) {
         if (var.LocalName == null) continue;
         if (!first) output.Write(","); first = false;
         output.Write(var.LocalName);
     }
     output.WriteLine();
 }
コード例 #12
0
		public override void Init(Variable[] variables) {
            output.WriteStartElement("sparql","http://www.w3.org/2007/SPARQL/results#");//http://www.w3.org/2007/SPARQL/results#
			output.WriteStartElement("head");
			foreach (Variable var in variables) {
				if (var.LocalName == null) continue;
				output.WriteStartElement("variable");
				output.WriteAttributeString("name", var.LocalName);
				output.WriteEndElement();
			}
			output.WriteEndElement(); // head
			output.WriteStartElement("results");
			
			// instead of <results>, we might want <boolean>true</boolean>
		}
コード例 #13
0
			public override void Init(Variable[] variables) {
				vars = new Variable[variables.Length];
				for (int i = 0; i < variables.Length; i++)
					vars[i] = (Variable)variableNames[variables[i].LocalName];
				sink.Init(vars);
			}
コード例 #14
0
                public override void Init(Variable[] variables)
                {
                    java.util.ArrayList vars = new java.util.ArrayList();
                    foreach (Variable b in variables)
                        if (varMap[b] != null) // because of bad treatment of meta
                            vars.add((SparqlVariable)varMap[b]);

                    bindings = new RdfBindingSetImpl(vars);
                }
コード例 #15
0
        public override void Run(SelectableSource source, QueryResultSink resultsink)
        {
            if (!(query is SelectQuery))
            {
                throw new InvalidOperationException("Only SELECT queries are supported by this method (" + query.GetType() + ").");
            }

            // Perform the query
            SelectQuery squery = (SelectQuery)query;

            RdfSourceWrapper sourcewrapper = new RdfSourceWrapper(source, QueryMeta, this);

            MyLogicFactory logic = new MyLogicFactory();

            foreach (RdfFunction f in extFunctions)
            {
                logic.registerExternalFunction(
                    new URIWrapper(f.Uri),
                    new ExtFuncWrapper(sourcewrapper, f));
            }

            squery.bindLogic(logic);

            RdfBindingSet results;

            try {
                results = squery.execute(sourcewrapper);
            } catch (java.lang.Exception e) {
                throw new QueryExecutionException("Error executing query: " + e.Message, e);
            }

            // Prepare binding objects
            java.util.List    vars     = results.getVariables();
            VariableBinding[] bindings = new VariableBinding[vars.size()];
            SparqlVariable[]  svars    = new SparqlVariable[vars.size()];
            SemWebVariable[]  vars2    = new SemWebVariable[vars.size()];
            for (int i = 0; i < bindings.Length; i++)
            {
                svars[i]    = (SparqlVariable)vars.get(i);
                vars2[i]    = new SemWebVariable(svars[i].getName());
                bindings[i] = new VariableBinding(vars2[i], null);
            }

            // Initialize the result sink
            resultsink.Init(bindings, false, false);             // set distinct and ordered

            // Set the comments
            resultsink.AddComments(queryString + "\n");
            resultsink.AddComments(sourcewrapper.GetLog());

            // Iterate the bindings
            java.util.Iterator iter = results.iterator();
            long ctr = -1, ctr2 = 0;

            while (iter.hasNext())
            {
                RdfBindingRow row = (RdfBindingRow)iter.next();

                // Since SPARQL processing may be lazy-delayed,
                // add any new comments that might have been logged.
                resultsink.AddComments(sourcewrapper.GetLog());

                ctr++;

                if (ctr < ReturnStart && ReturnStart != -1)
                {
                    continue;
                }

                for (int i = 0; i < bindings.Length; i++)
                {
                    Resource r = sourcewrapper.ToResource(row.getValue(svars[i]));
                    r           = sourcewrapper.Persist(r);
                    bindings[i] = new VariableBinding(bindings[i].Variable, r);
                }

                resultsink.AddComments(sourcewrapper.GetLog());

                resultsink.Add(bindings);

                ctr2++;
                if (ctr2 >= ReturnLimit && ReturnLimit != -1)
                {
                    break;
                }
            }

            resultsink.AddComments(sourcewrapper.GetLog());

            // Close the result sink.
            resultsink.Finished();
        }
コード例 #16
0
            Resource ToRes(object expr, java.util.Map knownValues, bool entities, Hashtable varMap1, Hashtable varMap2, RdfSourceWrapper src, QueryOptions opts, VariableList distinguishedVars, VariableList undistinguishedVars, java.util.Set sparqlDistinguished)
            {
                if (expr is SparqlVariable) {
                    Variable v;
                    if (varMap1.ContainsKey(expr)) {
                        v = (Variable)varMap1[expr];
                    } else {
                        v = new Variable(expr.ToString());
                        varMap1[expr] = v;
                        varMap2[v] = expr;

                        if (knownValues != null && knownValues.get(expr) != null) {
                            java.util.Set values = (java.util.Set)knownValues.get(expr);
                            VarKnownValuesList values2 = new VarKnownValuesList();
                            for (java.util.Iterator iter = values.iterator(); iter.hasNext(); ) {
                                Resource r = src.ToResource((name.levering.ryan.sparql.common.Value)iter.next());
                                if (r != null)
                                    values2.Add(r);
                            }

                            opts.VariableKnownValues[v] = values2;
                        }

                        if (sparqlDistinguished != null && sparqlDistinguished.contains(expr))
                            distinguishedVars.Add(v);
                        else
                            undistinguishedVars.Add(v);
                    }
                    return v;
                }

                return entities ? src.ToEntity((name.levering.ryan.sparql.common.Value)expr) : src.ToResource((name.levering.ryan.sparql.common.Value)expr);
            }
コード例 #17
0
        public void InteropSemWebInMemoryStoreSource()
        {
            MicrosoftSqlStoreManager mssql = new MicrosoftSqlStoreManager("dotnetrdf_experimental", "sa", "20sQl08");
            InMemoryStoreSource source = new InMemoryStoreSource(new SqlTripleStore(mssql));

            N3Writer writer = new N3Writer(Console.Out);

            Console.WriteLine("Outputting all Triples of the form ?s rdf:type ?type");
            Statement template = new Statement(new Variable(), new Entity(RdfSpecsHelper.RdfType), new Variable());
            source.Select(template, writer);
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Outputting all Triples of the form ?s rdf:type ?car");
            template = new Statement(new Variable(), new Entity(RdfSpecsHelper.RdfType), new Entity("http://example.org/vehicles/Car"));
            source.Select(template, writer);
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Outputting all Triples for Cars and Planes");
            SelectFilter filter = new SelectFilter();
            filter.Predicates = new Entity[] { new Entity(RdfSpecsHelper.RdfType) };
            filter.Objects = new Entity[] { new Entity("http://example.org/vehicles/Car"), new Entity("http://example.org/vehicles/Plane") };
            source.Select(filter, writer);
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Outputting the Speeds of all Cards");
            Variable car = new Variable("car");
            Statement[] pattern = new Statement[] 
            {
                new Statement(car, new Entity(RdfSpecsHelper.RdfType), new Entity("http://example.org/vehicles/Car")),
                new Statement(car, new Entity("http://example.org/vehicles/Speed"), new Variable("speed"))
            };
            source.Query(pattern, new QueryOptions(), new SemWebResultsConsolePrinter());
            Console.WriteLine();

            writer.Close();
        }
コード例 #18
0
ファイル: RdfReader.cs プロジェクト: ArsenShnurkov/beagle-1
		protected void AddVariable(Variable variable) {
			variables[variable] = variable;
		}
コード例 #19
0
		public VariableBinding(Variable variable, Resource target) {
			v = variable;
			t = target;
		}