Ejemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ontology"></param>
        public void ParseXml(Ontology ontology)
        {
            var xDocument            = XDocument.Parse(ontology.Xml);
            var ontologyXmlNameSpace = xDocument.Descendants(rdfNamespace + "RDF").Select(x => x.Attribute("xmlns").Value).FirstOrDefault();

            if (ontologyXmlNameSpace.IndexOf("#") != -1)
            {
                ontologyXmlNameSpace = ontologyXmlNameSpace.Substring(0, ontologyXmlNameSpace.IndexOf("#"));
            }

            var ontologyTerms = xDocument.Descendants(owlNamespace + "Class")
                                .Where(x => x.Attribute(rdfNamespace + "about") != null)
                                .Select(x => new OntologyTerm
            {
                TermRaw = x.ToString(),
                TermUri = x.Attribute(rdfNamespace + "about").Value,
                //TermName = UrlHelper.ExtractTermIdentifierFromUrl(x.Attribute(rdfNamespace + "about").Value),
                TermName = string.IsNullOrEmpty(x.Descendants(rdfsNamespace + "label")?.FirstOrDefault()?.Value)
                                    ? UrlHelper.ExtractTermIdentifierFromUrl(x.Attribute(rdfNamespace + "about").Value)
                                    : x.Descendants(rdfsNamespace + "label")?.FirstOrDefault()?.Value,
                ParentTermURI = x.Descendants(rdfsNamespace + "subClassOf")?.FirstOrDefault(y => !y.HasElements)?.Attribute(rdfNamespace + "resource").Value,
                Ontology      = ontology
            })
                                .ToList();

            ontologyTerms = ontologyTerms.Where(x => !string.IsNullOrEmpty(x.TermName)).ToList();

            ArrangeTerm(ontologyTerms);

            ontology.OntologyTerms = ontologyTerms;
        }
        /// <summary>
        /// Gets a short name representation for an ontology, based on the last segment
        /// of the ontology IRI or (in the case of anonymous ontologies) the ontology hash.
        /// Useful for qname prefixes.
        /// </summary>
        /// <param name="ontology"></param>
        /// <returns></returns>
        public static string GetShortName(this Ontology ontology)
        {
            // Fallback way of getting a persistent short identifier in the
            // (unlikely?) case that we are dealing w/ an anonymous ontology
            if (!ontology.IsNamed())
            {
                return(ontology.GetHashCode().ToString(invariantCulture));
            }

            // This is a simple string handling thing
            string ontologyUriString = ontology.GetUri().AbsoluteUri;

            // Trim any occurences of entity separation characters
            if (ontologyUriString.EndsWith("/", StringComparison.Ordinal) || ontologyUriString.EndsWith("#", StringComparison.Ordinal))
            {
                char[] trimChars = { '/', '#' };
                ontologyUriString = ontologyUriString.Trim(trimChars);
            }

            // Get the last bit of the string, after the last slash
            ontologyUriString = ontologyUriString.Substring(ontologyUriString.LastIndexOf('/') + 1);

            // If the string contains dots, treat them as file ending delimiter and get rid of them
            // one at a time
            while (ontologyUriString.Contains('.', StringComparison.Ordinal))
            {
                ontologyUriString = ontologyUriString.Substring(0, ontologyUriString.LastIndexOf('.'));
            }

            return(ontologyUriString);
        }
Ejemplo n.º 3
0
        public void TestOntologyTripleAssertion()
        {
            using (IGraph g = new Graph())
            {
                Ontology.AssertOntologyTriples(g);

                Assert.IsTrue(((SparqlResultSet)g.ExecuteQuery("SELECT * { ?s ?p ?o }")).Results.Count > 100);

                var personValues = ((SparqlResultSet)g.ExecuteQuery(
                                        "SELECT * { <http://www.stellman-greene.com/person#Person> ?p ?o } ORDER BY STR(?p)"
                                        )).Results
                                   .Select(r => new string[] { r["p"].ToString(), r["o"].ToString() });
                Assert.AreEqual(personValues.Count(), 3);
                Assert.IsTrue(personValues.ElementAt(0).SequenceEqual(new string[] { "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", "http://www.w3.org/2002/07/owl#Class" }));
                Assert.IsTrue(personValues.ElementAt(1).SequenceEqual(new string[] { "http://www.w3.org/2000/01/rdf-schema#comment", "Class that represents a person" }));
                Assert.IsTrue(personValues.ElementAt(2).SequenceEqual(new string[] { "http://www.w3.org/2000/01/rdf-schema#label", "Person" }));

                var isStarValues = ((SparqlResultSet)g.ExecuteQuery(
                                        "SELECT * { <http://www.stellman-greene.com/person#isStar> ?p ?o } ORDER BY STR(?p)"
                                        )).Results
                                   .Select(r => new string[] { r["p"].ToString(), r["o"].ToString() });
                Assert.AreEqual(isStarValues.Count(), 5);
                Assert.IsTrue(isStarValues.ElementAt(0).SequenceEqual(new string[] { "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", "http://www.w3.org/2002/07/owl#DatatypeProperty" }));
                Assert.IsTrue(isStarValues.ElementAt(1).SequenceEqual(new string[] { "http://www.w3.org/2000/01/rdf-schema#comment", "Property that indicates whether or not a person is a star" }));
                Assert.IsTrue(isStarValues.ElementAt(2).SequenceEqual(new string[] { "http://www.w3.org/2000/01/rdf-schema#domain", "http://www.stellman-greene.com/person#Person" }));
                Assert.IsTrue(isStarValues.ElementAt(3).SequenceEqual(new string[] { "http://www.w3.org/2000/01/rdf-schema#label", "Is Star" }));
                Assert.IsTrue(isStarValues.ElementAt(4).SequenceEqual(new string[] { "http://www.w3.org/2000/01/rdf-schema#range", "http://www.w3.org/2001/XMLSchema#boolean" }));
            }
        }
Ejemplo n.º 4
0
        public void  CompoundNounTest()
        {
            Ontology.EraseConcepts();
            ParseAndExecute("a cat is a kind of person",
                            "a persian is a kind of cat",
                            "a tabby is a kind of cat",
                            "a siamese is a kind of cat",
                            "a cat can be haughty",
                            "a cat can be cuddly",
                            "a cat can be crazy",
                            "a persian can be matted",
                            "thaumaturge and necromancer are kinds of magic user");
            var cat       = (CommonNoun)Noun.Find("cat");
            var magicUser = (CommonNoun)Noun.Find("magic", "user");
            var g         = new Generator(cat, magicUser);

            for (var n = 0; n < 100; n++)
            {
                var i = g.Solve();
                Assert.IsTrue(i.IsA(i.Individuals[0], cat));
                Assert.IsTrue(i.IsA(i.Individuals[0], "persian") ||
                              i.IsA(i.Individuals[0], "tabby") ||
                              i.IsA(i.Individuals[0], "siamese"));
                Console.WriteLine(i.Model.Model);
                Console.WriteLine(i.Description(i.Individuals[0]));
            }
        }
Ejemplo n.º 5
0
        public void DeclarationOrderTest()
        {
            var o = new Ontology("test");

            o.ParseAndExecute("Persian, tabby, Siamese, manx, Chartreux, and Maine coon are kinds of cat.",
                              "cat, dog, bunny, dragon, toad, basilisk, owl, flumph, boar, phoenix, unicorn, and homunculus are kinds of pet.");
        }
Ejemplo n.º 6
0
 public void InterningNounTest()
 {
     Ontology.EraseConcepts();
     ParseAndExecute("Tabby, Persian, and Maine Coon are kinds of cat");
     Assert.IsNotNull(Noun.Find("Persian"));
     Assert.IsNotNull(Noun.Find("Persians"));
 }
Ejemplo n.º 7
0
        public void ProperNameTest()
        {
            Ontology.EraseConcepts();
            ParseAndExecute("a cat is a kind of person",
                            "a persian is a kind of cat",
                            "a tabby is a kind of cat",
                            "a siamese is a kind of cat",
                            "a cat can be haughty",
                            "a cat can be cuddly",
                            "a cat can be crazy",
                            "a persian can be matted",
                            "thaumaturgy is a form of magic",
                            "necromancy is a form of magic",
                            "a magic user must practice one form of magic");
            var cat         = (CommonNoun)Noun.Find("cat");
            var magicUser   = (CommonNoun)Noun.Find("magic", "user");
            var thaumaturgy = Individual.AllPermanentIndividuals["thaumaturgy"];
            var necromancy  = Individual.AllPermanentIndividuals["necromancy"];
            var g           = new Generator(cat, magicUser);

            for (var n = 0; n < 100; n++)
            {
                var i = g.Solve();
                Assert.IsTrue(i.Holds("practices", i.Individuals[0], thaumaturgy) ||
                              i.Holds("practices", i.Individuals[0], necromancy));
                Console.WriteLine(i.Model.Model);
                Console.WriteLine(i.Description(i.Individuals[0]));
            }
        }
Ejemplo n.º 8
0
        public void PartTest()
        {
            Ontology.EraseConcepts();
            ParseAndExecute("a cat is a kind of person",
                            "a persian is a kind of cat",
                            "a tabby is a kind of cat",
                            "a siamese is a kind of cat",
                            "a cat can be haughty",
                            "a cat can be cuddly",
                            "a cat can be crazy",
                            "a persian can be matted",
                            "red, blue, and green are kinds of color",
                            "a cat has a color called its favorite color");
            var cat   = (CommonNoun)Noun.Find("cat");
            var color = (CommonNoun)Noun.Find("color");
            var g     = new Generator(cat);

            for (var n = 0; n < 100; n++)
            {
                var i = g.Solve();
                Assert.IsTrue(i.IsA(i.Individuals[0], cat));
                Assert.IsTrue(i.IsA(i.Individuals[0], "persian") ||
                              i.IsA(i.Individuals[0], "tabby") ||
                              i.IsA(i.Individuals[0], "siamese"));
                Assert.AreEqual(i.Individuals[0], i.Individuals[1].Container);
                Assert.IsTrue(i.IsA(i.Individuals[1], color));
                Console.WriteLine(i.Model.Model);
                Console.WriteLine(i.Description(i.Individuals[0]));
            }
        }
Ejemplo n.º 9
0
        public void MultipleRangePropertyTest()
        {
            var o = new Ontology("MultipleRangePropertyTest");

            o.Parser.ParseAndExecute("cats have an age between 1 and 20",
                                     "kittens are a kind of cat",
                                     "kittens have an age between 1 and 2",
                                     "adults are a kind of cat",
                                     "adults have an age between 2 and 20");
            var g   = o.Generator("cat");
            var age = o.Property("age");

            for (var n = 0; n < 200; n++)
            {
                var i      = g.Generate();
                var cat    = i.Individuals[0];
                var catAge = (float)(i.PropertyValue(cat, age));
                if (i.IsA(cat, "kitten"))
                {
                    Assert.IsTrue(catAge >= 1);
                    Assert.IsTrue(catAge <= 2);
                }
                else
                {
                    Assert.IsTrue(catAge >= 2);
                    Assert.IsTrue(catAge <= 20);
                }
            }
        }
Ejemplo n.º 10
0
        public void TestPersonWithNoPublications()
        {
            Person sylvia = _people.PersonList.Find(p => p.Setnb == "A7809652");

            Assert.AreEqual("Wassertheil-Smoller, Sylvia (A7809652)", sylvia.ToString());
            using (IGraph g = new Graph())
            {
                Ontology.AssertOntologyTriples(g);
                _updater.AddPersonToGraph(g, sylvia);

                var sylviaTriples = ((SparqlResultSet)g.ExecuteQuery("SELECT * { ?s ?p ?o }")).Results
                                    .Select(r => new string[] { r["s"].ToString(), r["p"].ToString(), r["o"].ToString() });

                string first = sylviaTriples.Where(r => r[1] == "http://www.stellman-greene.com/person#first").First()[2];
                Assert.AreEqual("Sylvia", first);

                string last = sylviaTriples.Where(r => r[1] == "http://www.stellman-greene.com/person#last").First()[2];
                Assert.AreEqual("Wassertheil-Smoller", last);

                string setnb = sylviaTriples.Where(r => r[1] == "http://www.stellman-greene.com/person#setnb").First()[2];
                Assert.AreEqual("A7809652", setnb);

                var sylviaColleagues = sylviaTriples
                                       .Where(r => r[0] == "http://www.stellman-greene.com/person/A7809652" && r[1] == "http://www.stellman-greene.com/person#colleagueOf")
                                       .Select(r => r[2])
                                       .ToList <string>();

                Assert.AreEqual(1, sylviaColleagues.Count());
                CollectionAssert.Contains(sylviaColleagues, "http://www.stellman-greene.com/person/X0000003");
            }
        }
Ejemplo n.º 11
0
        internal static KhartaOntology addUpdateContainer(KhartaOntology container)
        {
            Func <KhartaOntology, Ontology> toOntology = (KhartaOntology fromContainer) => FromContainer(fromContainer);
            Ontology _ontology = toOntology(container);

            //Ontology _ontology = (Ontology) container;// new Ontology() ;//(Ontology) container;
            int id = container.Id;
            // KhartaOntology container = new KhartaOntology();
            Type ct = container.GetType();
            Type ot = _ontology.GetType();
            IList <PropertyInfo> cprop = new List <PropertyInfo>(ct.GetProperties());
            IList <PropertyInfo> oprop = new List <PropertyInfo>(ot.GetProperties());

            //KhartaOntology container = new KhartaOntology();
            if (id == 0)
            {
                try
                {
                    using (var dbcontext = new KhartaDataModel())
                    {
                        _ontology = dbcontext.Ontologies.Add(_ontology);

                        dbcontext.SaveChanges();
                        foreach (PropertyInfo op in oprop)
                        {
                            var value = op.GetValue(_ontology, null);
                            op.SetValue(container, value, null);
                        }
                    }
                    return(container);
                }
                catch (Exception ex) {
                    Debug.WriteLine(ex.Message);
                }
            }
            else
            {
                using (var dbcontext = new KhartaDataModel())
                {
                    var containers = from o in dbcontext.Ontologies
                                     where o.Id.Equals(_ontology.Id)
                                     select o;
                    var currentContainer = containers.FirstOrDefault();


                    foreach (PropertyInfo op in oprop)
                    {
                        if (op.CanWrite)
                        {
                            var value = op.GetValue(_ontology, null);
                            op.SetValue(currentContainer, value, null);
                        }
                    }
                    dbcontext.SaveChanges();
                    container = ToContainer(currentContainer);
                }
            }

            return(container);
        }
Ejemplo n.º 12
0
        public static void GenerateOntologyBinFile()
        {
            string _ontologyDirectoryPath =
                @"..\..\..\Ontology\Formatted OntoSem\";
            Ontology     onto = new Ontology(_ontologyDirectoryPath);
            StreamReader sr   = new StreamReader(onto.OntologyPath + "\\Get.txt");
            string       str  = null;

            while ((str = sr.ReadLine()) != null)
            {
                if (str == "")
                {
                    continue;
                }
                onto.LoadConcept(str);
            }
            sr.Close();
            BinaryFormatter bf = new BinaryFormatter();
            FileStream      fs = new FileStream(
                onto.OntologyPath + "\\Ontology.bin", FileMode.Create);

            bf.Serialize(fs, onto);
            fs.Close();
            //MessageBox.Show("Finished");
        }
Ejemplo n.º 13
0
        public void VerbQuantificationTest()
        {
            var o = new Ontology(nameof(VerbQuantificationTest));

            o.ParseAndExecute(
                "employee and employer are kinds of person",
                "an employee must work for one employer",
                "an employer must be worked for by at least two employees");
            var g        = o.CommonNoun("person").MakeGenerator(10);
            var employee = o.CommonNoun("employee");
            var employer = o.CommonNoun("employer");
            var workFor  = o.Verb("work", "for");

            for (var count = 0; count < 100; count++)
            {
                var invention = g.Generate();
                foreach (var person in invention.PossibleIndividuals)
                {
                    if (person.IsA(employee))
                    {
                        Assert.AreEqual(1, invention.PossibleIndividuals.Count(p => person.RelatesTo(p, workFor)));
                    }
                    else if (person.IsA(employer))
                    {
                        Assert.IsTrue(2 <= invention.PossibleIndividuals.Count(p => p.RelatesTo(person, workFor)));
                    }
                    else
                    {
                        throw new Exception("Object in model that is neither an employee or employer");
                    }
                }
            }
        }
        private async Task LoadAsync(Models.Types?filterType)
        {
            List <Ontology> ontologies = await DigitalTwinsHelper.GetOntologiesWithTypes(_cache, Loggers.SilentLogger);

            List <Ontology> filteredOntologies = new List <Ontology>();
            Ontology        ontology;

            foreach (Ontology item in ontologies)
            {
                ontology = new Ontology()
                {
                    Id = item.Id, Name = item.Name, Loaded = item.Loaded
                };
                if (filterType != null)
                {
                    ontology.types = item.types.FindAll(t => t.Category.Equals(filterType.ToString()));
                }
                else
                {
                    ontology.types = item.types;
                }
                filteredOntologies.Add(ontology);
            }
            OntologyList = filteredOntologies;
        }
Ejemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ontology"></param>
        /// <param name="idOntologyTerm"></param>
        /// <returns></returns>
        public OntologyTerm FindTerm(Ontology ontology, int idOntologyTerm)
        {
            OntologyTerm termFound = null;

            termFound = FindTerm(ontology.OntologyTerms, idOntologyTerm);

            return(termFound);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Adds the content and its description to the message
 /// </summary>
 /// <param name="content">Content</param>
 /// <param name="language">Language</param>
 /// <param name="encoding">Encoding</param>
 /// <param name="ontology">Ontology</param>
 public void AddContent(string content, string language, string encoding,
                        Ontology ontology)
 {
     this._content  = content;
     this._language = language;
     this._encoding = encoding;
     this._ontology = ontology;
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Rerun the declarations that were not undone.
 /// </summary>
 private static void Replay()
 {
     Ontology.Reload();
     foreach (var decl in Declarations)
     {
         Parser.ParseAndExecute(decl);
     }
 }
Ejemplo n.º 18
0
        public void RiTest2()
        {
            // Due to Ri Boksenbaum
            var o = new Ontology("test");

            o.ParseAndExecute("Persian, tabby, Siamese, manx, Chartreux, and Maine coon are kinds of cat.",
                              "   The plural of Chartreux is Chartreux.");
        }
Ejemplo n.º 19
0
        public void OptionalAlternativeSetTest()
        {
            Ontology.EraseConcepts();
            ParseAndExecute("cats can be big or small");
            var cat = CommonNoun.Find("cat");

            Assert.AreEqual(1, cat.AlternativeSets.Count);
        }
Ejemplo n.º 20
0
        public void RequiredAlternativeSetTest()
        {
            Ontology.EraseConcepts();
            ParseAndExecute("cats are long haired or short haired");
            var cat = CommonNoun.Find("cat");

            Assert.AreEqual(1, cat.AlternativeSets.Count);
        }
Ejemplo n.º 21
0
        public void BeRelatedToTest()
        {
            Ontology.EraseConcepts();
            ParseAndExecute("A character can be related to one other character");
            var love = Verb.Find("be", "related", "to");

            Assert.IsNotNull(love);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Gets the version IRI of the ontology, if it is defined, or the ontology
 /// IRI if it is not. If neither is defined (i.e. the ontology is anonymous),
 /// throws an exception.
 /// </summary>
 /// <param name="ontology"></param>
 /// <returns></returns>
 public static Uri GetVersionOrOntologyIri(this Ontology ontology)
 {
     if (ontology.HasVersionIri())
     {
         return(ontology.GetVersionIri());
     }
     return(ontology.GetIri());
 }
Ejemplo n.º 23
0
        public void LockedOntologyTest()
        {
            var o = new Ontology("LockedOntologyTest");

            o.ParseAndExecute("a cat is a kind of person");
            o.IsLocked = true;
            o.ParseAndExecute("an alligator is a kind of cat");
        }
Ejemplo n.º 24
0
        public void RiTest()
        {
            // Due to Ri Boksenbaum
            var o = new Ontology("test");

            o.ParseAndExecute("sheep and orange are kinds of cat.",
                              "the plural of sheep is sheep");
        }
Ejemplo n.º 25
0
        public void ParseAntiReflexiveTest()
        {
            Ontology.EraseConcepts();
            ParseAndExecute("Cats are a kind of person.",
                            "Cats cannot love themselves");
            var love = Verb.Find("love");

            Assert.IsNotNull(love);
        }
Ejemplo n.º 26
0
        public void MultiPartTest()
        {
            var o = new Ontology("MultiPartTest");

            o.Parser.ParseAndExecute("A person has 4 pastimes called their hobbies");
            var invention = o.Generator("person").Generate();

            Assert.AreEqual(5, invention.Individuals.Count);
        }
Ejemplo n.º 27
0
        public void NewTest()
        {
            var o = new Ontology("test");

            o.ParseAndExecute("Persian, tabby, Siamese, manx, Chartreux, and Maine coon are kinds of cat.",
                              "Cats are black, white, grey, or ginger.",
                              "The plural of Chartreux is Chartreux",
                              "Chartreux are grey.");
        }
Ejemplo n.º 28
0
        public void ImagineNotKnowingTest()
        {
            var o = new Ontology("Not knowing test")
            {
                IsLocked = true
            };

            o.ParseAndExecute("imagine not knowing what a car is");
        }
Ejemplo n.º 29
0
        public static Uri GetVersionIri(this Ontology ontology)
        {
            if (!ontology.HasVersionIri())
            {
                throw new RdfException($"Ontology {ontology} does not have an owl:versionIRI annotation");
            }

            IUriNode versionIri = ontology.Graph.CreateUriNode(VocabularyHelper.OWL.versionIRI);
            return ontology.GetNodesViaProperty(versionIri).UriNodes().First().Uri;
        }
Ejemplo n.º 30
0
 void LoadOntology()
 {
     if (Onto == null)
     {
         BinaryFormatter      bf = new BinaryFormatter();
         System.IO.FileStream fs = new System.IO.FileStream(
             @"..\..\..\Ontology\Formatted OntoSem\Ontology.bin", FileMode.Open);
         Onto = (Ontology)bf.Deserialize(fs);
         fs.Close();
     }
 }
Ejemplo n.º 31
0
 public DebuggerDisplayProxy(Ontology ontology)
 {
     _ontology = ontology;
 }