add DataProperty in protege with Jena - jena

Anyone knows hoe to add Data Property in protege with Jena. I can easily add Object Property but for Data Property somehow doesn't work, instead of adding Properties in Data Property assertion it's adding the Annotation. Maybe something wrong with my code?
Code
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_MICRO_RULE_INF, null);
String NS = "http://www.semanticweb.org/thato/ontologies/2012/10/9/thesis_ontology#";
model.read(in, null);
in.close();
OntClass ApplicationModel = model.getOntClass(NS + "ApplicationModel");
Individual AM20 = model.createIndividual(NS + xmlDoc.getDocumentElement().getAttribute("guid")+ theAttribute.getNodeValue(), ApplicationModel);
Individual dom = model.getIndividual(NS + domainElement.getAttribute(attrDomain));
Individual pha = model.getIndividual(NS + neededString.trim());
Individual lev = model.getIndividual(NS + lodElement.getAttribute(attrLOD));
Individual typ = model.getIndividual(NS + theAttrType.getNodeValue());
Property urlAdd = model.createProperty(NS + "http://xxxxx.com");
// Create Object Property
ObjectProperty domain = model.createObjectProperty(NS +"hasDomain");
ObjectProperty fase = model.createObjectProperty(NS +"hasPhase");
ObjectProperty lod = model.createObjectProperty(NS +"hasLevelOfDetail");
ObjectProperty type = model.createObjectProperty(NS +"hasType");
model.add(AM20, domain, dom);
model.add(AM20, fase, pha);
model.add(AM20, lod, lev);
model.add(AM20, type, typ);
// Create Data Property
DatatypeProperty url = model.createDatatypeProperty(NS + "hasURL");
model.add(AM20, url, urlAdd );
PrintStream p= new PrintStream("./src/thesis_ontology.owl");
model.write(p, "RDF/XML-ABBREV", null);
p.close();

I guess I found the problem. Hope it can help someone someday :D
the code should be like this
OntClass ApplicationModel = model.getOntClass(NS + "ApplicationModel");
Individual AM20 = model.createIndividual(NS + xmlDoc.getDocumentElement().getAttribute("guid")+ theAttribute.getNodeValue(), ApplicationModel);
Individual dom = model.getIndividual(NS + domainElement.getAttribute(attrDomain));
Individual pha = model.getIndividual(NS + neededString.trim());
Individual lev = model.getIndividual(NS + lodElement.getAttribute(attrLOD));
Individual typ = model.getIndividual(NS + theAttrType.getNodeValue());
// Create Object Property
ObjectProperty domain = model.createObjectProperty(NS +"hasDomain");
ObjectProperty fase = model.createObjectProperty(NS +"hasPhase");
ObjectProperty lod = model.createObjectProperty(NS +"hasLevelOfDetail");
ObjectProperty type = model.createObjectProperty(NS +"hasType");
model.add(AM20, domain, dom);
model.add(AM20, fase, pha);
model.add(AM20, lod, lev);
model.add(AM20, type, typ);
// Create Data Property
DatatypeProperty url = model.createDatatypeProperty(NS + "hasURL");
model.add(AM20, url, "http://...");

Related

I want to put RDF/XML format directly in SDB

In Jena, I saved RDF/XML documents in SDB using the "read()" method and even created a file with RDF/XML documents in SDB using the "write" method.
What I want to try is to save Triple directly in SDB.
Here is my code
prefix = "http://example.org/terms/";
ns = "ex";
model.setNsPrefix(ns, prefix);
prefix3 = "http://www.w3.org/1999/02/22-rdf-syntax-ns";
ns3 = "rdf";
model.setNsPrefix(ns3, prefix3);
prefix6 = "http://www.test/2022/#";
ns6 = "base";
model.setNsPrefix(ns6, prefix6);
for(i = 0; i<index; i++) {
Resource s_A = model.createResource(A[i].o);
Property p_A = model.createProperty(prefix3);
Resource s_B = model.createResource(B[i].s);
Property p_B = model.createProperty(B[i].p);
Resource s_C = model.createResource(C[i].s);
Property p_C = model.createProperty(C[i].p);
//model.add(s_A, p_A, prefix6); //wish <ex:Description rdf:about=baseURI+"ID">
model.add(s_A, p_B, B[i].o); //wish <ex:Description.type>1</ex:Description.type>
model.add(s_A, p_C, C[i].o); //wish <ex:Description.open>0</ex:Description.open>
//wish </ex:Description>
}
I know this(model.add(s_A, p_A, prefix6);) part is wrong, but I don't know which method I use to wish. I don't know what else to do here.

Iterating multiple reasoned literals from the same property

The title may be a bit confusing but basically this is the problem: I am using Jena and a Pellet reasoner to produce property literals from a resource called Patient_Doug. The triple looks like this:
Patient_Doug-> hasSuggestion-> Literal inferred suggestion.
The problem is that the Protege Pellet reasoner comes up with three suggestions for Doug, because Doug is in a pretty bad way in hospital. The Protege reasoner suggests that Doug needs a Hi-Lo bed, an RF ID band and a bed closer to the nurse's station. Unfortunatly, in Jena, I can only get Hi-lo bed to print. Only one of 3 literals.
Here is some of the code.
OntModel model = ModelFactory.createOntologyModel( PelletReasonerFactory.THE_SPEC );
String ns = "http://altervista.org/owl/unit.owl#";
String inputFile = "c:\\jena\\acuity.owl";
InputStream in = FileManager.get().open(inputFile);
if (in == null) {
throw new IllegalArgumentException("File: " + inputFile + " not found");
}
model.read(in,"");
model.prepare();
//inf and reasoner wont run unless i use hp libraries!
//asserted data properties
Individual ind = model.getIndividual(ns+"Patient_Doug");
OntProperty abcValue = model.getOntProperty("http://example.org/hasABCValue");
//inferred data properties
OntProperty suggestion = model.getOntProperty(ns+"hasSuggestion");
//print asserted data properties
System.out.println("Properties for patient "+ind.getLocalName().toString());
System.out.println( abcValue.getLocalName()+"= "+ind.getPropertyValue(abcValue).asLiteral().getInt());
//print inferenced data properties
StmtIterator it = ind.listProperties(suggestion);
//this iterator only prints one suggestion in an infinite loop
while (it.hasNext()) {
System.out.println("A posible suggestion= "+ind.getPropertyValue(suggestion).asLiteral().getString());
}
}
The code works fine but the iterator at the end only prints only one subggestion in an infinite loop.
I would be grateful for any suggestions.
Thanks.
This code works to iterate and print the many inferred hasSuggestions. The hasSuggestion SWRL rules are in the OWL ontology
OntModel model = ModelFactory.createOntologyModel( PelletReasonerFactory.THE_SPEC );
String ns = "http://altervista.org/owl/unit.owl#";
String inputFile = "c:\\jena\\acuity.owl";
InputStream in = FileManager.get().open(inputFile);
if (in == null) {
throw new IllegalArgumentException("File: " + inputFile + " not found");
}
model.read(in,"");
model.prepare();
//inf and reasoner wont run unless i use hp libraries!
//asserted data properties
Individual ind = model.getIndividual(ns+"Patient_Doug");
OntProperty abcValue = model.getOntProperty("http://example.org/hasABCValue");
//inferred data properties
OntProperty suggestion = model.getOntProperty(ns+"hasSuggestion");
//print asserted data properties
System.out.println("Properties for patient "+ind.getLocalName().toString());
System.out.println( abcValue.getLocalName()+"= "+ind.getPropertyValue(abcValue).asLiteral().getInt());
for (StmtIterator j = ind.listProperties(suggestion); j.hasNext(); ) {
Statement s = j.next();
//System.out.println( " " + s.getPredicate().getLocalName() + " -> " );
System.out.println( "A possible suggestion... " + s.getLiteral().getLexicalForm());
}

Classify a text with weka after classifier has been trained

I am a beginner with weka.
I have managed to import dataset from the disk (one folder by category, all text related to this category inside the folder), apply StringToWordVector with tokenizer, train a Naive Multniomial categorizer ... The code is below (it is c# but Java is ok of course)
However, I can hardly find information on how to use the categorizer on a project. Say I have a text with unknown category, input by a user, how can I just apply the categorizer to this text and infer the category it belongs to ? (code "// what to do here below").
Any help would be greatly appreciated ;-)
Thanks in advance
Julien
string filepath = #"C:\Users\Julien\Desktop\Meal\";
ClassificationDatasetHelper classHelper = new ClassificationDatasetHelper();
weka.core.converters.TextDirectoryLoader tdl = new
weka.core.converters.TextDirectoryLoader();
tdl.setDirectory(new java.io.File(filepath));
tdl.setCharSet("UTF-8");
weka.core.Instances insts = tdl.getDataSet();
weka.filters.unsupervised.attribute.StringToWordVector swv = new weka.filters.unsupervised.attribute.StringToWordVector();
swv.setInputFormat(insts);
swv.setDoNotOperateOnPerClassBasis(false);
swv.setOutputWordCounts(true);
swv.setWordsToKeep(1000);
swv.setIDFTransform(true);
swv.setMinTermFreq(1);
swv.setDoNotOperateOnPerClassBasis(false);
swv.setPeriodicPruning(-1);
weka.core.tokenizers.NGramTokenizer tokenizer = new weka.core.tokenizers.NGramTokenizer();
tokenizer.setNGramMinSize(2);
tokenizer.setNGramMaxSize(2);
swv.setTokenizer(tokenizer);
insts = weka.filters.Filter.useFilter(insts, swv);
insts.setClassIndex(0);
weka.classifiers.Classifier cl = new weka.classifiers.bayes.NaiveBayesMultinomial();
int trainSize = insts.numInstances() * percentSplit / 100;
int testSize = insts.numInstances() - trainSize;
weka.core.Instances train = new weka.core.Instances(insts, 0, trainSize);
cl.buildClassifier(train);
string s = "Try to classify this text";
weka.core.Instance instanceToClassify = new weka.core.Instance();
// what to do here
// ???
double predictedClass = cl.classifyInstance(instanceToClassify);
Thanks
The best place to learn how to use Weka in your Java app is in the official Weka wiki.
https://waikato.github.io/weka-wiki/use_weka_in_your_java_code/
Basically, you provide a new dataset (the classifier will ignore the category attribute) and you ask it to label each instance for you, like this
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import weka.core.Instances;
...
// load unlabeled data
Instances unlabeled = new Instances(
new BufferedReader(
new FileReader("/some/where/unlabeled.arff")));
// set class attribute
unlabeled.setClassIndex(unlabeled.numAttributes() - 1);
// create copy
Instances labeled = new Instances(unlabeled);
// label instances
for (int i = 0; i < unlabeled.numInstances(); i++) {
double clsLabel = tree.classifyInstance(unlabeled.instance(i));
labeled.instance(i).setClassValue(clsLabel);
}
// save labeled data
BufferedWriter writer = new BufferedWriter(
new FileWriter("/some/where/labeled.arff"));
writer.write(labeled.toString());
writer.newLine();
writer.flush();
writer.close();

What am I missing ! Timetree query not working

MATCH startPath = (event:RESERVATION)-[]->(sd:DAY)<-[:`5`]-(sm:MONTH)<-[:`1`]-(sy:YEAR)<-[:`2016`]-(room:ROOM)
WHERE event.reservationId = 44
RETURN startPath
and
MATCH endPath = (event:RESERVATION)-[]->(ed:DAY)<-[:`6`]-(em:MONTH)<-[:`1`]-(ey:YEAR)<-[:`2016`]-(room:ROOM)
WHERE event.reservationId = 44
RETURN endPath
both return valid paths, but when combined as
MATCH startPath = (event:RESERVATION)-[]->(sd:DAY)<-[:`5`]-(sm:MONTH)<-[:`1`]-(sy:YEAR)<-[:`2016`]-(room:ROOM),
endPath = (event:RESERVATION)-[]->(ed:DAY)<-[:`6`]-(em:MONTH)<-[:`1`]-(ey:YEAR)<-[:`2016`]-(room:ROOM)
WHERE event.reservationId = 44
RETURN startPath, endPath
returns no row !
What am I missing ?
The last query requires both startPath and endPath to end with the same exact ROOM node (since they both use the same room identifier). Your data probably has no such node.

How to use string in path to object?

I need to use string in path to object.
var nameOfTrails:String = "trail"+this.getDepth();
_parent.createEmptyMovieClip(nameOfTrails,this.getDepth()+1);
_parent.nameOfTrails.beginFill(FillColor,FillAlpha);
How to do this in ActionScript 2.0?
In you case you could access instance you created like this:
_parent[nameOfTrails]
The point is that you can access an object using string with his name by searching proper object for property with that name.
In your example you creating variable with id of nameOfTrails value inside some object which relate to your current code scope as parent, and put reference to newly created MovieClip inside this variable. So now, object referenced by _parent have property named for example 'trail0' (by the way this.getDepth() is not so smart thing to do then you creating objects in other scope). All you need to do now is access that property using classical 'give me property of that object by his key' style - obj['propertyName'] and voila.
You can do that like this :
for(var i:Number = 0; i < 3; i++){
var movie_clip:MovieClip = this.createEmptyMovieClip('movie_clip_' + i, i);
movie_clip._y = i * 22;
var text_field:TextField = movie_clip.createTextField('text_field', 0, 0, 0, 120, 18);
text_field.text = 'movie clip : ' + i;
}
var j:Number = 2;
trace(this['movie_clip_' + j].text_field.text); // gives : movie clip : 2
trace(eval('movie_clip_' + 1).text_field.text); // gives : movie clip : 1
For more details, take a look on the eval function.
Hope that can help.

Resources