Exemplo n.º 1
0
        /// <summary>
        /// Returns all annotations contained in the manager as DLAnnotationAxiom.
        /// </summary>
        /// <param name="pfx2ns">If not null, it will be used to transform each prefix found to the full namespace.</param>
        /// <returns></returns>
        public Dictionary <ARS.EntityKind, List <DL.DLAnnotationAxiom> > getDLAnnotationAxioms(Func <string, string> pfx2ns = null)
        {
            var dlAnnotatedAxioms = new Dictionary <ARS.EntityKind, List <DL.DLAnnotationAxiom> >();

            foreach (var annotKv in _annotatedElements)
            {
                var kind = ParseSubjectKind(subjectType[annotKv.Key]);
                if (!dlAnnotatedAxioms.ContainsKey(kind))
                {
                    dlAnnotatedAxioms.Add(kind, new List <DL.DLAnnotationAxiom>());
                }
                var dlSubj = CNLTools.DLToFullUri(annotKv.Key, kind, pfx2ns);
                foreach (var annotEl in annotKv.Value)
                {
                    var nameToUse = annotEl.Type;

                    dlAnnotatedAxioms[kind].Add(new DL.DLAnnotationAxiom(null, dlSubj, subjectType[annotKv.Key], CNLTools.DLToFullUri(annotEl.Type, ARS.EntityKind.Role, pfx2ns), annotEl.Language, (string)annotEl.Value));
                }
            }
            return(dlAnnotatedAxioms);
        }
Exemplo n.º 2
0
        public static string GetOWLXML(CNL.DL.Paragraph para, bool owlXml, string externext, Dictionary <string, string> invUriMappings, AnnotationManager annotMan, string ontologyBase = null, Dictionary <string, Tuple <string, string> > prefixes = null, string defaultGuid = null, Dictionary <string, List <string> > owlOntologyAnnotation = null, string generatedBy = "CogniPy")
        {
            prefixes = prefixes ?? new Dictionary <string, Tuple <string, string> >();
            if (ontologyBase == null)
            {
                ontologyBase = "http://www.ontorion.com/ontologies/Ontology" + Guid.NewGuid().ToString("N");
            }

            //var ontologyBase = (ontologyNs ?? "http://www.ontorion.com/ontologies/Ontology" + Guid.NewGuid().ToString("N"));
            //if(!String.IsNullOrEmpty(defaultGuid))
            //    ontologyBase = (ontologyNs ?? "http://www.ontorion.com/ontologies/Ontology" + defaultGuid);

            if (!ontologyBase.EndsWith("/") && !ontologyBase.EndsWith("#") && !ontologyBase.Contains("#"))
            {
                ontologyBase += "#";
            }

            OWLOntologyManager manager = OWLManager.createOWLOntologyManager();

            CogniPy.ARS.Transform transform = new CogniPy.ARS.Transform();
            transform.InvUriMappings = invUriMappings;
            var df = manager.getOWLDataFactory();

            ontology = manager.createOntology(IRI.create(ontologyBase));

            org.semanticweb.owlapi.vocab.PrefixOWLOntologyFormat owlxmlFormat = null;
            if (owlXml)
            {
                owlxmlFormat = new org.semanticweb.owlapi.io.OWLXMLOntologyFormat();
            }
            else
            {
                owlxmlFormat = new org.semanticweb.owlapi.io.RDFXMLOntologyFormat();
            }

            owlxmlFormat.setDefaultPrefix(ontologyBase);

            foreach (var kv in prefixes)
            {
                owlxmlFormat.setPrefix(kv.Key.Replace("$", "."), kv.Value.Item1);                                                        // should we put here the Item2 (the location) and not the inner namespace???
                if (!String.IsNullOrEmpty(kv.Value.Item2) && !(kv.Value.Item2.EndsWith(".encnl") || kv.Value.Item2.EndsWith(".encnl#"))) // do not export cnl imports (not in OWL!)
                {
                    // here we need to use Item1 because we cannot export into OWL the specific location of the ontology ---> this is bad practice as in this way we loose the generality of the owl file
                    // imagine that the location is C://mydirectory/... and I add into an owl file: owl:import "C:/mydirectory/". This mean that only on my computer I will be able to import this file.
                    // On the other hand if we write owl:import "namespace of the file" there is a good chance that when someone else will open the file, the file will be imported from internet.

                    var decl = manager.getOWLDataFactory().getOWLImportsDeclaration(OWLPathUriTools.Path2IRI(kv.Value.Item1.TrimEnd('#')));
                    manager.applyChange(new AddImport(ontology, decl));
                }
            }

            manager.setOntologyFormat(ontology, owlxmlFormat);

            if (owlOntologyAnnotation != null)
            {
                foreach (var keyVal in owlOntologyAnnotation)
                {
                    foreach (string val in keyVal.Value)
                    {
                        manager.applyChange(new AddOntologyAnnotation(
                                                ontology,
                                                manager.getOWLDataFactory().getOWLAnnotation(
                                                    manager.getOWLDataFactory().getOWLAnnotationProperty(IRI.create(keyVal.Key)),
                                                    manager.getOWLDataFactory().getOWLLiteral(val))));
                    }
                }
            }

            transform.setOWLDataFactory(false, ontologyBase, df, owlxmlFormat, CNL.EN.CNLFactory.lex);

            var paraFromAnnotStatements = annotMan.getDLAnnotationAxioms();
            var stmts = para.Statements;

            foreach (var p in paraFromAnnotStatements)
            {
                stmts.AddRange(p.Value);
            }
            var conv = transform.Convert(new CogniPy.CNL.DL.Paragraph(null)
            {
                Statements = stmts
            });

            var om = new org.coode.xml.OWLOntologyXMLNamespaceManager(manager, ontology);

            foreach (var axiom in conv.axioms)
            {
                if (axiom.comment != null)
                {
                    var dp = axiom.comment.IndexOf(':');
                    var x  = axiom.comment.Substring(0, dp);
                    if (x.Trim() == "Namespace")
                    {
                        var ontologyIri = axiom.comment.Substring(dp + 1).Trim();
                        if (ontologyIri.EndsWith("."))
                        {
                            ontologyIri = ontologyIri.Substring(0, ontologyIri.Length - 1);
                        }
                        if (ontologyIri.StartsWith("\'") && ontologyIri.Length > 2)
                        {
                            ontologyIri = ontologyIri.Substring(1, ontologyIri.Length - 2).Replace("\'\'", "\'");
                        }
                        manager.removeOntology(ontology);
                        ontology = manager.createOntology(IRI.create(ontologyIri));
                        om.setDefaultNamespace(ontologyIri + "#");
                        transform.setOWLDataFactory(true, ontologyBase, df, owlxmlFormat, CNL.EN.CNLFactory.lex);
                    }
                    else if (x.Trim() == "References")
                    {
                        var refs = CNLTools.ParseReferences(axiom.comment.Substring(dp));
                        foreach (Match match in refs)
                        {
                            var onto = match.Groups["ont"].Value;
                            if (onto.StartsWith("\'") && onto.Length > 2)
                            {
                                onto = onto.Substring(1, onto.Length - 2).Replace("\'\'", "\'").Trim();
                            }

                            if (!string.IsNullOrEmpty(onto))
                            {
                                if (onto.ToLower().EndsWith(".encnl"))
                                {
                                    onto = OWLConverter.PathToIRIString(onto.Substring(0, onto.Length - ".encnl".Length) + externext);
                                }


                                var ns = match.Groups["ns"].Value;
                                if (ns.StartsWith("\'") && ns.Length > 2)
                                {
                                    ns = ns.Substring(1, ns.Length - 2).Replace("\'\'", "\'").Trim();
                                }
                                else
                                if (string.IsNullOrEmpty(ns))
                                {
                                    ns = onto;
                                }

                                om.setPrefix(match.Groups["pfx"].Value, ns);
                                owlxmlFormat.setPrefix(match.Groups["pfx"].Value, ns);
                                var decl = manager.getOWLDataFactory().getOWLImportsDeclaration(OWLPathUriTools.Path2IRI(onto));
                                manager.applyChange(new AddImport(ontology, decl));
                            }
                        }
                    }
                    else
                    {
                        //manager.applyChange(new AddOntologyAnnotation(
                        //    ontology,
                        //    manager.getOWLDataFactory().getOWLAnnotation(
                        //         manager.getOWLDataFactory().getOWLAnnotationProperty(IRI.create(ontologyBase + x)),
                        //         manager.getOWLDataFactory().getOWLLiteral(axiom.comment.Substring(dp)))));
                    }
                }
                else if (axiom.axiom != null)
                {
                    manager.addAxiom(ontology, axiom.axiom);
                }
            }

            foreach (var axiom in conv.additions)
            {
                manager.addAxiom(ontology, axiom);
            }

            var ontout = new org.semanticweb.owlapi.io.StringDocumentTarget();

            manager.saveOntology(ontology, owlxmlFormat, ontout);
            manager.removeOntology(ontology);
            var retdoc = new XmlDocument();

            retdoc.LoadXml(ontout.toString());
            foreach (var elem in retdoc.ChildNodes)
            {
                if (elem is XmlComment)
                {
                    retdoc.RemoveChild(elem as XmlComment);
                }
            }
            retdoc.AppendChild(retdoc.CreateComment("Generated by " + generatedBy + ", (with support from OwlApi)"));

            return(SerializeDoc(retdoc));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Loads the W3CAnnotations found in the line. By default the annotationManager is using DL internally if the text you are giving is not in DL, use the inputTranslator argument
        /// If the subject of an annotation is a Statement, then the Statement is expected to be written like: "statement where quote is ''"
        /// </summary>
        /// <param name="line"></param>
        /// <param name="append">Decides if the text should be appended to the annotationManager or not</param>
        /// <param name="inputTranslator">Used internally to translate for CNL to DL. Use it if the input is not in DL. From ENCNL, the translator is: x => Ontorion.CNL.EN.ENNameingConvention.ToDL(new Ontorion.CNL.EN.EnName() { id = x }, Ontorion.CNL.EN.endict.WordKind.NormalForm).id </param>
        /// <returns></returns>
        public void loadW3CAnnotationsFromText(string line, bool append = false, Func <string, string> inputTranslator = null)
        {
            if (String.IsNullOrEmpty(line) || String.IsNullOrWhiteSpace(line) || !line.Contains(":"))
            {
                return;
            }

            var localAnnotationManager = new AnnotationManager();

            var dp = 0;

            if (line.Contains(ANNOTATION_START))
            {
                dp = line.IndexOf(':') + 1;
            }

            bool newAnnotationSubjects = false;
            var  refs = w3cAnnotRg.Matches(line.Substring(dp).Trim());

            foreach (Match match in refs)
            {
                string annotated = match.Groups["annotated"].Value;
                string type      = match.Groups["type"].Value;
                string val       = match.Groups["value"].Value;
                string kind      = match.Groups["annotatedKind"].Value;
                // if one of these values are null this means that something went wrong during parsing... someone changed it manually?
                // in this case we skip this line.
                if (String.IsNullOrWhiteSpace(annotated) || String.IsNullOrWhiteSpace(type) || String.IsNullOrWhiteSpace(val) || String.IsNullOrWhiteSpace(kind))
                {
                    continue;
                }

                var res = ParseSubjectKind(kind);
                annotated = annotated.Trim();
                type      = type.Trim();

                if (inputTranslator != null)
                {
                    if (res != ARS.EntityKind.Statement && !CNLTools.isSurelyDLEntity(annotated, res))
                    {
                        annotated = inputTranslator(annotated);
                    }

                    if (!CNLTools.isSurelyDLEntity(type, ARS.EntityKind.Role))
                    {
                        type = inputTranslator(type);
                    }
                }

                // if the subject is a statement, then the annotation manager keeps it internally as: statement with quotes inside (no quotes around!)
                if (res == ARS.EntityKind.Statement && annotated.StartsWith("\"") && annotated.EndsWith("\""))
                {
                    annotated = annotated.Substring(1, annotated.Length - 2).Replace("\''", "\"");
                }
                else if (res == ARS.EntityKind.Statement && !annotated.StartsWith("\"") && !annotated.EndsWith("\"")) //statement should be quoted! If not, continue.
                {
                    continue;
                }

                if (!localAnnotationManager.ContainsAnnotationSubject(annotated.Trim()))
                {
                    newAnnotationSubjects = true;
                }
                localAnnotationManager.appendAnnotations(annotated.Trim(), kind.Trim(), new List <W3CAnnotation>()
                {
                    new W3CAnnotation(true)
                    {
                        Type = type.Trim(), Value = val.Trim(), Language = match.Groups["language"].Value
                    }
                });
            }

            if (newAnnotationSubjects && NewAnnotationSubject != null && FireNewSubjectEvent)
            {
                NewAnnotationSubject(this);
            }

            if (!append)
            {
                this.clearAnnotations();
            }

            appendAnnotations(localAnnotationManager);

            if (!append)
            {
                this.AssumeNotModifiedNow();
            }
        }
Exemplo n.º 4
0
 string applyFullUri(string nm)
 {
     return(CNLTools.DLToFullUri(nm, ARS.EntityKind.Instance, pfx2ns, _defaultNs));
 }