コード例 #1
0
ファイル: select.cs プロジェクト: JoshData/semweb-dotnet
    public static void Main()
    {
        Store store = new MemoryStore();
        store.Import(RdfReader.LoadFromUri(new Uri(example_foaf_file)));

        // Dump out the data, for fun
        using (RdfWriter writer = new RdfXmlWriter(Console.Out)) {
            writer.Write(store);
        }

        Console.WriteLine("These are the people in the file:");
        foreach (Statement s in store.Select(new Statement(null, rdftype, foafPerson))) {
            foreach (Resource r in store.SelectObjects(s.Subject, foafname))
                Console.WriteLine(r);
        }
        Console.WriteLine();

        Console.WriteLine("And here's RDF/XML just for some of the file:");
        using (RdfWriter w = new RdfXmlWriter(Console.Out)) {
            store.Select(new Statement(null, foafname, null), w);
            store.Select(new Statement(null, foafknows, null), w);
        }
        Console.WriteLine();
    }
コード例 #2
0
ファイル: rdfs.cs プロジェクト: JoshData/semweb-dotnet
    public static void Main()
    {
        // Create the instance data

        MemoryStore dataModel = new MemoryStore();

        BNode me = new BNode("me");
        BNode you = new BNode("you");

        Entity rdfType = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
        Entity rdfsLabel= "http://www.w3.org/2000/01/rdf-schema#label";
        Entity foafPerson = "http://xmlns.com/foaf/0.1/Person";
        Entity foafAgent = "http://xmlns.com/foaf/0.1/Agent";
        Entity foafName = "http://xmlns.com/foaf/0.1/name";

        dataModel.Add(new Statement(me, rdfType, foafPerson));
        dataModel.Add(new Statement(you, rdfType, foafPerson));
        dataModel.Add(new Statement(me, foafName, (Literal)"John Doe"));
        dataModel.Add(new Statement(you, foafName, (Literal)"Sam Smith"));

        // Create the RDFS engine and apply it to the data model.

        RDFS engine = new RDFS();
        engine.LoadSchema(RdfReader.LoadFromUri(new Uri("http://xmlns.com/foaf/0.1/index.rdf")));

        dataModel.AddReasoner(engine);

        // Query the data model

        // Ask for who are typed as Agents.  Note that the people are
        // typed as foaf:Person, and the schema asserts that foaf:Person
        // is a subclass of foaf:Agent.
        Console.WriteLine("Who are Agents?");
        foreach (Entity r in dataModel.SelectSubjects(rdfType, foafAgent))
            Console.WriteLine("\t" + r);

        // Ask for the rdfs:labels of everyone.  Note that the data model
        // has foaf:names for the people, and the schema asserts that
        // foaf:name is a subproperty of rdfs:label.
        Console.WriteLine("People's labels:");
        foreach (Statement s in dataModel.Select(new Statement(null, rdfsLabel, null)))
            Console.WriteLine("\t" + s);
    }
コード例 #3
0
ファイル: containers.cs プロジェクト: JoshData/semweb-dotnet
    public static void Main()
    {
        MemoryStore store = new MemoryStore();

        Entity container = new Entity("http://www.example.org/#container");

        store.Add(new Statement(container, RDF+"type", (Entity)(RDF+"Bag")));
        store.Add(new Statement(container, RDF+"_3", (Literal)"Three"));
        store.Add(new Statement(container, RDF+"_2", (Literal)"Two"));
        store.Add(new Statement(container, RDF+"_1", (Literal)"One"));

        // use the rdfs:member property to match for any rdf:_### predicates.
        Entity rdfs_member = (Entity)(RDFS+"member");

        using (RdfWriter writer = new N3Writer(Console.Out)) {
            writer.Namespaces.AddNamespace(RDF, "rdf");
            store.Select(new Statement(container, rdfs_member, null), writer);
        }

        foreach (Resource r in store.SelectObjects(container, rdfs_member))
            Console.WriteLine(r);
    }
コード例 #4
0
 public void AddNewRDFData(string rdfData, bool removeExistingDataForSubjects)
 {
     MemoryStore store = new MemoryStore();
     RdfXmlReader reader = new RdfXmlReader(new System.IO.StringReader(rdfData));
     store.Import(reader);
     // its possible that we want to update info about some existing concept
     // if removeExistingDataForSubjects is true we first remove existing information before we start adding statements
     if (removeExistingDataForSubjects)
     {
         foreach (Entity subject in store.SelectSubjects(null, null))
             _conceptsStore.Remove(new Statement(subject, null, null));
     }
     foreach (Statement s in store.Select(new Statement(null, null, null)))
         AddNewStatement(s);
     foreach (Entity subject in store.SelectSubjects(null, null))
         UpdateSuggestionsForUri(subject.Uri);
 }
コード例 #5
0
ファイル: Algos.cs プロジェクト: ArsenShnurkov/beagle-1
		public static void MakeLean(Store store, SelectableSource relativeTo, StatementSink removed) {
			// Break the data source into MSGs.  Make each MSG
			// lean first (in isolation).  Then check each lean MSG
			// to see if it's already entailed by the whole store,
			// or by relativeTo if it's provided (not null).
		
			MSG.Graph[] msgs = MSG.FindMSGs(store, true);
			
			foreach (MSG.Graph msgg in msgs) {
				// Load the MSG into memory.
				MemoryStore msg = new MemoryStore(msgg); // unnecessary duplication...

				// Make this MSG lean.  The "right" thing to do is
				// to consider all of the 'connected' subgraphs of MSG
				// against the whole store, rather than the MSG in
				// isolation.  But that gets much too expensive.
				MemoryStore msgremoved = new MemoryStore();
				MakeLeanMSG(new Store(msg), msgg.GetBNodes(), msgremoved);
				
				// Whatever was removed from msg, remove it from the main graph.
				store.RemoveAll(msgremoved.ToArray());
				
				// And track what was removed.
				if (removed != null) msgremoved.Select(removed);
				
				// If this MSG is now (somehow) empty (shouldn't happen,
				// but one never knows), don't test for entailment.
				if (msg.StatementCount == 0) continue;

				// Remove this MSG if it is already entailed.
				
				// The GraphMatch will treat all blank nodes in
				// msg as variables.
				GraphMatch match = new GraphMatch(msg);
				QueryResultBuffer sink = new QueryResultBuffer();
				match.Run(new SubtractionSource(store, msg), sink);
				if (sink.Bindings.Count > 0) {
					// This MSG can be removed.
					store.RemoveAll(msg.ToArray());
					if (removed != null) msg.Select(removed);
				} else if (relativeTo != null) {
					match.Run(relativeTo, sink);
					if (sink.Bindings.Count > 0) {
						// This MSG can be removed.
						store.RemoveAll(msg.ToArray());
						if (removed != null) msg.Select(removed);
					}
				}
			}
		}
コード例 #6
0
ファイル: InfoBox.cs プロジェクト: iainlane/f-spot
            public ImageInfo(ImageFile img)
            {
                // FIXME We use the memory store to hold the anonymous statements
                // as they are added so that we can query for them later to
                // resolve anonymous nodes.
                store = new MemoryStore ();

                if (img == null)
                    return;

                if (img is StatementSource) {
                    SemWeb.StatementSource source = (SemWeb.StatementSource)img;
                    source.Select (this);

                    // If we couldn't find the ISO speed because of the ordering
                    // search the memory store for the values
                    if (iso_speed == null && iso_anon != null) {
                        add = false;
                        store.Select (this);
                    }
                }

                if (img is JpegFile) {
                    int real_width;
                    int real_height;

                    JpegUtils.GetSize (img.Uri.LocalPath, out real_width, out real_height);
                    width = real_width.ToString ();
                    height = real_height.ToString ();
                }
                #if USE_EXIF_DATE
                date = img.Date;
                #endif
            }
コード例 #7
0
        public void InteropSemWebInMemoryStoreConversion()
        {
            //Set up a Store and load 3 Graphs into it
            TripleStore store = new TripleStore();
            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");
            store.Add(g);
            g = new Graph();
            FileLoader.Load(g, "Turtle.ttl");
            store.Add(g);
            g = new Graph();
            g.Assert(new Triple(g.CreateUriNode(new Uri("http://example.org/#this")), g.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)), g.CreateUriNode(new Uri("http://example.org/Graph"))));
            store.Add(g);

            InMemoryStoreSource source = new InMemoryStoreSource(store);

            //Put this all into a SemWeb MemoryStore
            MemoryStore mem = new MemoryStore();
            source.Select(mem);

            SemWebConsolePrinter printer = new SemWebConsolePrinter();
            mem.Select(printer);

            //Read it back into a dotNetRDF TripleStore
            InMemoryStoreSource source2 = new InMemoryStoreSource(new TripleStore());
            mem.Select(source2);

            //Check the two stores are equivalent
            IInMemoryQueryableStore store2 = source2.Store;
            foreach (IGraph graph in store.Graphs)
            {
                String baseUri = (graph.BaseUri == null) ? String.Empty : graph.BaseUri.ToString();
                Assert.IsTrue(store2.HasGraph(graph.BaseUri), "Second Store has Graph '" + baseUri + "' missing");

                Assert.AreEqual(graph, store2.Graph(graph.BaseUri), "Graph '" + baseUri + "' was not the same Graph in both Stores");
            }
            
        }
コード例 #8
0
		private void WriteCollection (MemoryStore substore, Gtk.HTMLStream stream)
		{
			string type = null;

			foreach (Statement stmt in substore) {
				if (stmt.Predicate.Uri == MetadataStore.Namespaces.Resolve ("rdf:type")) {
					string prefix;
					MetadataStore.Namespaces.Normalize (stmt.Object.Uri, out prefix, out type);
				}
			}
			
			stream.Write ("<table cellpadding=5 cellspacing=0 width=100%>");
			foreach (Statement sub in substore) {
				if (sub.Object is Literal) {
					string title;
					string value = ((Literal)(sub.Object)).Value;
					string vc = String.Empty;
					
					Description.GetDescription (substore, sub, out title, out value);

					if (type != "Alt")
						vc = " bgcolor=" + Color (Style.Backgrounds [(int)Gtk.StateType.Normal]);

					if (type == null)
						 stream.Write (String.Format ("<tr bgcolor={3}><td bgcolor={2}>{0}</td><td width=100%>{1}</td></tr>",  
								     Escape (title), 
								     Escape (value),
								     Color (Style.MidColors [(int)Gtk.StateType.Normal]),
								     Color (Style.Backgrounds [(int)Gtk.StateType.Normal])));
					else 
						stream.Write (String.Format ("<tr><td{1}>{0}</td></tr>", 
								    Escape (value),
								    vc));
				} else {
					if (type == null) {
						stream.Write ("<tr><td>");
						MemoryStore substore2 = substore.Select (new Statement ((Entity)sub.Object, null, null, null)).Load();
						if (substore.StatementCount > 0)
							WriteCollection (substore2, stream);
						stream.Write ("</tr><td>");
					}
				}
			}
			stream.Write ("</table>");
		}
コード例 #9
0
ファイル: MetadataDisplay.cs プロジェクト: iainlane/f-spot
        private void WriteCollection(MemoryStore substore, StringBuilder collection)
        {
            string type = null;

            foreach (Statement stmt in substore) {
                if (stmt.Predicate.Uri == MetadataStore.Namespaces.Resolve ("rdf:type")) {
                    string prefix;
                    MetadataStore.Namespaces.Normalize (stmt.Object.Uri, out prefix, out type);
                }
            }

            foreach (Statement sub in substore) {
                if (sub.Object is SemWeb.Literal) {
                    string title;
                    string value = ((SemWeb.Literal)sub.Object).Value;

                    Description.GetDescription (substore, sub, out title, out value);

                    if (type == null)
                        collection.AppendFormat ("\n\t<small>{0}: {1}</small>", title, value);
                    else
                        collection.AppendFormat ("\n\t<small>{0}</small>", value);

                } else {
                    if (type == null) {
                        MemoryStore substore2 = substore.Select (new Statement ((Entity)sub.Object, null, null, null)).Load();
                        if (substore.StatementCount > 0)
                            WriteCollection (substore2, collection);
                    }
                }
            }
        }
コード例 #10
0
ファイル: Euler.cs プロジェクト: shariqatariq/profiles-rns
        // The next few routines convert a set of axioms from a StatementSource
        // into a data structure of use for the algorithm, with Sequents and things.
        private static Hashtable RulesToCases(StatementSource rules)
        {
            Hashtable cases = new Hashtable();
            MemoryStore rules_store = new MemoryStore(rules);
            foreach (Statement p in rules_store) {
                if (p.Meta == Statement.DefaultMeta) {
                    if (p.Predicate == entLOGIMPLIES && p.Object is Entity) {
                        MemoryStore body = new MemoryStore();
                        MemoryStore head = new MemoryStore();

                        rules_store.Select(new Statement(null, null, null,  (Entity)p.Subject), new RemoveMeta(body));
                        rules_store.Select(new Statement(null, null, null,  (Entity)p.Object), new RemoveMeta(head));

                        // Any variables in the head not bound in the body represent existentially closed bnodes.
                        // (Euler's OWL test case does this. Wish they had used bnodes instead of vars...)
                        ResSet bodyvars = new ResSet();
                        foreach (Statement b in body) {
                            if (b.Subject is Variable) bodyvars.Add(b.Subject);
                            if (b.Predicate is Variable) bodyvars.Add(b.Predicate);
                            if (b.Object is Variable) bodyvars.Add(b.Object);
                        }
                        foreach (Entity v in head.GetEntities()) {
                            if (v is Variable && !bodyvars.Contains(v))
                                head.Replace(v, new BNode(((Variable)v).LocalName));
                        }

                        // Replace (...) lists in the body that are tied to the subjects
                        // of user predicates with callArgs objects.
                        Hashtable callArgs = new Hashtable();
                        CollectCallArgs(body, callArgs);

                        // Rules can't have more than one statement in their
                        // consequent.  The best we can do is break up
                        // the consequent into multiple rules.  (Since all head
                        // variables are bound in body, it's equivalent...?)
                        foreach (Statement h in head)
                            AddSequent(cases, new Sequent(h, body.ToArray(), callArgs));
                    } else {
                        AddSequent(cases, new Sequent(p, new Statement[0], null));
                    }
                }
            }

            return cases;
        }
コード例 #11
0
		private bool Query(int groupindex, BindingSet bindings, SelectableSource targetModel) {
			QueryStatement[] group = statements[groupindex];
			
			QueryStatement qs = group[0];
			
			int numMultiplyBound = IsMultiplyBound(qs.Subject, bindings)
				+ IsMultiplyBound(qs.Predicate, bindings)
				+ IsMultiplyBound(qs.Object, bindings);
			
			if (numMultiplyBound >= 1) {
				// If there is one or more multiply-bound variable,
				// then we need to iterate through the permutations
				// of the variables in the statement.
				
				Debug(qs.ToString() + " Something Multiply Bound");
				
				MemoryStore matches = new MemoryStore();
				targetModel.Select(
					new SelectFilter(
						(Entity[])qs.Subject.GetValues(bindings.Union, true),
						(Entity[])qs.Predicate.GetValues(bindings.Union, true),
						qs.Object.GetValues(bindings.Union, false),
						QueryMeta == null ? null : new Entity[] { QueryMeta }
						),
					new ClearMetaDupCheck(matches));
				
				Debug("\t" + matches.StatementCount + " Matches");
				
				if (matches.StatementCount == 0) {
					// This statement doesn't match any of
					// the existing bindings.  If this was
					// optional, preserve the bindings.
					return qs.Optional;
				}
				
				// We need to preserve the pairings of
				// the multiply bound variable with the matching
				// statements.
				
				ArrayList newbindings = new ArrayList();
				
				if (!qs.Optional) bindings.Union.Clear(qs);
				
				foreach (QueryResult binding in bindings.Results) {
					// Break apart the permutations in this binding.
					BindingEnumerator enumer2 = new BindingEnumerator(qs, binding);
					Entity s, p;
					Resource o;
					while (enumer2.MoveNext(out s, out p, out o)) {
						// Get the matching statements from the union query
						Statement bs = new Statement(s, p, o);
						MemoryStore innermatches = matches.Select(bs).Load();
						
						// If no matches, the binding didn't match the filter.
						if (innermatches.StatementCount == 0) {
							if (qs.Optional) {
								// Preserve the binding.
								QueryResult bc = binding.Clone();
								bc.Set(qs, bs);
								newbindings.Add(bc);
								continue;
							} else {
								// Toss out the binding.
								continue;
							}
						}
						
						for (int si = 0; si < innermatches.StatementCount; si++) {
							Statement m = innermatches[si];
							if (!MatchesFilters(m, qs, targetModel)) {
								if (qs.Optional) {
									QueryResult bc = binding.Clone();
									bc.Set(qs, bs);
									newbindings.Add(bc);
								}
								continue;
							}
							bindings.Union.Add(qs, m);
							
							QueryResult r = binding.Clone();
							r.Set(qs, m);
							r.StatementMatched[groupindex] = true;
							newbindings.Add(r);
						}
					}
				}
				
				bindings.Results = newbindings;
				
			} else {
				// There are no multiply bound variables, but if
				// there are more than two unbound variables,
				// we need to be sure to preserve the pairings
				// of the matching values.
			
				int numUnbound = IsUnbound(qs.Subject, bindings)
					+ IsUnbound(qs.Predicate, bindings)
					+ IsUnbound(qs.Object, bindings);
					
				bool sunbound = IsUnbound(qs.Subject, bindings) == 1;
				bool punbound = IsUnbound(qs.Predicate, bindings) == 1;
				bool ounbound = IsUnbound(qs.Object, bindings) == 1;
				
				Statement s = GetStatement(qs, bindings);
				
				// If we couldn't get a statement out of this,
				// then if this was not an optional filter,
				// fail.  If this was optional, don't change
				// the bindings any. 
				if (s == StatementFailed) return qs.Optional;
				
				if (numUnbound == 0) {
					Debug(qs.ToString() + " All bound");
					
					// All variables are singly bound already.
					// We can just test if the statement exists.
					if (targetModel.Contains(s)) {
						// Mark each binding that it matched this statement.
						foreach (QueryResult r in bindings.Results)
							r.StatementMatched[groupindex] = true;
					} else {
						return qs.Optional;
					}
				
				} else if (numUnbound == 1) {
					Debug(qs.ToString() + " 1 Unbound");
				
					// There is just one unbound variable.  The others
					// are not multiply bound, so they must be uniquely
					// bound (but they may not be bound in all results).
					// Run a combined select to find all possible values
					// of the unbound variable at once, and set these to
					// be the values of the variable for matching results.
					
					ResSet values = new ResSet();
					MemoryStore ms = new MemoryStore();
					targetModel.Select(s, ms);
					for (int si = 0; si < ms.StatementCount; si++) {
						Statement match = ms[si];
						if (!MatchesFilters(match, qs, targetModel)) continue;
						if (sunbound) values.Add(match.Subject);
						if (punbound) values.Add(match.Predicate);
						if (ounbound) values.Add(match.Object);
					}
					
					Debug("\t" + values.Count + " matches");
					
					if (values.Count == 0)
						return qs.Optional;
						
					int varIndex = -1;
					if (sunbound) varIndex = qs.Subject.VarIndex;
					if (punbound) varIndex = qs.Predicate.VarIndex;
					if (ounbound) varIndex = qs.Object.VarIndex;
					
					if (bindings.Results.Count == 0)
						bindings.Results.Add(new QueryResult(this));
					
					bindings.Union.Bindings[varIndex] = new ResSet();
					foreach (Resource r in values)
						bindings.Union.Bindings[varIndex].Add(r);
						
					foreach (QueryResult r in bindings.Results) {
						// Check that the bound variables are bound in this result.
						// If it is bound, it will be bound to the correct resource,
						// but it might not be bound at all if an optional statement
						// failed to match -- in which case, don't modify the binding.
						if (qs.Subject.IsVariable && !sunbound && r.Bindings[qs.Subject.VarIndex] == null) continue;
						if (qs.Predicate.IsVariable && !punbound && r.Bindings[qs.Predicate.VarIndex] == null) continue;
						if (qs.Object.IsVariable && !ounbound && r.Bindings[qs.Object.VarIndex] == null) continue;
					
						r.Bindings[varIndex] = values;
						r.StatementMatched[groupindex] = true;
					}
					
				} else {
					// There are two or more unbound variables, the
					// third variable being uniquely bound, if bound.
					// Keep track of the pairing of unbound variables.
					
					if (numUnbound == 3)
						throw new QueryExecutionException("Query would select all statements in the store.");
					
					Debug(qs.ToString() + " 2 or 3 Unbound");
				
					if (bindings.Results.Count == 0)
						bindings.Results.Add(new QueryResult(this));
						
					ArrayList newbindings = new ArrayList();
					MemoryStore ms = new MemoryStore();
					targetModel.Select(s, ms);
					for (int si = 0; si < ms.StatementCount; si++) {
						Statement match = ms[si];
						if (!MatchesFilters(match, qs, targetModel)) continue;
						bindings.Union.Add(qs, match);
						foreach (QueryResult r in bindings.Results) {
							if (numUnbound == 2) {
								// Check that the bound variable is bound in this result.
								// If it is bound, it will be bound to the correct resource,
								// but it might not be bound at all if an optional statement
								// failed to match -- in which case, preserve the binding if
								// this was an optional statement.
								bool matches = true;
								if (qs.Subject.IsVariable && !sunbound && r.Bindings[qs.Subject.VarIndex] == null) matches = false;
								if (qs.Predicate.IsVariable && !punbound && r.Bindings[qs.Predicate.VarIndex] == null) matches = false;
								if (qs.Object.IsVariable && !ounbound && r.Bindings[qs.Object.VarIndex] == null) matches = false;
								if (!matches) {
									if (qs.Optional)
										newbindings.Add(r);
									continue;
								}
							}
						
							QueryResult r2 = r.Clone();
							r2.Add(qs, match);
							r2.StatementMatched[groupindex] = true;
							newbindings.Add(r2);
						}
					}
					if (newbindings.Count == 0)
						return qs.Optional; // don't clear out bindings if this was optional and it failed
					bindings.Results = newbindings;
				}
			}
			
			return true;
		}