Commit 4d906b4a authored by Giustozzi Franco's avatar Giustozzi Franco
Browse files

Initial commit

parents
package csparql.ind;
import java.awt.Color;
import java.io.File;
import org.apache.http.message.BasicStatusLine;
import org.apache.log4j.PropertyConfigurator;
import org.knowm.xchart.QuickChart;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.XYChart;
import org.knowm.xchart.style.Styler.LegendPosition;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.larkc.csparql.common.utils.CsparqlUtils;
import eu.larkc.csparql.core.engine.CsparqlEngineImpl;
import eu.larkc.csparql.core.engine.CsparqlQueryResultProxy;
import csparql.ind.streamer.SensorsStreamer;
public class App {
private static Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
try{
//Configure log4j logger for the csparql engine
PropertyConfigurator.configure("log4j_configuration/csparql_readyToGoPack_log4j.properties");
//Create csparql engine instance
CsparqlEngineImpl engine = new CsparqlEngineImpl();
//Initialize the engine instance
//The initialization creates the static engine (SPARQL) and the stream engine (CEP)
engine.initialize(true);
String fileOntology = "ContextOntology-COInd4.owl";
// put static model
engine.putStaticNamedModel("http://streamreasoning.org/ContextOntology-COInd4",CsparqlUtils.serializeRDFFile(fileOntology));
/*
String queryS6 = "REGISTER QUERY S6detection AS "
+ "PREFIX : <http://semanticweb.org/STEaMINg/ContextOntology-COInd4#> "
+ "PREFIX sosa: <http://www.w3.org/ns/sosa/> "
+ "SELECT ?m ?pl "
+ "FROM STREAM <Stream_S_temp> [RANGE 60s STEP 60s] "
+ "FROM <http://streamreasoning.org/ContextOntology-COInd4> "
+ "WHERE { "
+ "{ ?m :isPartOf ?pl ."
+ " ?m sosa:hosts sosa:S_Temperature ."
+ " :S_Temperature :madeObservation ?o1 ."
+ " ?o1 :hasSimpleResult ?v1 ."
+ " FILTER ( "
+ " ?v1 > 30.0 "
+ " ) . }"
+ " } ";
*/
String queryS6 = "REGISTER QUERY S6detection AS "
+ "PREFIX : <http://semanticweb.org/STEaMINg/ContextOntology-COInd4#> "
+ "PREFIX sosa: <http://www.w3.org/ns/sosa/> "
+ "SELECT ?s (AVG(?v1) as ?avgTemp) "
+ "FROM STREAM <Stream_S_temp> [RANGE 10s STEP 10s] "
+ "FROM <http://streamreasoning.org/ContextOntology-COInd4> "
+ "WHERE { "
+ " ?s :madeObservation ?o1 ."
+ " ?o1 :hasSimpleResult ?v1 ."
+ " } "
+ " GROUP BY ?s "
+ " HAVING(AVG(?v1) > 30.0) ";
double[] data_temp = new double[9000];
double phase = 0;
double[][] initdata_temp = getInitData(phase,data_temp);
final XYChart chart = QuickChart.getChart("Capsule n°2,21.00.06.F9", "Time", "(°C)", "Temperature", initdata_temp[0], initdata_temp[1]);
chart.getStyler().setLegendPosition(LegendPosition.OutsideS);
//XYSeries series_TG_temp = chart.addSeries("TG_temp", initdata_TG_temp[0],initdata_TG_temp[1]);
//series_TG_temp.setMarker(SeriesMarkers.NONE);
chart.getStyler().setYAxisMin(25.0);
chart.getStyler().setYAxisMax(40.0);
chart.getStyler().setCursorEnabled(true);
chart.getStyler().setCursorColor(Color.GREEN);
chart.getStyler().setCursorFontColor(Color.ORANGE);
chart.getStyler().setCursorBackgroundColor(Color.BLUE);
final SwingWrapper<XYChart> sw = new SwingWrapper<XYChart>(chart);
sw.displayChart();
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLDataFactory factory = manager.getOWLDataFactory();
String ontologyURI = "http://semanticweb.org/STEaMINg/ContextOntology-COInd4";
String ns = ontologyURI + "#";
final OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new File(fileOntology));
SensorsStreamer Stream_Temp = new SensorsStreamer("Stream_S_temp",ns,"Temperature",2,ontology,factory,data_temp,chart,sw);
//Register new streams in the engine
engine.registerStream(Stream_Temp);
Thread Stream_C_Wtemp_Thread = new Thread(Stream_Temp);
//Register new query in the engine
CsparqlQueryResultProxy c_S6 = engine.registerQuery(queryS6, false);
//Attach a result consumer to the query result proxy to print the results on the console
c_S6.addObserver(new ConsoleFormatter("S6",ns,ontology,factory));
//Start streaming data
Stream_C_Wtemp_Thread.start();
}catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
private static double[][] getInitData(double phase, double[] values) {
double[] xData = new double[1];
double[] yData = new double[1];
for (int i = 0; i < xData.length; i++) {
xData[i] = phase+i;
int index=(int) (phase+i);
yData[i] = values[index];
}
return new double[][] { xData, yData };
}
}
\ No newline at end of file
package csparql.ind;
import eu.larkc.csparql.common.RDFTable;
import eu.larkc.csparql.core.ResultFormatter;
import java.util.Observable;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassAssertionAxiom;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
public class ConsoleFormatter extends ResultFormatter {
private String situationName;
private String baseUri;
private OWLOntology ontology;
private OWLDataFactory factory;
public ConsoleFormatter(String situationName, String baseUri, OWLOntology ontology, OWLDataFactory factory) {
this.situationName = situationName;
this.baseUri = baseUri;
this.ontology = ontology;
this.factory = factory;
}
@Override
public void update(Observable o, Object arg) {
RDFTable rdfTable = (RDFTable)arg;
System.out.println();
if (rdfTable.size()==0)
System.out.println("NO RESULT");
else {
System.out.println(situationName + " DETECTED. "+ rdfTable.size() + " result at SystemTime: "+System.currentTimeMillis());
rdfTable.stream().forEach((t) -> {
System.out.println(t.get(0) + " --- " + t.get(1) + " avg temp. " + situationName);
OWLClass Situation = factory.getOWLClass(IRI.create(baseUri + "Situation"));
OWLIndividual sit = factory.getOWLNamedIndividual(IRI.create(baseUri,situationName + "-" + System.currentTimeMillis()));
OWLClassAssertionAxiom sitType = factory.getOWLClassAssertionAxiom(Situation, sit);
ontology.add(sitType);
/*
OWLClass Machine = factory.getOWLClass(IRI.create(baseUri + "Machine"));
OWLIndividual M3 = factory.getOWLNamedIndividual(IRI.create(t.get(0)));
OWLClassAssertionAxiom machineM3 = factory.getOWLClassAssertionAxiom(Machine, M3);
ontology.add(machineM3);
OWLClass Line = factory.getOWLClass(IRI.create(baseUri + "Line"));
OWLIndividual PL1 = factory.getOWLNamedIndividual(IRI.create(t.get(1)));
OWLClassAssertionAxiom pordLinePL1 = factory.getOWLClassAssertionAxiom(Line, PL1);
ontology.add(pordLinePL1);
OWLObjectProperty concernBy = factory.getOWLObjectProperty(IRI.create(baseUri + "concernBy"));
OWLObjectPropertyAssertionAxiom concernByAssertM3 = factory.getOWLObjectPropertyAssertionAxiom(concernBy, M3, sit);
ontology.add(concernByAssertM3);
OWLObjectPropertyAssertionAxiom concernByAssertPL1 = factory.getOWLObjectPropertyAssertionAxiom(concernBy, PL1, sit);
ontology.add(concernByAssertPL1);
*/
try {
ontology.saveOntology();
} catch (OWLOntologyStorageException e1) {
e1.printStackTrace();
}
});
}
}
}
\ No newline at end of file
package csparql.ind.streamer;
import java.io.FileReader;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.opencsv.CSVReader;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.XYChart;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassAssertionAxiom;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLDataProperty;
import org.semanticweb.owlapi.model.OWLDataPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import eu.larkc.csparql.cep.api.RdfQuadruple;
import eu.larkc.csparql.cep.api.RdfStream;
public class SensorsStreamer extends RdfStream implements Runnable {
private long sleepTime;
private String baseUri;
private String prop;
private OWLOntology ontology;
private OWLDataFactory factory;
private double[] dataValues;
private XYChart chart;
private SwingWrapper<XYChart> sw;
public SensorsStreamer(String iri, String baseUri, String prop, long sleepTime,
OWLOntology ontology, OWLDataFactory factory, double[] dataValues, XYChart chart, SwingWrapper<XYChart> sw) {
super(iri);
this.sleepTime = sleepTime;
this.baseUri = baseUri;
this.prop = prop;
this.ontology = ontology;
this.factory = factory;
this.dataValues = dataValues;
this.chart = chart;
this.sw = sw;
}
public void run() {
try {
CSVReader reader = new CSVReader(new FileReader("example.csv"));
List<String[]> allRows = reader.readAll();
//String result;
Double result;
int observationIndex = 0;
int timeIndex = 0;
String ontologyURI = "http://semanticweb.org/STEaMINg/ContextOntology-COInd4";
String ns = ontologyURI + "#";
String pre_SOSAOnt = "http://www.w3.org/ns/sosa/";
String pre_TIME = "http://www.w3.org/2006/time#";
OWLClass Sensor = factory.getOWLClass(IRI.create(pre_SOSAOnt + "Sensor"));
OWLClass Observation = factory.getOWLClass(IRI.create(pre_SOSAOnt + "Observation"));
OWLClass ObservableProperty = factory.getOWLClass(IRI.create(pre_SOSAOnt + "ObservableProperty"));
OWLClass Instant = factory.getOWLClass(IRI.create(pre_TIME + "Instant"));
OWLObjectProperty madeObservation = factory.getOWLObjectProperty(IRI.create(pre_SOSAOnt + "madeObservation"));
OWLObjectProperty observedProperty = factory.getOWLObjectProperty(IRI.create(pre_SOSAOnt + "observedProperty"));
OWLDataProperty hasSimpleResult = factory.getOWLDataProperty(IRI.create(pre_SOSAOnt + "hasSimpleResult"));
OWLObjectProperty hasTime = factory.getOWLObjectProperty(IRI.create(ns,"hasTime"));
OWLDataProperty inXSDDateTimeStamp = factory.getOWLDataProperty(IRI.create(pre_TIME + "inXSDDateTimeStamp"));
while(true){
try{
result = Double.parseDouble(allRows.get(observationIndex)[3]);
Timestamp date = new Timestamp(System.currentTimeMillis());
dataValues[observationIndex] = result;
final double[][] data = getData(observationIndex,dataValues);
chart.updateXYSeries(prop, data[0], data[1], null);
sw.repaintChart();
RdfQuadruple q = new RdfQuadruple(baseUri + "S_" + prop, baseUri + "madeObservation", baseUri + "S_" + prop + "-Obs-" + observationIndex, System.currentTimeMillis());
System.out.println(q);
this.put(q);
q = new RdfQuadruple(baseUri + "S_" + prop + "-Obs-" + observationIndex, baseUri + "observedProperty", baseUri + prop, System.currentTimeMillis());
System.out.println(q);
this.put(q);
q = new RdfQuadruple(baseUri + "S_" + prop + "-Obs-" + observationIndex, baseUri + "hasSimpleResult", result + "^^http://www.w3.org/2001/XMLSchema#double", System.currentTimeMillis());
System.out.println(q);
this.put(q);
q = new RdfQuadruple(baseUri + "S_" + prop + "-Obs-" + observationIndex, baseUri + "hasTime", baseUri + "t-obs-S_" + prop + "-"+ timeIndex, System.currentTimeMillis());
System.out.println(q);
this.put(q);
q = new RdfQuadruple(baseUri + "t-obs-S_" + prop + "-"+ timeIndex, baseUri + "inXSDDateTime", date + "^^http://www.w3.org/2001/XMLSchema#dateTimeStamp", System.currentTimeMillis());
System.out.println(q);
this.put(q);
OWLIndividual sensor = factory.getOWLNamedIndividual(IRI.create(ns,"S_" + prop));
OWLClassAssertionAxiom sensorType = factory.getOWLClassAssertionAxiom(Sensor, sensor);
ontology.add(sensorType);
OWLIndividual obs = factory.getOWLNamedIndividual(IRI.create(ns,"S_" + prop + "-Obs-" + observationIndex));
OWLClassAssertionAxiom obsType = factory.getOWLClassAssertionAxiom(Observation, obs);
ontology.add(obsType);
OWLIndividual property = factory.getOWLNamedIndividual(IRI.create(ns,prop));
OWLClassAssertionAxiom propType = factory.getOWLClassAssertionAxiom(ObservableProperty, property);
ontology.add(propType);
OWLObjectPropertyAssertionAxiom sensormadeobs = factory.getOWLObjectPropertyAssertionAxiom(madeObservation, sensor, obs);
ontology.add(sensormadeobs);
OWLObjectPropertyAssertionAxiom observedProp = factory.getOWLObjectPropertyAssertionAxiom(observedProperty, obs, property);
ontology.add(observedProp);
OWLIndividual time = factory.getOWLNamedIndividual(IRI.create(pre_TIME,"t-obs-S_" + prop + "-"+ timeIndex));
OWLClassAssertionAxiom timeType = factory.getOWLClassAssertionAxiom(Instant, time);
ontology.add(timeType);
OWLObjectPropertyAssertionAxiom obshastime = factory.getOWLObjectPropertyAssertionAxiom(hasTime, obs, time);
ontology.add(obshastime);
OWLDataPropertyAssertionAxiom timehasdate = factory.getOWLDataPropertyAssertionAxiom(inXSDDateTimeStamp, time, date + "^^http://www.w3.org/2001/XMLSchema#dateTimeStamp");
ontology.add(timehasdate);
OWLDataPropertyAssertionAxiom obshassimpleresult = factory.getOWLDataPropertyAssertionAxiom(hasSimpleResult, obs, result + "^^http://www.w3.org/2001/XMLSchema#double");
ontology.add(obshassimpleresult);
try {
ontology.saveOntology();
} catch (OWLOntologyStorageException e1) {
e1.printStackTrace();
}
TimeUnit.SECONDS.sleep(sleepTime);
observationIndex++;
timeIndex++;
} catch(Exception e){
e.printStackTrace();
}
}
} catch (Exception e) {
//TODO: handle exception
}
}
private static double[][] getData(double phase,double[] values) {
ArrayList<Double> xData1 = new ArrayList<Double>();
ArrayList<Double> yData1 = new ArrayList<Double>();
for (int i = 0; i < phase; i++) {
xData1.add(i+0.0);
int index=(int) (i);
yData1.add(values[index]);
}
double[] xData = new double[xData1.size()];
double[] yData = new double[yData1.size()];
for (int i = 0; i < phase; i++) {
xData[i] = xData1.get(i);
yData[i] = yData1.get(i);
}
return new double[][] { xData, yData };
}
}
\ No newline at end of file
Markdown is supported
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