/
ExporterR.java
2868 lines (2673 loc) · 119 KB
/
ExporterR.java
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dna.export;
import java.io.File;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.rosuda.JRI.RConsoleOutputStream;
import org.rosuda.JRI.Rengine;
import dna.Dna;
import dna.SqlConnection;
import dna.dataStructures.AttributeVector;
import dna.dataStructures.Coder;
import dna.dataStructures.Data;
import dna.dataStructures.Document;
import dna.dataStructures.Statement;
import dna.dataStructures.StatementType;
public class ExporterR {
/* =================================================================================================================
* Object definitions; constructor; and helper functions
* =================================================================================================================
*/
// objects for R calls
String dbfile;
SqlConnection sql;
Data data;
Matrix matrix;
ArrayList<Matrix> timeWindowMatrices;
AttributeVector[] attributes;
Object[] eventListColumnsR;
String[] columnNames, columnTypes;
ExportHelper exportHelper;
/**
* Constructor for external R calls. Load and prepare data for export.
* @throws Exception
*/
public ExporterR(String dbtype, String dbfile, String login, String password, boolean verbose) throws Exception {
// divert stdout to R console
Rengine r = new Rengine();
RConsoleOutputStream rs = new RConsoleOutputStream(r, 0);
System.setOut(new PrintStream(rs));
System.setErr(new PrintStream(rs));
// check if database file or connection exists and connect
this.data = new Data();
this.dbfile = dbfile;
boolean dbExists = true;
if (dbtype.equals("sqlite")) {
File f = new File(this.dbfile);
if (f.exists()) {
dbExists = true;
} else {
dbExists = false;
}
} else if (dbtype.equals("mysql")) {
try {
SqlConnection testConnection = new SqlConnection(dbtype, this.dbfile, login, password);
testConnection.closeConnection();
dbExists = true;
} catch (Exception e) {
dbExists = false;
throw new Exception("Connection could not be opened.\n" + e.getStackTrace());
}
}
this.sql = new SqlConnection(dbtype, this.dbfile, login, password);
if (!dbExists) { // if the database does not exist, create default data structures
this.sql.createDataStructure();
if (verbose == true) {
System.out.println("Table structure created.");
}
// create default settings
Dna dna = new Dna();
this.data.getSettings().put("version", dna.version);
this.sql.upsertSetting("version", dna.version);
this.data.getSettings().put("date", dna.date);
this.sql.upsertSetting("date", dna.date);
this.data.getSettings().put("popupWidth", "220"); // default width of text fields in popup windows
this.sql.upsertSetting("popupWidth", "220");
this.data.getSettings().put("statementColor", "coder");
this.sql.upsertSetting("statementColor", "coder");
// create coder
Coder adminCoder = new Coder(1);
adminCoder.setName("admin");
this.data.addCoder(adminCoder);
this.sql.addCoder(adminCoder);
this.data.setActiveCoder(adminCoder.getId());
this.sql.upsertSetting("activeCoder", Integer.toString(adminCoder.getId()));
// create default statement types
try {
this.addStatementType("DNA Statement", "#FFFF00", new String[0], new String[0]);
this.addVariable("DNA Statement", "person", "short text", false, false);
this.addVariable("DNA Statement", "organization", "short text", false, false);
this.addVariable("DNA Statement", "concept", "short text", false, false);
this.addVariable("DNA Statement", "agreement", "boolean", false, false);
this.addStatementType("Annotation", "#D3D3D3", new String[0], new String[0]);
this.addVariable("Annotation", "note", "long text", false, false);
} catch (Exception e) {
e.printStackTrace();
}
}
// read in all data from the database and report summary
this.data = sql.getAllData();
if (verbose == true) {
String statementString = " statements and ";
if (this.data.getStatements().size() == 1) {
statementString = " statement and ";
}
String documentString = " documents.";
if (this.data.getDocuments().size() == 1) {
documentString = " document.";
}
System.out.println("Data loaded: " + data.getStatements().size() + statementString + data.getDocuments().size() + documentString);
}
this.exportHelper = new ExportHelper();
}
/**
* A function for printing details about the dataset. Used by rDNA.
*
* @return A string with details about the database.
*/
public String rShow() {
String statementString = " statements in ";
if (this.data.getStatements().size() == 1) {
statementString = " statement in ";
}
String documentString = " documents";
if (this.data.getDocuments().size() == 1) {
documentString = " document";
}
String s = "DNA database: " + this.dbfile + "\n" + data.getStatements().size() + statementString + data.getDocuments().size() + documentString + "\nStatement types: ";
for (int i = 0; i < data.getStatementTypes().size(); i++) {
s = s + data.getStatementTypes().get(i).getLabel();
if (i < data.getStatementTypes().size() - 1) {
s = s + ", ";
}
}
s = s + "\n";
return s;
}
/* =================================================================================================================
* Functions for generating and retrieving networks
* =================================================================================================================
*/
/**
* Compute one-mode or two-mode network matrix based on R arguments.
*
* @param networkType The network type as provided by rDNA (can be 'eventlist', 'twomode', or 'onemode')
* @param statementType Statement type as a String
* @param variable1 First variable for export, provided as a String
* @param variable1Document boolean indicating if the first variable is at the document level
* @param variable2 Second variable for export, provided as a String
* @param variable2Document boolean indicating if the second variable is at the document level
* @param qualifier Qualifier variable as a String
* @param qualifierAggregation Aggregation rule for the qualifier variable (can be 'ignore', 'combine', 'subtract', 'congruence', or 'conflict')
* @param normalization Normalization setting as a String, as provided by rDNA (can be 'no', 'activity', 'prominence', 'average', 'Jaccard', or 'cosine')
* @param includeIsolates boolean indicating whether nodes not currently present should still be inserted into the network matrix
* @param duplicates An input String from rDNA that can be 'include', 'document', 'week', 'month', 'year', or 'acrossrange'
* @param startDate Start date for the export, provided as a String with format "dd.MM.yyyy"
* @param stopDate Stop date for the export, provided as a String with format "dd.MM.yyyy"
* @param startTime Start time for the export, provided as a String with format "HH:mm:ss"
* @param stopTime Stop time for the export, provided as a String with format "HH:mm:ss"
* @param timewindow A string indicating the time window setting. Valid options are 'no', 'events', 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months', and 'years'.
* @param windowsize An int indicating the duration of the time window in the units specified in the timeWindow argument.
* @param excludeVariables A String array with n elements, indicating the variable of the n'th value
* @param excludeValues A String array with n elements, indicating the value pertaining to the n'th variable String
* @param excludeAuthors A String array of values to exclude in the 'author' variable at the document level
* @param excludeSources A String array of values to exclude in the 'source' variable at the document level
* @param excludeSections A String array of values to exclude in the 'section' variable at the document level
* @param excludeTypes A String array of values to exclude in the 'type' variable at the document level
* @param invertValues boolean indicating whether the statement-level exclude values should be included (= true) rather than excluded
* @param invertAuthors boolean indicating whether the document-level author values should be included (= true) rather than excluded
* @param invertSources boolean indicating whether the document-level source values should be included (= true) rather than excluded
* @param invertSections boolean indicating whether the document-level section values should be included (= true) rather than excluded
* @param invertTypes boolean indicating whether the document-level type values should be included (= true) rather than excluded
* @param verbose Report progress to the console?
* @return A Matrix object containing the resulting one-mode or two-mode network
*/
public void rNetwork(String networkType, String statementType, String variable1, boolean variable1Document, String variable2,
boolean variable2Document, String qualifier, String qualifierAggregation, String normalization, boolean includeIsolates,
String duplicates, String startDate, String stopDate, String startTime, String stopTime, String timewindow, int windowsize,
String[] excludeVariables, String[] excludeValues, String[] excludeAuthors, String[] excludeSources, String[] excludeSections,
String[] excludeTypes, boolean invertValues, boolean invertAuthors, boolean invertSources, boolean invertSections,
boolean invertTypes, boolean verbose) {
// step 1: preprocess arguments
int max = 5;
if (networkType.equals("eventlist")) {
max = 4;
}
if (verbose == true) {
System.out.print("(1/" + max + "): Processing network options... ");
}
// format network type
// valid R input: 'eventlist', 'twomode', or 'onemode'
// valid Java output: 'Event list', 'Two-mode network', or 'One-mode network'
if (networkType.equals("eventlist")) {
networkType = "Event list";
} else if (networkType.equals("twomode")) {
networkType = "Two-mode network";
} else if (networkType.equals("onemode")) {
networkType = "One-mode network";
} else {
System.err.println("Network type was not recognized. Use 'twomode', 'onemode', or 'eventlist'.");
}
// process and check validity of statement type etc.
// valid R input for qualifierAggregation: 'ignore', 'combine', 'subtract', 'congruence', or 'conflict'
StatementType st = data.getStatementType(statementType);
if (st == null) {
System.err.println("Statement type '" + statementType + " does not exist!");
}
if (!st.getVariables().containsKey(variable1)) {
System.err.println("Variable 1 ('" + variable1 + "') does not exist in this statement type.");
}
if (!st.getVariables().get(variable1).equals("short text")) {
System.err.println("Variable 1 ('" + variable1 + "') is not a short text variable.");
}
if (!st.getVariables().containsKey(variable2)) {
System.err.println("Variable 2 ('" + variable2 + "') does not exist in this statement type.");
}
if (!st.getVariables().get(variable2).equals("short text")) {
System.err.println("Variable 2 ('" + variable2 + "') is not a short text variable.");
}
if (!st.getVariables().containsKey(qualifier)) {
System.err.println("The qualifier variable ('" + qualifier + "') does not exist in this statement type.");
}
if (!st.getVariables().get(qualifier).equals("boolean") && !st.getVariables().get(qualifier).equals("integer")) {
System.err.println("The qualifier variable ('" + qualifier + "') is not a boolean or integer variable.");
}
if (!qualifierAggregation.equals("ignore") && !qualifierAggregation.equals("subtract") && !qualifierAggregation.equals("combine")
&& !qualifierAggregation.equals("congruence") && !qualifierAggregation.equals("conflict")) {
System.err.println("'qualifierAggregation' must be 'ignore', 'combine', 'subtract', 'congruence', or 'conflict'.");
}
if (qualifierAggregation.equals("combine") && !networkType.equals("Two-mode network")) {
System.err.println("qualifierAggregation = 'combine' is only possible with two-mode networks.");
}
if (qualifierAggregation.equals("congruence") && !networkType.equals("One-mode network")) {
System.err.println("qualifierAggregation = 'congruence' is only possible with one-mode networks.");
}
if (qualifierAggregation.equals("conflict") && !networkType.equals("One-mode network")) {
System.err.println("qualifierAggregation = 'conflict' is only possible with one-mode networks.");
}
boolean ignoreQualifier = qualifier.equals("ignore");
int statementTypeId = st.getId();
// format normalization argument
// R input can be: 'no', 'activity', 'prominence', 'average', 'Jaccard', or 'cosine'
// formatted Java output can be: 'no', 'activity', 'prominence', 'average activity', 'Jaccard', or 'cosine'
if (normalization.equals("jaccard")) {
normalization = "Jaccard";
}
if (normalization.equals("Cosine")) {
normalization = "cosine";
}
if (!normalization.equals("no") && !normalization.equals("activity") && !normalization.equals("prominence")
&& !normalization.equals("average") && !normalization.equals("Jaccard") && !normalization.equals("cosine")) {
System.err.println("'normalization' must be 'no', 'activity', 'prominence', 'average', 'Jaccard', or 'cosine'.");
}
if (normalization.equals("activity") && !networkType.equals("Two-mode network")) {
System.err.println("'normalization = 'activity' is only possible with two-mode networks.");
}
if (normalization.equals("prominence") && !networkType.equals("Two-mode network")) {
System.err.println("'normalization = 'prominence' is only possible with two-mode networks.");
}
if (normalization.equals("average") && !networkType.equals("One-mode network")) {
System.err.println("'normalization = 'average' is only possible with one-mode networks.");
}
if (normalization.equals("Jaccard") && !networkType.equals("One-mode network")) {
System.err.println("'normalization = 'Jaccard' is only possible with one-mode networks.");
}
if (normalization.equals("cosine") && !networkType.equals("One-mode network")) {
System.err.println("'normalization = 'cosine' is only possible with one-mode networks.");
}
if (normalization.equals("average")) {
normalization = "average activity";
}
// format duplicates argument
// valid R input: 'include', 'document', 'week', 'month', 'year', or 'acrossrange'
// valid Java output: 'include all duplicates', 'ignore per document', 'ignore per calendar week', 'ignore per calendar month', 'ignore per calendar year', or 'ignore across date range'
if (!duplicates.equals("include") && !duplicates.equals("document") && !duplicates.equals("week") && !duplicates.equals("month")
&& !duplicates.equals("year") && !duplicates.equals("acrossrange")) {
System.err.println("'duplicates' must be 'include', 'document', 'week', 'month', 'year', or 'acrossrange'.");
}
if (duplicates.equals("include")) {
duplicates = "include all duplicates";
} else if (duplicates.equals("document")) {
duplicates = "ignore per document";
} else if (duplicates.equals("week")) {
duplicates = "ignore per calendar week";
} else if (duplicates.equals("month")) {
duplicates = "ignore per calendar month";
} else if (duplicates.equals("year")) {
duplicates = "ignore per calendar year";
} else if (duplicates.equals("acrossrange")) {
duplicates = "ignore across date range";
}
// format dates and times with input formats "dd.MM.yyyy" and "HH:mm:ss"
DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
String startString = startDate + " " + startTime;
Date start = null;
try {
start = df.parse(startString);
} catch (ParseException e) {
System.err.println("Start date or time is invalid!");
}
if (!startString.equals(df.format(start))) {
startDate = null;
System.err.println("Start date or time is invalid!");
}
String stopString = stopDate + " " + stopTime;
Date stop = null;
try {
stop = df.parse(stopString);
} catch (ParseException e) {
System.err.println("Stop date or time is invalid!");
}
if (!stopString.equals(df.format(stop))) {
stopDate = null;
System.err.println("Stop date or time is invalid!");
}
// format time window arguments
if (timewindow == null || timewindow.startsWith("no")) {
timewindow = "no time window";
}
if (timewindow.equals("seconds")) {
timewindow = "using seconds";
}
if (timewindow.equals("minutes")) {
timewindow = "using minutes";
}
if (timewindow.equals("hours")) {
timewindow = "using hours";
}
if (timewindow.equals("days")) {
timewindow = "using days";
}
if (timewindow.equals("weeks")) {
timewindow = "using weeks";
}
if (timewindow.equals("months")) {
timewindow = "using months";
}
if (timewindow.equals("years")) {
timewindow = "using years";
}
if (timewindow.equals("events")) {
timewindow = "using events";
}
// process exclude variables: create HashMap with variable:value pairs
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
if (excludeVariables.length > 0) {
for (int i = 0; i < excludeVariables.length; i++) {
ArrayList<String> values = map.get(excludeVariables[i]);
if (values == null) {
values = new ArrayList<String>();
}
if (!values.contains(excludeValues[i])) {
values.add(excludeValues[i]);
}
Collections.sort(values);
map.put(excludeVariables[i], values);
}
}
if (invertValues == true) {
Iterator<String> mapIterator = map.keySet().iterator();
while (mapIterator.hasNext()) {
String key = mapIterator.next();
ArrayList<String> values = map.get(key);
String[] labels = exportHelper.extractLabels(data.getStatements(), data.getStatements(), data.getDocuments(), key, false, statementTypeId, includeIsolates);
ArrayList<String> newValues = new ArrayList<String>();
for (int i = 0; i < labels.length; i++) {
if (!values.contains(labels[i])) {
newValues.add(labels[i]);
}
}
map.put(key, newValues);
}
}
// process document-level exclude variables using repeated calls of private function 'processExcludeDocument'
ArrayList<String> authorExclude = processExcludeDocument("author", excludeAuthors, invertAuthors, data.getStatements(), data.getStatements(),
data.getDocuments(), statementTypeId, includeIsolates);
ArrayList<String> sourceExclude = processExcludeDocument("source", excludeSources, invertSources, data.getStatements(), data.getStatements(),
data.getDocuments(), statementTypeId, includeIsolates);
ArrayList<String> sectionExclude = processExcludeDocument("section", excludeSections, invertSections, data.getStatements(), data.getStatements(),
data.getDocuments(), statementTypeId, includeIsolates);
ArrayList<String> typeExclude = processExcludeDocument("type", excludeTypes, invertTypes, data.getStatements(), data.getStatements(),
data.getDocuments(), statementTypeId, includeIsolates);
if (verbose == true) {
System.out.print("Done.\n");
}
// step 2: filter
boolean filterEmptyFields = true;
if (networkType.equals("Event list")) {
filterEmptyFields = false;
}
if (verbose == true) {
System.out.print("(2/" + max + "): Filtering statements...\n");
}
ArrayList<Statement> filteredStatements = exportHelper.filter(this.data.getStatements(), this.data.getDocuments(), start, stop, st, variable1, variable2,
variable1Document, variable2Document, qualifier, ignoreQualifier, duplicates, authorExclude, sourceExclude, sectionExclude,
typeExclude, map, filterEmptyFields, verbose);
if (verbose == true) {
System.out.print(" " + filteredStatements.size() + " out of " + data.getStatements().size() + " statements retained.\n");
}
if (!timewindow.equals("no time window") && startDate.equals("01.01.1900") && startTime.equals("00:00:00")) {
start = filteredStatements.get(0).getDate();
}
if (!timewindow.equals("no time window") && stopDate.equals("31.12.2099") && stopTime.equals("23:59:59")) {
if (timewindow.equals("using events")) {
stop = filteredStatements.get(filteredStatements.size() - 1).getDate();
} else {
GregorianCalendar stopTemp = new GregorianCalendar();
stopTemp.setTime(start);
GregorianCalendar lastDateTemp = new GregorianCalendar();
lastDateTemp.setTime(filteredStatements.get(filteredStatements.size() - 1).getDate());
while (stopTemp.before(lastDateTemp)) {
if (timewindow.equals("using seconds")) {
stopTemp.add(Calendar.SECOND, 1);
}
if (timewindow.equals("using minutes")) {
stopTemp.add(Calendar.MINUTE, 1);
}
if (timewindow.equals("using hours")) {
stopTemp.add(Calendar.HOUR, 1);
}
if (timewindow.equals("using days")) {
stopTemp.add(Calendar.DAY_OF_MONTH, 1);
}
if (timewindow.equals("using weeks")) {
stopTemp.add(Calendar.WEEK_OF_YEAR, 1);
}
if (timewindow.equals("using months")) {
stopTemp.add(Calendar.MONTH, 1);
}
if (timewindow.equals("using years")) {
stopTemp.add(Calendar.YEAR, 1);
}
}
stop = stopTemp.getTime();
}
}
// step 3: compile node labels
String[] names1 = null;
String[] names2 = null;
if (!networkType.equals("Event list")) {
if (verbose == true) {
System.out.print("(3/" + max + "): Compiling node labels... ");
}
names1 = exportHelper.extractLabels(filteredStatements, data.getStatements(), data.getDocuments(), variable1, variable1Document,
statementTypeId, includeIsolates);
names2 = exportHelper.extractLabels(filteredStatements, data.getStatements(), data.getDocuments(), variable2, variable2Document,
statementTypeId, includeIsolates);
if (verbose == true) {
System.out.print("\n " + names1.length + " entries for the first and " + names2.length + " entries for the second variable.\n");
}
}
// step 4: create matrix
if (verbose == true) {
int step = 4;
if (networkType.equals("Event list")) {
step = 3;
}
System.out.print("(" + step + "/" + max + "): Computing network matrix... ");
}
Matrix m = null;
timeWindowMatrices = null;
if (networkType.equals("Two-mode network")) {
if (timewindow.equals("no time window")) {
m = exportHelper.computeTwoModeMatrix(filteredStatements, data.getDocuments(), st, variable1, variable2, variable1Document,
variable2Document, names1, names2, qualifier, qualifierAggregation, normalization, verbose);
} else {
this.timeWindowMatrices = exportHelper.computeTimeWindowMatrices(filteredStatements, data.getDocuments(), st, variable1, variable2,
variable1Document, variable2Document, names1, names2, qualifier, qualifierAggregation, normalization, true, start, stop,
timewindow, windowsize, includeIsolates);
}
this.matrix = m;
} else if (networkType.equals("One-mode network")) {
if (timewindow.equals("no time window")) {
m = exportHelper.computeOneModeMatrix(filteredStatements, data.getDocuments(), st, variable1, variable2, variable1Document,
variable2Document, names1, names2, qualifier, qualifierAggregation, normalization);
} else {
this.timeWindowMatrices = exportHelper.computeTimeWindowMatrices(filteredStatements, data.getDocuments(), st, variable1, variable2,
variable1Document, variable2Document, names1, names2, qualifier, qualifierAggregation, normalization, false, start, stop,
timewindow, windowsize, includeIsolates);
}
this.matrix = m;
} else if (networkType.equals("Event list")) {
// convert list of filtered statements into event list in the form of an Object[], including all statement- and document-level variables
this.matrix = null;
String key, value;
Document doc;
for (int i = 0; i < filteredStatements.size(); i++) {
if (filteredStatements.get(i).getStatementTypeId() != statementTypeId) {
throw new IllegalArgumentException("More than one statement type was selected. Cannot export to a spreadsheet!");
}
}
// HashMap for fast lookup of document indices by ID
HashMap<Integer, Integer> docMap = new HashMap<Integer, Integer>();
for (int i = 0; i < data.getDocuments().size(); i++) {
docMap.put(data.getDocuments().get(i).getId(), i);
}
// Get variable names and types of current statement type
HashMap<String, String> variables = st.getVariables();
Iterator<String> keyIterator;
ArrayList<String> variableNames = new ArrayList<String>();
ArrayList<String> variableTypes = new ArrayList<String>();
keyIterator = variables.keySet().iterator();
while (keyIterator.hasNext()){
key = keyIterator.next();
value = variables.get(key);
variableNames.add(key);
variableTypes.add(value);
}
columnNames = new String[variableNames.size()];
columnTypes = new String[variableTypes.size()];
for (int i = 0; i < variableNames.size(); i++) {
columnNames[i] = variableNames.get(i);
columnTypes[i] = variableTypes.get(i);
}
// create array of columns and populate document-level and statement-level columns; leave out variables for now
eventListColumnsR = new Object[variableNames.size() + 8];
int[] ids = new int[filteredStatements.size()];
long[] time = new long[filteredStatements.size()];
int[] docId = new int[filteredStatements.size()];
String[] docTitle = new String[filteredStatements.size()];
String[] author = new String[filteredStatements.size()];
String[] source = new String[filteredStatements.size()];
String[] section = new String[filteredStatements.size()];
String[] type = new String[filteredStatements.size()];
for (int i = 0; i < filteredStatements.size(); i++) {
ids[i] = filteredStatements.get(i).getId();
time[i] = filteredStatements.get(i).getDate().getTime() / 1000; // convert milliseconds to seconds (since 1/1/1970)
docId[i] = filteredStatements.get(i).getDocumentId();
doc = data.getDocuments().get(docMap.get(docId[i]));
docTitle[i] = doc.getTitle();
author[i] = doc.getAuthor();
source[i] = doc.getSource();
section[i] = doc.getSection();
type[i] = doc.getType();
}
eventListColumnsR[0] = ids;
eventListColumnsR[1] = time;
eventListColumnsR[2] = docId;
eventListColumnsR[3] = docTitle;
eventListColumnsR[4] = author;
eventListColumnsR[5] = source;
eventListColumnsR[6] = section;
eventListColumnsR[7] = type;
// Now add the variables to the columns array
for (int i = 0; i < variableNames.size(); i++) {
if (columnTypes[i].equals("short text") || columnTypes[i].equals("long text")) {
eventListColumnsR[i + 8] = new String[filteredStatements.size()];
} else {
eventListColumnsR[i + 8] = new int[filteredStatements.size()];
}
}
for (int i = 0; i < filteredStatements.size(); i++) {
for (int j = 0; j < variableNames.size(); j++) {
if (columnTypes[j].equals("short text") || columnTypes[j].equals("long text")) {
String[] temp = ((String[]) eventListColumnsR[j + 8]);
temp[i] = (String) filteredStatements.get(i).getValues().get(columnNames[j]);
eventListColumnsR[j + 8] = temp;
} else {
int[] temp = ((int[]) eventListColumnsR[j + 8]);
temp[i] = (int) filteredStatements.get(i).getValues().get(columnNames[j]);
eventListColumnsR[j + 8] = temp;
}
}
}
}
if (verbose == true) {
if (qualifierAggregation.equals("combine")) {
System.out.print(" Done.\n");
} else {
System.out.print("Done.\n");
}
int step = 5;
if (networkType.equals("Event list")) {
step = 4;
}
System.out.println("(" + step + "/" + max + "): Retrieving results.");
}
}
/**
* Process exclude arguments for a document-level variable for R export.
*
* @param documentVariable String denoting the document-level variable for which the excludeValues should be excluded
* @param excludeValues Values to be excluded in the docuementVariable, provided as an array of Strings
* @param invert boolean indicating whether the values should be included (= true) rather than excluded
* @param statements ArrayList<String> of filtered statements
* @param originalStatements Original ArrayList<String> of statements before applying the filter
* @param documents ArrayList<Document> containing all documents in which the statements are embedded
* @param statementTypeId int ID of the statement type to which the variables belong
* @param isolates Should isolates be included in the network export?
* @return ArrayList<String> of values to be excluded
*/
private ArrayList<String> processExcludeDocument(String documentVariable, String[] excludeValues, boolean invert, ArrayList<Statement> statements,
ArrayList<Statement> originalStatements, ArrayList<Document> documents, int statementTypeId, boolean isolates) {
ArrayList<String> excludeValuesList = new ArrayList<String>();
if (excludeValues.length > 0) {
for (int i = 0; i < excludeValues.length; i++) {
excludeValuesList.add(excludeValues[i]);
}
}
ArrayList<String> exclude = new ArrayList<String>();
if (invert == false) {
exclude.addAll(excludeValuesList);
} else {
String[] labels = exportHelper.extractLabels(statements, originalStatements, data.getDocuments(), documentVariable, true, statementTypeId, isolates);
for (int i = 0; i < labels.length; i++) {
if (!excludeValuesList.contains(labels[i])) {
exclude.add(labels[i]);
}
}
}
return exclude;
}
/**
* Return variable names in this.eventListColumnsR
*
* @return array of Strings with variable names
*/
public String[] getEventListColumnsRNames() {
return columnNames;
}
/**
* Return variable types in this.eventListColumnsR
*
* @return array of Strings with variable types
*/
public String[] getEventListColumnsRTypes() {
return columnTypes;
}
/**
* Return Object[] from this.eventListColumnsR
*
* @return array of array of different data types, which represent the columns
*/
public Object[] getEventListColumnsR() {
return eventListColumnsR;
}
/**
* Return double[][] from this.matrix.
*
* @return network matrix
*/
public double[][] getMatrix() {
return matrix.getMatrix();
}
/**
* Return row names from this.matrix.
*
* @return String array of node names for the row variable.
*/
public String[] getRowNames() {
return matrix.getRownames();
}
/**
* Return column names from this.matrix.
*
* @return String array of node names for the column variable.
*/
public String[] getColumnNames() {
return matrix.getColnames();
}
/**
* Return a single matrix in this.timeWindowMatrices.
*
* @return double[][] matrix
*/
public double[][] getTimeWindowNetwork(int t) {
return this.timeWindowMatrices.get(t).getMatrix();
}
/**
* Return the row names of a single matrix in this.timeWindowMatrices.
*
* @return String[] row names
*/
public String[] getTimeWindowRowNames(int t) {
return timeWindowMatrices.get(t).getRownames();
}
/**
* Return the column names of a single matrix in this.timeWindowMatrices.
*
* @return String[] column names
*/
public String[] getTimeWindowColumnNames(int t) {
return timeWindowMatrices.get(t).getColnames();
}
/**
* Return time labels corresponding to a time window sequence.
*
* @return array of Unix times as seconds since 1/1/1970
* @throws Exception
*/
public long[] getTimeWindowTimes() throws Exception {
long[] times = new long[timeWindowMatrices.size()];
if (times.length > 0) {
for (int i = 0; i < timeWindowMatrices.size(); i++) {
times[i] = (long) (timeWindowMatrices.get(i).getDate().getTime() / 1000);
}
} else {
throw new Exception("Not a single network matrix has been generated. Does the time window size exceed the time range?");
}
return times;
}
/**
* Return numbers of statements corresponding to a time window sequence.
*
* @return array of integers representing how many statements a time window network is composed of
* @throws Exception
*/
public int[] getTimeWindowNumStatements() throws Exception {
int[] numStatements = new int[timeWindowMatrices.size()];
if (numStatements.length > 0) {
for (int i = 0; i < timeWindowMatrices.size(); i++) {
numStatements[i] = timeWindowMatrices.get(i).getNumStatements();
}
} else {
throw new Exception("Not a single network matrix has been generated. Does the time window size exceed the time range?");
}
return numStatements;
}
/* =================================================================================================================
* Functions for managing attributes
* =================================================================================================================
*/
/**
* Retrieve attributes for a specific variable defined in a statement type (here: definition for String statement type label).
*
* @param statementTypeLabel Name of the statement type in which the variable is defined. Make sure there are no duplicate names!
* @param variable Variable name for which the values and attributes should be retrieved.
* @param values An array of values to which the attributes should be limited. Useful for handing over the nodes of a network, for example.
* @return Object array containing arrays with the ID, value, color, type, alias, notes, and frequency of each entry.
*/
public Object[] getAttributes(String statementTypeLabel, String variable, String[] values) {
StatementType st = this.data.getStatementType(statementTypeLabel);
int id = -1;
if (st != null) {
id = st.getId();
}
return getAttributes(id, variable, values);
}
/**
* Retrieve attributes for a specific variable defined in a statement type (here: definition for int statement type ID).
*
* @param statementTypeId ID of the statement type in which the variable is defined.
* @param variable Variable name for which the values and attributes should be retrieved.
* @param values An array of values to which the attributes should be limited. Useful for handing over the nodes of a network, for example.
* @return Object array containing arrays with the ID, value, color, type, alias, notes, and frequency of each entry.
*/
public Object[] getAttributes(int statementTypeId, String variable, String[] values) {
if (statementTypeId == -1) {
Object[] o = new Object[7];
String[] value = new String[0];
int[] id = new int[0];
String[] color = new String[0];
String[] type = new String[0];
String[] alias = new String[0];
String[] notes = new String[0];
int[] frequency = new int[0];
o[0] = id;
o[1] = value;
o[2] = color;
o[3] = type;
o[4] = alias;
o[5] = notes;
o[6] = frequency;
System.err.println("Statement type was not found!");
return o;
}
AttributeVector[] av = this.data.getAttributes(variable, statementTypeId);
// create master list of values to be included (check if present in the file)
ArrayList<String> valuesList = new ArrayList<String>();
if (values.length < 1) {
for (int j = 0; j < av.length; j++) {
if (!av[j].getValue().equals("")) {
valuesList.add(av[j].getValue());
}
}
} else {
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < av.length; j++) {
if (values[i].equals(av[j].getValue()) && !valuesList.contains(values[i]) && !values[i].equals("")) {
valuesList.add(values[i]);
}
}
if (!valuesList.contains(values[i])) {
System.err.println("Value '" + values[i] + "' is not contained in the database and will be ignored.");
}
}
}
Collections.sort(valuesList);
// create arrays of values and other attribute metadata
String[] value = new String[valuesList.size()];
int[] id = new int[valuesList.size()];
String[] color = new String[valuesList.size()];
String[] type = new String[valuesList.size()];
String[] alias = new String[valuesList.size()];
String[] notes = new String[valuesList.size()];
int[] frequency = new int[valuesList.size()];
// populate arrays
for (int i = 0; i < valuesList.size(); i++) {
for (int j = 0; j < av.length; j++) {
if (av[j].getValue().equals(valuesList.get(i))) {
value[i] = av[j].getValue();
id[i] = av[j].getId();
color[i] = String.format("#%02X%02X%02X", av[j].getColor().getRed(), av[j].getColor().getGreen(), av[j].getColor().getBlue());
type[i] = av[j].getType();
alias[i] = av[j].getAlias();
notes[i] = av[j].getNotes();
}
}
// compute frequencies of each value
frequency[i] = 0;
for (int k = 0; k < this.data.getStatements().size(); k++) {
if (this.data.getStatements().get(k).getStatementTypeId() == statementTypeId) {
if (((String) this.data.getStatements().get(k).getValues().get(variable)).equals(value[i])) {
frequency[i] = frequency[i] + 1;
}
}
}
}
// create object array and return results
Object[] attributes = new Object[7];
attributes[0] = id;
attributes[1] = value;
attributes[2] = color;
attributes[3] = type;
attributes[4] = alias;
attributes[5] = notes;
attributes[6] = frequency;
return attributes;
}
/**
* Update the list of attributes based on an array of arrays for the attribute data.
*
* @param statementTypeLabel Statement type label for which the attributes will be updated (as a String).
* @param variable Variable name for which the attributes will be updated.
* @param attributes Array of objects containing attribute ID, value, color, type, alias, and notes.
* @param removeStatements Delete statements containing attribute values that are removed?
* @param simulate If true, changes are not actually carried out.
* @param verbose Should statistics on updating process be reported?
* @throws Exception
*/
public void setAttributes(String statementTypeLabel, String variable, Object[] attributes, boolean removeStatements, boolean simulate, boolean verbose) throws Exception {
StatementType st = this.data.getStatementType(statementTypeLabel);
int id = -1;
if (st != null) {
id = st.getId();
}
setAttributes(id, variable, attributes, removeStatements, simulate, verbose);
}
/**
* Update the list of attributes based on an array of arrays for the attribute data.
*
* @param statementTypeId Statement type ID for which the attributes will be updated.
* @param variable Variable name for which the attributes will be updated.
* @param attributes Array of objects containing attribute ID, value, color, type, alias, and notes.
* @param removeStatements Delete statements containing attribute values that are removed?
* @param simulate If true, changes are not actually carried out.
* @param verbose Should statistics on updating process be reported?
* @throws Exception
*/
public void setAttributes(int statementTypeId, String variable, Object[] attributes, boolean removeStatements, boolean simulate, boolean verbose) throws Exception {
int[] id = (int[]) attributes[0];
String[] value = (String[]) attributes[1];
String[] color = (String[]) attributes[2];
String[] type = (String[]) attributes[3];
String[] alias = (String[]) attributes[4];
String[] notes = (String[]) attributes[5];
// check for duplicate attribute values and IDs and throw exception if necessary
if (id.length > 0) {
for (int i = 0; i < id.length; i++) {
for (int j = 0; j < id.length; j++) {
if (i != j && value[i].equals(value[j])) {
throw new Exception("Duplicate attribute values are not permitted (ID " + id[i] + " and ID " + id[j] + ", value \"" + value[i] + "\").");
}
if (i != j && id[i] == id[j]) {
throw new Exception("Duplicate attribute IDs are not permitted (ID " + id[i] + " and ID " + id[j] + ").");
}
}
}
}
int updateCountValue = 0;
int updateCountColor = 0;
int updateCountType = 0;
int updateCountAlias = 0;
int updateCountNotes = 0;
int updateCountNewAttributes = 0;
int updateCountDeleted = 0;
int updateCountStatementsDeleted = 0;
int updateCountStatementsChanged = 0;
if (verbose == true) {
if (simulate == true) {
System.out.println("Simulation mode: no actual changes are made to the database!");
} else {
System.out.println("Changes will be written both in memory and to the SQL database!");
}
}
// delete attribute IDs in database that are not in the array provided by the user and update fields if the attribute ID exists and entries have changed
HashMap<String, String> valueChangeMap = new HashMap<String, String>();
ArrayList<String> deleteList = new ArrayList<String>();
ArrayList<Integer> deleteListId = new ArrayList<Integer>();
if (this.data.getAttributes(variable, statementTypeId).length > 0) {
for (int j = this.data.getAttributes(variable, statementTypeId).length - 1; j > -1; j--) {
// mark attribute in database for deletion if necessary or update fields
boolean delete = true;
if (this.data.getAttributes(variable, statementTypeId)[j].getValue().equals("")) {
delete = false;
} else if (id.length > 0) {
for (int i = 0; i < id.length; i++) {
if (this.data.getAttributes(variable, statementTypeId)[j].getId() == id[i]) {
delete = false;
if (!this.data.getAttributes(variable, statementTypeId)[j].getValue().equals(value[i])) {
updateCountValue++;
valueChangeMap.put(this.data.getAttributes(variable, statementTypeId)[j].getValue(), value[i]); // save values to be recoded in hash map
if (simulate == false) {
this.data.getAttributes(variable, statementTypeId)[j].setValue(value[i]);
this.sql.updateAttribute(id[i], "Value", value[i]);
}
}