コード例 #1
0
        public IGraph MergeTwoOntologies(IGraph o1, IGraph o2, double classThreshold, double propertyThreshold, IProgress <double> progress = null)
        {
            _merged = new OntologyGraph();
            _merged.Merge(o1);
            _merged.Merge(o2);

            Dictionary <string, List <SimilarClassPropertyDescription> > simDict = GetSimilarOntologyClassesMatrix(includeProperties: true, progress: progress);
            List <SimilarClassPropertyDescription> similarClasses = new List <SimilarClassPropertyDescription>();

            foreach (var key in simDict.Keys)
            {
                SimilarClassPropertyDescription map = (from mapping
                                                       in simDict[key]
                                                       where mapping.SimilarityScore == simDict[key].Max(x => x.SimilarityScore)
                                                       select mapping).First(); //select pairs with highest similarity score
                similarClasses.Add(map);
            }

            (this as IInteractiveMerger).MergeOntologyClasses(
                similarClasses,
                simPair => simPair.SimilarityScore >= classThreshold,        //no user interaction here
                propPair => propPair.SimilarityScore >= propertyThreshold,   //no user interaction here
                propertyThreshold,
                new ShortestFederatedNamesGenerator(),
                new XSDTypeCaster(),
                progress);

            return(_merged);
        }
コード例 #2
0
 public static bool HasBaseUriOntology(this OntologyGraph graph)
 {
     IUriNode baseUriNode = graph.CreateUriNode(graph.BaseUri);
     IUriNode rdfType = graph.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
     IUriNode owlOntology = graph.CreateUriNode(new Uri(OntologyHelper.OwlOntology));
     return graph.ContainsTriple(new Triple(baseUriNode, rdfType, owlOntology));
 }
コード例 #3
0
ファイル: Program.cs プロジェクト: yuryk53/MappingGenerator
        static void TryMergeOntologies(OntologyGraph o1, OntologyGraph o2)
        {
            IOntologyMerger merger = new WordNetOntologyMerger();

            merger.Initialize(o1, o2);

            Dictionary <string, List <SimilarClassPropertyDescription> > simDict = merger.GetSimilarOntologyClassesMatrix();
            List <SimilarClassPropertyDescription> similarClasses = new List <SimilarClassPropertyDescription>();

            foreach (var key in simDict.Keys)
            {
                SimilarClassPropertyDescription map = (from mapping
                                                       in simDict[key]
                                                       where mapping.SimilarityScore == simDict[key].Max(x => x.SimilarityScore)
                                                       select mapping).First();
                similarClasses.Add(map);
            }


            IInteractiveMerger interactiveMerger = merger as IInteractiveMerger;

            interactiveMerger.MergeOntologyClasses(similarClasses,
                                                   AskUserIfCanMerge,
                                                   AskUserIfCanMerge,
                                                   0.6,
                                                   new ShortestFederatedNamesGenerator(),
                                                   new XSDTypeCaster());
        }
コード例 #4
0
ファイル: OWLManager.cs プロジェクト: albarsil/OntoSeman
        /** Carrega a ontologia atraves do modulo passado como parametro no construtor
         * */
        public OntologyGraph LoadOntology(string path)
        {
            Ontology = new OntologyGraph();

            FileLoader.Load(Ontology, path);

            return(Ontology);
        }
コード例 #5
0
ファイル: CompileUnit.cs プロジェクト: ukparliament/Mapping
 internal CompileUnit(string name, OntologyGraph ontology,
                      CompileUnitOption compileUnitOption, string modelOutputLocation = null)
 {
     this.ontology = ontology;
     this.name     = name;
     this.AddReferences();
     this.AddNamespace(compileUnitOption);
 }
コード例 #6
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="graph"></param>
 public ImportOptionsForm(OntologyGraph graph)
 {
     InitializeComponent();
     this.graph = graph;
     RdfOntologyOperations.instance.resourcesToImport.Clear();
     RdfOntologyOperations.instance.nestedProperties.Clear();
     InitializeTreeView();
 }
コード例 #7
0
 public void LoadGraph()
 {
     if (Graph == null)
     {
         Graph = new OntologyGraph();
         Graph.LoadFromFile(HostingEnvironment.MapPath(OntologyPath));
     }
 }
コード例 #8
0
        public static IEnumerable <OntologyProperty> IsScopedDomainOf(this OntologyClass cls)
        {
            OntologyGraph          graph         = cls.Graph as OntologyGraph;
            IUriNode               onProperty    = graph.CreateUriNode(new Uri("http://www.w3.org/2002/07/owl#onProperty"));
            IEnumerable <IUriNode> propertyNodes = cls.DirectSuperClasses.Where(superClass => superClass.IsRestriction())
                                                   .SelectMany(restriction => restriction.GetNodesViaProperty(onProperty)).UriNodes();

            return(propertyNodes.Select(node => graph.CreateOntologyProperty(node)));
        }
コード例 #9
0
 /// <summary>
 /// Gets all owl:Ontology nodes declared in the graph, packaged as Ontology objects.
 /// </summary>
 /// <param name="graph"></param>
 /// <returns></returns>
 public static IEnumerable<Ontology> GetOntologies(this OntologyGraph graph)
 {
     IUriNode rdfType = graph.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
     IUriNode owlOntology = graph.CreateUriNode(new Uri(OntologyHelper.OwlOntology));
     IEnumerable<IUriNode> ontologyNodes = graph.GetTriplesWithPredicateObject(rdfType, owlOntology)
         .Select(triple => triple.Subject)
         .UriNodes();
     return ontologyNodes.Select(node => new Ontology(node, graph));
 }
コード例 #10
0
        public static IEnumerable <Individual> GetIndividuals(this OntologyGraph graph, OntologyClass ontologyClass)
        {
            IUriNode classNode = ontologyClass.GetUriNode();
            IUriNode rdfType   = graph.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType));

            return(graph.GetTriplesWithPredicateObject(rdfType, classNode)
                   .Where(triple => triple.Subject.IsUri())
                   .Select(triple => new Individual(triple.Subject, graph)));
        }
コード例 #11
0
 public void LoadGraph()
 {
     if (Graph == null)
     {
         Graph = new OntologyGraph();
         if (File.Exists(Path.Combine(Environment.CurrentDirectory, "Ontology.owl")))
         {
             Graph.LoadFromFile(Path.Combine(Environment.CurrentDirectory, "Ontology.owl"));
         }
     }
 }
コード例 #12
0
        private void btnSaveChanges_Click(object sender, RoutedEventArgs e)
        {
            /*
             *  1. Find old datatype property
             *  2. Delete old datatype property
             *  3. Create new object property
             *  4. Add new object property
             *  5. Add new user-defined range
             */

            //1. Find old datatype property
            OntologyGraph ontology = tviInfo.OntologyGraph;
            INode         subj     = ontology.CreateUriNode(new Uri(tviInfo.URI));
            INode         pred     = ontology.CreateUriNode("rdf:type");
            INode         obj      = ontology.CreateUriNode("owl:DatatypeProperty");


            //2. Delete old datatype property & its ranges
            List <Triple> dtRangeTriples = ontology.GetTriplesWithSubjectPredicate(subj, ontology.CreateUriNode("rdfs:range")).ToList();
            bool          b1             = ontology.Retract(dtRangeTriples);

            ontology.Retract(subj, pred, obj);


            //3. Create new object property
            obj = ontology.CreateUriNode("owl:ObjectProperty");

            //4. Add new object property
            ontology.Assert(subj, pred, obj);

            //5. Add new range
            //rdfs:range rdf:resource="&kms;User"
            string rangeUserDefined = this.comboRange.SelectedItem.ToString();

            if (rangeUserDefined.Contains("foaf:") && !ontology.NamespaceMap.HasNamespace("foaf"))
            {
                ontology.NamespaceMap.AddNamespace("foaf", new Uri(Properties.Settings.Default.foafUri));
            }
            pred = ontology.CreateUriNode("rdfs:range");
            obj  = ontology.CreateUriNode(rangeUserDefined);
            ontology.Assert(subj, pred, obj);

            if (OnPropertyConverted != null)
            {
                tviInfo.Range  = this.comboRange.SelectedItem.ToString();
                tviInfo.Domain = this.lblDomain.Content.ToString();
                tviInfo.Type   = MainWindow.OntologyObjectType.OBJECT_PROPERTY;

                OnPropertyConverted(tviInfo); //after the conversion was done
            }
            this.Close();
        }
コード例 #13
0
 /// <summary>
 /// Returns the "main" owl:Ontology declared in the the graph. Will
 /// return the owl:Ontology whose identifier matches the RDF graph base
 /// URI; if no such owl:Ontology is present, will return the first declared
 /// owl:Ontology; if there are none, will throw an RdfException.
 /// </summary>
 /// <param name="graph"></param>
 /// <returns></returns>
 public static Ontology GetOntology(this OntologyGraph graph)
 {
     if (graph.HasBaseUriOntology())
     {
         return graph.GetBaseUriOntology();
     }
     IEnumerable<Ontology> graphOntologies = graph.GetOntologies();
     if (graphOntologies.Any())
     {
         return graphOntologies.First();
     }
     throw new RdfException($"The graph {graph} doesn't contain any owl:Ontology declarations.");
 }
コード例 #14
0
ファイル: Namespace.cs プロジェクト: ukparliament/Mapping
        internal Namespace(string name, OntologyGraph ontology,
                           CompileUnitOption compileUnitOption) : base(name)
        {
            this.ontology = ontology;

            if (compileUnitOption == CompileUnitOption.InterfaceOnly)
            {
                this.AddInterfaces();
            }
            else
            if (compileUnitOption == CompileUnitOption.ModelImplementation)
            {
                this.AddClasses(compileUnitOption);
            }
        }
コード例 #15
0
        public void Initialize(OntologyGraph o1, OntologyGraph o2)
        {
            if (_merged == null)
            {
                _merged = new OntologyGraph();
                _merged.Merge(o1);
                _merged.Merge(o2);

                _o1 = o1;
                _o2 = o2;
            }
            else
            {
                throw new InvalidOperationException("The graph has been already initialized!");
            }
        }
コード例 #16
0
        static void Main(string[] args)
        {
            int countClass    = 0;
            int countInstance = 0;

            OntologyGraph g = new OntologyGraph();

            FileLoader.Load(g, "games.owl");

            OntologyClass    someClass = g.CreateOntologyClass(new Uri("http://www.w3.org/2002/07/owl#Thing"));
            OntologyProperty property  = g.CreateOntologyProperty(new Uri("http://www.semanticweb.org/user/ontologies/2018/10/games#hasDifficulty"));
            //  OntologyClass indirectClass = g.CreateOntologyClass(new Uri("http://www.semanticweb.org/user/ontologies/2018/10/games#Solitairer"));
            //  OntologyClass superClass=g.CreateOntologyClass(new Uri("http://www.semanticweb.org/user/ontologies/2018/10/games#Game"));
            int count = 0;

            foreach (OntologyClass c in someClass.SubClasses)
            {
                count++;
                countClass++;
                Console.WriteLine(count + ")" +
                                  "Класс онтологии: " + c.Resource.ToString());

                if (c.Instances.Count() != 0)
                {
                    foreach (var instance in c.Instances)
                    {
                        countInstance++;

                        Console.WriteLine("Экземпляр онтологии: " + instance.Resource.ToString());
                    }
                }

                OntologyProperty[] properties = c.IsDomainOf.SelectMany(x => EnumerateProperties(x)).DistinctBy(x => x.ToString()).ToArray();
                properties.ForEach(p => Console.WriteLine("Cвойства данного класса: " + p));
            }
            Console.WriteLine("");
            Console.WriteLine("Всего классов в онтологии: " + countClass);
            Console.WriteLine("");
            Console.WriteLine("Всего примеров в онтологии: " + countInstance);
            Console.WriteLine("");
            Console.WriteLine("Класс онтологии, содержащий hasDifficulty: ");
            OntologyClass[] classes = property.Domains.SelectMany(x => EnumerateClasses(x)).DistinctBy(x => x.ToString()).ToArray();
            classes.ForEach(c => Console.WriteLine(c));

            Console.ReadKey();
        }
コード例 #17
0
ファイル: UnitTest1.cs プロジェクト: yuryk53/MappingGenerator
        public void Test_GenerateOntologyFromDB()
        {
            //test owl file creation, test all classes/attributes to be present
            //Arrange
            string fileName = $"{dbName}_test.owl";

            //Act
            IGraph g = generator.GenerateOntologyFromDB(dbName, $"xmlns: {dbPrefix} =\"{dbURI}\"", fileName);

            //Assert
            Assert.IsTrue(File.Exists(fileName)); //check file creation

            OntologyGraph ograph = new OntologyGraph();

            ograph.Merge(g);

            //check that each table is present in ontology as class
            IEnumerable <OntologyClass> oclasses = ograph.AllClasses;

            foreach (string tableName in tables.Except(nmRelTables))
            {
                string        classUri = $"{dbURI}{tableName}";
                OntologyClass oclass   = (from c in oclasses where (c.Resource as UriNode).Uri.ToString() == classUri select c).FirstOrDefault();
                Assert.IsNotNull(oclass);

                //check for properties
                OntologyClass classOfClasses = ograph.CreateOntologyClass(ograph.CreateUriNode("owl:Class"));
                var           classProps     = ograph.GetTriplesWithPredicateObject(ograph.CreateUriNode("rdfs:domain"), ograph.CreateUriNode(new Uri(classUri))).ToList();

                foreach (var propNameExpected in tableAttributesDict[tableName])
                {
                    Triple triple = classProps.FirstOrDefault(t => t.Subject.ToString().Split('#')[1] == propNameExpected);
                    Assert.IsNotNull(triple); //if null -> we didn't find the property in ontology that should be there
                }
            }

            //check that all n:m tables are mapped as object properties
            IEnumerable <OntologyProperty> objectProperties = ograph.OwlObjectProperties;

            foreach (var opropName in nmRelTables)
            {
                Assert.IsNotNull(objectProperties.FirstOrDefault(p => p.ToString().Split('#')[1] == opropName));
            }
        }
コード例 #18
0
        private bool TryLoadOntologyGraph()
        {
            bool parsedSuccessfully = true;

            _ontology = new OntologyGraph();
            foreach (var f in _args.Inputs)
            {
                try
                {
                    FileLoader.Load(_ontology, f);
                }
                catch (Exception ex)
                {
                    LogError("Error loading ontology from file '{0}'. Cause: {1}", f, ex.Message);
                    parsedSuccessfully = false;
                }
            }
            return(parsedSuccessfully);
        }
コード例 #19
0
        public static Ontology GetOntology(this OntologyGraph graph)
        {
            IUriNode rdfType     = graph.CreateUriNode(new Uri(RdfSpecsHelper.RdfType));
            IUriNode owlOntology = graph.CreateUriNode(new Uri(OntologyHelper.OwlOntology));
            IEnumerable <IUriNode> ontologyNodes = graph.GetTriplesWithPredicateObject(rdfType, owlOntology)
                                                   .Select(triple => triple.Subject)
                                                   .UriNodes();

            switch (ontologyNodes.Count())
            {
            case 0:
                throw new RdfException($"The graph {graph} doesn't contain any owl:Ontology declarations.");

            case 1:
                return(new Ontology(ontologyNodes.Single(), graph));

            default:
                IUriNode ontologyNode = ontologyNodes.Where(node => node.Uri.AbsoluteUri.Equals(graph.BaseUri.AbsoluteUri)).DefaultIfEmpty(ontologyNodes.First()).First();
                return(new Ontology(ontologyNode, graph));
            }
        }
コード例 #20
0
        private static OntologyGraph GenerateOntologyGraph(string ontologyFilePath)
        {
            var ontology = new OntologyGraph();

            ontology.LoadFromFile(ontologyFilePath);
            IUriNode ontologyNode = ontology.GetTriplesWithObject(ontology.CreateUriNode("owl:Ontology"))
                                    .SingleOrDefault()
                                    .Subject as IUriNode;

            Triple[] externalTriples = ontology.AllClasses
                                       .Where(c => c.IsDefinedBy.Any(cn => cn.Equals(ontologyNode)) == false)
                                       .SelectMany(c => c.TriplesWithSubject)
                                       .Union(ontology.AllClasses
                                              .SelectMany(c => c.SuperClasses)
                                              .Where(sc => sc.IsDefinedBy.Any(scn => scn.Equals(ontologyNode)) == false)
                                              .SelectMany(sc => sc.TriplesWithObject))
                                       .ToArray();
            foreach (Triple triple in externalTriples)
            {
                ontology.Retract(triple);
            }
            return(ontology);
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: yuryk53/MappingGenerator
        static void Main(string[] args)
        {
            //DBSemanticsGenerator generator = new DBSemanticsGenerator(@"Data Source=ASUS\SQLEXPRESS;Initial Catalog=LMSv1;Integrated Security=True");
            //generator.GenerateOntologyFromDB("LMSv1", "xmlns: lms =\"http://www.example.org/LMS/\"", "LMSv1.owl");
            OntologyGraph gLMS = new OntologyGraph();

            gLMS.LoadFromFile("LMSv1.owl");
            //gLMS.SaveToFile("LMS_dotNetRdf.owl");

            //generator = new DBSemanticsGenerator(@"Data Source=ASUS\SQLEXPRESS;Initial Catalog=KMSv1;Integrated Security=True");
            //generator.GenerateOntologyFromDB("KMSv1", "xmlns: kms =\"http://www.example.org/KMS/\"", "KMSv1.owl");
            OntologyGraph gKMS = new OntologyGraph();

            gKMS.LoadFromFile("KMSv1.owl");
            //gLMS.SaveToFile("KMS_dotNetRdf.owl");

            TryMergeOntologies(gLMS, gKMS);

            //IOntologyMerger merger = new WordNetOntologyMerger();
            //merger.Initialize(gLMS, gKMS);
            //Dictionary<string, List<SimilarClassPropertyDescription>> simDict = merger.GetSimilarOntologyClassesMatrix();



            //PrintSimilaritiesIntoFile("similarities.txt", simDict);

            //foreach (var key in simDict.Keys)
            //{
            //    SimilarClassPropertyDescription map = (from mapping
            //                                           in simDict[key]
            //                                           where mapping.SimilarityScore == simDict[key].Max(x => x.SimilarityScore)
            //                                           select mapping).First();
            //    Console.WriteLine($"{map.ObjectName1}\n{map.ObjectName2}\nSimilarity score: {map.SimilarityScore}\n\n");
            //}

            //Console.WriteLine();
        }
コード例 #22
0
        //for each of the tables make owl:Class with fields as owl:ObjectProperty or owl:DataProperty
        public IGraph GenerateOntologyFromDB(string dbName, string dbNamespace, string ontologyName, bool includeViews = false)
        {
            DBLoader      dbLoader     = new DBLoader(connString);
            List <string> tableNames   = dbLoader.GetTableNames(includeViews);
            List <string> nmTableNames = new List <string>();
            //referenced tables = ObjectProperty (FK fields)
            //other fields = DataProperty

            //for each table create owl:Class
            OntologyGraph g  = new OntologyGraph();
            string        ns = dbNamespace;

            //RdfXmlWriter writer = new RdfXmlWriter();
            //writer.PrettyPrintMode = true;
            //writer.Save(g, PathWrapper.Combine(Environment.CurrentDirectory, "LMS.owl"));
            ////header was printed

            OWLWriter owlWriter = new OWLWriter();

            owlWriter.AddNamespace(ns);
            StringBuilder sb = new StringBuilder();

            owlWriter.WriteHeader(sb);
            string globalUri = MatchUri(ns);

            foreach (string tableName in tableNames)
            {
                //check, if it's not a n:m mapping table
                HashSet <string> PKs = new HashSet <string>(GetPrimaryKeys(dbName, tableName));
                if (PKs.Count >= 2)
                {
                    HashSet <string> FKs = new HashSet <string>(GetReferencingTableColumns(dbName, tableName));
                    //if all PK columns are FKs at the same time -> probably, we have n:m relation
                    if (FKs.IsSupersetOf(PKs))  //is ProperSubset maybe ???
                    {
                        nmTableNames.Add(tableName);
                        continue; //go to next table
                    }
                }

                string tableUri = ComposeTableUri(globalUri, tableName);//globalUri.Remove(globalUri.LastIndexOf('"')) + tableName;
                //OntologyClass newClass = g.CreateOntologyClass(new Uri(tableUri));
                owlWriter.EmitSimpleOWLClass(sb, tableUri);

                List <string> tableColumns = dbLoader.GetColumnNames(tableName);
                //now distinguish between DataProperty and ObjectProperty columns
                List <string> dataColumns   = new List <string>(),
                              objectColumns = GetReferencingTableColumns(dbName, tableName); //referenced via Foreign Key

                dataColumns = (from column in tableColumns select column).Except(objectColumns).ToList();


                //seek to the end of file (till the </rdf:RDF>


                foreach (string dataColumn in dataColumns)
                {
                    //newClass.AddLiteralProperty($"{tableUri}/{dataColumn}", g.CreateLiteralNode(dataColumn), true);
                    string xsdType = ConvertNativeToXsdDataType(GetTableAttributeDataType(dbName, tableName, dataColumn));
                    owlWriter.EmitSimpleDataTypeProp(sb, $"{tableUri}#{dataColumn}", tableUri, xsdType);
                }

                foreach (string objectColumn in objectColumns)
                {
                    string referencedTable = GetReferencedTableName(dbName, tableName, objectColumn);
                    string refTableUri     = ComposeTableUri(globalUri, referencedTable);//globalUri.Remove(globalUri.LastIndexOf('"')) + referencedTable;
                    owlWriter.EmitSimpleObjectProp(sb, $"{tableUri}#{objectColumn}", tableUri, refTableUri);
                }

                //foreach(string objectColumn in objectColumns)
                //{
                //    IUriNode uriNode = g.Create
                //}
            }

            //process n:m tables
            //all n:m tables we should present as Object Properties, where domain='PK1 table' and range='PK2 table'
            foreach (var tableName in nmTableNames)
            {
                //string tableUri = ComposeTableUri(globalUri, tableName);
                List <string> PKs      = GetPrimaryKeys(dbName, tableName);
                string        tableN   = GetReferencedTableName(dbName, tableName, PKs[0]);
                string        tableM   = GetReferencedTableName(dbName, tableName, PKs[1]);
                string        tableUri = $"{ComposeTableUri(globalUri, tableN)}#{tableName}"; //where tableN - domain table
                //table N = domain (or vice versa)
                //table M = range (or vice versa)
                owlWriter.EmitSimpleObjectProp(sb, tableUri, ComposeTableUri(globalUri, tableN), ComposeTableUri(globalUri, tableM));
            }


            owlWriter.WriteFooter(sb);
            File.WriteAllText(Path.Combine(Environment.CurrentDirectory, ontologyName), sb.ToString());

            g.LoadFromString(sb.ToString(), new VDS.RDF.Parsing.RdfXmlParser());

            return(g);
        }
コード例 #23
0
ファイル: OWLManager.cs プロジェクト: albarsil/OntoSeman
 public void Merge(OntologyGraph onto)
 {
     throw new NotImplementedException();
 }
コード例 #24
0
        /// <summary>
        /// Launch the ontology import wizard and generate an Excel skeleton from the ontology.
        /// </summary>
        public void LoadOntology()
        {
            this.resourcesToImport.Clear();
            this.nestedProperties.Clear();

            // Displays an OpenFileDialog so the user can select an ontology.
            OpenFileDialog openOntologyFileDialog = new OpenFileDialog();

            openOntologyFileDialog.Filter = "RDF/XML (*.rdf)|*.rdf|Turtle (*.ttl)|*.ttl|JSON-LD (*.jsonld)|*.jsonld|NTriples (*.nt)|*.nt|NQuads (*.nq)|*.nq|TriG (*.trig)|*.trig";
            openOntologyFileDialog.Title  = "Select an ontology file";

            // Show the Dialog.
            // If the user clicked OK in the dialog and an OWL file was selected, open it.
            if (openOntologyFileDialog.ShowDialog() == DialogResult.OK)
            {
                OntologyGraph g = new OntologyGraph();
                FileLoader.Load(g, openOntologyFileDialog.FileName);

                ImportOptionsForm importOptionsForm = new ImportOptionsForm(g);
                if (importOptionsForm.ShowDialog() == DialogResult.OK)
                {
                    // Iterate through the named bottom classes; generate one worksheet for each
                    foreach (OntologyClass oClass in g.OwlClasses)
                    {
                        if (oClass.Resource.NodeType == NodeType.Uri && resourcesToImport.Contains(oClass.ToString()))
                        {
                            Worksheet newWorksheet = Globals.ThisAddIn.Application.Worksheets.Add();

                            UriNode classAsUriNode = (UriNode)oClass.Resource;
                            newWorksheet.Name = Helper.GetLocalName(classAsUriNode.Uri);

                            // Start iterating from the first column
                            int column = 1;

                            // Add column for the IRI identifier
                            // <IRI> is a special identifier used for this purpose, signaling that a) the IRI shall
                            // be minted from this column, and b) the subsequent row will contain the OWL class for all minted entities
                            string identifierColumnName = Helper.GetExcelColumnName(column);
                            string identifierColumnHeaderCellIdentifier = String.Format("{0}1", identifierColumnName);
                            Range  identifierColumnHeaderCell           = newWorksheet.get_Range(identifierColumnHeaderCellIdentifier);
                            identifierColumnHeaderCell.Value = "Identifier";
                            string identifierNote = "<IRI>";
                            identifierNote += String.Format("\n<{0}>", classAsUriNode.Uri.ToString());
                            identifierColumnHeaderCell.NoteText(identifierNote);
                            column++;

                            // Iterate through the properties for which this class is in the domain;
                            // generate one column for each property (named from label and if that does not exist from IRI)
                            // Order the columns by type, with datatype properties coming before object properties,
                            // then by string representation
                            foreach (OntologyProperty oProperty in oClass.IsDomainOf.OrderBy(o => o.Types.First()).OrderBy(o => o.ToString()))
                            {
                                if (oProperty.Resource.NodeType == NodeType.Uri && resourcesToImport.Contains(oProperty.ToString()))
                                {
                                    // This is because Excel uses strange adressing, i.e., "A1" instead of something
                                    // numeric and zero-indexed such as "0,0".
                                    string headerColumnName     = Helper.GetExcelColumnName(column);
                                    string headerCellIdentifier = String.Format("{0}1", headerColumnName);
                                    Range  headerCellRange      = newWorksheet.get_Range(headerCellIdentifier);

                                    UriNode propertyAsUriNode = (UriNode)oProperty.Resource;

                                    // TODO: the below code is extremely repetitive. Sometime, when not sick and brain is working better,
                                    // Future Karl will refactor and simplify this (hopefully)
                                    if (nestedProperties.Keys.Contains(propertyAsUriNode.Uri.AbsoluteUri))
                                    {
                                        foreach (string nestedPropertyUri in nestedProperties[propertyAsUriNode.Uri.AbsoluteUri])
                                        {
                                            // Repeat header cell selection for each nested property
                                            headerColumnName     = Helper.GetExcelColumnName(column);
                                            headerCellIdentifier = String.Format("{0}1", headerColumnName);
                                            headerCellRange      = newWorksheet.get_Range(headerCellIdentifier);

                                            // Find and assign label
                                            string headerLabel;

                                            // Assign property IRI
                                            string noteText = String.Format("<{0}>", propertyAsUriNode.Uri.ToString());

                                            // Asign property type hinting
                                            string propertyType = oProperty.Types.First().ToString();
                                            noteText += String.Format("\n<{0}>", propertyType);

                                            // Assign range hinting IRI
                                            // TODO: what if no range exists? see same case below and after else clause
                                            OntologyClass[] namedRanges = oProperty.Ranges.Where(o => o.Resource.NodeType == NodeType.Uri).ToArray();
                                            if (namedRanges.Count() > 0)
                                            {
                                                UriNode rangeAsUriNode = (UriNode)namedRanges.First().Resource;
                                                string  rangeUri       = rangeAsUriNode.Uri.ToString();
                                                noteText += String.Format("\n<{0}>", rangeUri);
                                            }

                                            // Branching for special case of rdfs:label
                                            if (nestedPropertyUri.Equals(OntologyHelper.PropertyLabel))
                                            {
                                                // Assign header label
                                                headerLabel = "rdfs:label";

                                                // Nested property IRI (i.e., rdfs:label)
                                                noteText += String.Format("\n<{0}>", OntologyHelper.PropertyLabel);

                                                // Nested property type
                                                noteText += String.Format("\n<{0}>", OntologyHelper.OwlAnnotationProperty);

                                                // Nested property range
                                                noteText += String.Format("\n<{0}>", XmlSpecsHelper.XmlSchemaDataTypeString);
                                            }
                                            else
                                            {
                                                // Get the property from the ontology
                                                OntologyProperty nestedProperty          = g.OwlProperties.Where(property => ((UriNode)property.Resource).Uri.AbsoluteUri.Equals(nestedPropertyUri)).First();
                                                UriNode          nestedPropertyAsUriNode = (UriNode)nestedProperty.Resource;

                                                // Assign header label
                                                if (nestedProperty.Label.Count() > 0)
                                                {
                                                    ILiteralNode labelNode = nestedProperty.Label.First();
                                                    headerLabel = labelNode.Value;
                                                }
                                                else
                                                {
                                                    headerLabel = Helper.GetLocalName(nestedPropertyAsUriNode.Uri);
                                                }

                                                // Nested property IRI
                                                noteText += String.Format("\n<{0}>", nestedPropertyAsUriNode.Uri.ToString());

                                                // Asign nested property type hinting
                                                string nestedPropertyType;
                                                if (nestedProperty.Types.Count() > 0)
                                                {
                                                    nestedPropertyType = nestedProperty.Types.First().ToString();
                                                }
                                                else
                                                {
                                                    nestedPropertyType = "";
                                                }
                                                noteText += String.Format("\n<{0}>", nestedPropertyType);

                                                // Nested range hinting IRI
                                                OntologyClass[] namedNestedRanges = nestedProperty.Ranges.Where(o => o.Resource.NodeType == NodeType.Uri).ToArray();
                                                string          nestedRange;
                                                if (namedNestedRanges.Count() > 0)
                                                {
                                                    nestedRange = ((UriNode)namedNestedRanges.First().Resource).Uri.ToString();
                                                }
                                                else
                                                {
                                                    nestedRange = "";
                                                }
                                                noteText += String.Format("\n<{0}>", nestedRange);
                                            }

                                            // Assign header label
                                            headerLabel           = headerLabel + " (through " + Helper.GetLocalName(propertyAsUriNode.Uri) + ")";
                                            headerCellRange.Value = headerLabel;

                                            // Assign note text
                                            headerCellRange.AddComment(noteText);
                                            column++;
                                        }
                                    }
                                    else
                                    {
                                        // Find and assign label
                                        string propertyLabel;
                                        if (oProperty.Label.Count() > 0)
                                        {
                                            ILiteralNode labelNode = oProperty.Label.First();
                                            propertyLabel = labelNode.Value;
                                        }
                                        else
                                        {
                                            propertyLabel = Helper.GetLocalName(propertyAsUriNode.Uri);
                                        }
                                        headerCellRange.Value = propertyLabel;

                                        // Assign property IRI
                                        string noteText = String.Format("<{0}>", propertyAsUriNode.Uri.ToString());

                                        // Asign property type hinting
                                        string propertyType = oProperty.Types.First().ToString();
                                        noteText += String.Format("\n<{0}>", propertyType);

                                        // Assign range hinting IRI (provided simple )
                                        OntologyClass[] namedRanges = oProperty.Ranges.Where(o => o.Resource.NodeType == NodeType.Uri).ToArray();
                                        if (namedRanges.Count() > 0)
                                        {
                                            UriNode rangeAsUriNode = (UriNode)namedRanges.First().Resource;
                                            string  rangeUri       = rangeAsUriNode.Uri.ToString();
                                            noteText += String.Format("\n<{0}>", rangeUri);
                                        }

                                        // Assign note text
                                        headerCellRange.AddComment(noteText);
                                        column++;
                                    }
                                }
                            }

                            // Bold the header row and fit the columns so things look nice
                            Range headerRow = newWorksheet.get_Range("A1").EntireRow;
                            headerRow.Font.Bold = true;
                            headerRow.Columns.AutoFit();
                        }
                    }
                }
            }
        }
コード例 #25
0
        public static IEnumerable <OntologyClass> GetDatatypes(this OntologyGraph graph)
        {
            INode rdfsDatatype = graph.CreateUriNode(VocabularyHelper.RDFS.Datatype);

            return(graph.GetClasses(rdfsDatatype));
        }
コード例 #26
0
 /// <summary>
 /// Wrapper around an ontology class that exposes some methods particular to ontology restrictions.
 /// </summary>
 /// <param name="wrappedClass"></param>
 public OntologyRestriction(OntologyClass wrappedClass)
 {
     _wrappedClass = wrappedClass;
     _graph        = wrappedClass.Graph as OntologyGraph;
 }
コード例 #27
0
        public static IEnumerable <Relationship> GetRelationships(this OntologyClass cls)
        {
            List <Relationship> relationships = new List <Relationship>();

            // Start w/ rdfs:domain declarations. At this time we only consider no-range (i.e.,
            // range is owl:Thing) or named singleton ranges
            IEnumerable <OntologyProperty> rdfsDomainProperties = cls.IsDomainOf.Where(
                property =>
                property.Ranges.Count() == 0 ||
                (property.Ranges.Count() == 1 && (property.Ranges.First().IsNamed() || property.Ranges.First().IsDatatype())));

            foreach (OntologyProperty property in rdfsDomainProperties)
            {
                Relationship newRelationship;
                if (property.Ranges.Count() == 0)
                {
                    OntologyGraph oGraph = cls.Graph as OntologyGraph;
                    OntologyClass target;
                    if (property.IsObjectProperty())
                    {
                        target = oGraph.CreateOntologyClass(VocabularyHelper.OWL.Thing);
                    }
                    else
                    {
                        target = oGraph.CreateOntologyClass(VocabularyHelper.RDFS.Literal);
                    }
                    newRelationship = new Relationship(property, target);
                }
                else
                {
                    OntologyClass range = property.Ranges.First();
                    newRelationship = new Relationship(property, range);
                }

                if (property.IsFunctional())
                {
                    newRelationship.ExactCount = 1;
                }

                relationships.Add(newRelationship);
            }

            // Continue w/ OWL restrictions on the class
            IEnumerable <OntologyRestriction> ontologyRestrictions = cls.DirectSuperClasses
                                                                     .Where(superClass => superClass.IsRestriction())
                                                                     .Select(superClass => new OntologyRestriction(superClass));

            foreach (OntologyRestriction ontologyRestriction in ontologyRestrictions)
            {
                OntologyProperty restrictionProperty = ontologyRestriction.OnProperty;
                OntologyClass    restrictionClass    = ontologyRestriction.OnClass;
                if (restrictionProperty.IsNamed() && (restrictionClass.IsNamed() || restrictionClass.IsDatatype()))
                {
                    Relationship newRelationship = new Relationship(restrictionProperty, restrictionClass);

                    int min     = ontologyRestriction.MinimumCardinality;
                    int exactly = ontologyRestriction.ExactCardinality;
                    int max     = ontologyRestriction.MaximumCardinality;

                    if (min != 0)
                    {
                        newRelationship.MinimumCount = min;
                    }
                    if (exactly != 0)
                    {
                        newRelationship.ExactCount = exactly;
                    }
                    if (max != 0)
                    {
                        newRelationship.MaximumCount = max;
                    }

                    relationships.Add(newRelationship);
                }
            }

            // Iterate over the gathered list of Relationships and narrow down to the most specific ones, using a Dictionary for lookup and the MergeWith() method for in-place narrowing
            Dictionary <OntologyProperty, Relationship> relationshipsDict = new Dictionary <OntologyProperty, Relationship>(new OntologyResourceComparer());

            foreach (Relationship relationship in relationships)
            {
                OntologyProperty property = relationship.Property;
                OntologyResource target   = relationship.Target;
                // If we already have this property listed in the dictionary, first narrow down the relationship by combining it with the old copy
                if (relationshipsDict.ContainsKey(property))
                {
                    Relationship oldRelationship = relationshipsDict[property];
                    relationship.MergeWith(oldRelationship);
                }
                // Put relationship in the dictionary
                relationshipsDict[property] = relationship;
            }

            // Return the values
            return(relationshipsDict.Values);
        }
コード例 #28
0
        private void migrarDataToOwl()
        {
            string StrClassName = string.Empty, individualValue = string.Empty,
                   individualID = string.Empty, recipeIdValue = string.Empty, fileRoute = string.Empty,
                   recipeID = string.Empty, NombreRecipe = string.Empty, sal = string.Empty,
                   calorias = string.Empty, fibra = string.Empty, azucar = string.Empty,
                   grasas = string.Empty, grasasSaturadas = string.Empty, carbohidratos = string.Empty,
                   proteinas = string.Empty, colesterol = string.Empty, recipeTipoPlatoData = string.Empty,
                   paisNombre = string.Empty;

            OntologyClass clase         = null;
            Individual    ObjIndividual = null;

            OntologyGraph OwlFile = new OntologyGraph();

            FileLoader.Load(OwlFile, "FoodOntologyRecomenderOwl2142018.owl");
            fileRoute       = OwlFile.BaseUri.ToString();
            OwlFile.BaseUri = new Uri("http://www.semanticweb.org/joaquin/ontologies/2017/11/untitled-ontology-26");



            foreach (DataRow recipeItem in RecipeData.Rows)
            {
                recipeID = recipeItem["recipeID"].ToSafeString();
                var filas = RecipeData.Select($"recipeid = {recipeID}");

                NombreRecipe        = recipeItem["recipeName"].ToSafeString();
                sal                 = recipeItem["sal"].ToSafeString();
                calorias            = recipeItem["calorias"].ToSafeString();
                fibra               = recipeItem["fibra"].ToSafeString();
                azucar              = recipeItem["azucar"].ToSafeString();
                grasas              = recipeItem["grasas"].ToSafeString();
                grasasSaturadas     = recipeItem["grasasSaturadas"].ToSafeString();
                carbohidratos       = recipeItem["proteinas"].ToSafeString();
                proteinas           = recipeItem["proteinas"].ToSafeString();
                colesterol          = recipeItem["colesterol"].ToSafeString();
                recipeTipoPlatoData = recipeItem["recipeTipoPlatoData"].ToSafeString();
                paisNombre          = recipeItem["paisNombre"].ToSafeString();

                var Uriclass          = new Uri($"{OwlFile.BaseUri.ToString()}#Receta");
                var UriRecipe         = new Uri($"{OwlFile.BaseUri.ToString()}/{recipeID}");
                var UriRecipeSal      = new Uri($"{OwlFile.BaseUri.ToString()}/recetaSalt");
                var UriRecipeCalorias = new Uri($"{OwlFile.BaseUri.ToString()}/recetaCalorias");
                var uriHasIngredient  = new  Uri($"{OwlFile.BaseUri.ToString()}/recetaTieneIngrediente");


                var SalNode   = OwlFile.CreateLiteralNode(sal, new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal));
                var oCalorias = OwlFile.CreateLiteralNode(calorias, new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal));



                //var oFibra = OwlFile.CreateLiteralNode(fibra, new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal));
                //var oAzucar = OwlFile.CreateLiteralNode(azucar, new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal));
                //var oGrasas = OwlFile.CreateLiteralNode(grasas, new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal));
                //var oGrasasSaturadas = OwlFile.CreateLiteralNode(grasasSaturadas, new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal));
                //var oCarbohidratos = OwlFile.CreateLiteralNode(carbohidratos, new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal));
                //var oProteinas = OwlFile.CreateLiteralNode(proteinas, new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal));
                //var oColesterol = OwlFile.CreateLiteralNode(colesterol, new Uri(XmlSpecsHelper.XmlSchemaDataTypeDecimal));
                //var oRecipeTipoPlatoData = OwlFile.CreateLiteralNode(recipeTipoPlatoData, new Uri(XmlSpecsHelper.XmlSchemaDataTypeString));
                //var oPaisNombre = OwlFile.CreateLiteralNode(paisNombre, new Uri(XmlSpecsHelper.XmlSchemaDataTypeString));
                //  INode ObjOwl = OwlFile.CreateUriNode(new Uri($"{OwlFile.BaseUri.ToString()}/recetaTieneIngrediente"));



                // OntologyClass objClassRecipe = OwlFile.CreateOntologyClass(uriRecipe);
                INode nodoIndReceta = OwlFile.CreateUriNode(new
                                                            Uri($"{OwlFile.BaseUri.ToString()}/{recipeID}"));
                INode      ClassRecetaNode  = OwlFile.CreateUriNode(Uriclass);
                INode      NodeHasIngrediet = OwlFile.CreateUriNode(uriHasIngredient);
                INode      salVal           = OwlFile.CreateUriNode(UriRecipeSal);
                INode      calVal           = OwlFile.CreateUriNode(UriRecipeCalorias);
                Individual InReceta         = new Individual(nodoIndReceta, ClassRecetaNode, OwlFile);
                OwlFile.CreateIndividual(nodoIndReceta);

                OntologyProperty PropRecipeHasIngredient = OwlFile.CreateOntologyProperty(uriHasIngredient);
                OntologyProperty recipeSal = new OntologyProperty(UriRecipeSal, OwlFile);
                OntologyProperty oSal      = new OntologyProperty(UriRecipeSal, OwlFile);
                OntologyProperty oCal      = new OntologyProperty(UriRecipeCalorias, OwlFile);


                oCal.AddLiteralProperty(UriRecipeCalorias, oCalorias, true);

                // InReceta.AddResourceProperty(UriRecipeSal,salVal, true);
                InReceta.AddLiteralProperty(UriRecipeCalorias, oCalorias, true);
                // InReceta.AddLiteralProperty(UriRecipeSal.ToString(), SalNode, true);
                //  InReceta.AddLiteralProperty(UriRecipeCalorias.ToString(),oCalorias, true);
                //  oSal.AddRange(new Uri($"{UriRecipeSal}/{SalNode}"));
                //  oCal.AddRange(new Uri($"{UriRecipeCalorias}/{oCalorias}"));

                //  oSal.AddRange(SalNode);
                //  recipeSal.AddRange(SalNode);
                InReceta.AddLabel(NombreRecipe);
                InReceta.AddLiteralProperty(UriRecipeSal.ToString(), SalNode, true);
                var propiedades      = OwlFile.OwlDatatypeProperties;
                var objectproperties = OwlFile.OwlObjectProperties;


                //InReceta.AddLiteralProperty(UriRecipeCalorias, oCalorias, true);



                //recipeResource.AddLiteralProperty($"{OwlFile.BaseUri.ToString()}/recetaSalt", oSal, true);
                //recipeResource.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/recetaCalorias", oCalorias, true);
                //recipeResource.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/recetaFibra", oFibra, true);
                //recipeResource.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/recetaAzucar", oAzucar, true);
                //recipeResource.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/recetaFat", oGrasas, true);
                //recipeResource.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/recetaSaturates", oGrasasSaturadas, true);
                //recipeResource.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/recetaCabs", oCarbohidratos, true);
                //recipeResource.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/recetaProtein", oProteinas, true);
                //recipeResource.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/recetaColesterol", oColesterol, true);
                //recipeResource.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/tipoPlato", oRecipeTipoPlatoData, true);
                //recipeResource.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/Nacionalidad", oPaisNombre, true);

                foreach (DataRow ingredientItem in filas)
                {
                    StrClassName    = ingredientItem["ClassOf"].ToString();
                    individualValue = ingredientItem["ingredienteDescripcion"].ToString();
                    recipeIdValue   = ingredientItem["recipeID"].ToString();
                    individualID    = $"{recipeIdValue}_{ingredientItem["ingredienteID"].ToString()}";

                    var           uri            = new Uri($"{OwlFile.BaseUri.ToString()}#{StrClassName}");
                    OntologyClass objClass       = OwlFile.CreateOntologyClass(uri);
                    INode         nodoIndividual = OwlFile.CreateUriNode(new
                                                                         Uri($"{OwlFile.BaseUri.ToString()}/{individualID}"));
                    var        label      = OwlFile.CreateLiteralNode(individualValue, "es");
                    Individual individual = new Individual(nodoIndividual, objClass.Resource, OwlFile);
                    individual.AddLiteralProperty(uri, label, true);
                    OwlFile.CreateIndividual(individual.Resource, objClass.Resource);
                    //  INode hasIngredient = OwlFile.CreateUriNode(new Uri($"{OwlFile.BaseUri.ToString()}/recetaTieneIngrediente"));
                    //recipeResource.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/recetaTieneIngrediente", nodoIndividual,true);
                    //  individualReceta.AddResourceProperty($"{OwlFile.BaseUri.ToString()}/recetaTieneIngrediente", nodoIndividual, true);
                    // Triple t = new Triple(nodoReceta, hasIngredient, nodoIndividual);
                    //  OwlFile.Assert(t);
                    //   OntologyResource hasIngredient =  OwlFile.CreateOntologyResource(nodoIndividual);
                    // hasIngredient.AddResourceProperty()
                    //  var pro =   OwlFile.OwlObjectProperties;
                }
            }
            OwlFile.SaveToFile($"{objFileTool.GetAplicationDirectory()}/FoodOntologyRecomenderOwl2142018.owl");
            MessageBox.Show("Datos Registrados con exito");
        }
コード例 #29
0
        public static Ontology GetBaseUriOntology(this OntologyGraph graph)
        {
            IUriNode ontologyUriNode = graph.CreateUriNode(graph.BaseUri);

            return(new Ontology(ontologyUriNode, graph));
        }
コード例 #30
0
        private static CodeCompileUnit GenerateModelImplementationDom(string ontologyFilePath, string namespaceName)
        {
            OntologyGraph ontology = GenerateOntologyGraph(ontologyFilePath);

            return(new CompileUnit(namespaceName, ontology, CompileUnitOption.ModelImplementation));
        }