OWL API changing IRIs of entities in axioms - java

I am using OWL API. My question is how can I modify IRIs of all Entities in all OWLAxiom axioms in my OWLOntology read from file. For example I want to modify all "http://xxx" to "http://yyy" in all axioms in my ontology. The selected example axiom in this ontology is:
SubClassOf(<http://xxx#A> <http://xxx#B>)
I need to receive e.g.:
SubClassOf(<http://yyy#A> <http://yyy#B>)
My question especially implies to changing the default IRI, therefore, I tried to specify:
PrefixOWLOntologyFormat prefix = (PrefixOWLOntologyFormat) manager.getOntologyFormat(ontology);
prefix.setDefaultPrefix(...new...);
but it didn't change the IRIs in axioms.

One solution is to use the OWLEntityRenamer class.
one basic usage is the following one :
OWLEntityRenamer renamer = new OWLEntityRenamer(manager, Collections.singleton(ontology));
Map<OWLEntity, IRI> entity2IRIMap = new HashMap<>();
...
ont.applyChanges(renamer.changeIRI(entity2IRIMap));
All individuals targeted by your Map<> will be rename.
If you want to rename all yours individual by a pattern, you have to queries a complet list of your individuals to build the Map<>.
Here a complete small example using OWLEntityRenamer :
final OWLOntologyManager m = OWLManager.createOWLOntologyManager();
final OWLOntology o = m.createOntology();
o.add(OWL.classAssertion(OWL.Individual("xxx:1"), OWL.Class("b:y")));
o.add(OWL.classAssertion(OWL.Individual("xxx:2"), OWL.Class("b:y")));
o.add(OWL.classAssertion(OWL.Individual("xxx:3"), OWL.Class("b:y")));
o.individualsInSignature().forEach(System.out::println);
final OWLEntityRenamer renamer = new OWLEntityRenamer(m, Collections.singleton(o));
final Map<OWLEntity, IRI> entity2IRIMap = new HashMap<>();
o.individualsInSignature().forEach(toRename ->
{
final IRI iri = toRename.getIRI();
entity2IRIMap.put(toRename, IRI.create(iri.toString().replaceFirst("xxx", "yyy")));
});
o.applyChanges(renamer.changeIRI(entity2IRIMap));
o.individualsInSignature().forEach(System.out::println);
Should print :
<xxx:3>
<xxx:2>
<xxx:1>
<yyy:3>
<yyy:2>
<yyy:1>

Related

Get all mailMerge fields from docx using docx4J

I have .docx file, containing mailMerge fields.
I want to extract all field names to List.
I saw some examples of dox4J, how to replace these fields with mapped value, but I DO NOT want to replace them, I need to read them only.
Is there a semy easy way to do that using docx4J?
Have a look at https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/FieldsDiagnostics.java
You can also look at the code in MailMerger:
// find fields
ComplexFieldLocator fl = new ComplexFieldLocator();
new TraversalUtil(shellClone, fl);
// canonicalise and setup fieldRefs
List<FieldRef> fieldRefs = new ArrayList<FieldRef>();
canonicaliseStarts(fl, fieldRefs);
// Populate
for (FieldRef fr : fieldRefs) {
if ( fr.getFldName().equals("MERGEFIELD") ) {
String instr = extractInstr(fr.getInstructions() );
String datafieldName = getDatafieldNameFromInstr(instr);

How to consume a H2OModel computed and saved in Python API

I've been reading the H2O documentation for a while, and I haven't found a clear example of how to load model trained and saved using the Python API. I was following the next example.
import h2o
from h2o.estimators.naive_bayes import H2ONaiveBayesEstimator
model = H2ONaiveBayesEstimator()
h2o_df = h2o.import_file("http://s3.amazonaws.com/h2o-public-test-data/smalldata/airlines/allyears2k_headers.zip")
model.train(y = "IsDepDelayed", x = ["Year", "Origin"],
training_frame = h2o_df,
family = "binomial",
lambda_search = True,
max_active_predictors = 10)
h2o.save_model(model, path=models)
But if you check the official documentation it states that you have to download the model as a POJO from the flow UI. Is it the only way? or, may I achieve the same result via python? Just for information, I show the doc's example below. I need some guidance.
import java.io.*;
import hex.genmodel.easy.RowData;
import hex.genmodel.easy.EasyPredictModelWrapper;
import hex.genmodel.easy.prediction.*;
public class main {
private static String modelClassName = "gbm_pojo_test";
public static void main(String[] args) throws Exception {
hex.genmodel.GenModel rawModel;
rawModel = (hex.genmodel.GenModel) Class.forName(modelClassName).newInstance();
EasyPredictModelWrapper model = new EasyPredictModelWrapper(rawModel);
//
// By default, unknown categorical levels throw PredictUnknownCategoricalLevelException.
// Optionally configure the wrapper to treat unknown categorical levels as N/A instead:
//
// EasyPredictModelWrapper model = new EasyPredictModelWrapper(
// new EasyPredictModelWrapper.Config()
// .setModel(rawModel)
// .setConvertUnknownCategoricalLevelsToNa(true));
RowData row = new RowData();
row.put("Year", "1987");
row.put("Month", "10");
row.put("DayofMonth", "14");
row.put("DayOfWeek", "3");
row.put("CRSDepTime", "730");
row.put("UniqueCarrier", "PS");
row.put("Origin", "SAN");
row.put("Dest", "SFO");
BinomialModelPrediction p = model.predictBinomial(row);
System.out.println("Label (aka prediction) is flight departure delayed: " + p.label);
System.out.print("Class probabilities: ");
for (int i = 0; i < p.classProbabilities.length; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(p.classProbabilities[i]);
}
System.out.println("");
}
}
h2o.save_model will save the binary model to the provided file system, however, looking at the Java application above it seems you want to use model into a Java based scoring application.
Because of that you should be using h2o.download_pojo API to save the model to local file system along with genmodel jar file. The API is documented as below:
download_pojo(model, path=u'', get_jar=True)
Download the POJO for this model to the directory specified by the path; if the path is "", then dump to screen.
:param model: the model whose scoring POJO should be retrieved.
:param path: an absolute path to the directory where POJO should be saved.
:param get_jar: retrieve the h2o-genmodel.jar also.
Once you have download POJO, you can use the above sample application to perform the scoring and make sure the POJO class name and the "modelClassName" are same along with model type.

About inserting dynamic data into the static content at run time

I have a template like this in properties file: Dear xxxxxx, you are payment is succesfull.
After loading this template from properties file, I want to replace that "xxxxxx" with dynamic data in Java class.
Please help me on this.
I used Message.format("template",object array which is having dynamic data);
Try this way
placeholderReplacementMap is map that contain your static value and dynamic value key pair
Map<String, Object> placeholderReplacementMap = new HashMap<>();
StrSubstitutor substitutor = new StrSubstitutor(placeholderReplacementMap);
placeholderReplacementMap.put("xxxxxx", dynamicValue);
String newString = substitutor.replace("Dear xxxxxx","you are payment is succesful");

how to create OSLC docs using Jena?

I need to create RDF/XML documents containing objects in the OSLC namespace.
e.g.
<oslc_disc:ServiceProviderCatalog
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/terms/"
xmlns:oslc_disc="http://open-services.net/xmlns/discovery/1.0/"
rdf:about="{self}">
<dc:title>{catalog title}</dc:title>
<oslc_disc:details rdf:resource="{catalog details uri}" />
what is the simplest way to create this doc using the Jena API ?
( I know about Lyo, they use a JSP for this doc :-)
Thanks, Carsten
Here's a complete example to start you off. Be aware that this will be equivalent to XML output you want, but may not be identical. The order of properties, for example, may vary, and there are other ways to write the same content.
import com.hp.hpl.jena.rdf.model.*
import com.hp.hpl.jena.vocabulary.DCTerms;
public class Jena {
// Vocab items -- could use schemagen to generate a class for this
final static String OSLC_DISC_NS = "http://open-services.net/xmlns/discovery/1.0/";
final static Resource ServiceProviderCatalog =
ResourceFactory.createResource(OSLC_DISC_NS + "ServiceProviderCatalog");
final static Property details =
ResourceFactory.createProperty(OSLC_DISC_NS, "details");
public static void main(String[] args) {
// Inputs
String selfURI = "http://example.com/self";
String catalogTitle = "Catalog title";
String catalogDetailsURI = "http://example.com/catalogDetailsURI";
// Create in memory model
Model model = ModelFactory.createDefaultModel();
// Set prefixes
model.setNsPrefix("dc", DCTerms.NS);
model.setNsPrefix("oslc_disc", OSLC_DISC_NS);
// Add item of type spcatalog
Resource self = model.createResource(selfURI, ServiceProviderCatalog);
// Add the title
self.addProperty(DCTerms.title, catalogTitle);
// Add details, which points to a resource
self.addProperty(details, model.createResource(catalogDetailsURI));
// Write pretty RDF/XML
model.write(System.out, "RDF/XML-ABBREV");
}
}

Create Product in MS Dynamics CRM 2011 via SOAP/Java

I generated all required java classes from crm.dynamics.com/XRMServices/2011/Discovery.svc?wsdl and crm.dynamics.com/XRMServices/2011/Organization.svc?wsdl schemas.
I authenticated in CRM with LiveId.
Now i need to create Product in Product Catalog. Here is code for this:
Entity newEntryInfo = new Entity();
AttributeCollection collection = new AttributeCollection();
addAttribute(collection, "name", "Tama Starclassic Performer");
addAttribute(collection, "productnumber", "1");
addAttribute(collection, "price", createMoney("100.0"));
addAttribute(collection, "isstockitem", Boolean.TRUE);
addAttribute(collection, "statuscode", 1);
newEntryInfo.setAttributes(collection);
newEntryInfo.setLogicalName("product");
Guid productGuid = serviceStub.create(newEntryInfo);
private void addAttribute(AttributeCollection collection, String key, Object value) {
KeyValuePairOfstringanyType values = new KeyValuePairOfstringanyType();
values.setKey(key);
values.setValue(value);
collection.addKeyValuePairOfstringanyType(values);
}
Execution shows error "The unit schedule id is missing."
Looks like i need to provide "Unit Group" and "Default Unit" for new product.
Question: How can i set those values? Should i use RelatedEntities (how create it) or Attributes (how create it)
As it is a lookup on the form, you should be able to set the value with an EntityReference.
Using your methods that would be:
addAttribute(collection, "fieldName", new EntityReference("entityName", new Guid("id"))
Where:
fieldName is the schema name of the field you want to populate
entityName is the schema name of the entity you want to populate the field with
id is the Guid of a record which is the same type as entityName.
To put that into a context (where I happen to know the schema names off the top of my head).
//Create a new contact first
Entity contact = new Entity("contact");
contact["lastname"] = "Wood";
Guid contactId = service.Create(contact);
//Create an incident/case which links to that new contact
Entity incident = new Entity("incident");
incident["customerid"] = new EntityReference("contact", contactId)
service.Create(incident)
As a side is there a particular reason you are using a such a long winded code style? The entity class has an index which links to underlying attribute dictionary. Its a bit more straight forward.
If you are looking for more examples check out: Use the Late Bound Entity Class in Code

Categories