Remove functional property in ontology using jena - jena

Currently I am using Jena to work around ontology file, but could not find a way to remove functional attribute from certain property.
Could anyone point out how to do this using Jena?
-- Edit --
What I wanted to do is to iterate all over the properties in the ontology and if it found functionalProperty, then convert it into non-functional property
My code is something like this:
Iterator<OntProperty> ont = model.listOntProperties();
while(ont.hasNext()) {
OntProperty p = ont.next();
if(p.isFunctionalProperty()) {
p.removeProperty(RDF.type, OWL.FunctionalProperty);
}
}
But currently it yield java.util.ConcurrentModificationException error.
Thanks!

The various ontology API classes in Jena, such as FunctionalProperty are there just to provide a convenient programming API. All of the state information is actually held in the underlying Model. Therefore, to make a property not be a functional property any more, you just need to remove the corresponding rdf:type triple from the model.
For example (untested code, but should work):
OntModel m = ModelFactory.createOntology( OntModelSpec.OWL_MEM );
NS = "http://www.example.com/ontology#";
FunctionalProperty p = m.createFunctionalProperty( NS + "p" );
// now change p to normal object property
// setRDFType removes all existing rdf:type triples and adds one new one
// alternatively, we could just call:
// p.removeProperty( RDF.type, OWL.FunctionalProperty );
p.setRDFType( OWL.ObjectProperty );
ObjectProperty p1 = p.as( ObjectProperty.class );
Update
Your code throws a ConcurrentModificationError because you are trying to make changes to a collection while iterating over that collection - hence modifying it concurrently with iterating. The solution is to do the work in two phases: first create a collection object, such as an ArrayList with the properties you want to change, and secondly make the changes to those properties.
List<FunctionalProperty> fps = new ArrayList<FunctionalProperty>();
Iterator<OntProperty> ont = model.listOntProperties();
while(ont.hasNext()) {
OntProperty p = ont.next();
if(p.isFunctionalProperty()) {
fps.add( p.asFunctionalProperty() );
}
}
for (FunctionalProperty fp: fps) {
fp.removeProperty(RDF.type, OWL.FunctionalProperty);
}

Related

How to find requirements by keywords using DOORS DXL

I have identified 3-5 keywords for every requirement in module-A. Each keyword is separated by a comma. Now I want to search every requirement in module-B to see which of them have words that match each of the key words.
Not sure exactly what you're looking for. You might have to specify if none of these solutions I'm about to propose are exactly what you're looking for.
If you're trying to create a filter which displays only objects with those keywords in your current view, you can create an advanced filter by first going to filter (Tools > Filter > Define) and then select the Advanced button on the bottom left of the filter menu that appears.
At this point you can create custom rules for the filter. I would just create an individual rule for each word with the following definition:
Attribute: Object Text
Condition: contains
Value: <insert word here>
Match Case: uncheck
Regular Expression: uncheck
Then select the Add button to add the rule to the list of available rules in the Advanced Options.
At this point you can select multiple rules in the list of available rules and you can AND/OR these rules together to create a custom filter for the view that you want.
So that's for if you're trying to create a custom view with just objects containing specific words.
If you're talking about writing DXL code to automatically spit out requirements that have a particular word in it. You can use the something that looks like this:
Object o
String s
int offset, len
for o in entire (current Module) do
{
if (isDeleted(o)) continue
s = o."Object Text"""
if findPlainText(s, "<insert word here>", offset, len, false)
{
print identifier(o) // or replace this line with however you want to display object
}
}
Hope this is helpful. Cheers!
Edit:
To perform actions on a comma separated list, one at a time, you can use a while loop with some sort of search function that cuts off words one at a time.
void processWord (string someWord, Module mTarget, Object oSource)
{
Object oTarget
string objID = identifier(oSource)
for oTarget in mTarget do
{
if (<someWord in oTarget Object Text>) // edit function as necessary to do this
{
if (oTarget."Exists""" == "")
oTarget."Exists" = objID
else
oTarget."Exists" = oTarget."Exists" "," objID
}
}
}
int offset, len
string searchCriteria
Module mSource = read("<path of source module>", true)
Module mTarget = edit("<path of target module>", true)
Object oSource
for oSource in mSource do // can use "for object in entire(m)" for all objects
{
if (oSource != rqmt) continue // create conditions specific to your module here
searchCriteria = oSource."Search Criteria"""
while (findPlainText(searchCriteria, ",", offset, len, false))
{
processWord(searchCriteria[0:offset-1], mTarget, oSource)
searchCriteria = searchCriteria[offset+1:]
}
}
processWord(searchCriteria, mTarget, oSource) // for last value in comma separated list

Repast: how to get a particular agent set based on the specific conditions?

I am previously working with Netlogo and there are some very good built-in methods that allow me to filter and control the desired agents from the total population. (see: http://ccl.northwestern.edu/netlogo/docs/dictionary.html#agentsetgroup). For instance, I could very easily to command the different class of people agent in a simulation with simple codes like:
ask peoples with [wealth_type = "rich"] [donate money...]
ask peoples with [wealth_type = "poor"] [get money from rich people...]
In Repast, are there list of methods specifically built for easy controlling of agent set?
The equivalent in Repast Simphony Java is to use a Query. Queries apply a predicate to each agent in the Context and returns those that evaluate to true in an iterator. The PropertyEquals query evaluates an agent's property w/r to some value (e.g. "wealth_type" and "rich"). Note that "property" here refers to a Java property, i.e., a getter type method:
String getWealthType() {
return wealthType;
}
where "wealthType" is the name of the property.
As an example, in the JZombies example model, we can query Humans whose energy is equal to 5.
Query<Object> query = new PropertyEquals<Object>(context, "energy", 5);
for (Object o : query.query()) {
Human h = (Human)o;
System.out.println(h.getEnergy());
}
The query() iterator returns all the humans whose energy is equal to 5.
You can get a bit more complicated in the equivalence test by providing your own predicate. For example,
PropertyEqualsPredicate<Integer, Integer> pep = (a, b) -> {
return a * 2 == b;
};
Query<Object> query2 = new PropertyEquals<Object>(context, "energy", 8, pep);
for (Object o : query2.query()) {
Human h = (Human)o;
System.out.println(h.getEnergy());
}
Here, we are checking if the energy * 2 == 8. The predicate is passed the agent's property value in the first parameter and the value to compare against in the second parameter. Given that the predicate returns a boolean, you could also test for inequality, greater than etc.
Simphony has a variety of queries available. See,
https://repast.github.io/docs/api/repast_simphony/repast/simphony/query/package-summary.html
https://repast.github.io/docs/RepastReference/RepastReference.html#_repast_model_design_fundamental_concepts
for more info.
You can also do this in Simphony's ReLogo dialect:
ask (turtles()){
if (wealth_type == "rich") {
donateMoney()
}
if (wealth_type == "poor") {
getMoneyFromRichPeople()
}
}
If you want to just collect the richTurtles you can do (where "it" is the default method to access the individual turtle that is iterated over with findAll):
richTurtles = turtles().findAll{
it.wealth_type == "rich"
}
or with an explicit closure argument:
richTurtles = turtles().findAll{x->
x.wealth_type == "rich"
}

this method cannot be translated into a store expression [duplicate]

I saw this code work with LINQ to SQL but when I use Entity Framework, it throws this error:
LINQ to Entities does not recognize the method 'System.Linq.IQueryable'1[MyProject.Models.CommunityFeatures] GetCommunityFeatures()' method, and this method cannot be translated into a store expression.`
The repository code is this:
public IQueryable<Models.Estate> GetEstates()
{
return from e in entity.Estates
let AllCommFeat = GetCommunityFeatures()
let AllHomeFeat = GetHomeFeatures()
select new Models.Estate
{
EstateId = e.EstateId,
AllHomeFeatures = new LazyList<HomeFeatures>(AllHomeFeat),
AllCommunityFeatures = new LazyList<CommunityFeatures>(AllCommFeat)
};
}
public IQueryable<Models.CommunityFeatures> GetCommunityFeatures()
{
return from f in entity.CommunityFeatures
select new CommunityFeatures
{
Name = f.CommunityFeature1,
CommunityFeatureId = f.CommunityFeatureId
};
}
public IQueryable<Models.HomeFeatures> GetHomeFeatures()
{
return from f in entity.HomeFeatures
select new HomeFeatures()
{
Name = f.HomeFeature1,
HomeFeatureId = f.HomeFeatureId
};
}
LazyList is a List that extends the power of IQueryable.
Could someone explain why this error occurs?
Reason:
By design, LINQ to Entities requires the whole LINQ query expression to be translated to a server query. Only a few uncorrelated subexpressions (expressions in the query that do not depend on the results from the server) are evaluated on the client before the query is translated. Arbitrary method invocations that do not have a known translation, like GetHomeFeatures() in this case, are not supported.
To be more specific, LINQ to Entities only support Parameterless constructors and Initializers.
Solution:
Therefore, to get over this exception you need to merge your sub query into the main one for GetCommunityFeatures() and GetHomeFeatures() instead of directly invoking methods from within the LINQ query. Also, there is an issue on the lines that you were trying to instantiate a new instance of LazyList using its parameterized constructors, just as you might have been doing in LINQ to SQL. For that the solution would be to switch to client evaluation of LINQ queries (LINQ to Objects). This will require you to invoke the AsEnumerable method for your LINQ to Entities queries prior to calling the LazyList constructor.
Something like this should work:
public IQueryable<Models.Estate> GetEstates()
{
return from e in entity.Estates.AsEnumerable()
let AllCommFeat = from f in entity.CommunityFeatures
select new CommunityFeatures {
Name = f.CommunityFeature1,
CommunityFeatureId = f.CommunityFeatureId
},
let AllHomeFeat = from f in entity.HomeFeatures
select new HomeFeatures() {
Name = f.HomeFeature1,
HomeFeatureId = f.HomeFeatureId
},
select new Models.Estate {
EstateId = e.EstateId,
AllHomeFeatures = new LazyList<HomeFeatures>(AllHomeFeat),
AllCommunityFeatures = new LazyList<CommunityFeatures>(AllCommFeat)
};
}
More Info: Please take a look at LINQ to Entities, what is not supported? for more info.
Also check out LINQ to Entities, Workarounds on what is not supported for a detailed discussion on the possible solutions.
(Both links are the cached versions because the original website is down)

Jena - Find statements by property and object class

I'm looking for the way how to get all statements from my model by its property and by a class of an object.
For example I have property :driverOf and individuals either of type Bus or Truck. Then I want to get all statements where the property is :driverOf and the object is instanceOf Bus. Thanks.
UPDATE 1
Actually I need the result to be a set of statements (resp. StmtIterator) because in my app I use statement objects already. I think the most clean solution would be to have subproperties of :driverOf property, something like :driverOfBus and :driverOfTruck. But it would make my app more complicated, so I would like to find out some simple workaround.
You could use sparql query. You have to replace labels with full namespaces.
String queryString =
"SELECT ?x WHERE { ?x driverOflabel ?y . {?y a Buslabel} UNION { ?y a Trucklabel} . }";
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, YOURMODEL);
try {
ResultSet results = qexec.execSelect();
while(results.hasNext()) {
QuerySolution soln = results.nextSolution();
System.out.println(soln.toString());
}
} finally {
qexec.close();
}
I hope i understood this correctly:
Say you have model m and namespace NAMESPACE
// Get the property and the subject
Property driverOf = m.getProperty(NAMESPACE + "driverOf");
Resource bus = m.getResource(NAMESPACE + "bus");
// Get all statements/triples of the form (****, driverOf, bus)
StmtIterator stmtIterator = m.listStatements(null, driverOf, bus);
while (stmtIterator.hasNext()){
Statement s = stmtIterator.nextStatement();
Resource busDriver = s.getObject();
// do something to the busdriver (only nice things, everybody likes busdrivers)
}

Reasoner returns no instances of owl:Thing, but Abox contains instances

I have two ontologies, photo1 and index. Photo1 contains ABox assertions, and index contains Tbox assertions.
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology photo1 = manager.loadOntologyFromOntologyDocument(new File("files/ontologies/OBMA2/photo1.owl"));
OWLDataFactory factory = manager.getOWLDataFactory();
reasoner = new FaCTPlusPlusReasonerFactory().createReasoner(photo1);
reasoner = (FaCTPlusPlusReasoner) reasoner;
System.out.println(reasoner.getInstances(factory.getOWLThing(), false));
The above prints:
Nodeset[
Node( <http://www.semanticweb.org/noor/ontologies/2013/6/photo1.owl#photo1> ),
Node( <http://www.semanticweb.org/noor/ontologies/2013/6/photo1.owl#photo1-tiger2> ),
Node( <http://www.semanticweb.org/noor/ontologies/2013/6/photo1.owl#photo1-tiger1> )
]
However, now, I'm loading the Tbox and adding all ABox axioms from photo1 and then getting instances of owl:Thing as follows:
OWLOntologyManager managerTbox = OWLManager.createOWLOntologyManager();
OWLOntology Tbox = manager.loadOntologyFromOntologyDocument(new File("files/ontologies/index.owl"));
OWLDataFactory factoryTbox = manager.getOWLDataFactory();
OWLReasoner reasonerTbox = new FaCTPlusPlusReasonerFactory().createReasoner(Tbox);
//adding the axioms from the photo1 abox to Tbox's abox
managerTbox.addAxioms(Tbox, photo1.getABoxAxioms(true));
reasonerTbox = (FaCTPlusPlusReasoner) reasonerTbox;
System.out.println(reasonerTbox.getInstances(factoryTbox.getOWLThing(), false));
Now, even though I have added all axioms from Photo1's ABox to TBox's ABox, I get no output:
Nodeset[]
I'm not much of an OWL API user, but I suspect that what's happening is that the ABox axioms that you're including in the second case don't include the individual declarations for the individuals that the axioms talk about, and that as a result, the ABox axioms are getting ignored.
From the OWLAPI source, the ABoxAxiomTypes are defined as:
public static final Set<AxiomType<?>> ABoxAxiomTypes = new HashSet<AxiomType<?>>(
Arrays.asList(CLASS_ASSERTION, SAME_INDIVIDUAL,
DIFFERENT_INDIVIDUALS, OBJECT_PROPERTY_ASSERTION,
NEGATIVE_OBJECT_PROPERTY_ASSERTION,
DATA_PROPERTY_ASSERTION, NEGATIVE_DATA_PROPERTY_ASSERTION,
DATATYPE_DEFINITION));
I expect that if you add photo1's OWLDeclarationAxioms first (which it looks like you'd retrieve using getAxioms(AxiomType<Declaration>), and then add its ABoxAxioms, you might get the results that you're expecting.
You are creating a buffering reasoner with the first call to the reasoner factory; then you are adding the axioms to the ontology correctly, but the reasoner will not see the updates until you call reasoner.flush().
You can create a non-buffering reasoner with the same factory (see OWLReasonerFactory.createNonBufferingReasoner()), but this might have performance repercussions, as there might be a reclassification at every change.

Resources