aboutsummaryrefslogtreecommitdiff
path: root/external/uk/ac/ox/cs/data/sample/DataSampling.java
blob: 1a788e3bda0c159ccc599642d1baf255d75cb3e9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package uk.ac.ox.cs.data.sample;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;

import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.impl.StatementImpl;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.rio.RDFHandler;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.ntriples.NTriplesParser;
import org.openrdf.rio.turtle.*;

import uk.ac.ox.cs.pagoda.owl.OWLHelper;
import uk.ac.ox.cs.pagoda.util.Namespace;
import uk.ac.ox.cs.pagoda.util.Utility;

public class DataSampling {
	
	File[] m_list;
	RDFGraph m_graph;
	double m_percentage;
	Set<String> excludeEntities = new HashSet<String>(); 
	
	public DataSampling(String prefix, String fileName, String excludeFile, double percentage, boolean inTurtle) {
		if (excludeFile != null) {
			try {
				Scanner scanner = new Scanner(new File(excludeFile));
				while (scanner.hasNextLine())
					excludeEntities.add(OWLHelper.removeAngles(scanner.nextLine().trim())); 
				scanner.close(); 
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		excludeEntities.add("http://www.w3.org/2002/07/owl#imports"); 

		File file = new File(fileName); 
		if (file.isDirectory())	m_list = file.listFiles();
		else m_list = new File[] {file};
		m_percentage = percentage; 
		
		RDFParser parser = inTurtle ? new TurtleParser() : new NTriplesParser();
		
		GraphRDFHandler handler = new GraphRDFHandler(excludeEntities); 
		parser.setRDFHandler(handler);
		
		FileInputStream istream;
		try {
			for (File tFile: m_list) {
				parser.parse(istream = new FileInputStream(tFile), prefix);
				istream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RDFParseException e) {
			e.printStackTrace();
		} catch (RDFHandlerException e) {
			e.printStackTrace();
		}
		
		m_graph = handler.getGraph(); 
	}
	
	public void sample(String outputFile, boolean multiStart) {
		try {
			FileOutputStream ostream = new FileOutputStream(outputFile); 
			TurtleWriter writer = new TurtleWriter(ostream);
			writer.startRDF();
			
			if (m_percentage < 100) {
				Sampler sam = multiStart ? 
						new RandomWalkMulti(m_graph, writer) : 
							new RandomWalk(m_graph, writer);
				sam.setLimit((int) (m_graph.numberOfStatement / 100 * m_percentage));
				System.out.println("Statement limit: " + (m_graph.numberOfStatement / 100 * m_percentage)); 
				sam.sample();
				sam.dispose(); 
			}
			else {
				m_graph.visit(writer);
			}
			writer.endRDF();
			ostream.close();
		} catch (IOException e) {
			e.printStackTrace(); 
		} catch (RDFHandlerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		sampleReactome();
//		sampleChEMBL(); 
	}
	
	static void sampleReactome() {
//		double[] ps = {40, 70, 100}; 
		double[] ps = {0.25, 0.5, 0.75}; 
		for (double per: ps) {
		DataSampling sampling = new DataSampling(
				"http://www.biopax.org/release/biopax-level3.owl#", 
//				"/home/yzhou/krr-nas-share/Yujiao/ontologies/bio2rdf/reactome/data/data.ttl", 
				"/home/yzhou/krr-nas-share/Yujiao/ontologies/bio2rdf/reactome/data/simplified.nt",
//				"/home/yzhou/krr-nas-share/Yujiao/ontologies/bio2rdf/reactome/graph sampling/reactome_sample_40.ttl", 
				"/home/yzhou/krr-nas-share/Yujiao/ontologies/bio2rdf/reactome/graph sampling/exclude",
				per, 
				true); 
		sampling.sample("/home/yzhou/krr-nas-share/Yujiao/ontologies/bio2rdf/reactome/graph sampling/sample_test_" + per + ".ttl", true);
//		sampling.sample("/home/yzhou/krr-nas-share/Yujiao/ontologies/bio2rdf/reactome/graph sampling/simplifed_sample_test_" + per + ".ttl", true);
//		sampling.sample("output/sample_reactome_multi.ttl", true);
		}
	}

	static void sampleChEMBL() {
		DataSampling sampling = new DataSampling(
				"http://rdf.ebi.ac.uk/terms/chembl", 
				"/home/yzhou/RDFdata/ChEMBL/facts/chembl_kbfile.nt", 
				null,
				100, 
				false);
		
		sampling.sample("output/sample_chembl_multi.ttl", true); 
		sampling.sample("output/sample_chembl.ttl", false); 
	}
	
}

class RDFGraph {
	
	Map<Value, Integer> index = new HashMap<Value, Integer>();
	Map<Integer, Value> inverseIndex = new HashMap<Integer, Value>(); 
	MapToList<Integer> labels = new MapToList<Integer>(); 
	
	MapToList<RDFEdge> edges = new MapToList<RDFEdge>();
	Set<String> excludeEntities; 
	
	int numberOfIndividuals = 0, numberOfProperties = 0; 
	
	public RDFGraph(Set<String> exclude) {
		excludeEntities = exclude; 
		for (String str: excludeEntities) 
			System.out.println(str); 
		System.out.println("---------------"); 
	}

	public void visit(TurtleWriter writer) throws RDFHandlerException {
		Integer key; 
		for (Entry<Integer, LinkedList<Integer>> entry: labels.entrySet()) {
			key = entry.getKey(); 
			for (Integer type: entry.getValue())
				writer.handleStatement(getStatement(key, type)); 
		}
		
		for (Entry<Integer, LinkedList<RDFEdge>> entry: edges.entrySet()) {
			key = entry.getKey();
			if ((inverseIndex.get(key) instanceof URI) && 
					((URI) inverseIndex.get(key)).toString().equals("http://www.reactome.org/biopax/46/879693#UnificationXref9"))
				System.out.println("Here");

			for (RDFEdge edge: entry.getValue())
				writer.handleStatement(getStatement(key, edge.m_label, edge.m_dst));
		}
	}

	private int getID(Value v, boolean isIndividual) {
		if (v.toString().contains("imports"))
			System.out.println(v.toString()); 
		if (excludeEntities.contains(v.toString())) {
			return 0; 
		}
		
		Integer id = index.get(v); 
		if (id == null)
			if (isIndividual) {
				index.put(v, id = ++numberOfIndividuals);
				inverseIndex.put(id, v);
			}
			else {
				index.put(v, id = --numberOfProperties);
				inverseIndex.put(id, v); 
			}
		return id; 
	}
	
	int numberOfStatement = 0;
	int counter = 0; 
	
	public void addTriple(Resource s, URI p, Value o) {
		++numberOfStatement; 
		if (numberOfStatement % 1000000 == 0) {
			Utility.logInfo("No.of statements: " + numberOfStatement, "\tNo.of individuals: " + numberOfIndividuals, "\tNo.of predicates: " + (-numberOfProperties));
		}
		
		if (p.equals(rdftype)) {
			int type = getID(o, false), i = getID(s, true);
			if (i == 0) {
//				System.out.println("<" + s + "> <" + p + "> <" + o + ">"); 
				return ; 
			}
			labels.add(i, type); 
		}
		else { 
			int i = getID(s, true), j = getID(o, true), prop = getID(p, false) ;
			if (i == 0 || j == 0 || prop == 0) {
//				System.out.println("<" + s + "> <" + p + "> <" + o + ">"); 
				return ; 
			}
			edges.add(i, new RDFEdge(prop, j)); 
		}
	}
	
	URI rdftype = new URIImpl(Namespace.RDF_TYPE); 

	public Statement getStatement(int... args) {
		if (args.length == 2) 
			return new StatementImpl((Resource) inverseIndex.get(args[0]), rdftype, (Value) inverseIndex.get(args[1]));
		else if (args.length == 3) 
			return new StatementImpl((Resource) inverseIndex.get(args[0]), (URI) inverseIndex.get(args[1]), (Value) inverseIndex.get(args[2]));
		return null;
	}

	public String getRawString(int id) {
		return inverseIndex.get(id).toString();
	}
	
}

class MapToList<T> {
	
	private Map<Integer, LinkedList<T>> map = new HashMap<Integer, LinkedList<T>>();
	
	public void add(int key, T value) {
		LinkedList<T> list = map.get(key); 
		if (list == null) 
			map.put(key, list = new LinkedList<T>()); 
		list.add(value); 
	}

	public Set<Map.Entry<Integer, LinkedList<T>>> entrySet() {
		return map.entrySet();
	}

	public void shuffle() {
		for (List<T> list: map.values())
			Collections.shuffle(list);
	}

	public LinkedList<T> get(int key) {
		return map.get(key); 
	}

}

class RDFEdge {
	
	int m_label, m_dst; 

	public RDFEdge(int label, int dst) {
		m_label = label; 
		m_dst = dst; 
	}

}

class GraphRDFHandler implements RDFHandler {
	
	RDFGraph m_graph;
	Set<String> m_exclude; 
	
	public GraphRDFHandler(Set<String> excludeEntities) {
		m_exclude = excludeEntities; 
	}
	
	@Override
	public void startRDF() throws RDFHandlerException {
		m_graph = new RDFGraph(m_exclude);		
	}

	public RDFGraph getGraph() {
		return m_graph;
	}

	@Override
	public void endRDF() throws RDFHandlerException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void handleNamespace(String prefix, String uri)
			throws RDFHandlerException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void handleStatement(Statement st) throws RDFHandlerException {
		m_graph.addTriple(st.getSubject(), st.getPredicate(), st.getObject());
	}

	@Override
	public void handleComment(String comment) throws RDFHandlerException {
		// TODO Auto-generated method stub
		
	}
	
}