SWRLb - greaterThan and lessThan triggered - owl

I have a problem using SWRL rules. I have a robot that should notify a human in case of two abnormal situations. For my test case I use the tension of a user:
if the tension is less than 14, then the robot alert that the tension is low:
(:hasTension :Charles ?x) ∧ greaterThan(?x, "14.0"^^xsd:float) → (:hasAlert :Samii "Your tension is high"^^xsd::string)
if the tension is greater than 14, the robot alert that the tension is high.
(:hasTension :Charles ?x) ∧ lessThan(?x, "14.0"^^xsd:float) → (:hasAlert :Samii "Your tension is low"^^xsd::string)
I am Using OWL API with pellet reasoner (openllet fork of pellet). To do so I have my SWRL rules using builtin swrlb:greaterThan and swrlb:lessThan. For the test I add the axiom
:Charles :hasTension "10"^^xsd:float
and query the data property
:Samii :hasAlert ?alert
But when I query the ontology, I get two alerts: one for greaterThan and the other for lessThan. I think my rules are well formed, and I don't have any warning or error from the API saying the builtin are not implemented, so I believe that the rules should work as I'd expect. Any idea why I'm getting the unexpected alert?
Resources
My test "main"
package com.samii.restful;
import java.util.ArrayList;
import org.apache.jena.rdf.model.Statement;
public class Local {
public static void main(String[] args)
{
String path = ""+ Servlet.class.getResource("/Ontologies/justAtest_RDFXML.owl");
Local.mainPelletOWLAPI(path);
}
public static void mainPelletOWLAPI( String path ){
OWLManagement owl_management = new OWLManagement( path );
System.out.println( "[main].main => \n\n== Before adding axiom ==" );
owl_management.printOntology();
System.out.println( "[main].main => \n\n== Query ==" );
String URI = "file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML#";
String ssubject = "Samii";
String spredicate = "hasAlert";
ArrayList<Object> literals = owl_management.queryDataProperty(URI, ssubject, spredicate);
System.out.println("[main].main() -> Number of literals: " + literals.size() );
if( !literals.isEmpty() ){
for( Object literal : literals){
System.out.print( "->" + ssubject + " " + spredicate + " " + literal );
}
}
ssubject = "Charles";
spredicate = "hasTension";
String sobject = "10";
owl_management.updateFunctionalObjectsProperty(URI, ssubject, spredicate, sobject, "float");
System.out.println( "[main].main => \n\n== After adding axiom ==" );
owl_management.printOntology();
System.out.println( "[main].main => \n\n== Query ==" );
ssubject = "Samii";
spredicate = "hasAlert";
literals = owl_management.queryDataProperty(URI, ssubject, spredicate);
System.out.println("[main].main() -> Number of literals: " + literals.size() );
if( !literals.isEmpty() ){
for( Object literal : literals){
System.out.println( "->" + ssubject + " " + spredicate + " " + literal );
}
}
}
}
The core:
package com.samii.restful;
import java.util.ArrayList;
import java.util.Set;
import java.lang.Object;
import com.clarkparsia.pellet.owlapi.PelletReasoner;
import com.clarkparsia.pellet.owlapi.PelletReasonerFactory;
import org.mindswap.pellet.exceptions.InconsistentOntologyException;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.AddAxiom;
import org.semanticweb.owlapi.model.RemoveAxiom;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLDatatype;
import org.semanticweb.owlapi.model.OWLFunctionalDataPropertyAxiom;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLDataProperty;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.reasoner.FreshEntitiesException;
import org.semanticweb.owlapi.reasoner.Node;
import org.semanticweb.owlapi.reasoner.NodeSet;
import org.semanticweb.owlapi.reasoner.ReasonerInterruptedException;
import org.semanticweb.owlapi.reasoner.TimeOutException;
import org.semanticweb.owlapi.vocab.OWL2Datatype;
import org.semanticweb.owlapi.util.ShortFormProvider;
import org.semanticweb.owlapi.util.SimpleShortFormProvider;
import org.semanticweb.owlapi.io.SystemOutDocumentTarget;
import org.semanticweb.owlapi.io.OWLFunctionalSyntaxOntologyFormat;
public class OWLManagement {
OWLOntologyManager _manager;
OWLOntology _ontology;
OWLDataFactory _factory;
PelletReasoner _reasoner;
OWLManagement(String ontology_file_path){
_manager = OWLManager.createOWLOntologyManager();
_factory = _manager.getOWLDataFactory();
try{
_ontology = _manager.loadOntology(IRI.create( ontology_file_path ));
}
catch(Exception e){
System.out.println("Exception " + e.toString());
}
//_reasoner = PelletReasonerFactory.getInstance().createReasoner(_ontology);
_reasoner = PelletReasonerFactory.getInstance().createNonBufferingReasoner(_ontology);
_reasoner.prepareReasoner();
}
public boolean updateFunctionalObjectsProperty( String URI, String ssubject, String spredicate, String sobject, String stype ){
OWLLiteral literal;
switch(stype){
case "float":
OWLDatatype xsd_float = _factory.getOWLDatatype( OWL2Datatype.XSD_FLOAT );
literal = _factory.getOWLLiteral(sobject , xsd_float);
break;
default:
literal = _factory.getOWLLiteral("undefined type");
break;
}
OWLNamedIndividual individual = _factory.getOWLNamedIndividual(URI, ssubject);
OWLDataProperty data_property = _factory.getOWLDataProperty(URI, spredicate);
//OWLFunctionalDataPropertyAxiom functional_data_property = _factory.getOWLFunctionalDataPropertyAxiom( data_property );
OWLAxiom axiom = _factory.getOWLDataPropertyAssertionAxiom( data_property, individual, literal);
Set<OWLLiteral> literals = _reasoner.getDataPropertyValues( individual, data_property );
if( !literals.isEmpty() ){
//_manager.removeAxiom( _ontology, axiom );
_manager.applyChange(new RemoveAxiom( _ontology, axiom) );
}
_manager.applyChange(new AddAxiom( _ontology, axiom) );
return true;
}
public void printOntology(){
try{
// print out the ontology on System.out
_manager.saveOntology(_ontology, new OWLFunctionalSyntaxOntologyFormat(), new SystemOutDocumentTarget());
} catch(Exception e){
System.out.println("[OWLManagement].printOntology() -> Catched exception:");
System.out.println("Exception " + e.toString());
}
//_manager.saveOntology(o, new OWLXMLOntologyFormat(), documentIRI2);
// save in RDF/XML
//_manager.saveOntology(o, documentIRI2);
// Remove the ontology from the manager
//_manager.removeOntology(o);
}
public ArrayList<Object> queryDataProperty( String URI, String ssubject, String spredicate ){
OWLNamedIndividual individual = _factory.getOWLNamedIndividual(URI, ssubject);
OWLDataProperty data_property = _factory.getOWLDataProperty(URI, spredicate);
Set<OWLLiteral> literals = null;
try{
literals = _reasoner.getDataPropertyValues( individual, data_property );
System.out.println("[OWLManagement].printOntology() -> Number of literals: " + literals.size() );
} catch( InconsistentOntologyException e ){
System.out.println("[OWLManagement].printOntology() -> Catched InconsistentOntologyException:");
System.out.println("Exception " + e.toString());
} catch( FreshEntitiesException e ){
System.out.println("[OWLManagement].printOntology() -> Catched FreshEntitiesException:");
System.out.println("Exception " + e.toString());
} catch( ReasonerInterruptedException e ){
System.out.println("[OWLManagement].printOntology() -> Catched ReasonerInterruptedException:");
System.out.println("Exception " + e.toString());
} catch( TimeOutException e ){
System.out.println("[OWLManagement].printOntology() -> Catched TimeOutException:");
System.out.println("Exception " + e.toString());
} catch( Exception e){
System.out.println("[OWLManagement].printOntology() -> Catched exception:");
System.out.println("Exception " + e.toString());
}
ArrayList<Object> objects = new ArrayList<Object>();
if( !literals.isEmpty() ){
for(OWLLiteral literal: literals){
if( literal.isInteger() ){
objects.add( literal.parseInteger() );
} else if( literal.isFloat() ){
objects.add( literal.parseFloat() );
} else if( literal.isDouble() ){
objects.add( literal.parseDouble() );
} else if( literal.isBoolean() ){
objects.add( literal.parseBoolean() );
} else{
objects.add( literal.getLiteral() );
}
}
}
System.out.println("[OWLManagement].printOntology() -> Number of objects: " + literals.size() );
return objects;
}
}
and my ontolgy
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE rdf:RDF [
<!ENTITY owl "http://www.w3.org/2002/07/owl#" >
<!ENTITY owl11 "http://www.w3.org/2006/12/owl11#" >
<!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" >
<!ENTITY owl11xml "http://www.w3.org/2006/12/owl11-xml#" >
<!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" >
<!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" >
<!ENTITY CR-owl-guide-20030818 "http://www.w3.org/TR/2003/CR-owl-guide-20030818/" >
<!ENTITY local "file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML#" >
<!ENTITY swrlb "http://www.w3.org/2003/11/swrlb#" >
<!ENTITY swrl "http://www.w3.org/2003/11/swrl#" >
]>
<rdf:RDF xml:base ="file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML"
xmlns ="file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML#"
xmlns:local="file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML#"
xmlns:owl="http://www.w3.org/2002/07/owl#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:var="urn:swrl#"
xmlns:xml="http://www.w3.org/XML/1998/namespace"
xmlns:swrlb="http://www.w3.org/2003/11/swrlb#"
xmlns:swrl="http://www.w3.org/2003/11/swrl#">
<!--owl:Ontology rdf:about="file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML#"/-->
<owl:Ontology rdf:about=""/>
<!--Defining classes about robots-->
<owl:Class rdf:about="&local;Robot"/>
<owl:Class rdf:about="&local;Humanoid">
<rdfs:subClassOf rdf:resource="&local;Robot"/>
</owl:Class>
<owl:AllDisjointClasses>
<owl:members rdf:parseType="Collection">
<owl:Class rdf:about="&local;Animal"/>
<owl:Class rdf:about="&local;Robot"/>
</owl:members>
</owl:AllDisjointClasses>
<!--Defining classes about animals-->
<owl:Class rdf:about="&local;Animal"/>
<owl:Class rdf:about="&local;Mammal"/>
<owl:Class rdf:about="&local;Human">
<rdfs:subClassOf rdf:resource="&local;Mammal"/>
</owl:Class>
<owl:Class rdf:about="&local;Person">
<owl:equivalentClass rdf:resource="&local;Human"/>
</owl:Class>
<owl:Class rdf:about="&local;Man">
<rdfs:subClassOf rdf:resource="&local;Human"/>
</owl:Class>
<owl:Class rdf:about="&local;Woman">
<rdfs:subClassOf rdf:resource="&local;Human"/>
</owl:Class>
<owl:AllDisjointClasses>
<owl:members rdf:parseType="Collection">
<owl:Class rdf:about="&local;Man"/>
<owl:Class rdf:about="&local;Woman"/>
</owl:members>
</owl:AllDisjointClasses>
<owl:ObjectProperty rdf:about="&local;hasRobot">
<rdfs:domain rdf:resource="&local;Human"/>
<rdfs:range rdf:resource="&local;Robot"/>
</owl:ObjectProperty>
<owl:DatatypeProperty rdf:about="&local;hasAlert"/>
<!--owl:DatatypeProperty rdf:about="&local;hasAlert">
<rdfs:range rdf:resource="&xsd;string"/>
</owl:DatatypeProperty-->
<!--rdfs:Property rdf:about="&local;hasAlert">
<rdfs:domain rdf:resource="&local;Robot"/>
<rdfs:range rdf:resource="&xsd;string"/>
</rdfs:Property-->
<owl:DatatypeProperty rdf:about="&local;hasTemperature">
<rdf:type rdf:resource="&owl;FunctionalProperty"/>
<!--rdfs:range rdf:resource="&xsd;nonNegativeInteger"/-->
</owl:DatatypeProperty>
<owl:DatatypeProperty rdf:about="&local;hasTension">
<rdf:type rdf:resource="&owl;FunctionalProperty"/>
<!--rdfs:range rdf:resource="&xsd;nonNegativeInteger"/-->
</owl:DatatypeProperty>
<owl:NamedIndividual rdf:about="&local;Charles">
<rdf:type rdf:resource="&local;Man"/>
<!--local:hasTension rdf:datatype="&xsd;float">14</local:hasTension-->
</owl:NamedIndividual>
<owl:NegativePropertyAssertion>
<owl:sourceIndividual rdf:resource="&local;Charles"/>
<owl:assertionProperty rdf:resource="&local;hasRobot"/>
<owl:targetIndividual rdf:resource="&local;Samii"/>
</owl:NegativePropertyAssertion>
<owl:NamedIndividual rdf:about="&local;Walid">
<rdf:type rdf:resource="&local;Man"/>
<local:hasRobot rdf:resource="&local;Samii"/>
<local:hasTemperature rdf:datatype="&xsd;float">37.5</local:hasTemperature>
</owl:NamedIndividual>
<owl:NamedIndividual rdf:about="&local;Samii">
<rdf:type rdf:resource="&local;Humanoid"/>
</owl:NamedIndividual>
<!-- Rules -->
<swrl:Variable rdf:about="&local;x" />
<swrl:Variable rdf:about="&local;alert" />
<swrl:Imp rdf:about="&local;ruleAlertTensionBasse">
<swrl:head rdf:parseType="Collection">
<swrl:DatavaluedPropertyAtom>
<swrl:propertyPredicate rdf:resource="&local;hasAlert"/>
<swrl:argument1 rdf:resource="&local;Samii" />
<swrl:argument2 rdf:datatype="&xsd;string">T'as tension est drôlement basse</swrl:argument2>
</swrl:DatavaluedPropertyAtom>
</swrl:head>
<swrl:body rdf:parseType="Collection">
<swrl:DatavaluedPropertyAtom>
<swrl:propertyPredicate rdf:resource="&local;hasTension"/>
<swrl:argument1 rdf:resource="&local;Charles" />
<swrl:argument2 rdf:resource="&local;x" />
</swrl:DatavaluedPropertyAtom>
<swrl:BuiltinAtom>
<swrl:builtin rdf:resource="&swrlb;lessThan" />
<swrl:arguments>
<rdf:List>
<rdf:first rdf:resource="&local;x"/>
<rdf:rest>
<rdf:List>
<rdf:first rdf:datatype="&xsd;float">14.0</rdf:first>
<rdf:rest rdf:resource="&rdf;nil"/>
</rdf:List>
</rdf:rest>
</rdf:List>
</swrl:arguments>
</swrl:BuiltinAtom>
</swrl:body>
</swrl:Imp>
<swrl:Imp rdf:about="&local;ruleAlertTensionHaute">
<swrl:head rdf:parseType="Collection">
<swrl:DatavaluedPropertyAtom>
<swrl:propertyPredicate rdf:resource="&local;hasAlert"/>
<swrl:argument1 rdf:resource="&local;Samii" />
<swrl:argument2 rdf:datatype="&xsd;string">T'as tension est drôlement haute</swrl:argument2>
</swrl:DatavaluedPropertyAtom>
</swrl:head>
<swrl:body rdf:parseType="Collection">
<swrl:DatavaluedPropertyAtom>
<swrl:propertyPredicate rdf:resource="&local;hasTension"/>
<swrl:argument1 rdf:resource="&local;Charles" />
<swrl:argument2 rdf:resource="&local;x" />
</swrl:DatavaluedPropertyAtom>
<swrl:BuiltinAtom>
<swrl:builtin rdf:resource="&swrlb;greaterThan" />
<swrl:arguments>
<rdf:List>
<rdf:first rdf:resource="&local;x"/>
<rdf:rest>
<rdf:List>
<rdf:first rdf:datatype="&xsd;float">14.0</rdf:first>
<rdf:rest rdf:resource="&rdf;nil"/>
</rdf:List>
</rdf:rest>
</rdf:List>
</swrl:arguments>
</swrl:BuiltinAtom>
</swrl:body>
</swrl:Imp>
</rdf:RDF>
The output of my test case:
== Before adding axiom ==
Prefix(:=<file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML#>)
Prefix(owl:=<http://www.w3.org/2002/07/owl#>)
Prefix(rdf:=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>)
Prefix(var:=<urn:swrl#>)
Prefix(xml:=<http://www.w3.org/XML/1998/namespace>)
Prefix(xsd:=<http://www.w3.org/2001/XMLSchema#>)
Prefix(rdfs:=<http://www.w3.org/2000/01/rdf-schema#>)
Prefix(swrl:=<http://www.w3.org/2003/11/swrl#>)
Prefix(local:=<file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML#>)
Prefix(owl11:=<http://www.w3.org/2006/12/owl11#>)
Prefix(swrlb:=<http://www.w3.org/2003/11/swrlb#>)
Prefix(owl11xml:=<http://www.w3.org/2006/12/owl11-xml#>)
Prefix(CR-owl-guide-20030818:=<http://www.w3.org/TR/2003/CR-owl-guide-20030818/>)
Ontology(<file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML>
Declaration(Class(local:Animal))
Declaration(Class(local:Human))
Declaration(Class(local:Humanoid))
Declaration(Class(local:Mammal))
Declaration(Class(local:Man))
Declaration(Class(local:Person))
Declaration(Class(local:Robot))
Declaration(Class(local:Woman))
Declaration(ObjectProperty(local:hasRobot))
Declaration(DataProperty(local:hasAlert))
Declaration(DataProperty(local:hasTemperature))
Declaration(DataProperty(local:hasTension))
Declaration(NamedIndividual(local:Charles))
Declaration(NamedIndividual(local:Samii))
Declaration(NamedIndividual(local:Walid))
############################
# Object Properties
############################
# Object Property: local:hasRobot (local:hasRobot)
ObjectPropertyDomain(local:hasRobot local:Human)
ObjectPropertyRange(local:hasRobot local:Robot)
############################
# Data Properties
############################
# Data Property: local:hasTemperature (local:hasTemperature)
FunctionalDataProperty(local:hasTemperature)
# Data Property: local:hasTension (local:hasTension)
FunctionalDataProperty(local:hasTension)
############################
# Classes
############################
# Class: local:Animal (local:Animal)
DisjointClasses(local:Animal local:Robot)
# Class: local:Human (local:Human)
EquivalentClasses(local:Human local:Person)
SubClassOf(local:Human local:Mammal)
# Class: local:Humanoid (local:Humanoid)
SubClassOf(local:Humanoid local:Robot)
# Class: local:Man (local:Man)
SubClassOf(local:Man local:Human)
DisjointClasses(local:Man local:Woman)
# Class: local:Woman (local:Woman)
SubClassOf(local:Woman local:Human)
############################
# Named Individuals
############################
# Individual: local:Charles (local:Charles)
ClassAssertion(local:Man local:Charles)
NegativeObjectPropertyAssertion(local:hasRobot local:Charles local:Samii)
# Individual: local:Samii (local:Samii)
ClassAssertion(local:Humanoid local:Samii)
# Individual: local:Walid (local:Walid)
ClassAssertion(local:Man local:Walid)
ObjectPropertyAssertion(local:hasRobot local:Walid local:Samii)
DataPropertyAssertion(local:hasTemperature local:Walid "37.5"^^xsd:float)
DLSafeRule(Body(DataPropertyAtom(local:hasTension local:Charles Variable(local:x)) BuiltInAtom(swrlb:greaterThan Variable(local:x) "14.0"^^xsd:float))Head(DataPropertyAtom(local:hasAlert local:Samii "T'as tension est drôlement haute"^^xsd:string)))
DLSafeRule(Body(DataPropertyAtom(local:hasTension local:Charles Variable(local:x)) BuiltInAtom(swrlb:lessThan Variable(local:x) "14.0"^^xsd:float))Head(DataPropertyAtom(local:hasAlert local:Samii "T'as tension est drôlement basse"^^xsd:string)))
)[main].main =>
== Query ==
[OWLManagement].printOntology() -> Number of literals: 0
[OWLManagement].printOntology() -> Number of objects: 0
[main].main() -> Number of literals: 0
[main].main =>
== After adding axiom ==
Prefix(:=<file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML#>)
Prefix(owl:=<http://www.w3.org/2002/07/owl#>)
Prefix(rdf:=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>)
Prefix(var:=<urn:swrl#>)
Prefix(xml:=<http://www.w3.org/XML/1998/namespace>)
Prefix(xsd:=<http://www.w3.org/2001/XMLSchema#>)
Prefix(rdfs:=<http://www.w3.org/2000/01/rdf-schema#>)
Prefix(swrl:=<http://www.w3.org/2003/11/swrl#>)
Prefix(local:=<file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML#>)
Prefix(owl11:=<http://www.w3.org/2006/12/owl11#>)
Prefix(swrlb:=<http://www.w3.org/2003/11/swrlb#>)
Prefix(owl11xml:=<http://www.w3.org/2006/12/owl11-xml#>)
Prefix(CR-owl-guide-20030818:=<http://www.w3.org/TR/2003/CR-owl-guide-20030818/>)
Ontology(<file:///C:/Users/cclercq/.eclipse/ws_Samii/Samii/WebContent/Ontologies/justAtest_RDFXML>
Declaration(Class(local:Animal))
Declaration(Class(local:Human))
Declaration(Class(local:Humanoid))
Declaration(Class(local:Mammal))
Declaration(Class(local:Man))
Declaration(Class(local:Person))
Declaration(Class(local:Robot))
Declaration(Class(local:Woman))
Declaration(ObjectProperty(local:hasRobot))
Declaration(DataProperty(local:hasAlert))
Declaration(DataProperty(local:hasTemperature))
Declaration(DataProperty(local:hasTension))
Declaration(NamedIndividual(local:Charles))
Declaration(NamedIndividual(local:Samii))
Declaration(NamedIndividual(local:Walid))
############################
# Object Properties
############################
# Object Property: local:hasRobot (local:hasRobot)
ObjectPropertyDomain(local:hasRobot local:Human)
ObjectPropertyRange(local:hasRobot local:Robot)
############################
# Data Properties
############################
# Data Property: local:hasTemperature (local:hasTemperature)
FunctionalDataProperty(local:hasTemperature)
# Data Property: local:hasTension (local:hasTension)
FunctionalDataProperty(local:hasTension)
############################
# Classes
############################
# Class: local:Animal (local:Animal)
DisjointClasses(local:Animal local:Robot)
# Class: local:Human (local:Human)
EquivalentClasses(local:Human local:Person)
SubClassOf(local:Human local:Mammal)
# Class: local:Humanoid (local:Humanoid)
SubClassOf(local:Humanoid local:Robot)
# Class: local:Man (local:Man)
SubClassOf(local:Man local:Human)
DisjointClasses(local:Man local:Woman)
# Class: local:Woman (local:Woman)
SubClassOf(local:Woman local:Human)
############################
# Named Individuals
############################
# Individual: local:Charles (local:Charles)
ClassAssertion(local:Man local:Charles)
NegativeObjectPropertyAssertion(local:hasRobot local:Charles local:Samii)
DataPropertyAssertion(local:hasTension local:Charles "10.0"^^xsd:float)
# Individual: local:Samii (local:Samii)
ClassAssertion(local:Humanoid local:Samii)
# Individual: local:Walid (local:Walid)
ClassAssertion(local:Man local:Walid)
ObjectPropertyAssertion(local:hasRobot local:Walid local:Samii)
DataPropertyAssertion(local:hasTemperature local:Walid "37.5"^^xsd:float)
DLSafeRule(Body(DataPropertyAtom(local:hasTension local:Charles Variable(local:x)) BuiltInAtom(swrlb:greaterThan Variable(local:x) "14.0"^^xsd:float))Head(DataPropertyAtom(local:hasAlert local:Samii "T'as tension est drôlement haute"^^xsd:string)))
DLSafeRule(Body(DataPropertyAtom(local:hasTension local:Charles Variable(local:x)) BuiltInAtom(swrlb:lessThan Variable(local:x) "14.0"^^xsd:float))Head(DataPropertyAtom(local:hasAlert local:Samii "T'as tension est drôlement basse"^^xsd:string)))
)[main].main =>
== Query ==
[OWLManagement].printOntology() -> Number of literals: 2
[OWLManagement].printOntology() -> Number of objects: 2
[main].main() -> Number of literals: 2
->Samii hasAlert T'as tension est drôlement haute
->Samii hasAlert T'as tension est drôlement basse

It seems that the problem comes from the version of Pellet or OWL-API used. I was originally using openllet 2.5.1.
Using the last "official" version of Pellet (2.3.6-ansell) with its version of OWL-API (3.4.9.2-ansell), the result is what I was expecting:
with "tension" < 14:
== Query ==
[OWLManagement].printOntology() -> Number of literals: 1
[OWLManagement].printOntology() -> Number of objects: 1
[main].main() -> Number of literals: 1
->Samii hasAlert T'as tension est drôlement basse
with "tension" >14
== Query ==
[OWLManagement].printOntology() -> Number of literals: 1
[OWLManagement].printOntology() -> Number of objects: 1
[main].main() -> Number of literals: 1
->Samii hasAlert T'as tension est drôlement haute
By the way, I tried with the version of ignazio1977 to used OWL-API version 4.0.2, but I got the same problem than with openllet 2.5.1.

Related

How to use tensorflow ai trained text model in react

i have created a simple chatbot model in python from a video tutorial.
Now i have read that i can use this model in react with tendorflow.js lib but i cant get it to run. I searched around a while but i cant find a real working example.
1.st the code for creating the model (train)
training.py
import random
import json
import numpy as np
import nltk
nltk.download("punkt")
nltk.download("wordnet")
nltk.download('omw-1.4')
from nltk.stem import WordNetLemmatizer
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.optimizers import SGD
import tensorflowjs as tfjs
lemmatizer = WordNetLemmatizer()
intents = json.loads(open("./model/Chatbot/intents.json").read())
words = []
classes = []
documents = []
ignore_letters = ["?", "!", ".", ","]
for intent in intents["intents"]:
for pattern in intent["patterns"]:
word_list = nltk.word_tokenize(pattern)
words.extend(word_list)
documents.append((word_list, intent["tag"]))
if intent["tag"] not in classes:
classes.append(intent["tag"])
words = [lemmatizer.lemmatize(word) for word in words if word not in ignore_letters]
words = sorted(set(words))
classes = sorted(set(classes))
pickle.dump(words, open("./model/Chatbot/words.pkl", "wb"))
pickle.dump(classes, open("./model/Chatbot/classes.pkl", "wb"))
training = []
output_empty = [0] * len(classes)
for document in documents:
bag = []
word_patterns = document[0]
word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns]
for word in words:
bag.append(1) if word in word_patterns else bag.append(0)
output_row = list(output_empty)
output_row[classes.index(document[1])] = 1
training.append([bag, output_row])
random.shuffle(training)
training = np.array(training)
train_x = list(training[:, 0])
train_y = list(training[:, 1])
model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(64, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation="softmax"))
sgd = SGD(learning_rate=0.01, momentum=0.9, nesterov=True)
model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])
hist = model.fit(np.array(train_x), np.array(train_y), epochs=1000, batch_size=5, verbose=1)
model.save("./model/Chatbot/chatbotmodel.h5", hist)
tfjs.converters.save_keras_model(model, "./model/Chatbot/")
print("Done")
in the pre-last line the model was exported to model.json and 1 group1-shard1of1.bin file
intents.json (example)
{
"intents": [
{
"tag": "greeting",
"patterns": [
"Hey",
"Hola",
"Hello",
"Hi",
"Ist da jemand?",
"Hallo",
"Guten Tag",
"Hey",
"Moin"
],
"responses": [
"Hallo, schön das du hier bist",
"Schoen dich wiederzusehen",
"Hallo, wie kann ich helfen?"
],
"context_set": "greeting"
}
]
}
in python i can start now chatbot.py which works
import random
import json
import pickle
import numpy as np
import nltk
from nltk.stem import WordNetLemmatizer
from tensorflow import keras
from keras.models import load_model
lemmatizer = WordNetLemmatizer()
intents = json.loads(open("./model/Chatbot/intents.json").read())
words = pickle.load(open("./model/Chatbot/words.pkl", "rb"))
classes = pickle.load(open("./model/Chatbot/classes.pkl", "rb"), fix_imports=True, encoding="ASCII")
model = load_model("./model/Chatbot/chatbotmodel.h5")
context = ""
def clean_up_sentence(sentence):
sentence_words = nltk.word_tokenize(sentence)
sentence_words = [lemmatizer.lemmatize(word) for word in sentence_words]
return sentence_words
def bag_of_words(sentence):
sentence_words = clean_up_sentence(sentence)
bag = [0] * len(words)
for w in sentence_words:
for i, word in enumerate(words):
if word == w:
bag[i] = 1
return np.array(bag)
def predict_class(sentence):
bow = bag_of_words(sentence) # [0 0 0 0 0 0 0 0 0]?
print(np.array([bow]))
res = model.predict(np.array([bow]))[0] # [8.58373418e-02 3.18233818e-02 9.12701711e-02 3.93254980e-02...
print(res)
ERROR_TRESHOLD = 0.25
results = [[i, r] for i, r in enumerate(res) if r > ERROR_TRESHOLD] # Hallo => [[21, 0.35744026]]
results.sort(key=lambda x: x[1], reverse=True) # moin => [[21, 0.35744026]]
return_list = []
for r in results:
return_list.append({"intent": classes[r[0]], "probability": str(r[1])})
return return_list # hallo [{'intent': 'greeting', 'probability': '0.35744026'}]
def get_response(intents_list, intents_json):
tag = intents_list[0]["intent"] # hallo [{'intent': 'greeting', 'probability': '0.35744026'}] ===> 'greeting'
list_of_intents = intents_json["intents"] # ==> alle intents aus datei
print(intents_list)
for i in list_of_intents:
if "context_set" in i:
context = i["context_set"]
print(context)
if i["tag"] == tag:
result = random.choice(i["responses"])
break
return result
print("Go! Bot is running")
while True:
message = input("")
ints = predict_class(message) # # hallo [{'intent': 'greeting', 'probability': '0.35744026'}]
res = get_response(ints, intents)
print(res)
2. Try to get it run in react.
import { useEffect, useState } from 'react';
import * as tf from '#tensorflow/tfjs';
const url = {
model: 'https://example.com/model.json',
};
function App() {
async function loadModel(url) {
try {
let message = "Hallo";
//const inputTensor = tf.tensor([parseInt(message)]);
const model = await tf.loadLayersModel(url.model);
setModel(model);
let result = model.predict(message); // make prediction like in Python
//let bow = bag_of_words(message) // [0 0 0 0 0 0 0 0 0]?
}
catch (err) {
console.log(err);
}
}
useEffect(() => {
tf.ready().then(() => {
loadModel(url)
});
}, [])
}
At this point, the model.json and group1-shard1of1.bin are both imported correct, but when i try to model.predict('hallo') i get the following error:
Error when checking model : the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see 1 Tensor(s), but instead got 5 Tensors(s).
Maybe u have an idea to solve it? Thanks.

nominal value not declared in header

I'm generating a arff file with groovy from a xslx,
but when i try to open this file in weka i got this error:
File "..." not recognised as an 'Arff data files' file.
Reason:
nominal value not declared in header, read Token[Ativo], line 16
i can't understand why i'm getting this error
can someone helpme to fix this error, and explain why it's happening?
Generated file
#relation kd-itempedido
#attribute tipopedido {Assistencia,Recompra,Venda,Troca}
#attribute aprovado {0.0,1.0}
#attribute fasepedido {Aprovado,Cancelado,EmAprovacao,Liberado,Novo}
#attribute statusinternopedido {NegociarPagamento,PedidosDeTeste,AguardandoOcorrencia,Nada,AguardandoBoletoDeposito,PedidoDuplicado,SuspeitaDeFraude}
#attribute canal {Marketplace,Desktop}
#attribute origem {LojasAmericanas,Optimise,MercadoLivre,Cityads,Zanox,Zoom,Rakuten,Lomadee,Facebook,Viptarget,Submarino,Criteo,Muccashop,Chaordic,Walmart,Googlead,Nada,Extra,Lojaskd,Shopback,Afilio,Shoptime,Nextperformance,CarrinhoAbandonado,Bing}
#attribute mercado {S,N}
#attribute cluster {EntregaImediata,Fiprec,Icconv,Esgotado}
#attribute statusitem {Ativo}
#attribute statusproduto {Inativo,Ativo,AtivoSemEstoque,ForaDeLinha}
#attribute polo {Polo1,Polo3,Polo2}
#data
Venda,0.0,Novo,Nada,Desktop,Googlead,S,Fiprec,Ativo,Ativo,Polo2
Venda,0.0,Novo,Nada,Desktop,Googlead,S,Fiprec,Ativo,Ativo,Polo2
Venda,0.0,Novo,Nada,Desktop,Googlead,S,Ativo,Inativo,Polo2
Venda,0.0,Novo,Nada,Desktop,Muccashop,N,Ativo,Ativo,Polo3
Groovy (VM -Dfile.encoding=ascii utf-8 utf8)
#Grapes([
#Grab('org.apache.poi:poi:3.10.1'),
#Grab('org.apache.poi:poi-ooxml:3.10.1')])
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.text.Normalizer
import static org.apache.poi.ss.usermodel.Cell.*
import java.nio.file.Paths
def path = "/home/eric/Documents/development/ufpr/Solid Eric/ItemPedido1000.xlsx"
def relation = "kd-itempedido"
def columns = ["tipopedido", "aprovado", "fasepedido", "statusinternopedido", "canal", "origem", "mercado", "cluster", "statusitem","statusproduto", "polo"]
def arff = "ItemPedido.arff"
new XslxToArffParser(path, relation, columns, arff);
class Data{
def rows = new ArrayList<List>();
#Override
String toString() {
def s = ""
for (r in rows){
for(d in r){
s+=d
if(r.indexOf(d) < (r.size()-1))
s+=","
}
s+="\n"
}
return s
}
}
class Atributo {
def descricao;
def possibilidades = new HashSet<Object>();
def index;
#Override
String toString() {
def builder = new StringBuilder()
builder.append("#attribute ").append(descricao)
builder.append(" {")
for(def i = 0; i<possibilidades.size(); i++){
builder.append(possibilidades[i])
if((i+1) != possibilidades.size())
builder.append(",")
}
builder.append("}").append("\n")
return builder.toString();
}
}
class XslxToArffParser {
def attributes =[:];
def data = new Data();
def sheet = null;
XslxToArffParser(path, relation, columns, arffPath){
load(path)
getAttributes(columns)
collectData()
saveArff(relation, arffPath)
}
def String parse(String s){
s = Normalizer.normalize(s, Normalizer.Form.NFD)
s = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "")
s = s.split(/[^\w]/).collect { it.toLowerCase().capitalize() }.join("")
s = s.replaceAll(" ", "")
s = s.replaceAll("[^A-Za-z0-9]", "")
s = s.isEmpty() ? "Nada" : s
return s
}
def load(path) {
Paths.get(path).withInputStream { input ->
def workbook = new XSSFWorkbook(input)
sheet = workbook.getSheetAt(0)
}
}
def getAttributes(columns){
for (cell in sheet.getRow(0).cellIterator()) {
def index = cell.columnIndex
def description = parse(cell.stringCellValue).toLowerCase()
if(columns.contains(description)){
attributes << [(index):new Atributo(descricao: description, index: index)]
}
}
}
def collectData(){
def headerFlag = true
for (row in sheet.rowIterator()) {
if (headerFlag) {
headerFlag = false
continue
}
def r = []
for (cell in row.cellIterator()) {
def index = cell.columnIndex;
def value = cell.cellType == CELL_TYPE_STRING ? parse(cell.stringCellValue) : cell.numericCellValue
def attr = attributes[index]
if(attr != null){
attr.possibilidades.add(value)
r << value
}
}
data.rows.add(r)
}
}
def saveArff(relation, path){
Paths.get(path).withWriter { writer ->
writer.write "#relation " + relation
writer.write "\n"
for(a in attributes.values())
writer.write a.toString()
writer.write "#data"
writer.write "\n"
writer.write data.toString()
}
}
}
Solved. "row.cellIterator()" does not iterate over null/blank cells
It has been a while since I used Weka, but looking at the file you showed and the error message, I suspect the problem is in the last two rows of the data file. They don't have a value for the attribute "cluster".
After the S or N (for attribute "mercado"), they have "Ativo". That "Ativo" value is not defined as one of the possible values of the nominal attribute cluster. The file did read "Ativo" though (which is why the error message says ''read Token[Ativo]'', but it expected to read a value for the cluster attribute, it did not yet expect a value for the statusitem attribute.

Using "shared logic" across multiple Typewriter templates?

We have multiple Typewriter .tst templates in our project, and would like to share some common logic/methods between them. Is there a way to do this?
You can use T4 templates to generate the Typewriter templates. Put the code inside a reusable T4 template (*.ttinclude) and create tt-files to pass parameters to the rendering method of this base template.
(I use a Visual Studio extension for File nesting.)
Each tt-file looks something like this;
<## template debug="true" hostSpecific="true" #>
<## output extension=".tst" #>
<## include file="..\ModelsTemplate.ttinclude" #>
<# this.ModelsTemplate_Render("UserSettings"); #>
...and my ttinclude file looks like this (it is a bit project specific, but I included it all so that anyone who wants to try it out can easily get something working);
<## IntelliSenseLanguage processor="tangibleT4Editor" language="C#" #>
<#+
void ModelsTemplate_Render(string #subnamespace) {
ModelsTemplate_Render("MyApp.ViewData", #subnamespace);
}
void ModelsTemplate_Render(string #mainnamespace, string #subnamespace) {
string renderedMainNamespace = #mainnamespace;
#>
// <auto-generated>
// This code was generated by a tool.
// Template: <#= Host.TemplateFile #>
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
${
// Enable extension methods by adding using Typewriter.Extensions.*
using Typewriter.Extensions.Types;
using System.Text.RegularExpressions;
Template(Settings settings)
{
settings.IncludeProject("MyApp.ViewData");
}
static string DebugInfo = "";
string PrintDebugInfo(File f){
if (string.IsNullOrEmpty(DebugInfo)) {
return "";
}
return "/*" + Environment.NewLine + "Template debug info: " + DebugInfo + Environment.NewLine + "*/";
}
string BaseClassFullPath(Class baseClass)
{
//DebugInfo = DebugInfo + Environment.NewLine + "baseClass.FullName:" + baseClass.FullName;
var result = baseClass.Name;
// Until we find a better way to handle implementations of generic base classes...
result = result.Replace("<bool?>", "<boolean>");
result = result.Replace("<int?>", "<number>");
result = result.Replace("<long?>", "<number>");
result = result.Replace("<decimal?>", "<number>");
result = result.Replace("<double?>", "<number>");
result = result.Replace("<System.Double>", "<number>");
result = result.Replace("<System.Double?>", "<number>");
result = result.Replace("<System.DateTime?>", "<Date>");
return result;
}
string NullableFilter(string typeName)
{
return typeName.Replace("?", "");
}
string TypeFilteredPath(Type type)
{
//DebugInfo = DebugInfo + Environment.NewLine + "type:" + type.FullName + " - genericType:" + type.Unwrap().FullName;
return NullableFilter(type.Name);
}
string TypeFiltered(Type type)
{
if (type.IsEnumerable)
{
var genericType = type.Unwrap();
if (!genericType.FullName.StartsWith("System"))
{
return TypeFilteredPath(genericType)+"[]";
}
}
return TypeFilteredPath(type);
}
string PropertyTypeFiltered(Property prop)
{
return TypeFiltered(prop.Type);
}
string ImplementedInterfaces(Class c){
if (!c.Interfaces.Any()){
return string.Empty;
}
return "implements " + string.Join(", ", c.Interfaces.Select(x => x.FullName));
}
string ExtendedInterfaces(Interface i){
if (!i.Interfaces.Any()){
return string.Empty;
}
return "extends " + string.Join(", ", i.Interfaces.Select(x => x.FullName));
}
string DescriptionAttributeValue(Attribute a){
if (!a.FullName.Contains("DescriptionAttribute")){
return string.Empty;
}
return a.Value;
}
string GetPropertyDefinitionWithScope(Property p){
var definition = GetPropertyDefinition(p);
if (definition != "")
return "public " + definition;
else
return definition;
}
string GetPropertyDefinition(Property p){
var ignoreAttribute = p.Attributes.SingleOrDefault(x => x.FullName.Contains("TypeScriptIgnoreMemberAttribute"));
if (ignoreAttribute != null)
return "";
var typeAttribute = p.Attributes.SingleOrDefault(x => x.FullName.Contains("TypeScriptTypeAttribute"));
if (typeAttribute != null) {
return p.name + ": " + typeAttribute.Value + ";";
}
return p.name + ": " + TypeFiltered(p.Type) + ";";
}
string WriteImports(Class theClass){
//return "import { ViewDataEntity } from '../common/ViewDataEntity';";
var list = new List<string>();
var typesToImport = theClass.Properties.Select(x => x.Type.Unwrap()).Where(x => x.Namespace.Contains("MyApp.ViewData.")).ToList();
if (theClass.BaseClass?.Namespace.Contains("MyApp.ViewData.") == true)
typesToImport.Add(theClass.BaseClass);
foreach (var impType in typesToImport)
{
var modules = impType.Namespace.Replace("MyApp.ViewData.", "").Split('.').ToList();
string modPart = string.Join("/", modules.Select(x => CamelCase(x)));
list.Add($"import {{ {impType.Name} }} from '../{modPart}/{impType.Name}';");
}
return string.Join(Environment.NewLine, list.Distinct());
}
string CamelCase(string value){
return value.First().ToString().ToLower() + value.Substring(1);
}
}//namespace <#= renderedMainNamespace #>.<#= #subnamespace #> {
$Classes(c => c.Namespace.StartsWith("<#= #mainnamespace #>.<#= #subnamespace #>"))[
$WriteImports
export class $Name$TypeParameters $BaseClass[extends $BaseClassFullPath ] $ImplementedInterfaces {$Properties[
$GetPropertyDefinitionWithScope]
}]
$Interfaces(<#= #mainnamespace #>.<#= #subnamespace #>.*)[
export interface $Name $ExtendedInterfaces {
$Properties[
$GetPropertyDefinition]
}]
$Enums(<#= #mainnamespace #>.<#= #subnamespace #>.*)[
export class $Name {
$Values[// $Value - "$Attributes[$Value]"
static $Name = "$Name";
]
}]
$PrintDebugInfo
//}<#+
}
#>
Unfortunately there's no way to share code in tst templates. Support for this will probably come in a future version though.

Combined display of EditText for Query with JSON Result to be able to scroll it

Need advice on how to define screen to be able to scroll the result of the json , as attached :
package com.lm.vciwhereabout;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class querynameentry3 extends ListActivity {
EditText username; // To take username as input from user
Button submit;
TextView tv; // TextView to show the result of MySQL query
String returnString; // to store the result of MySQL query after decoding JSON
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState)
{
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network
access on the application's main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsonuse);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1));
username = (EditText) findViewById(R.id.edtxUsername);
submit = (Button) findViewById(R.id.btnsubmit);
tv = (TextView) findViewById(R.id.showresult);
// define the action when user clicks on submit button
submit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// declare parameters that are passed to PHP script i.e. the name "username" and its value submitted by user
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
postParameters.add(new BasicNameValuePair("username",
username.getText().toString()));
String response = null;
// call executeHttpPost method passing necessary parameters
try
{
response = CustomHttpClient.executeHttpPost(
"http://192.168.0.245/vciwhereabout/waboutbyuser.php", // your ip address if using localhost server
postParameters);
// store the result returned by PHP script that runs MySQL query
String result = response.toString();
//parse json data
try{
returnString = "";
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","post_id: "+json_data.getInt("post_id")+
", username: "+json_data.getString("username")+
", fdate: "+json_data.getString("fdate")+
", tdate: "+json_data.getString("tdate")+
", ftime: "+json_data.getString("ftime")+
", ttime: "+json_data.getString("ttime")+
", custbranch: "+json_data.getString("custbranch")+
", custname: "+json_data.getString("custname")+
", custaddr: "+json_data.getString("custaddr")+
", custcity: "+json_data.getString("custcity")+
", note: "+json_data.getString("note")
);
//Get an output to the screen
returnString += "Username :" + json_data.getString("username")
+ "\n" + "From Date :" + json_data.getString("fdate")
+ "\n" + "To Date :" + json_data.getString("tdate")
+ "\n" + "From Time :" + json_data.getString("ftime")
+ "\n" + "To Time :" + json_data.getString("ttime")
+ "\n" + "Cust/Branch :" + json_data.getString("custbranch")
+ "\n" + "Name :" + json_data.getString("custname")
+ "\n" + "Address :" + json_data.getString("custaddr")
+ "\n" + "City :" + json_data.getString("custcity")
+ "\n" + "Note :" + json_data.getString("note") + "\n"
+ "-------------------------------------------" ;
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
try{
tv.setText(returnString);
}
catch(Exception e){
Log.e("log_tag","Error in Display!" + e.toString());;
}
}
catch (Exception e) {
Log.e("log_tag","Error in http connection!!" + e.toString());
}
}
});
}
private void setListAdapter(ArrayAdapter<String> arrayAdapter) {
// TODO Auto-generated method stub
}
}
And this is the layout activity_jsonuse.xml :
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Staff Name to be Query" />
<EditText
android:id="#+id/edtxusername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" >
</EditText>
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_gravity="center"
/>
<TextView
android:id="#+id/showresult"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Result" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/> </LinearLayout>
On make the output to the screen, how do I defined it / changed it, so I can scroll the results ?
Since I have already define the layout for the query with edittext, could I make or call the new layout to just display the result with the scroll capability ( in one .java activities) ? Please help guide me on my code above.
Thanks a lot (I'm new on Android and Programming).
With addition of the scrollview as attached , solved. But the virtual keyboard still appear after displaying the result. How to removed the virtual keyboard automatically, after result appeared on screen ? Thanks.
<ScrollView
> android:layout_width="fill_parent"
> android:lines="20"
> android:layout_height="390dip" >
> <TextView
> android:id="#+id/showresult2"
> android:layout_width="fill_parent"
> android:layout_height="wrap_content"
> android:singleLine="false"
> android:textAppearance="?android:attr/textAppearanceLarge"
>
> android:paddingBottom="2dip"
> android:paddingLeft="45dip"
> android:textColor="#5d5d5d"
>
> />
>
> </ScrollView>
With the addition of the scrollview as attched, solved my problem.
<ScrollView
> android:layout_width="fill_parent"
> android:lines="20"
> android:layout_height="390dip" >
> <TextView
> android:id="#+id/showresult2"
> android:layout_width="fill_parent"
> android:layout_height="wrap_content"
> android:singleLine="false"
> android:textAppearance="?android:attr/textAppearanceLarge"
>
> android:paddingBottom="2dip"
> android:paddingLeft="45dip"
> android:textColor="#5d5d5d"
>
> />
>
> </ScrollVi
ew>

OWL api find properties of class

I've an ontology file and I can obtain all classes in its (I'm using OWL-API). Well, I should retrieve, for each classes, data properties and object properties present into my file .owl, there is any way to get them with OWL-API?
public void test(){
File file = new File("Ontology.owl");
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology;
try {
ontology = manager.loadOntologyFromOntologyDocument(file);
Set<OWLClass> classes;
Set<OWLObjectProperty> prop;
Set<OWLDataProperty> dataProp;
Set<OWLNamedIndividual> individuals;
classes = ontology.getClassesInSignature();
prop = ontology.getObjectPropertiesInSignature();
dataProp = ontology.getDataPropertiesInSignature();
individuals = ontology.getIndividualsInSignature();
//configurator = new OWLAPIOntologyConfigurator(this);
System.out.println("Classes");
System.out.println("--------------------------------");
for (OWLClass cls : classes) {
System.out.println("+: " + cls.getIRI().getShortForm());
System.out.println(" \tObject Property Domain");
for (OWLObjectPropertyDomainAxiom op : ontology.getAxioms(AxiomType.OBJECT_PROPERTY_DOMAIN)) {
if (op.getDomain().equals(cls)) {
for(OWLObjectProperty oop : op.getObjectPropertiesInSignature()){
System.out.println("\t\t +: " + oop.getIRI().getShortForm());
}
//System.out.println("\t\t +: " + op.getProperty().getNamedProperty().getIRI().getShortForm());
}
}
System.out.println(" \tData Property Domain");
for (OWLDataPropertyDomainAxiom dp : ontology.getAxioms(AxiomType.DATA_PROPERTY_DOMAIN)) {
if (dp.getDomain().equals(cls)) {
for(OWLDataProperty odp : dp.getDataPropertiesInSignature()){
System.out.println("\t\t +: " + odp.getIRI().getShortForm());
}
//System.out.println("\t\t +:" + dp.getProperty());
}
}
}
} catch (OWLOntologyCreationException ex) {
Logger.getLogger(OntologyAPI.class.getName()).log(Level.SEVERE, null, ex);
}
}
This should be an answer, I think, rather than a comment.
To get the properties of a class, you just use getSuperClasses. So, if you have a class like so
A
:subClassOf (r some B)
then (getSuperClasses A) will return a set with a single OWLClassExpression which will be an instance of OWLObjectSomeValuesFrom. In turn, you can get the property with getProperty.

Resources