예제 #1
0
        /// <summary>
        /// Get the comment on a property
        /// </summary>
        /// <param name="relationship"></param>
        /// <returns>Comment string</returns>
        private static string GetComment(OntologyProperty property)
        {
            string comment;

            try
            {
                comment = property.Comment.First().ToString();
                comment = Trim(comment);

                int MAX_COMMENT_LENGTH = 512;

                // Trim large comments.
                if (comment.Length > MAX_COMMENT_LENGTH)
                {
                    // Remove any characters beyond the maximum length.
                    comment = comment.Substring(0, MAX_COMMENT_LENGTH);
                }
            }
            catch (Exception e)
            {
                //Console.WriteLine($"Missing rdfs:comment on {relationship.ToString()}");
                //Console.WriteLine($"{e.Message}");
                comment = null;
            }

            return(comment);
        }
예제 #2
0
        internal InterfaceProperty(OntologyProperty ontologyProperty)
        {
            this.ontologyProperty = ontologyProperty;

            this.Initialize();
            this.AddType();
        }
예제 #3
0
        public ListViewPropertyEntry(OntologyProperty prop)
        {
            this.Name  = prop.GetNameStr(true);
            this.Range = prop.GetRangeStr(false);

            this.Property = prop;
        }
예제 #4
0
 public Relationship(OntologyProperty property, OntologyClass target)
 {
     if (!property.IsNamed() || !(target.IsNamed() || target.IsDatatype()))
     {
         throw new ArgumentException("Only named properties and named or datatype targets allowed.");
     }
     Property = property;
     Target   = target;
 }
예제 #5
0
        private static bool IsFunctional(this OntologyProperty ontologyProperty)
        {
            var functionalTriple = new Triple(
                ontologyProperty.Resource,
                ontologyProperty.Graph.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)),
                ontologyProperty.Graph.CreateUriNode("owl:FunctionalProperty"));

            return(ontologyProperty.Graph.ContainsTriple(functionalTriple));
        }
        public PropertyWithBackingField(OntologyProperty ontologyProperty)
        {
            this.name             = ontologyProperty.ToPascalCase();
            this.type             = ontologyProperty.ToTypeReference(false);
            this.ontologyProperty = ontologyProperty;

            this.AddField();
            this.AddProperty();
        }
예제 #7
0
        public static void SetSubjectsByObjectProperty(this OntologyResource resource, string propertyName, List <UriNode> values)
        {
            resource.RemovePropertyByObject(propertyName);
            OntologyProperty property = ((OntologyGraph)resource.Graph).OwlProperties.FirstOrDefault(s => s.Resource.ToString().EndsWith(propertyName));

            if (values != null && values.Any() && property != null)
            {
                IEnumerable <Triple> triples = values.Select(v => new Triple(v, property.Resource, resource.Resource, resource.Graph));
                resource.Graph.Assert(triples);
            }
        }
예제 #8
0
        public static void SetProperty(this OntologyResource resource, string propertyName, INode value)
        {
            resource.RemoveProperty(propertyName);
            OntologyProperty property = ((OntologyGraph)resource.Graph).OwlProperties.FirstOrDefault(s => s.Resource.ToString().EndsWith(propertyName));

            if (value != null && property != null)
            {
                Triple triple = new Triple(resource.Resource, property.Resource, value, resource.Graph);
                resource.Graph.Assert(triple);
            }
        }
예제 #9
0
        private void NestedProperty_CheckedChanged(object sender, EventArgs e)
        {
            OntologyProperty selectedProperty = ((PropertyListItem)propertiesListBox.SelectedItem).property;
            Uri selectedPropertyUri           = ((UriNode)selectedProperty.Resource).Uri;
            Uri nestedPropertyUri             = (Uri)((ToolStripMenuItem)sender).Tag;

            if (((ToolStripMenuItem)sender).Checked)
            {
                RdfOntologyOperations.instance.nestedProperties[selectedPropertyUri.AbsoluteUri].Add(nestedPropertyUri.AbsoluteUri);
            }
            else
            {
                RdfOntologyOperations.instance.nestedProperties[selectedPropertyUri.AbsoluteUri].Remove(nestedPropertyUri.AbsoluteUri);
            }
        }
예제 #10
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();
        }
예제 #11
0
        /// <summary>
        /// Get a display name for a Relationship
        /// </summary>
        /// <param name="relationship"></param>
        /// <returns>Display name string</returns>
        private static string GetRelationshipDisplayName(OntologyProperty relationship)
        {
            string displayName;

            try
            {
                // Use the first rdfs:label on the ObjectProperty for the DTDL relationship displayName
                displayName = relationship.Label.First().ToString();
                displayName = Trim(displayName);
            }
            catch (Exception e)
            {
                //Console.WriteLine($"Missing rdfs:label on {relationship.ToString()}");
                //Console.WriteLine($"{e.Message}");
                displayName = null;
            }

            return(displayName);
        }
예제 #12
0
        internal static CodeTypeReference ToTypeReference(this OntologyProperty ontologyProperty, bool isInterfaceTypeAllowed)
        {
            var rangeClass   = ontologyProperty.Ranges.FirstOrDefault();
            var isFunctional = ontologyProperty.IsFunctional();
            var result       = null as CodeTypeReference;

            if (rangeClass == null)
            {
                result = new CodeTypeReference(typeof(string));
            }
            else if (Utils.XsdTypeDictionary.TryGetValue(rangeClass.ToUri().AbsoluteUri, out Type mappedType))
            {
                if (isFunctional && mappedType.IsValueType)
                {
                    result = new CodeTypeReference(typeof(Nullable <>).MakeGenericType(mappedType));
                }
                else
                {
                    result = new CodeTypeReference(mappedType);
                }
            }
            else
            {
                if (isInterfaceTypeAllowed)
                {
                    result = new CodeTypeReference(rangeClass.ToInterfaceName());
                }
                else
                {
                    result = new CodeTypeReference(rangeClass.ToMemberName());
                }
            }

            if (!isFunctional)
            {
                var enumerable = new CodeTypeReference(typeof(IEnumerable <>));
                enumerable.TypeArguments.Add(result);

                return(enumerable);
            }

            return(result);
        }
예제 #13
0
        private void PropCtxMenuRangeTypeSelector_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_noise)
            {
                return;
            }
            string           selectedOption   = (string)propCtxMenuRangeTypeSelector.SelectedItem;
            OntologyProperty selectedProperty = ((PropertyListItem)propertiesListBox.SelectedItem).property;
            Uri selectedPropertyUri           = ((UriNode)selectedProperty.Resource).Uri;

            if (selectedOption.Equals(NESTED_ANON_INDIVIDUAL_LABEL))
            {
                propCtxMenuSubProperties.Enabled = true;
                RdfOntologyOperations.instance.nestedProperties[selectedPropertyUri.AbsoluteUri] = new HashSet <string>();
            }
            else
            {
                propCtxMenuSubProperties.Enabled = false;
                RdfOntologyOperations.instance.nestedProperties.Remove(selectedPropertyUri.AbsoluteUri);
            }
        }
        IGraph IInteractiveMerger.MergeOntologyClasses(List <SimilarClassPropertyDescription> mergedClassPairs,
                                                       Func <SimilarClassPropertyDescription, bool> canWeMergeClassPairCallback,
                                                       Func <SimilarClassPropertyDescription, bool> canWeMergePropertyPairCallback,
                                                       double mergePropertiesThreshold,
                                                       IFederatedNamesGenerator federatedNamesGen,
                                                       ITypeCaster typeCaster,
                                                       IProgress <double> progress = null,
                                                       Func <string, string, IProgress <double>, Dictionary <string, List <SimilarClassPropertyDescription> > > getSimilarClassPropertiesMatrixMethod = null,
                                                       string federatedStem = null)
        {
            if (federatedStem == null)
            {
                federatedStem = ConfigurationManager.AppSettings["defaultFederatedStem"];
            }

            if (getSimilarClassPropertiesMatrixMethod == null) //user didn't provide his own method -> use default one
            {
                getSimilarClassPropertiesMatrixMethod = new Func <string, string, IProgress <double>, Dictionary <string, List <SimilarClassPropertyDescription> > >
                                                            (GetSimilarClassPropertiesMatrix);
            }

            int    mergedClassPairNumber      = 0;
            double classPairProgressStepDelta = 1.0 / mergedClassPairs.Count;

            foreach (SimilarClassPropertyDescription mergedClassPair in mergedClassPairs)
            {
                mergedClassPairNumber++;
                mergedClassPair.MergeClassRelation = MergeClassRelation.SubClassOf; //by default, howerver, using callback user can change this
                if (mergedClassPair.SimilarityScore >= mergePropertiesThreshold)
                {
                    if (mergedClassPair.MergeClassRelation == MergeClassRelation.SubClassOf)
                    {
                        //merge using rdfs:subClassOf (traverse all merged classes and add this attribute to them)



                        //now compose federated URI for a federated class
                        //use the shortest length class name from merged classes
                        string o1ClassName = GetClassNameFromUri(mergedClassPair.ObjectName1);
                        string o2ClassName = GetClassNameFromUri(mergedClassPair.ObjectName2);

                        string federatedClassName = federatedNamesGen.GenerateFederatedName(o1ClassName, o2ClassName);

                        string federatedUri = federatedStem + federatedClassName;
                        mergedClassPair.FederatedURI = federatedUri;

                        string fed = GetClassNameFromUri(mergedClassPair.ObjectName1);


                        if (canWeMergeClassPairCallback != null)
                        {
                            if (!canWeMergeClassPairCallback(mergedClassPair))
                            {
                                continue; //we are not allowed to merge these classes, go on, nothing to see here
                            }
                        }

                        //if callback function was not provided or we are allowed to merge classes -> merge them
                        OntologyClass federatedClass = _merged.CreateOntologyClass(new Uri(federatedUri)); //check federatedClassName to a URI!!!


                        OntologyClass oclass1 = _merged.AllClasses.Where(oclass => oclass.Resource.ToString() == mergedClassPair.ObjectName1).First();
                        federatedClass.AddSubClass(oclass1);
                        OntologyClass oclass2 = _merged.AllClasses.Where(oclass => oclass.Resource.ToString() == mergedClassPair.ObjectName2).First();
                        federatedClass.AddSubClass(oclass2);

                        //everything's OK -> add current federated property to ontology graph
                        OntologyResource ontologyClassResource = _merged.CreateOntologyResource(new Uri(OntologyHelper.OwlClass));

                        federatedClass.AddType(ontologyClassResource);



                        //now obtain all merged classes' properties for merging, give them federated URIs and merge them
                        //before merging, ask a user using callback if he wants to merge the particular props
                        string            class1 = mergedClassPair.ObjectName1;
                        string            class2 = mergedClassPair.ObjectName2;
                        Progress <double> getClassPropsMatrixProgress = null;

                        if (progress != null)   //report progress
                        {
                            getClassPropsMatrixProgress = new Progress <double>(pValue =>
                            {
                                //take into account main loop progress
                                double progressValue = (mergedClassPairNumber / (double)mergedClassPairs.Count) - classPairProgressStepDelta + pValue * classPairProgressStepDelta;
                                progress.Report(progressValue);
                            });
                        }

                        #region Merge properties for selected classes
                        //Dictionary<string, List<SimilarClassPropertyDescription>> simDict = GetSimilarClassPropertiesMatrix(
                        //    classUri1: class1,
                        //    classUri2: class2,
                        //    progress: getClassPropsMatrixProgress); //obtain properties similarity matrix

                        Dictionary <string, List <SimilarClassPropertyDescription> > simDict = getSimilarClassPropertiesMatrixMethod(
                            class1,                     //classUri1
                            class2,                     //classUri2
                            getClassPropsMatrixProgress //progress
                            );                          //obtain properties similarity matrix

                        List <SimilarClassPropertyDescription> highestScoreMergePairs = 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();
                            highestScoreMergePairs.Add(map);
                        }

                        //now we have property pairs which are most likely to be equivalent, try to merge them asking user before each merge
                        foreach (var mergePropertyPair in highestScoreMergePairs)
                        {
                            if (mergedClassPair.SimilarityScore >= mergePropertiesThreshold)
                            {
                                mergePropertyPair.MergePropRelation = MergePropertyRelation.EquivalentProperty; //by default


                                //generate federated property URI to suggest to user
                                int    indexOfLastSharp01 = mergePropertyPair.ObjectName1.LastIndexOf('#');
                                string o1PropName         = mergePropertyPair.ObjectName1.Substring(indexOfLastSharp01 + 1,
                                                                                                    mergePropertyPair.ObjectName1.Length - 1 - indexOfLastSharp01);
                                int    indexOfLastSharp02 = mergePropertyPair.ObjectName2.LastIndexOf('#');
                                string o2PropName         = mergePropertyPair.ObjectName2.Substring(indexOfLastSharp02 + 1,
                                                                                                    mergePropertyPair.ObjectName2.Length - 1 - indexOfLastSharp02);


                                string federatedPropertyName = federatedNamesGen.GenerateFederatedName(
                                    o1PropName, o2PropName);

                                string federatedPropURI = $"{mergedClassPair.FederatedURI}#{federatedPropertyName}";
                                mergePropertyPair.FederatedURI = federatedPropURI;
                                //federated property URI generation END

                                if (canWeMergePropertyPairCallback(mergePropertyPair))   //ask user if we're allowed to merge
                                {
                                    //we're allowed to merge -> add to _merged ontology graph (to federated class) federated property
                                    OntologyProperty federatedProperty = _merged.CreateOntologyProperty(new Uri(mergePropertyPair.FederatedURI));
                                    if (mergePropertyPair.MergePropRelation == MergePropertyRelation.EquivalentProperty)
                                    {
                                        federatedProperty.AddEquivalentProperty(new Uri(mergePropertyPair.ObjectName1));
                                        federatedProperty.AddEquivalentProperty(new Uri(mergePropertyPair.ObjectName2));
                                    }

                                    INode oprop1 = _merged.Nodes.Where(node => node.ToString() == mergePropertyPair.ObjectName1).First(); //!!!!!! спорная ситуация
                                    federatedProperty.AddSubProperty(_merged.CreateOntologyProperty(oprop1));
                                    INode oprop2 = _merged.Nodes.Where(node => node.ToString() == mergePropertyPair.ObjectName2).First(); //!!!!!! спорная ситуация
                                    federatedProperty.AddSubProperty(_merged.CreateOntologyProperty(oprop2));

                                    //to specify domain and range we should MERGE THE DATATYPES!!!

                                    var prop01Range = _o1.GetTriplesWithSubjectPredicate(_o1.CreateUriNode(new Uri(mergePropertyPair.ObjectName1)), _o1.CreateUriNode("rdfs:range")).ToList();
                                    var prop02Range = _o2.GetTriplesWithSubjectPredicate(_o2.CreateUriNode(new Uri(mergePropertyPair.ObjectName2)), _o2.CreateUriNode("rdfs:range")).ToList();

                                    if (prop01Range.Count > 1 || prop02Range.Count > 1)
                                    {
                                        throw new InvalidOperationException($"Property can have only one rdfs:range defined! [Properties {mergePropertyPair.ObjectName1} & {mergePropertyPair.ObjectName2} ]");
                                    }
                                    if (prop01Range.Count != prop02Range.Count)
                                    {
                                        throw new InvalidOperationException($"Properties should both have 1 (or zero) range(s) defined [Properties {mergePropertyPair.ObjectName1} & {mergePropertyPair.ObjectName2} ]");
                                    }
                                    //however, props are allowed to not have range defined

                                    string prop01RangeStr = (prop01Range.First() as Triple).Object.ToString();
                                    string prop02RangeStr = (prop02Range.First() as Triple).Object.ToString();

                                    string castedRange = string.Empty;
                                    //check, if prop01RangeStr OR prop02RangeStr not to be a resource (otherwise, it's a range of an object property,
                                    //and, if ranges of different ObjectProperties don't coincide, we can't merge them, so, delete current federatedProperty
                                    Regex r = new Regex(@"http\w{0,1}://.+");
                                    SimilarClassPropertyDescription mergedClasses = null; //in case we merge resource ranges and need a federated range (case 2)
                                    if (r.IsMatch(prop01RangeStr) || r.IsMatch(prop02RangeStr))
                                    {
                                        //check that prop01RangeStr==prop02RangeStr
                                        if (prop01RangeStr == prop02RangeStr)
                                        {
                                            //OK->federated Range is equal to prop01RangeStr\prop02RangeStr
                                            castedRange = prop01RangeStr;
                                            //federatedProperty.AddRange(new Uri($"xsd:{castedRange}")); -> BUG
                                            federatedProperty.AddRange(new Uri(castedRange));
                                            federatedProperty.AddDomain(new Uri(mergedClassPair.FederatedURI));
                                            OntologyResource ontologyPropertyResource = _merged.CreateOntologyResource(new Uri(OntologyHelper.OwlObjectProperty));
                                            federatedProperty.AddType(ontologyPropertyResource);
                                        }
                                        else if ((mergedClasses = mergedClassPairs.FirstOrDefault(simClassProp => {
                                            return((simClassProp.ObjectName1 == prop01RangeStr &&
                                                    simClassProp.ObjectName2 == prop02RangeStr) ||
                                                   (simClassProp.ObjectName1 == prop02RangeStr &&
                                                    simClassProp.ObjectName2 == prop01RangeStr));
                                        })) != null)   //we've found merge pair which states that classes, correspoinding to prop01RangeStr & prop02RangeStr are being merged
                                        {
                                            //if ranges' URIs correspond to classes which are being merged, than we CREATE an ObjectProperty with several ranges
                                            federatedProperty.AddRange(new Uri(prop01RangeStr));
                                            federatedProperty.AddRange(new Uri(prop02RangeStr));
                                            federatedProperty.AddDomain(new Uri(mergedClassPair.FederatedURI));
                                            //add here FEDERATED range too
                                            //get federated class name -> superclass of these 2 given merged classes
                                            if (string.IsNullOrEmpty(mergedClasses.FederatedURI)) //if classes have not been merged yet
                                            {
                                                //fragment copied from above [when merging classes]
                                                o1ClassName = GetClassNameFromUri(mergedClasses.ObjectName1);
                                                o2ClassName = GetClassNameFromUri(mergedClasses.ObjectName2);

                                                federatedClassName = federatedNamesGen.GenerateFederatedName(o1ClassName, o2ClassName);

                                                federatedUri = federatedStem + federatedClassName;
                                                mergedClasses.FederatedURI = federatedUri;
                                            }
                                            federatedProperty.AddRange(new Uri(mergedClasses.FederatedURI));

                                            OntologyResource ontologyPropertyResource = _merged.CreateOntologyResource(new Uri(OntologyHelper.OwlObjectProperty));
                                            federatedProperty.AddType(ontologyPropertyResource);
                                        }
                                        else
                                        {
                                            //ranges of different ObjectProperties don't coincide, we can't merge them, so, don't add current federatedProperty to graph
                                            //federated schema should reference federated schema, otherwise it's a logical error!
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        //ranges should be XSD!, because we're using XSDTypeCaster by default
                                        castedRange = typeCaster.CastTypes(prop01RangeStr, prop02RangeStr);
                                        federatedProperty.AddRange(new Uri($"xsd:{castedRange}"));
                                        federatedProperty.AddDomain(new Uri(mergedClassPair.FederatedURI));

                                        //everything's OK -> add current federated property to ontology graph
                                        OntologyResource ontologyPropertyResource = _merged.CreateOntologyResource(new Uri(OntologyHelper.OwlDatatypeProperty));
                                        federatedProperty.AddType(ontologyPropertyResource);
                                    }
                                }
                                else
                                {
                                    continue; //we're not allowed to merge this pair
                                }
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        throw new NotImplementedException("Merging for other types of relations is not implemented!");
                    }
                }
                else
                {
                    continue;  //didn't pass through threshold
                }
            }
            _merged.SaveToFile("mergedOntology.log.owl");
            return(_merged);
        }
 public static bool IsAnnotationProperty(this OntologyProperty property)
 {
     return(property.Types.UriNodes().Any(propertyType => propertyType.Uri.ToString().Equals(OntologyHelper.OwlAnnotationProperty, StringComparison.Ordinal)));
 }
 public static bool IsFunctional(this OntologyProperty property)
 {
     // Note the toString-based comparison; because .NET Uri class does not differentiate by Uri fragment!
     return(property.Types.UriNodes().Any(propertyType => propertyType.Uri.ToString().Equals(VocabularyHelper.OWL.FunctionalProperty.ToString())));
 }
        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);
        }
예제 #18
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");
        }
예제 #19
0
        public void ValidateAgainstModel(OntologyInfo oInfo)
        {
            OntologyClass oClass = oInfo.GetClass(this.fullURIname);

            if (oClass == null)
            {
                throw new Exception("Class URI does not exist in the model: " + this.fullURIname);
            }

            // build hash of ontology properties for this class...
            Dictionary <String, OntologyProperty> oPropHash = new Dictionary <string, OntologyProperty>();

            foreach (OntologyProperty op in oInfo.GetInheritedProperies(oClass))
            {
                oPropHash.Add(op.GetNameStr(), op);
            }

            // check each property's URI and range
            foreach (PropertyItem myPropItem in this.props)
            {
                // domain
                if (!oPropHash.ContainsKey(myPropItem.GetValueTypeURI()))
                {
                    throw new Exception(String.Format("Node %s contains property %s which does not exist in the model", this.GetSparqlID(), myPropItem.GetUriRelationship()));
                }

                // range
                OntologyRange oRange = oPropHash[myPropItem.GetUriRelationship()].GetRange();
                if (!oRange.GetFullName().Equals(myPropItem.GetValueTypeURI()))
                {
                    throw new Exception(String.Format("Node %s, property %s has type %s which doesn't match %s in model", this.GetSparqlID(), myPropItem.GetUriRelationship(), myPropItem.GetValueTypeURI(), oRange.GetFullName()));
                }
            }

            // check the node items
            foreach (NodeItem myNodeItem in this.nodes)
            {
                if (myNodeItem.GetConnected())
                {   // domain
                    if (!oPropHash.ContainsKey(myNodeItem.GetUriConnectBy()))
                    {
                        throw new Exception(String.Format("Node %s contains node connection %s which does not exist in the model", this.GetSparqlID(), myNodeItem.GetUriConnectBy()));
                    }

                    // range checks
                    OntologyProperty oProp  = oPropHash[myNodeItem.GetUriConnectBy()];
                    OntologyRange    oRange = oProp.GetRange();
                    if (!myNodeItem.GetUriValueType().Equals(oRange.GetFullName()))
                    {   // this is odd to create d before failing hard but i am performing a very literal port so this is bing maintained.
                        List <OntologyProperty> d = oInfo.GetInheritedProperies(oClass);
                        throw new Exception(String.Format("Node %s contains node connection %s with type %s which doesn't match %s in model", this.GetSparqlID(), myNodeItem.GetUriConnectBy(), myNodeItem.GetUriValueType(), oRange.GetFullName()));
                    }

                    // connected node types
                    foreach (Node n in myNodeItem.GetNodeList())
                    {
                        OntologyClass rangeClass  = oInfo.GetClass(oRange.GetFullName());
                        OntologyClass myNodeClass = oInfo.GetClass(n.GetFullUriName());

                        if (!oInfo.ClassIsA(myNodeClass, rangeClass))
                        {
                            throw new Exception(String.Format("Node %s, node connection %s connects to node %s with type %s which isn't a type of %s in model", this.GetSparqlID(), myNodeItem.GetUriConnectBy(), n.GetSparqlID(), n.GetFullUriName(), oRange.GetFullName()));
                        }
                    }
                }
            }
        }
예제 #20
0
 public void Properties_have_one_domain_one_range(OntologyProperty property)
 {
     Assert.AreEqual(1, property.Domains.Count(), "Properties must have exactly one domain.");
     Assert.AreEqual(1, property.Ranges.Count(), "Properties must have exactly one range.");
 }
예제 #21
0
 public PropertyListItem(OntologyProperty property)
 {
     this.property = property;
 }
        /// <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();
                        }
                    }
                }
            }
        }
예제 #23
0
 private static IEnumerable <OntologyProperty> EnumerateProperties(OntologyProperty ontologyProperty)
 {
     return(ontologyProperty.SubProperties.SelectMany(x => EnumerateProperties(x)).Concat(new[] { ontologyProperty }));
 }
예제 #24
0
        public void Properties_are_camel_cased(OntologyProperty property)
        {
            var localName = new Uri(BaseUri).MakeRelativeUri((property.Resource as IUriNode).Uri).ToString();

            StringAssert.Matches(localName, new Regex(@"^[a-z]([a-z]|[A-Z]|[0-9])*$"), "Properties must be camelCased.");
        }
예제 #25
0
        private void PropertyContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            OntologyProperty selectedProperty = ((PropertyListItem)propertiesListBox.SelectedItem).property;
            Uri selectedPropertyUri           = ((UriNode)selectedProperty.Resource).Uri;

            // Populate the range type selector
            propCtxMenuRangeTypeSelector.Items.Clear();
            propCtxMenuRangeTypeSelector.Items.AddRange(new String[] { NAMED_INDIVIDUAL_LABEL,
                                                                       NESTED_ANON_INDIVIDUAL_LABEL });

            _noise = true;
            if (!RdfOntologyOperations.instance.nestedProperties.ContainsKey(selectedPropertyUri.AbsoluteUri))
            {
                propCtxMenuRangeTypeSelector.SelectedIndex = 0;
                propCtxMenuSubProperties.Enabled           = false;
            }
            else
            {
                propCtxMenuRangeTypeSelector.SelectedIndex = 1;
                propCtxMenuSubProperties.Enabled           = true;
            }
            _noise = false;

            // Load submenus in propCtxMenuSubProperties based on the selected property
            propCtxMenuSubProperties.DropDownItems.Clear();
            List <Uri> subPropertyUris = new List <Uri>();

            subPropertyUris.Add(new Uri(OntologyHelper.PropertyLabel));

            // TODO: This is horribly slow on non-trivial sized graphs; very likely needs to be changed!
            foreach (OntologyClass range in selectedProperty.Ranges)
            {
                foreach (OntologyProperty subPropertyCandidate in graph.OwlProperties)
                {
                    if (subPropertyCandidate.Domains.Contains(range))
                    {
                        Uri subPropertyCandidateUri = ((UriNode)subPropertyCandidate.Resource).Uri;
                        subPropertyUris.Add(subPropertyCandidateUri);
                    }
                }
            }
            foreach (Uri subPropertyUri in subPropertyUris)
            {
                ToolStripMenuItem newItem = new ToolStripMenuItem(subPropertyUri.ToString())
                {
                    Checked      = false,
                    CheckOnClick = true,
                    Tag          = subPropertyUri,
                };
                newItem.CheckedChanged += new EventHandler(this.NestedProperty_CheckedChanged);
                propCtxMenuSubProperties.DropDownItems.Add(newItem);

                if (RdfOntologyOperations.instance.nestedProperties.ContainsKey(selectedPropertyUri.AbsoluteUri))
                {
                    HashSet <string> nestedProperties = RdfOntologyOperations.instance.nestedProperties[selectedPropertyUri.AbsoluteUri];
                    if (nestedProperties.Contains(subPropertyUri.AbsoluteUri))
                    {
                        newItem.Checked = true;
                    }
                    else
                    {
                        newItem.Checked = false;
                    }
                }
            }
        }