forked from OpenSHAPA/openshapa
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathDatavyu_API.rb
More file actions
2889 lines (2515 loc) · 91.7 KB
/
Datavyu_API.rb
File metadata and controls
2889 lines (2515 loc) · 91.7 KB
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
# Ruby API for Datavyu
# @author Jesse Lingeman
# @author Shohan Hasan
# Please read the function headers for information on how to use them.
# Licensing information:
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require 'java'
require 'csv'
require 'time'
require 'date'
require 'set'
require 'rbconfig'
require 'matrix'
import 'org.datavyu.Datavyu'
import 'org.datavyu.models.db.DataStore'
import 'org.datavyu.models.db.MatrixCellValue'
import 'org.datavyu.models.db.NominalCellValue'
import 'org.datavyu.models.db.TextCellValue'
import 'org.datavyu.models.db.CellValue'
import 'org.datavyu.models.db.Variable'
import 'org.datavyu.models.db.Cell'
import 'org.datavyu.models.db.Argument'
import 'org.datavyu.models.project.Project'
import 'org.datavyu.controllers.SaveController'
import 'org.datavyu.controllers.OpenController'
import 'org.datavyu.controllers.project.ProjectController'
$debug = false
# Prints the specified message if global variable #debug set true.
# @param s item to print to console
# @return nil
def print_debug(*str)
p str if $debug
end
# Set $db, this is so that JRuby doesn't decide
# to overwrite it halfway thru the script.
$db = Datavyu.get_project_controller.get_data_store
$pj = Datavyu.get_project_controller.get_project
$sp = Datavyu.get_view
# Ruby representation of a spreadsheet cell.
# Generally, the two ways to get access to a cell are:
# RColumn.cells to get a list of cells from a column
# RColumn.new_cell to create a blank cell in a column.
# @!attribute ordinal
# @note Prone to change after saving the column to Datavyu.
# @return [Fixnum] ordinal number of the cell
# @!attribute onset
# @return [Fixnum] onset time of the cell in milliseconds
# @!attribute offset
# @return [Fixnum] offset time of the cell in milliseconds
# @!attribute [rw] arglist
# @note Use RColumn methods to modify column codes.
# Changing this list for the cell has no effect on the column.
# @return [Array<String>] list of codes inherited from parent column.
# @!attribute argvals
# @note Dangerous to modify this directly since the order
# of the values must match the order of the code names.
# @return [Array] list of code values
# @!attribute db_cell
# @note MODIFY AT OWN RISK.
# @return native Datavyu object corresponding to this cell.
# @!attribute parent
# @note MODIFY AT OWN RISK.
# @return [RColumn] the column this cell belongs to
class RCell
attr_accessor :ordinal, :onset, :offset, :arglist, :argvals, :db_cell, :parent
# @!visibility private
# @note This method is not for general use, it is used only when creating
# this variable from the database in the get_column method.
# Sets up methods that can be used to reference the arguments in
# the cell.
# @param argvals (required): Values of the arguments being created
# @param arglist (required): Names of the arguments being created
def set_args(argvals, arglist)
@arglist = arglist
@argvals = (argvals == '')? arglist.map{ '' } : argvals.map{ |x| x.nil?? '' : x }
# Add getter/setter methods for each code
arglist.each_with_index do |arg, i|
instance_eval "def #{arg}; return argvals[#{i}]; end"
instance_eval "def #{arg}=(val); argvals[#{i}] = val.to_s; end"
end
end
# Map the specified code names to their values.
# If no names specified, use self.arglist.
# @note Onset, offset, and ordinal are returned as Integers; all else are Strings
# @param codes [Array<String>] (optional): Names of codes.
# @return [Array] Values of specified codes.
def get_codes(*codes)
codes = self.arglist if codes.nil? || codes.empty?
codes.flatten!
vals = codes.map do |cname|
case(cname)
when 'onset'
self.onset
when 'offset'
self.offset
when 'ordinal'
self.ordinal
else
@arglist.include?(cname)? self.get_arg(cname) : raise("Failed to get the following code from cell #{self.ordinal} in column #{self.parent}: #{cname}")
end
end
return vals
end
alias :get_args :get_codes
alias :getArgs :get_codes
# Defines an alias for a code
# @!visibility private
# @param i [Integer] index of code to change
# @param new_name [String] new name for code
def change_code_name(i, new_name)
instance_eval "def #{new_name}; return argvals[#{i}]; end"
instance_eval "def #{new_name}=(val); argvals[#{i}] = val.to_s; end"
end
alias :change_arg_name :change_code_name
# Add specified code to end of arglist.
# @param new_name [String] name of new code
# @!visibility private
def add_code(new_name)
@argvals << ""
i = argvals.length - 1
instance_eval "def #{new_name}; return argvals[#{i}]; end"
instance_eval "def #{new_name}=(val); argvals[#{i}] = val.to_s; end"
end
alias :add_arg :add_code
# Removes code from arglist and associated value from argvals
# @param name [String] name of code to remove
# @return [nil]
def remove_code(name)
@argvals.delete(arglist.index(name))
@arglist.delete(name)
end
alias :remove_arg :remove_code
# Get value of a code
# @param name [String] name of code
# @return [String, Integer] value of code
def get_code(name)
if %w(onset offset ordinal).include?(name) || @arglist.include?(name)
return self.send(name)
else
raise "Cell does not have code '#{name}'"
end
# return argvals[arglist.index(name)] if arglist.include?(name)
end
alias :get_arg :get_code
# Changes the value of an argument in a cell.
# @param arg [String] name of the argument to be changed
# @param val [String, Fixnum] value to change the argument to
# @return [nil]
# @example
# trial = get_column("trial")
# trial.cells[0].change_code("onset", 1000)
# set_column(trial)
def change_code(arg, val)
if arg == "onset"
val = val.to_i if val.class == String
@onset = val
elsif arg == "offset"
val = val.to_i if val.class == String
@offset = val
elsif arg == "ordinal"
val = val.to_i if val.class == String
@ordinal = val
else
san_arg = RColumn.sanitize_codename(arg)
if self.arglist.include?(san_arg)
for i in 0..arglist.length-1
if arglist[i] == arg and not arg.nil?
argvals[i] = val.to_s
end
end
else
raise "Unable to change code '#{arg}'; no such code found."
end
end
end
alias :change_arg :change_code
# Print ordinal, onset, offset, and values of all codes in the cell to console.
# @param sep [String] separator used between the arguments
# @return [nil]
# @example Print the first cell in the 'trial' column
# trial = get_column("trial")
# puts trial.cells[0].print_all()
def print_all(sep="\t")
print @ordinal.to_s + sep + @onset.to_s + sep + @offset.to_s + sep
@arglist.each do |arg|
t = eval "self.#{arg}"
if t == nil
v = ""
else
v = t
end
print v + sep
end
end
# Check if self is nested temporally nested
# @param outer_cell [RCell]: cell to check nesting against
# @return [true, false]
# @example
# trial = get_column("trial")
# id = get_column("id")
# if trial.cells[0].is_within(id.cells[0])
# do something
# end
def is_within(outer_cell)
return (outer_cell.onset <= @onset && outer_cell.offset >= @offset && outer_cell.onset <= @offset && outer_cell.offset >= @onset)
end
# Check to see if this cell encases another cell temporally
# @param inner_cell [RCell] cell to check if contained by this cell
# @return [true, false]
# @example
# trial = get_column("trial")
# id = get_column("id")
# if id.cells[0].contains(trial.cells[0])
# do something
# end
def contains(inner_cell)
if (inner_cell.onset >= @onset && inner_cell.offset <= @offset && inner_cell.onset <= @offset && inner_cell.offset >= @onset)
return true
else
return false
end
end
# Duration of this cell (currently defined as offset minus onset)
# @return [Integer] duration of cell in ms
# @example
# duration = myCell.duration
def duration
return @offset - @onset
end
# Override method missing.
# Check if the method is trying to get/set an arg.
# If it is, define accessor method and send the method to self.
# @!visibility private
def method_missing(m, *args, &block)
mn = m.to_s
code = (mn.end_with?('=')) ? mn.chop : mn
if (@arglist.include?(code))
index = arglist.index(code)
instance_eval "def #{code}; return argvals[#{index}]; end"
instance_eval "def #{code}=(val); argvals[#{index}] = val.to_s; end"
self.send m.to_sym, *args
else
super
end
end
# Check if given time falls within this cell's [onset, offset]
# @param time time in milliseconds to check
# @return [true, false] true if the given time is greater-than-or-equal to this cell's onset and less-than-or-equal to this cell's offset
def spans(time)
(self.onset <= time) && (self.offset >= time)
end
# Check if there is any intersection between this cell and given cell
# @param cell [RCell] other cell
# @return [true, false] true if there is any temporal overlap between self and given cell
# @note If the onset of one cell is the offset of another, the two cells are considered to be overlapping.
def overlaps_cell(cell)
cell.spans(self.onset) || cell.spans(self.offset) || self.spans(cell.onset) || self.spans(cell.offset)
end
# Check if there is any intersection between this cell and given time range (inclusive).
# @param [Numeric] range time range
# @return [true, false] true if there is any temporal overlap between self and given time range
def overlaps_range(range)
dummy_cell = RCell.new
dummy_cell.onset = range.first
dummy_cell.offset = range.last
overlaps_cell(dummy_cell)
end
# Gives the intersection region between self and given cell
# @param [RCell] cell other cell
# @return [Range] time range of intersection
def overlapping_region(cell)
r = Range.new([self.onset, cell.onset].max, [self.offset, cell.offset].min)
return r
end
end
# Ruby implementation of Datavyu column.
# @!attribute name
# @return [String] name of the column
# @!attribute cells
# @return [Array<RCell>] list of cells in this column
# @!attribute arglist
# @return [Array<String>] names of codes for cell in this column, excluding onset, offset, and ordinal
# @!attribute db_var
# @note Not intended for general use. Modify at own risk.
# @return Java object for this column
# @!attribute [rw] hidden
# @return [true, false] visibility of column in spreadsheet
class RColumn
attr_accessor :name, :type, :cells, :arglist, :old_args, :dirty, :db_var, :hidden
def initialize()
self.hidden = false
end
# Validate code name. Replace non-alphanumeric characters
# with underscores and prepend an underscore if the code
# starts with a number.
# @param name string to validate
# @return [String] validated code name
# @since 1.3.6
def self.sanitize_codename(name)
sanitized = name.gsub(/(\W)+/, '').downcase
sanitized.gsub!(/(^\d{1})/, '_\\1')
sanitized
end
def convert_argname(arg)
RColumn.sanitize_codename(arg)
end
# @note This function is not for general use.
# Creates the cell object in the Variable object.
# @param newcells (required): Array of cells coming from the database via get_column
# @param arglist (required): Array of the names of the arguments from the database
def set_cells(newcells, arglist)
print_debug "Setting cells"
@cells = Array.new
@arglist = Array.new
arglist.each do |arg|
# Regex to delete any character not a-z,0-9,or _
print_debug arg
@arglist << RColumn.sanitize_codename(arg)
end
if !newcells.nil?
ord = 0
newcells.each do |cell|
ord += 1
c = RCell.new
c.onset = cell.getOnset
c.offset = cell.getOffset
c.db_cell = cell
c.parent = @name
vals = Array.new
if cell.getVariable.getRootNode.type == Argument::Type::MATRIX
for val in cell.getCellValue().getArguments
vals << val.toString
end
else
vals << cell.getCellValue().toString
end
c.set_args(vals, @arglist)
c.ordinal = ord
@cells << c
end
end
end
# Creates a new, blank cell at the end of this variable's cell array.
# If a template cell is provided, copies over onset and offset times and code values for any matching code names.
# @param cell [RCell] template cell
# @return [RCell] Reference to the cell that was just created. Modify the cell using this reference.
# @example
# trial = get_column("trial")
# new_cell = trial.new_cell()
# new_cell.onset = 1000
# set_column(trial)
def new_cell(cell = nil)
c = RCell.new
c.set_args('', @arglist)
if(cell.nil?)
c.onset = 0
c.offset = 0
c.ordinal = 0
else
c.onset = cell.onset
c.offset = cell.offset
self.arglist.each do |code|
c.change_code(code, cell.get_arg(code)) if cell.arglist.include?(code)
end
end
c.parent = @name
@cells << c
return c
end
alias :make_new_cell :new_cell
alias :create_cell :new_cell
# Sorts cells and saves column's cells by ascending onset times.
# @return nil
def sort_cells()
cells.sort! { |a, b| a.onset <=> b.onset }
end
# Changes the name of a code. Updates the name for all cells in the column
# @param old_name the name of the argument you want to change
# @param new_name the name you want to change old_name to
# @return nil
def change_code_name(old_name, new_name)
i = @old_args.index(old_name)
@old_args[i] = new_name
# Sanitize code
old_name = RColumn.sanitize_codename(old_name)
i = @arglist.index(old_name)
@arglist[i] = new_name
for cell in @cells
cell.change_code_name(i, new_name)
end
@dirty = true
end
alias :change_arg_name :change_code_name
# Add a code to this column. Updates all cells in column with new code.
# @param [String] name the name of the new code
# @return nil
def add_code(name)
@old_args << name
san_name = RColumn.sanitize_codename(name)
@arglist << san_name
for cell in @cells
cell.add_arg(san_name)
end
@dirty = true
end
alias :add_arg :add_code
# Remove a code from this column. Updates all cells in column.
# @param [String] name the name of the code to remove
# @return nil
def remove_code(name)
@old_args.delete(name)
san_name = RColumn.sanitize_codename(name)
@arglist.delete(san_name)
for cell in @cells
cell.remove_arg(san_name)
end
@dirty = true
end
alias :remove_arg :remove_code
# Set hidden state of this column
# @param value [true, false] true to hide column in spreadsheet, false to show
# @return nil
def set_hidden(value)
@hidden = value
end
# Resamples the cells of this column using given step size.
# Optionally can specify the start and end time-points.
# @param [Integer] step step size to resample with, in milliseconds
# @param [Hash] opts options
# @option opts [String] :column_name (self.name) name of returned column
# @option opts [Integer] :start_time (earliest onset) time to start resampling from, in milliseconds
# @option opts [Integer] :stop_time (latest offset) time to stop resampling at, in milliseconds
# @return [RColumn] new column with resampled cells
# @note Undefined behavior for columns whose cells overlap with each other.
# @since 1.3.6
def resample(step, opts={})
@resample_defaults = {
:column_name => self.name,
:start_time => :earliest,
:stop_time => :latest
}
opts = @resample_defaults.merge(opts)
if opts[:start_time] == :earliest
opts[:start_time] = @cells.map(&:onset).min
end
if opts[:stop_time] == :latest
opts[:stop_time] = @cells.map(&:offset).max
end
# Construct new column
ncol = new_column(opts[:column_name], self.arglist)
# Construct new cells spanning range.
( (opts[:start_time])..(opts[:stop_time]) ).step(step) do |time|
ncell = ncol.new_cell
ncell.onset = time
ncell.offset = time + step - 1
# Find overlapping cells from self in this time region
overlap_cells = self.cells.select{ |x| x.overlaps_cell(ncell) }
# if overlap_cells.empty?
# puts "no source cell for time #{time}"
# next
# end
next if overlap_cells.empty? # no source cell
# Map each to their intersecting region and find the one with the largest duration.
sorted_by_intersection = overlap_cells.sort do |x, y|
r1 = x.overlapping_region(ncell)
d1 = r1.last - r1.first
r2 = y.overlapping_region(ncell)
d2 = r2.last - r2.first
d2 <=> d1 # largest first
end
winner = sorted_by_intersection.first
ncell.arglist.each do |code|
ncell.change_code(code, winner.get_code(code))
end
# p ncol.cells.size
end
return ncol
end
end
# Patch Matrix class with setter method. See fmendez.com/blog
class Matrix
# Add setter method of form matrix[0][0] = 1
# @param row row index
# @param column column index
# @param value new value
# @return nil
def []=(row, column, value)
@rows[row][column] = value
end
end
# Class for keeping track of the agreement table for one code.
# !@attr table
# @return [Matrix] contingency table of values
# !@attr codes
# @return [Array<String>] list of code values; indices serve as keys for table
class CTable
attr_accessor :table, :codes
def initialize(*values)
raise "CTable must have at least 2 valid values. Got : #{values}" if values.size<2
@codes = values
@table = Matrix.zero(values.size)
end
# Add a code pair. Order always pri,rel. Increments the appropriate index of the table by 1.
# @param pri_value primary coder's value
# @param rel_value reliability coder's value
# @return nil
def add(pri_value, rel_value)
pri_idx = @codes.index(pri_value)
raise "Invalid primary value: #{pri_value}" if pri_idx.nil?
rel_idx = @codes.index(rel_value)
raise "Invalid reliability value: #{rel_value}" if rel_idx.nil?
@table[pri_idx, rel_idx] += 1
end
# Compute kappa
# @return simple kappa score
def kappa
agree = @table.trace
total = self.total
efs = self.efs
k = (agree-efs)/(total-efs)
return k
end
# Return the expected frequency of agreement by chance for the given index
# @param idx [Integer] index in codes
# @return [Fixnum] agreement by chance
def ef(idx)
raise "Index out of bounds: requested #{idx}, have #{@codes.size}." if idx >= @codes.size
# The expected frequency is (row_total * column_total)/matrix_total
row_total = @table.row(idx).to_a.reduce(:+)
col_total = @table.column(idx).to_a.reduce(:+)
ret = (row_total * col_total)/self.total.to_f
return ret
end
# Return the sum of the expected frequency of agreement by chance for all indices in table
# @return [Fixnum] sum of a agreement by chance
def efs
sum = 0
for idx in 0..@codes.size-1
sum += self.ef(idx).to_f
end
return sum
end
# Return the sum of all elements in matrix table
# @return [Integer] sum of matrix elements
def total
v = Matrix.row_vector([1] * @codes.size) # row vector of 1s
vt = v.t # column vector of 1s
ret = (v * @table * vt)
return ret[0,0]
end
# Table to String
# Return formatted string to display the table
# @return [String] tab-delimited string showing values in contingency table
def to_s
str = "\t" + codes.join("\t") + "\n"
for i in 0..@codes.size-1
str << @codes[i] + "\t"
for j in 0..@codes.size-1
str << @table[i,j].to_s + "\t"
end
str << "\n"
end
return str
end
end
# Compute Cohen's kappa from the given primary and reliability columns.
# @param pri_col [RColumn, String] primary coder's column
# @param rel_col [RColumn, String] reliability coder's column
# @param codes [Array<String>] codes to compute scores for
# @return [Hash<String, Fixnum>] mapping from code names to kappa values
# @return [Hash<String, Matrix>] mapping from code names to contingency tables
# @example
# primary_column_name = 'trial'
# reliability_column_name = 'trial_rel'
# codes_to_compute = ['condition', 'result']
# kappas, tables = compute_kappa(colPri, colRel, codes_to_compute)
# kappas.each_pair { |code, k| puts "#{code}: #{k}" }
def compute_kappa(pri_col, rel_col, *codes)
codes = pri_col.arglist if codes.nil? || codes.empty?
raise "No codes!" if codes.empty?
pri_col = get_column(pri_col) if pri_col.class == String
rel_col = get_column(rel_col) if rel_col.class == String
codes.flatten!
raise "Invalid parameters for getKappa()" unless (pri_col.class==RColumn && rel_col.class==RColumn)
# Get the list of observed values in each cell, per code
cells = pri_col.cells + rel_col.cells
# Build a hashmap from the list of codes to all observed values for that code
# across primary and reliability cells.
observed_values = Hash.new{ |h, k| h[k] = [] }
cells.each do |cell|
codes.each do |code|
observed_values[code] << cell.get_code(code)
end
end
# Take the unique values for each code.
# Filter out codes that do not have minimum number of required values to compute kappa.
observed_values.delete_if do |c, vs|
vs.uniq!
if vs.size < 2
puts "Cannot compute score for #{c} (less than 2 values observed): #{v.join(',')}"
true
else
false
end
end
# Init contingency tables for each code name
tables = Hash.new
observed_values.each_pair do |codename, codevalues|
tables[codename] = CTable.new(*codevalues)
end
# Get the pairs of corresponding primary and reliability cells
cellPairs = Hash.new
rel_col.cells.each do |relcell|
cellPairs[relcell] = pri_col.cells.find{ |pricell| pricell.onset == relcell.onset} # match by onset times
end
cellPairs.each_pair do |pricell, relcell|
tables.keys.each do |x|
tables[x].add(pricell.get_code(x), relcell.get_code(x))
end
end
kappas = Hash.new
tables.each_pair do |codename, ctable|
kappas[codename] = ctable.kappa
end
return kappas, tables
end
alias :computeKappa :compute_kappa
# Construct a Ruby representation of the Datavyu column, if it exists.
# @param name [String] the name of the column in the spreadsheet
# @return [RColumn] Ruby object representation of the variable inside Datavyu or nil if the named column does not exist
# @note Prints warning message to console if column name is not found in spreadsheet.
# @example
# trial = get_column("trial")
def get_column(name)
var = $db.getVariable(name)
if (var == nil)
printNoColumnFoundWarning(name.to_s)
return nil
end
# Convert each cell into an array and store in an array of arrays
cells = var.getCells()
arg_names = Array.new
# Now get the arguments for each of the cells
# For matrix vars only
type = var.getRootNode.type
if type == Argument::Type::MATRIX
# Matrix var
arg_names = Array.new
for arg in var.getRootNode.childArguments
arg_names << arg.name
end
else
# Nominal or text
arg_names = ["var"]
end
v = RColumn.new
v.name = name
v.old_args = arg_names
v.type = type
v.set_cells(cells, arg_names)
v.sort_cells
v.dirty = false
v.db_var = var
return v
end
alias :getVariable :get_column
alias :getColumn :get_column
# Translate a Ruby column object into a Datavyu column and saves it to the spreadsheet.
# If two parameters are specified, the first parameter is the name under which the column will be saved.
# @note This function will overwrite existing spreadsheet columns with the same name as specified column / name.
# @overload set_column(name, column, sanitize_codes)
# Saves column to spreadsheet with given name
# @param name [String] Name to save column as
# @param column [RColumn] Column object to save
# @param sanitize_codes [Boolean] When true, uses sanitized names for codes
# @overload set_column(column, sanitize_codes)
# @param args [String, RColumn] the name and RColumn object to save; the name parameter may be omitted
# @return nil
# @example
# trial = get_column("trial")
# ... Do some modification to trial ...
# set_column(trial)
def set_column(*args, sanitize_codes: true)
if args.length == 1
var = args[0]
name = var.name
elsif args.length == 2
var = args[1]
name = args[0]
end
# If substantial changes have been made to the structure of the column,
# just delete the whole thing first.
# If the column was dirty, redo the vocab too
if var.db_var == nil or var.db_var.get_name != name
if getColumnList().include?(name)
deleteVariable(name)
end
# Create a new variable
v = $db.createVariable(name, Argument::Type::MATRIX)
var.db_var = v
if var.arglist.length > 0
var.db_var.removeArgument("code01")
end
# Set variable's vocab
var.arglist.zip(var.old_args).each do |arg, old_arg|
new_arg = v.addArgument(Argument::Type::NOMINAL)
an = sanitize_codes ? arg : old_arg
new_arg.name = an
main_arg = var.db_var.getRootNode()
child_args = main_arg.childArguments
child_args.get(child_args.length-1).name = arg
var.db_var.setRootNode(main_arg)
end
var.db_var = v
end
#p var
if var.dirty
# deleteVariable(name)
# If the variable is dirty, then we have to do something to the vocab.
# Compare the variable's vocab and the Ruby cell version to see
# what is different.
#p var.db_var
if var.db_var.getRootNode.type == Argument::Type::MATRIX
values = var.db_var.getRootNode.childArguments
#p values
for arg in var.old_args
#p var.old_args
flag = false
for dbarg in values
if arg == dbarg.name
flag = true
break
end
end
# If we didn't find it in dbarg, we have to create it
if flag == false
# Add the argument
new_arg = var.db_var.addArgument(Argument::Type::NOMINAL)
# Make sure argument doesn't have < or > in it.
arg = arg.delete("<").delete(">")
# Change the argument's name by getting the variable back,
# and then setting it. This hoop jumping is annoying.
new_arg.name = arg
main_arg = var.db_var.getRootNode()
child_args = main_arg.childArguments
child_args.get(child_args.length-1).name = arg
var.db_var.setVariableType(main_arg)
end
end
# Now see if we have deleted any arguments
deleted_args = values.map { |x| x.name } - var.old_args
deleted_args.each do |arg|
puts "DELETING ARG: #{arg}"
var.db_var.removeArgument(arg)
end
end
end
# Create new cells and fill them in for each cell in the variable
for cell in var.cells
# Copy the information from the ruby variable to the new cell
if cell.db_cell == nil or cell.parent != name
cell.db_cell = var.db_var.createCell()
end
value = cell.db_cell.getCellValue()
if cell.onset != cell.db_cell.getOnset
cell.db_cell.setOnset(cell.onset)
end
if cell.offset != cell.db_cell.getOffset
cell.db_cell.setOffset(cell.offset)
end
# Matrix cell
if cell.db_cell.getVariable.getRootNode.type == Argument::Type::MATRIX
values = cell.db_cell.getCellValue().getArguments()
for arg in var.old_args
# Find the arg in the dataStore's arglist that we are looking for
for i in 0...values.size
dbarg = values[i]
dbarg_name = dbarg.getArgument.name
if dbarg_name == arg and not ["", nil].include?(cell.get_arg(var.convert_argname(arg)))
dbarg.set(cell.get_arg(var.convert_argname(arg)))
break
end
end
end
# Non-matrix cell
else
value = cell.db_cell.getCellValue()
value.set(cell.get_arg("var"))
end
# Save the changes back to the DB
end
# if var.hidden
var.db_var.setHidden(var.hidden)
# end
end
alias :setVariable :set_column
alias :setColumn :set_column
# Deletes a variable from the spreadsheet and rebuilds it from
# the given RColumn object.
# Behaves similar to setVariable(), but this will ALWAYS delete
# and rebuild the spreadsheet column and its vocab.
def set_column!(*args, sanitize_codes: true)
if args.length == 1
var = args[0]
name = var.name
elsif args.length == 2
var = args[1]
name = args[0]
end
var.db_var = nil
set_column(name, var, sanitize_codes: sanitize_codes)
end
alias :setVariable! :set_column!
# Create a reliability column that is a copy
# of another column in the database, copying every nth cell and
# carrying over some of the arguments from the original, if wanted.
# @param relname [String, RColumn] the name of the reliability column to be created
# @param var_to_copy [String] the name of the variable in the database you wish to copy
# @param multiple_to_keep [Integer] the number of cells to skip. For every other cell, use 2
# @param args_to_keep [Array<String>]: names of codes to keep from original column
# @return [RColumn] Ruby object representation of the rel column
# @example
# rel_trial = make_rel("rel.trial", "trial", 2, "onset", "trialnum", "unit")
def make_reliability(relname, var_to_copy, multiple_to_keep, *args_to_keep)
# Get the primary variable from the DB
if var_to_copy.class == String
var_to_copy = get_column(var_to_copy)
else
var_to_copy = get_column(var_to_copy.name)
end
if args_to_keep[0].class == Array
args_to_keep = args_to_keep[0]
end
# Clip down cells to fit multiple to keep
for i in 0..var_to_copy.cells.length-1
if multiple_to_keep == 0
var_to_copy.cells[i] = nil
elsif var_to_copy.cells[i].ordinal % multiple_to_keep != 0
var_to_copy.cells[i] = nil
else
var_to_copy.cells[i].ordinal = var_to_copy.cells[i].ordinal / multiple_to_keep
end
end
# Clear out the nil cells
var_to_copy.cells.compact!
var_to_copy.cells.each do |cell|
if !args_to_keep.include?("onset")
cell.onset = 0
end
if !args_to_keep.include?("offset")
cell.offset = 0
end
cell.arglist.each do |arg|
if !args_to_keep.include?(arg)
cell.change_code(arg, "")
end
end
end
setVariable(relname, var_to_copy)
return var_to_copy
end
alias :makeReliability :make_reliability
alias :make_rel :make_reliability