I have written an interface that given for example the Pizza ontology it can distinguish between asserted and inferred axioms. For example, given Class: Food SubClassOf: Thing it will tell you that it is inferred. My question is that if I have an unsatisfiable class TomatoTopping, and I want to know if Class: TomatoTopping SubClassOf: Nothing is asserted, inferred or none, I will get the response that the axiom doesn't exist. Although I can see TomatoTopping under Nothing in the hierarchy. What is the problem? Can't I query such an axiom or my logic is flawed?
This is the code that identifies Class: Food SubClassOf: Thing but not Class: TomatoTopping SubClassOf: Nothing
// parsing input
Set<OntologyAxiomPair> frame = parsingProcess(tool, input);
Iterator<OntologyAxiomPair> frameit = frame.iterator();
while (frameit.hasNext()) {
OntologyAxiomPair newPair = frameit.next();
OWLAxiom tempAx = newPair.getAxiom();
// the axiom type must be anything but declaration
if (!tempAx.isOfType(AxiomType.DECLARATION)) {
// get asseted and inferred axioms
Set<OWLAxiom> asserted = getOntology().getAxioms();
if (asserted.contains(tempAx)) {
Result = "System: this axiom is an asserted axiom.";
displayUserMessage(Result, asetBlue);
break;
}
// Use an inferred axiom generators
else
{
// Calling TrOWL
RELReasoner reasoner = relfactory.createReasoner(getOntology());
if(reasoner.isEntailed( tempAx)){
Result = "System: this axiom is an inferred axiom.";
displayUserMessage(Result, asetMagenta);
break;
}
}
}
}
I think I discovered what the problem is. The Manchester Syntax parser needs a datafactory.
OWLOntologyManager manager = inputOntology.getOWLOntologyManager();
this.dataFactory = manager.getOWLDataFactory();
Since the manager is not classified by a reasoner, the OWL:Nothing does not appear. Do you know of a way to classify a manager and then extract datafactroy?
Related
Is there a way to get inferences from HermiT reasoner that contain negation (ObjectComplementOf)? Here is what I tried:
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
dataFactory = manager.getOWLDataFactory();
IRI iri = IRI.create("http://www.test.owl");
OWLOntology ontology = manager.createOntology(iri);
OWLClass clsA = dataFactory.getOWLClass(IRI.create(iri + "#A"));
OWLClass clsB = dataFactory.getOWLClass(IRI.create(iri + "#B"));
OWLAxiom axiom = dataFactory.getOWLSubClassOfAxiom(clsA, clsB.getComplementNNF());
OWLIndividual john = dataFactory.getOWLNamedIndividual(IRI.create(iri + "#JOHN"));
OWLClassAssertionAxiom assertionAxiom = dataFactory.getOWLClassAssertionAxiom(clsA, john);
ontology.add(axiom);
ontology.add(assertionAxiom);
OWLReasonerFactory reasoner_factory = new ReasonerFactory();
OWLReasoner reasoner = reasoner_factory.createReasoner(ontology);
OWLOntology inferred_ontology = manager.createOntology();
// Create an inferred axiom generator, and add the generators of choice.
List<InferredAxiomGenerator<? extends OWLAxiom>> gens = new ArrayList<>();
gens.add(new InferredSubClassAxiomGenerator());
gens.add(new InferredClassAssertionAxiomGenerator());
gens.add(new InferredDisjointClassesAxiomGenerator());
gens.add(new InferredEquivalentClassAxiomGenerator());
// Create the inferred ontology generator, and fill the empty ontology.
InferredOntologyGenerator iog = new InferredOntologyGenerator(reasoner, gens);
iog.fillOntology(dataFactory, inferred_ontology);
The (cleaned) result:
//KB: A SubClassOf not(B), A(JOHN)
ENTAILMENTS:{
SubClassOf(A owl:Thing),
SubClassOf(B owl:Thing),
DisjointClasses(A owl:Nothing),
DisjointClasses(B owl:Nothing),
DisjointClasses(A B),
ClassAssertion(owl:Thing JOHN),
ClassAssertion(A JOHN)
}
My question: How can I also get this assertion:
ClassAssertion(ObjectComplementOf(B) JOHN)?
It's not possible to generate all inferred axioms that use class or property expressions. The reason for that is that the list of class (and property) expressions is infinite, so the reasoner would embark on an impossible task if it tried to generate all axioms of that kind.
If you have a criterion for selecting a finite subset of class expressions (e.g., the list of complements for each named class in the ontology) you could implement an axiom generator that asks the reasoner whether those classes have instances, and create the axioms that way.
Reasoners could also do the same, to provide a partial answer to a question with infinite answers - but, far as I'm aware, there are no reasoners which do that. HermiT certainly does not.
In FileNet P8, I need to get the datatype of the property of a custom class using JAVA API. Is there any way to do the same?
This should give you an idea of what you need to do:
//SymbolicName of the property we will search for.
String strSearchName = PropertyNames.DATE_LAST_MODIFIED;
//Document (or other object) that we will use to get classDescription.
Document document = (Document) arg0;
PropertyDescription objPropDesc = null;
PropertyDescriptionList pdl = document.get_ClassDescription().get_PropertyDescriptions();
Iterator<?> iter = pdl.iterator();
while (iter.hasNext())
{
objPropDesc = (PropertyDescription) iter.next();
// Get SymbolicName property from the property cache
String strPropDescSymbolicName = objPropDesc.get_SymbolicName();
if (strPropDescSymbolicName.equalsIgnoreCase(strSearchName))
{
// PropertyDescription object found
System.out.println("Property description selected: " + strPropDescSymbolicName);
System.out.println(objPropDesc);
TypeID type = objPropDesc.get_DataType();
System.out.println(type.toString());
break;
}
}
The idea is to:
Take an object (Document in this case).
Get its Class Description.
Get the list of Property Descriptions from the Class Description.
Loop through the Property Descritpions until you locate the Description you are trying to find.
Get the TypeId from the Property Description.
The TypeId contains the information you need to know what the Type is of the Property.
I borrowed code from here : Working with Properties
You should also familiarize yourself with this : Properties
Edit to add a different method:
In the case of creating documents, we need to be able to obtain the Class Description object. This means we will need to perform additional round trips.
// Get the ClassDescription
String strSymbolicName = "myClassName";
ClassDescription objClassDesc = Factory.ClassDescription.fetchInstance(myObjStore, strSymbolicName, null);
// find the PropertyDescription
PropertyDescription pds = null;
PropertyDescriptionList pdl = objClassDesc.get_PropertyDescriptions();
Iterator<?> itr = pdl.iterator();
while(itr.hasNext()){
pds = (PropertyDescription) itr.next();
System.out.println("Symbolic Name is "+pds.get_SymbolicName()+" DataType is "+pds.get_DataType().toString());
}
// You can now use it in a loop of several documents if you wish.
...
Take a look here as well : Working With Classes
Christopher Powell's answer is correct, there is one thing it does not cover, though (depending on the definition of the custom class in question). Consider this as a "best practice" or just an extension of the code borrowed from the URL that Christopher mentioned.
The FileNet P8 class hierarchy allows for inheritance of property definitions. Simple example: one can search through the 'Document' class - which is the root class of the class hierarchy - of an object store, and use some property of a subclass in the search sql. Imagine Subclass1 as an immediate subclass of Document. Subclass1 has a property Property1. Even if Document does not have this property in its class description, a search in Document with Property1='somevalue' will return objects of Subclass1 (if there is a match with 'somevalue').
However,
objClassDesc.get_PropertyDescriptions();
won't return property descriptions of subclasses, thus you might end up with API_PROPERTY_NOT_IN_CACHE errors.
To give you a good starting point if you are facing this case, look at below code:
PropertyDescriptionList ownProps = objClassDesc.get_PropertyDescriptions();
PropertyDescriptionList subclassProps = null;
if (objClassDesc.get_HasProperSubclassProperties()) {
logger.debug("Document class '"+documentClassname+"' supports 'include descendant properties' queries, including descendant properties.");
subclassProps = objClassDesc.get_ProperSubclassPropertyDescriptions();
}
List<PropertyDescription> result = mergePropertyDescriptionLists(ownProps, subclassProps);
If you need to merge those two lists, you are better off using a List of PropertyDescription objects instead of PropertyDescriptionList: the ones returned by the server are read-only.
#SuppressWarnings("unchecked")
protected List<PropertyDescription> mergePropertyDescriptionLists(PropertyDescriptionList list1, PropertyDescriptionList list2) throws Exception {
try {
#SuppressWarnings("unchecked")
List<PropertyDescription> mergedList = new ArrayList<PropertyDescription>();
if (list1 != null && (list1.size() > 0)) {
mergedList.addAll(list1);
}
if (list2 != null && (list2.size() > 0)) {
mergedList.addAll(list2);
}
return mergedList;
} catch (Throwable t) {
throw new Exception("Failed to merge property description lists.", t);
}
}
I am currently implementing cross-referencing for my Xtext dsl. A dsl file can contain more then one XImportSection and in some special case an XImportSection does not necessariely contain all import statements. It means I need to customize the "XImportSectionNamespaceScopeProvider" to find/build the correct XimportSection. During the implementation I figured out an unexpected behavior of the editor and/or some validation.
I used the following dsl code snipped for testing my implementation:
delta MyDelta {
adds {
package my.pkg;
import java.util.List;
public class MyClass
implements List
{
}
}
modifies my.pkg.MyClass { // (1)
adds import java.util.ArrayList;
adds superclass ArrayList<String>;
}
}
The dsl source code is described by the following grammar rules (not complete!):
AddsUnit:
{AddsUnit} 'adds' '{' unit=JavaCompilationUnit? '}';
ModifiesUnit:
'modifies' unit=[ClassOrInterface|QualifiedName] '{'
modifiesPackage=ModifiesPackage?
modifiesImports+=ModifiesImport*
modifiesSuperclass=ModifiesInheritance?
'}';
JavaCompilationUnit:
=> (annotations+=Annotation*
'package' name=QualifiedName EOL)?
importSection=XImportSection?
typeDeclarations+=ClassOrInterfaceDeclaration;
ClassOrInterfaceDeclaration:
annotations+=Annotation* modifiers+=Modifier* classOrInterface=ClassOrInterface;
ClassOrInterface: // (2a)
ClassDeclaration | InterfaceDeclaration | EnumDeclaration | AnnotationTypeDeclaration;
ClassDeclaration: // (2b)
'class' name=QualifiedName typeParameters=TypeParameters?
('extends' superClass=JvmTypeReference)?
('implements' interfaces=Typelist)?
body=ClassBody;
To provide better tool support, a ModifiesUnit references the class which is modified. This Xtext specific implementation enables hyperlinking to the class.
I am currently working on customized XImportSectionScopeProvider which provides all namespace scopes for a ModifiesUnit. The default implemantation contain a method protected List<ImportNormalizer> internalGetImportedNamespaceResolvers(EObject context, boolean ignoreCase) assumes that there is only one class-like element in a source file. But for my language there can be more then one. For this reason I have to customize it.
My idea now is the following implementation (using the Xtend programming language):
override List<ImportNormalizer> internalGetImportedNamespaceResolvers(EObject context, boolean ignoreCase) {
switch (context) {
ModifiesUnit: context.buildImportSection
default: // ... anything else
}
}
Before I startet this work, the reference worked fine and nothing unexpected happend. My goal now is to build a customized XImportSection for the ModifiesUnit which is used by Xbase to resolve references to JVM types. To do that, I need a copy of the XImportSection of the referenced ClassOrInterface. To get access to the XImportSection, I first call ModifiesUnit.getUnit(). Directly after this call is executed, the editor shows the unexpected behaviour. The minimal implementation which leads to the error looks like this:
def XImportSection buildImportSection(ModifiesUnit u) {
val ci = u.unit // Since this expression is executed, the error occurs!
// ...
}
Here, I don't know what is going internally! But it calculates an error. The editor shows the follwoing error on the qualified name at (1): "Cyclic linking detected : ModifiesUnit.unit->ModifiesUnit.unit".
My questions are: What does it mean? Why does Xtext show this error? Why does it appear if I access the referenced object?
I also figured out a strange thing there: In my first approach my code threw a NullPointerException. Ok, I tried to figure out why by printing the object ci. The result is:
org.deltaj.scoping.deltaJ.impl.ClassOrInterfaceImpl#4642f064 (eProxyURI: platform:/resource/Test/src/My.dj#xtextLink_::0.0.0.1.1::0::/2)
org.deltaj.scoping.deltaJ.impl.ClassDeclarationImpl#1c70366 (name: MyClass)
Ok, it seems to be that this method is executed two times and Xtext resolves the proxy between the first and second execution. It is fine for me as long as the received object is the correct one once. I handle it with an if-instanceof statement.
But why do I get two references there? Does it rely on the ParserRule ClassOrInterface (2a) which only is an abstract super rule of ClassDeclaration (2b)? But why is Xtext not able to resolve the reference for the ClassOrInterface?
OK, now I found a solution for my problem. During I was experimenting with my implementation, I saw that the "Problems" view stil contained unresolved references. This was the reason to rethink what my implementation did. At first, I decided to build the returned list List<ImportNormalizer directly instead of building an XImportSection which then will be converted to this list. During implementing this, I noticed that I have built the scope only for ModifiesUnitelements instead of elements which need the scope within a ModifiesUnit. This is the reason for the cyclic linking error. Now, I am building the list only if it is needed. The result is that the cyclic linking error occurs does not occur any more and all references to JVM types are resolved correctly without any errors in the problems view.
My implementation now looks like this:
class DeltaJXImportSectionNamespaceScopeProvider extends XImportSectionNamespaceScopeProvider {
override List<ImportNormalizer> internalGetImportedNamespaceResolvers(EObject context, boolean ignoreCase) {
// A scope will only be provided for elements which really need a scope. A scope is only necessary for elements
// which are siblings of a JavaCompilationUnit or a ModifiesUnit.
if (context.checkElement) { // (1)
return Collections.emptyList
}
// Finding the container which contains the import section
val container = context.jvmUnit // (2)
// For a non null container create the import normalizer list depending of returned element. If the container is
// null, no scope is needed.
return if (container != null) { // (3)
switch (container) {
JavaCompilationUnit: container.provideJcuImportNormalizerList(ignoreCase)
ModifiesUnit: container.provideMcuImportNormalizerList(ignoreCase)
}
} else {
Collections.emptyList
}
}
// Iterates upwards through the AST until a ModifiesUnit or a JavaCompilationUnit is found. (2)
def EObject jvmUnit(EObject o) {
switch (o) {
ModifiesUnit: o
JavaCompilationUnit: o
default: o.eContainer.jvmUnit
}
}
// Creates the list with all imports of a JCU (3a)
def List<ImportNormalizer> provideJcuImportNormalizerList(JavaCompilationUnit jcu, boolean ignoreCase) {
val is = jcu.importSection
return if (is != null) {
is.getImportedNamespaceResolvers(ignoreCase)
} else {
Collections.emptyList
}
}
// Creates the list of all imports of a ModifiesUnit. This implementation is similar to
// getImportedNamespaceResolvers(XImportSection, boolean) // (3b)
def List<ImportNormalizer> provideMcuImportNormalizerList(ModifiesUnit mu, boolean ignoreCase) {
val List<ImportNormalizer> result = Lists.newArrayList
result.addAll((mu.unit.jvmUnit as JavaCompilationUnit).provideJcuImportNormalizerList(ignoreCase))
for (imp : mu.modifiesImports) {
if (imp instanceof AddsImport) {
val decl = imp.importDeclaration
if (!decl.static) {
result.add(decl.transform(ignoreCase))
}
}
}
result
}
// Creates an ImportNormalizer for a given XImportSection
def ImportNormalizer transform(XImportDeclaration decl, boolean ignoreCase) {
var value = decl.importedNamespace
if (value == null) {
value = decl.importedTypeName
}
return value.createImportedNamespaceResolver(ignoreCase)
}
// Determines whether an element needs to be processed. (1)
def checkElement(EObject o) {
return o instanceof DeltaJUnit || o instanceof Delta || o instanceof AddsUnit || o instanceof ModifiesUnit ||
o instanceof RemovesUnit
}
}
As one can see, elements which do not need namespaces for correct scopes, will be ignored (1).
For each element which might need namespace for a correct scope the n-father element which directly contains the imports is determined (2).
With the correct father element the namespace list can be calculated (3) for JCU's (3a) and MU's (3b).
UPDATE: After getting an unexpected-in-a-good-way answer, I've added some context to the bottom of this question, stating exactly how I'll be using these string-function-calls.
I need to translate a string such as
my.package.ClassName#functionName(1, "a string value", true)
into a reflective call to that function. Getting the package, class, and function name is not a problem. I have started rolling my own solution for parsing the parameter list, and determining the type of each and returning an appropriate object.
(I'm limiting the universe of types to the eight primitives, plus string. null would be considered a string, and commas and double-quotes must be strictly escaped with some simple marker, such as __DBL_QT__, to avoid complications with unescaping and splitting on the comma.)
I am not asking how to do this via string-parsing, as I understand how. It's just a lot of work and I'm hoping there's a solution already out there. Unfortunately it's such generic terminology, I'm getting nowhere with searching.
I understand asking for an external existing library is off topic for SO. I'm just hoping to get some feedback before it's shutdown, or even a suggestion on better search terms. Or perhaps, there is a completely different approach that might be suggested...
Thank you.
Context:
Each function call is found within a function's JavaDoc block, and represents a piece of example code--either its source code or its System.out output--which will be displayed in that spot.
The parameters are for customizing its display, such as
indentation,
eliminating irrelevant parts (like the license-block), and
for JavaDoc-linking the most important functions.
This customization is mostly for the source-code presentation, but may also be applied to its output.
(The first parameter is always an Appendable, which will do the actual outputting.)
The user needs to be be able to call any function, which in many cases will be a private-static function located directly below the JavaDoc-ed function itself.
The application I'm writing will read in the source-code file (the one containing the JavaDoc blocks, in which these string-function-calls exist), and create a duplicate of the *.java file, which will subsequently processed by javadoc.
So for every piece of example code, there will be likely two, and possibly more of these string-function-calls. There may be more, because I may want to show different slices of the same example, in different contexts--perhaps the whole example in the overall class JavaDoc block, and snippets from it in the relevant functions in that class.
I have already written the process that parses the source code (the source code containing the JavaDoc blocks, which is separate from the one that reads the example-code), and re-outputs its source-code blindly with insert example-code here and insert example-code-output here markers.
I'm now at the point where I have this string-function-call in an InsertExampleCode object, in a string-field. Now I need to do as described at the top of this question. Figure out which function they want to invoke, and do so.
Change the # to a dot (.), write a class definition around it so that you have a valid Java source file, include tools.jar in your classpath and invoke com.sun.tools.javac.Main.
Create your own instance of a ClassLoader to load the compiled class, and run it (make it implement a useful interface, such as java.util.concurrent.Callable so that you can get the result of the invocation easily)
That should do the trick.
The class I created for this, called com.github.aliteralmind.codelet.simplesig.SimpleMethodSignature, is a significant piece of Codelet, used to translate the "customizer" portion of each taglet, which is a function that customizes the taglet's output.
(Installation instructions. The only jars that must be in your classpath are codelet and xbnjava.)
Example string signatures, in taglets:
{#.codelet.and.out com.github.aliteralmind.codelet.examples.adder.AdderDemo%eliminateCommentBlocksAndPackageDecl()}
The customizer portion is everything following the percent sign (%). This customizer contains only the function name and empty parameters. This implies that the function must exist in one of a few, strictly-specified, set of classes.
{#.codelet.and.out com.github.aliteralmind.codelet.examples.adder.AdderDemo%lineRange(1, false, "Adder adder", 2, false, "println(adder.getSum())", "^ ")}
This specifies parameters as well, which are, by design, "simple"--either non-null strings, or a primitive type.
{#.codelet.and.out com.github.aliteralmind.codelet.examples.adder.AdderDemo%com.github.aliteralmind.codelet.examples.LineRangeWithLinksCompact#adderDemo_lineSnippetWithLinks()}
Specifies the explicit package and class in which the function exists.
Because of the nature of these taglets and how the string-signatures are implemented, I decided to stick with direct string parsing instead of dynamic compilation.
Two example uses of SimpleMethodSignature:
In this first example, the full signature (the package, class, and function name, including all its parameters) are specified in the string.
import com.github.aliteralmind.codelet.simplesig.SimpleMethodSignature;
import com.github.xbn.lang.reflect.InvokeMethodWithRtx;
import java.lang.reflect.Method;
public class SimpleMethodSigNoDefaults {
public static final void main(String[] ignored) {
String strSig = "com.github.aliteralmind.codelet.examples.simplesig." +
"SimpleMethodSigNoDefaults#getStringForBoolInt(false, 3)";
SimpleMethodSignature simpleSig = null;
try {
simpleSig = SimpleMethodSignature.newFromStringAndDefaults(
String.class, strSig, null, null,
null); //debug (on=System.out, off=null)
} catch(ClassNotFoundException cnfx) {
throw new RuntimeException(cnfx);
}
Method m = null;
try {
m = simpleSig.getMethod();
} catch(NoSuchMethodException nsmx) {
throw new RuntimeException(nsmx);
}
m.setAccessible(true);
Object returnValue = new InvokeMethodWithRtx(m).sstatic().
parameters(simpleSig.getParamValueObjectList().toArray()).invokeGetReturnValue();
System.out.println(returnValue);
}
public static final String getStringForBoolInt(Boolean b, Integer i) {
return "b=" + b + ", i=" + i;
}
}
Output:
b=false, i=3
This second example demonstrates a string signature in which the (package and) class name are not specified. The potential classes, one in which the function must exist, are provided directly.
import com.github.aliteralmind.codelet.simplesig.SimpleMethodSignature;
import com.github.xbn.lang.reflect.InvokeMethodWithRtx;
import java.lang.reflect.Method;
public class SimpleMethodSigWithClassDefaults {
public static final void main(String[] ignored) {
String strSig = "getStringForBoolInt(false, 3)";
SimpleMethodSignature simpleSig = null;
try {
simpleSig = SimpleMethodSignature.newFromStringAndDefaults(
String.class, strSig, null,
new Class[]{Object.class, SimpleMethodSigWithClassDefaults.class, SimpleMethodSignature.class},
null); //debug (on=System.out, off=null)
} catch(ClassNotFoundException cnfx) {
throw new RuntimeException(cnfx);
}
Method m = null;
try {
m = simpleSig.getMethod();
} catch(NoSuchMethodException nsmx) {
throw new RuntimeException(nsmx);
}
m.setAccessible(true);
Object returnValue = new InvokeMethodWithRtx(m).sstatic().
parameters(simpleSig.getParamValueObjectList().toArray()).invokeGetReturnValue();
System.out.println(returnValue);
}
public static final String getStringForBoolInt(Boolean b, Integer i) {
return "b=" + b + ", i=" + i;
}
}
Output:
b=false, i=3
I got a small problem with the output of ANTLR.
Ive a realy small grammar which looks like this:
test : states;
states : '.states' state+;
state : stateID=ID {
System.out.println("state: " + $stateID.text);
| stateID=ID '{' state* '}' {
System.out.println("SubState: " + $stateID.text);};
And what I want to parse looks like this:
a{
b
c{
d
}
}
Well, the problem is, the first token I'll get is 'b' followed by 'd' and then 'c'.
But my intention is to parse it into my datastructure and I need to know their parents.
What I know by this order is, c is the parent of d, but what about b?
If I rewrote the example to this form:
a{
c{
d
}
b
}
Everything is fine. So is there a way to know who is the parent of b, without having the constraint to write it in the last example?
In ANTLR 4 using grammar-actions is no longer recommended. The parser may visit and test different rules and alternatives in unexpected orders, so unless you're adding error-handling code it's better to let the process run normally and then inspect the result.
So you let the parser create its tree, and then write a custom listener that will emit your println calls at each step. For example, suppose you're working with a grammar called Foo, so that and ANTLR autogenerates a FooBaseListener class.
So first you'd make something like:
public class PrintingFooListener extends FooBaseListener {
#Override
public void enterState(FooParser.StateContext ctx)
{
// It is possible to get all sorts of token/subrule/text
// information from the ctx input, especially if you labeled
// the parser/lexer rules.
System.out.println("I entered State");
}
}
Then use the ParseTreeWalker utility class to navigate through the parse tree with your visitor in-tow:
// Assume lexing, etc. already done before this point
ParserRuleContext<Token> tree = parser.myMainRule(); // Do parse
ParseTreeWalker walker = new ParseTreeWalker(); // Premade utility class
PrintingFooListener listener = new PrintingFooListener(); // Your customized subclass
walker.walk(listener, tree);