Commit cb83fb33 authored by Naga Sai Datta Raviteja Kanagarla's avatar Naga Sai Datta Raviteja Kanagarla
Browse files

Final Version of Code for Grading

parent 4226c2cb
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>carcinogenesis_classifier</artifactId>
<version>1.0-SNAPSHOT</version>
<name>carcinogenesis_classifier</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<repositories>
<repository>
<id>snapshot.maven.aksw</id>
<url>http://maven.aksw.org/archiva/repository/snapshots/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dllearner</groupId>
<artifactId>components-core</artifactId>
<version>1.5.0</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
package org.example;
import java.io.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.google.common.collect.Sets;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.NodeFactory;
import org.apache.jena.graph.Triple;
import org.apache.jena.rdf.model.*;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr ;
import org.apache.jena.riot.lang.PipedRDFIterator;
import org.apache.jena.riot.lang.PipedRDFStream;
import org.apache.jena.riot.lang.PipedTriplesStream;
import org.dllearner.algorithms.celoe.CELOE;
import org.dllearner.algorithms.celoe.OEHeuristicRuntime;
import org.dllearner.core.AbstractCELA;
import org.dllearner.core.ComponentInitException;
import org.dllearner.core.KnowledgeSource;
import org.dllearner.kb.OWLAPIOntology;
import org.dllearner.learningproblems.PosNegLPStandard;
import org.dllearner.reasoning.ClosedWorldReasoner;
import org.dllearner.reasoning.OWLAPIReasoner;
import org.dllearner.refinementoperators.RhoDRDown;
import org.dllearner.utilities.OwlApiJenaUtils;
import org.dllearner.utilities.statistics.Stat;
import org.semanticweb.owlapi.model.*;
import uk.ac.manchester.cs.owl.owlapi.OWLNamedIndividualImpl;
public class App {
private static final String ontologyFileName = "resources/carcinogenesis.owl";
private static final String gradingSetFileName = "resources/kg-mini-project-grading.ttl";
static LearningProblem[] learningProblemsArray;
static LearningProblem lp;
static ArrayList<OWLIndividual> positiveSamples;
static ArrayList<OWLIndividual> negativeSamples;
static Set<OWLIndividual> carcinogenesisSet;
static Triple triple;
public static void main(String[] args) throws OWLOntologyCreationException, IOException, ComponentInitException {
OWLOntology ontology;
Set<OWLIndividual> posGradingSet ;
Set<OWLIndividual> negGradingSet;
Sets.SetView<OWLIndividual> unknownIndividualsSet;
ontology = loadOntology();
ConvertToTTL outputWriter = new ConvertToTTL();
outputWriter.writeConstants();
Node lpClassNode = NodeFactory.createURI("https://lpbenchgen.org/class/LearningProblem");
Node includesResourcesNode = NodeFactory.createURI("https://lpbenchgen.org/property/includesResource");
learningProblemsArray = new LearningProblem[25];
positiveSamples = new ArrayList<>();
negativeSamples = new ArrayList<>();
Stat fScore = new Stat();
int learningProblemsIndex = 0;
PipedRDFIterator<Triple> iter = new PipedRDFIterator<>();
final PipedRDFStream<Triple> inputStream = new PipedTriplesStream(iter);
ExecutorService executor = Executors.newSingleThreadExecutor();
Runnable parser = new Runnable() {
@Override
public void run() {
RDFDataMgr.parse(inputStream, gradingSetFileName);
}
};
executor.submit(parser);
while (iter.hasNext()) {
triple = iter.next(); // get the next statement
Node subject = triple.getSubject(); // get the subject from triple
Node predicate = triple.getPredicate(); // get the predicate from triple
Node object = triple.getObject(); // get the object from triple
if (object.equals(lpClassNode)) {
if (learningProblemsIndex > 0) {
lp.setPositiveSamples(positiveSamples);
lp.setNegativeSamples(negativeSamples);
learningProblemsArray[learningProblemsIndex-1] = lp;
}
learningProblemsIndex++;
lp = new LearningProblem();
positiveSamples = new ArrayList<>();
negativeSamples = new ArrayList<>();
} else {
if (lp.getLpID().isEmpty()) {
lp.setLpID(subject.getLocalName());
}
String obj_str = object.toString();
OWLIndividual resource = new OWLNamedIndividualImpl(IRI.create(obj_str));
if (predicate.equals(includesResourcesNode)) {
positiveSamples.add(resource);
} else {
negativeSamples.add(resource);
}
}
}
executor.shutdown();
//Setting up the positive and negative individuals
lp.setPositiveSamples(positiveSamples);
lp.setNegativeSamples(negativeSamples);
learningProblemsArray[learningProblemsIndex-1] = lp;
//Initializing the Knowledge Source
KnowledgeSource ks = new OWLAPIOntology(ontology);
ks.init();
// Initializing the Reasoner
OWLAPIReasoner baseReasoner = new OWLAPIReasoner(ks);
baseReasoner.setUseFallbackReasoner(true);
baseReasoner.init();
ClosedWorldReasoner rc = new ClosedWorldReasoner(ks);
rc.setReasonerComponent(baseReasoner);
rc.setHandlePunning(true);
rc.setMaterializeExistentialRestrictions(true);
rc.init();
carcinogenesisSet=rc.getIndividuals(); //Get all individuals from Carcinogenesis
for (learningProblemsIndex = 0; learningProblemsIndex < learningProblemsArray.length; learningProblemsIndex++) {
String lpID = learningProblemsArray[learningProblemsIndex].getLpID();
positiveSamples = learningProblemsArray[learningProblemsIndex].getPositiveSamples();
negativeSamples = learningProblemsArray[learningProblemsIndex].getNegativeSamples();
posGradingSet = new TreeSet<>(positiveSamples);
negGradingSet = new TreeSet<>(negativeSamples);
unknownIndividualsSet = Sets.difference(carcinogenesisSet, posGradingSet);
unknownIndividualsSet = Sets.difference(unknownIndividualsSet, negGradingSet);
System.out.println("Number of unknown individuals is " + unknownIndividualsSet.size());
// Initializing the PosNegLPStandard learning problem
PosNegLPStandard lp = new PosNegLPStandard(rc);
lp.setPositiveExamples(posGradingSet);
lp.setNegativeExamples(negGradingSet);
lp.init();
// Initializing the Learning Algorithm
AbstractCELA la;
OEHeuristicRuntime heuristic = new OEHeuristicRuntime();
heuristic.setExpansionPenaltyFactor(0.1);
la = new CELOE(lp, rc);
((CELOE) la).setHeuristic(heuristic);
((CELOE) la).setMaxExecutionTimeInSeconds(40);
((CELOE) la).setNoisePercentage(30);
((CELOE) la).setWriteSearchTree(false);
((CELOE) la).setReplaceSearchTree(true);
//Initializing the operator
RhoDRDown op = new RhoDRDown();
op.setInstanceBasedDisjoints(true);
op.setUseNegation(false);
op.setUseHasValueConstructor(true);
op.setUseAllConstructor(false);
op.setReasoner(rc);
op.setSubHierarchy(rc.getClassHierarchy());
op.setObjectPropertyHierarchy(rc.getObjectPropertyHierarchy());
op.setDataPropertyHierarchy(rc.getDatatypePropertyHierarchy());
op.init();
((CELOE) la).setOperator(op);
la.init();
la.start();
// Owl class Expression which represents the learning problem.
OWLClassExpression concept = la.getCurrentlyBestDescription();
// Returns the set of owl individuals for which the concept evaluates to true
Set<OWLIndividual> posResults = rc.hasType(concept, unknownIndividualsSet);
// Returns the set of owl individuals which do not evaluates to true
Set<OWLIndividual> negResults = Sets.difference(unknownIndividualsSet, posResults);
// Write classification result to output file
outputWriter.writeToFile(lpID, new ArrayList<>(posResults),
true, learningProblemsIndex + 1);
outputWriter.writeToFile(lpID, new ArrayList<>(negResults),
false, learningProblemsIndex + 1);
}
}
//function for loading ontology from carcinogenesis.owl
public static OWLOntology loadOntology() throws IOException {
Model model = ModelFactory.createDefaultModel();
try (InputStream is = new FileInputStream(new File(ontologyFileName))) {
model.read(is, null, Lang.RDFXML.getName());
}
//convert JENA model to OWL API ontology
OWLOntology ontology = OwlApiJenaUtils.getOWLOntology(model);
return ontology;
}
}
\ No newline at end of file
package org.example;
import org.semanticweb.owlapi.model.OWLIndividual;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.io.Writer;
public class ConvertToTTL {
static final String carcinogenesisPrefix = "@prefix carcinogenesis: <http://dl-learner.org/carcinogenesis#> .";
static final String lpResourcePrefix = "@prefix lpres: <https://lpbenchgen.org/resource/> .";
static final String lpPropertyPrefix = "@prefix lpprop: <https://lpbenchgen.org/property/> .";
static final String outputFileName = "CarcinogenesisClassificationResult";
public static void writeConstants() {
try {
FileWriter outfileConstantWriter = new FileWriter(outputFileName + ".ttl");
outfileConstantWriter.write(carcinogenesisPrefix);
outfileConstantWriter.append("\n");
outfileConstantWriter.append(lpResourcePrefix);
outfileConstantWriter.append("\n");
outfileConstantWriter.append(lpPropertyPrefix);
outfileConstantWriter.append("\n\n");
outfileConstantWriter.close();
} catch (Exception e) {
e.getStackTrace();
}
}
public static void writeToFile(String lp_id, ArrayList<OWLIndividual> results,
boolean isPositiveResultList, int index) {
try {
Writer outfileContentWriter;
int i;
String line1;
String resource;
outfileContentWriter = new BufferedWriter(new FileWriter(outputFileName + ".ttl", true));
if (isPositiveResultList) {
line1 = "lpres:result_" + index + "pos\t" + "lpprop:belongsToLP\t" + "true ;";
} else {
line1 = "lpres:result_" + index + "neg\t" + "lpprop:belongsToLP\t" + "false ;";
}
String line2 = "\tlpprop:pertainsTo\t" + "lpres:" + lp_id + " ;";
String line3Begin = "\tlpprop:resource\t";
outfileContentWriter.append(line1);
outfileContentWriter.append("\n");
outfileContentWriter.append(line2);
outfileContentWriter.append("\n");
outfileContentWriter.append(line3Begin);
for(i = 0; i < (results.size() - 1); i++) {
resource = results.get(i).toString();
outfileContentWriter.append("carcinogenesis:" + resource + " , ");
}
resource = results.get(results.size() - 1).toString();
outfileContentWriter.append("carcinogenesis:" + resource + " .\n\n");
outfileContentWriter.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}
\ No newline at end of file
package org.example;
import java.util.ArrayList;
import org.semanticweb.owlapi.model.*;
public class LearningProblem
{
String lpID = new String();
ArrayList<OWLIndividual> positiveSamples = new ArrayList<>();
ArrayList<OWLIndividual> negativeSamples = new ArrayList<>();
public LearningProblem(String lpID, ArrayList<OWLIndividual> positive_samples, ArrayList<OWLIndividual> negative_samples)
{
this.lpID =lpID;
this.positiveSamples =positive_samples;
this.negativeSamples =negative_samples;
}
public LearningProblem() {}
public String getLpID()
{
return lpID;
}
public ArrayList<OWLIndividual> getPositiveSamples()
{
return positiveSamples;
}
public ArrayList<OWLIndividual> getNegativeSamples()
{
return negativeSamples;
}
public void setLpID(String lpID)
{
this.lpID =lpID;
}
public void setPositiveSamples(ArrayList<OWLIndividual> positive_samples)
{
this.positiveSamples = positive_samples;
}
public void setNegativeSamples(ArrayList<OWLIndividual> negative_samples)
{
this.negativeSamples = negative_samples;
}
}
package org.example;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Unit test for simple App.
*/
public class AppTest
{
/**
* Rigorous Test :-)
*/
@Test
public void shouldAnswerWithTrue()
{
assertTrue( true );
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment