OWLKoalaGoalReasoner(String,String)   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
c 0
b 0
f 0
cc 1
rs 10
1
package it.cnr.istc.pst.cognition.koala.reasoner.owl.jena;
2
3
import java.io.BufferedWriter;
4
import java.io.File;
5
import java.io.FileWriter;
6
import java.io.IOException;
7
import java.io.PrintWriter;
8
import java.util.ArrayList;
9
import java.util.HashSet;
10
import java.util.List;
11
import java.util.Set;
12
13
import org.apache.jena.rdf.model.Property;
14
import org.apache.jena.rdf.model.Resource;
15
import org.apache.jena.rdf.model.Statement;
16
17
import it.cnr.istc.pst.cognition.koala.reasoner.goal.GoalReasoner;
18
import it.cnr.istc.pst.cognition.koala.reasoner.observation.ObservationReasoner;
19
import it.cnr.istc.pst.cognition.koala.reasoner.observation.ObservationReasonerUpdate;
20
21
/**
22
 * 
23
 * @author anacleto
24
 *
25
 */
26
public class OWLKoalaGoalReasoner extends GoalReasoner
27
{
28
	private OWLKoalaModel kb;								// knowledge base model
29
	private Set<Statement> cache;						// cache of inferred statements about assistive tasks
30
	private PrintWriter writer;
31
	
32
	private long inferenceTime;							// count time spent doing inference
33
	private int inferenceCounter;						// count number of inferred goals
34
	
35
	/**
36
	 * 
37
	 * @param ontologyFilePath
38
	 * @param ruleFilePath
39
	 */
40
	public OWLKoalaGoalReasoner(String ontologyFilePath, String ruleFilePath) {
41
		super();
42
		// create a knowledge-base instance
43
		this.kb = new OWLKoalaModel(ontologyFilePath, ruleFilePath);
44
		// initialize cache
45
		this.cache = new HashSet<Statement>();
46
		this.inferenceTime = 0;
47
		this.inferenceCounter = 0;
48
	}
49
50
	/**
51
	 * 
52
	 */
53 View Code Duplication
	@Override
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
54
	protected void doInitialize(ObservationReasoner env) 
55
	{
56
		// set parameters
57
		this.inferenceTime = 0;
58
		this.inferenceCounter = 0;
59
		
60
		// current time 
61
		long now = System.currentTimeMillis();
62
		// setup model
63
		this.kb.setup(env.getModel().getModel());
64
		// get inference time
65
		long time = System.currentTimeMillis() - now;
66
		// update counter
67
		this.inferenceTime += time;
68
		
69
		// clear cache
70
		this.cache.clear();
71
		try
72
		{
73
			// create data file
74
			File dataFile = new File("data/goal_reasoner_" + System.currentTimeMillis() + ".csv");
75
			// create file and write the header of the CSV
76
			this.writer = new PrintWriter(new BufferedWriter(new FileWriter(dataFile)));
77
			// write header
78
			this.writer.print("timestamp;number of inferred goals;total inference time\n");
79
			this.writer.flush();
80
		}
81
		catch (IOException ex) {
82
			// set to null writer
83
			this.writer = null;
84
			// print error message 
85
			System.err.println("[GoalReasoner] Error opening writer buffer for data\n- message: " + ex.getMessage());
86
		}
87
	}
88
	
89
	/**
90
	 * 
91
	 */
92
	@Override
93
	protected void doGoalTriggering(List<ObservationReasonerUpdate> notifications) 
94
	{
95
		// get current time
96
		long timestamp = System.currentTimeMillis();
97
		// handle notifications
98
		for (ObservationReasonerUpdate notification : notifications) 
99
		{
100
			// current time 
101
			long now = System.currentTimeMillis();
102
			try
103
			{
104
				// event type
105
				String typeUri = notification.getEventType();
106
				// propagate information into the knowledge base
107
				Resource event = this.kb.createIndividual(typeUri);
108
				// get associated observable feature
109
				Resource observableFeature = this.kb.getResource(notification.getConcernedFeatureId());
110
				// get concerns property
111
				Property concerns = this.kb.getProperty(OWLKoalaNameSpace.KOALA.getNs() + "concerns");
112
				// assert property
113
				this.kb.assertProperty(
114
						event.getURI(), 
115
						concerns.getURI(), 
116
						observableFeature.getURI());
117
118
				System.out.println("[GoalReasoner] Update received from observation reasoner\n"
119
						+ "\t- " + event + "\n"
120
						+ "\t- asserting property " + event.getURI() + " " + concerns.getURI() + " " + observableFeature.getURI());
121
			}
122
			catch (Exception ex) {
123
				System.err.println("[GoalReasoner] Error while handling notification\n"
124
						+ "- notification: " + notification + "\n"
125
						+ "- message: " + ex.getMessage());
126
			}
127
			finally {
128
				// compute inference time
129
				long time = System.currentTimeMillis() - now;
130
				// update counter
131
				this.inferenceTime += time;
132
			}
133
		}
134
		
135
		try
136
		{
137
			// get the list of inferred events
138
			List<Statement> list = this.kb.getStatements(
139
					OWLKoalaNameSpace.SSN.getNs() + "isProxyFor");
140
			
141
			// check inferred events
142
			for (Statement s : list) 
143
			{
144
				// check if already notified
145
				if (!this.cache.contains(s))
146
				{
147
					// update inference counter
148
					this.inferenceCounter++;
149
					
150
					// get statement elements
151
					Resource subject = s.getSubject();
152
					
153
					
154
					// get type property
155
					Property pType = this.kb.getProperty(OWLKoalaNameSpace.RDF.getNs() + "type");
156
					// get event property statement
157
					Statement pStatement = subject.getProperty(pType);
158
					// get inferred event type
159
					Resource taskType = pStatement.getResource();
160
					
161
					// get the observable feature associated
162
					Property supports = this.kb.getProperty(OWLKoalaNameSpace.KOALA.getNs()+ "supports");
163
					// get concerns property statement
164
					Statement sStatement = subject.getProperty(supports);
165
					// get supported service
166
					Resource serviceType = sStatement.getResource();
167
					
168
					// get "explanation"
169
					Property precProperty = this.kb.getProperty(OWLKoalaNameSpace.KOALA.getNs() + "hasPrecondition");
170
					// get precondition
171
					Resource precondition = subject.getProperty(precProperty).getResource();
172
					
173
					// events triggering goal
174
					List<Resource> events = new ArrayList<Resource>();
175
					// get events enabling assistive task
176
					List<Statement> eStatements = this.kb.getStatements(
177
							precondition.getLocalName(), 
178
							OWLKoalaNameSpace.DUL.getNs()+ "includesEvent", 
179
							null);
180
					
181
					for (Statement es : eStatements) {
182
						// add resource
183
						events.add(es.getResource());
184
					}
185
					
186
					// print some data
187
					System.out.println("[GoalReasoner] Assistive task detected:\n"
188
							+ "- task: " + taskType + "\n"
189
							+ "- supported-service: " + serviceType + "\n"
190
							+ "- triggering-event(s): " + events + "\n");
191
					
192
					// add statement to the cache
193
					this.cache.add(s);
194
				}
195
			}
196
		}
197
		catch (Exception ex) {
198
			System.err.println("[GoalReasoner] Error while checking inferred assistive tasks\n- message= " + ex.getMessage());
199
		}
200
		finally 
201
		{
202
			// write data
203
			if (this.writer != null) 
204
			{
205
				// print inferred task type and service type
206
				this.writer.print(timestamp + ";" + this.inferenceCounter + ";" + this.inferenceTime + "\n");
207
				// write record
208
				this.writer.flush();
209
			}
210
		}
211
	}
212
	
213
	
214
	/**
215
	 * 
216
	 */
217
	@Override
218
	protected void doClose() 
219
	{
220
		// check if writer has been opened
221
		if (this.writer != null) {
222
			// close writer
223
			writer.close();
224
		}
225
		
226
	}
227
}
228