-
Notifications
You must be signed in to change notification settings - Fork 7
/
python_to_R.py
3438 lines (2854 loc) · 107 KB
/
python_to_R.py
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
##################
# #
# George Dietz #
# Byron Wallace #
# CEBM@Brown #
# #
##################
import math
from collections import OrderedDict
from ome_globals import *
import ome_globals
import rpy2
import rpy2.robjects
from rpy2 import robjects as ro
import rpy2.rlike.container as rlc
from rpy2.robjects.packages import importr
from rpy2_helper import *
base = importr('base')
debug = False
# Need this class to deal with logging R output
class RExecutor:
def __init__(self):
self.R_log_dialog = None
print("New RExecutor created")
def set_R_log_dialog(self, dialog):
self.R_log_dialog = dialog
def unset_R_log_dialog(self):
self.R_log_dialog = None
def execute_in_R(self, r_str, show_output=False, reset_wd=True):
r_cmd_header = '''
############################# Executing R command #############################
# #
'''.strip()
r_cmd_footer = '''
# #
###############################################################################
'''.strip()
try:
if (debug):
print("\n" + r_cmd_header)
print("R STATEMENT:\n%s\n" % r_str)
# send R string to logger
if self.R_log_dialog:
self.R_log_dialog.append(r_str)
res = ro.r(r_str)
if show_output:
self.R_log_dialog.append("R OUTPUT:\n%s\n" % str(res))
return res
except Exception as e:
print("Error during R command execution: %s\n" % e)
if reset_wd:
reset_Rs_working_dir()
raise CrazyRError("Some crazy R error occurred: %s" % str(e))
finally:
if (debug):
print(r_cmd_footer + "\n")
exR = RExecutor()
# ################### R Library Loader ####################
class RlibLoader:
def __init__(self):
print("R Libary loader (RlibLoader) initialized...")
def load_ape(self):
return self._load_r_lib("ape")
def load_grid(self):
return self._load_r_lib("grid")
def load_igraph(self):
return self._load_r_lib("igraph")
def load_metafor(self):
return self._load_r_lib("metafor")
def load_mice(self):
return self._load_r_lib("mice")
def load_openmeer(self):
return self._load_r_lib("openmeer")
def load_openmetar(self):
return self._load_r_lib("openmetar")
def load_rmeta(self):
return self._load_r_lib("rmeta")
def _load_r_lib(self, name):
try:
exR.execute_in_R("library(%s)" % name)
msg = "%s package successfully loaded" % name
print(msg)
return (True, msg)
except:
raise Exception("The %s R package is not installed.\nPlease \
install this package and then re-start OpenMeta." % name)
def load_all_libraries(self):
self.load_ape()
self.load_grid()
self.load_igraph()
self.load_metafor()
self.load_mice()
self.load_openmeer()
self.load_openmetar()
# self.load_rmeta()
# #################### END OF R Library Loader ####################
def load_ape_file(ape_path, tree_format):
# uses r package APE to load a tree in to object of class phylo (R object)
print("loading ape file... {0} of format {1}".format(
ape_path, tree_format))
# ext = ape_path.split(".")[-1]
# r_str = "phylo.tree <- read."
if tree_format == "caic":
print("parsing caic file")
r_str = 'read.caic("%s")' % ape_path
elif tree_format == "nexus":
print("parsing nexus file")
r_str = 'read.nexus("%s")' % ape_path
elif tree_format in ["newick", "new_hampshire"]:
print("parsing either a Newick or New Hampshire file...")
r_str = 'read.tree("%s")' % ape_path
else:
# @TODO return error message to user
print("I do not know how to parse {0} files!".format(tree_format))
raise Exception("Unrecognized tree file format")
phylo_obj = exR.execute_in_R(r_str)
# Validate tree
exR.execute_in_R("validate.tree(%s)" % phylo_obj.r_repr())
print("ok! loaded.")
return phylo_obj
def reset_Rs_working_dir():
'''
Resets R's working directory to the the application base_path,
not to r_tmp!
'''
print("resetting R working dir")
# Fix paths issue in windows
base_path = ome_globals.get_base_path()
base_path = ome_globals.to_posix_path(base_path)
print("Trying to set base_path to %s" % base_path)
r_str = "setwd('%s')" % base_path
# Executing r call with escaped backslashes
result = exR.execute_in_R(r_str)
print("Set R's working directory to %s" % base_path)
return result
def set_conf_level_in_R(conf_lev):
invalid_conf_lev_msg = "Confidence level needs to be between 0 and 100"
if conf_lev is None:
raise ValueError(invalid_conf_lev_msg)
elif not (0 < conf_lev < 100):
raise ValueError(invalid_conf_lev_msg)
r_str = "set.global.conf.level(" + str(float(conf_lev)) + ")"
new_cl_in_R = exR.execute_in_R(r_str)[0]
if (debug):
print("Set confidence level in R to: %f" % new_cl_in_R)
return new_cl_in_R
def generate_forest_plot(
file_path,
side_by_side=False,
params_name="plot.data",
):
if side_by_side:
print "generating a side-by-side forest plot..."
exR.execute_in_R("two.forest.plots(%s, '%s')" %
(params_name, file_path))
else:
conf_level = exR.execute_in_R("get.global.conf.level()")[0]
print("Confidence Level before generation: %s" % str(conf_level))
print("generating a forest plot....")
exR.execute_in_R("forest.plot(%s, '%s')" % (params_name, file_path))
def regenerate_phylo_forest_plot(
img_path,
params_name="params",
data_name="data",
res_name="res",
params_path="NULL",
level_name="level",
):
r_str = '''
regenerate_phylo_forest_plot(
plot.params={params_name},
data={data_name},
res={res_name},
level={level_name},
params.out.path=\"{params_path}\",
out.path=\"{img_path}\")
'''.format(
params_name=params_name,
data_name=data_name,
res_name=res_name,
level_name=level_name,
params_path=params_path,
img_path=img_path,
)
exR.execute_in_R(r_str)
def regenerate_funnel_plot(params_path, file_path, edited_funnel_params=None):
if edited_funnel_params:
funnel_params_r_str = unpack_r_parameters(
prepare_funnel_params_for_R(edited_funnel_params))
r_str = '''
regenerate.funnel.plot(
out.path='%s',
plot.path='%s',
edited.funnel.params=list(%s))
''' % (params_path, file_path, funnel_params_r_str)
else:
r_str = '''
regenerate.funnel.plot(
out.path='%s',
plot.path='%s')
''' % (params_path, file_path)
exR.execute_in_R(r_str)
def regenerate_exploratory_plot(
params_path,
file_path,
plot_type,
edited_params=None,
):
if plot_type == "histogram":
params_r = histogram_params_toR(
edited_params) if edited_params else None
plot_type = "HISTOGRAM"
elif plot_type == "scatterplot":
params_r = scatterplot_params_to_R(
edited_params) if edited_params else None
plot_type = "SCATTERPLOT"
else:
raise Exception("Unrecognized plot type")
if edited_params:
r_str = '''
regenerate.exploratory.plot(
out.path='%s',
plot.path='%s',
plot.type='%s',
edited.params=%s)
''' % (params_path, file_path, plot_type, params_r.r_repr())
else:
r_str = '''
regenerate.exploratory.plot(
out.path='%s',
plot.path='%s',
plot.type='%s')
''' % (params_path, file_path, plot_type)
exR.execute_in_R(r_str)
def load_in_R(fpath):
''' loads what is presumed to be .Rdata into the R environment '''
r_str = "load('%s')" % fpath
exR.execute_in_R(r_str)
def generate_reg_plot(file_path, params_name="plot.data"):
r_str = "meta.regression.plot(%s, '%s')" % (params_name, file_path)
exR.execute_in_R(r_str)
def gather_data(model, data_location, vars_given_directly=False):
'''
Gathers the relevant data in one convenient location for the purpose
of sending to R
'''
# list of studies as currently shown on the spreadsheet
studies = model.get_studies_in_current_order()
data = {}
for k, col_or_var in data_location.items():
if vars_given_directly:
var = col_or_var
else:
var = model.get_variable_assigned_to_column(col_or_var)
data[k] = [study.get_var(var) for study in studies]
data['study_labels'] = [study.get_label() for study in studies]
return data
def gather_data_for_single_study(data_location, study):
# data_location is mapping location key --> var
data = dict([(k, study.get_var(var)) for k, var in data_location.items()])
data['study_labels'] = study.get_label()
return data
def None_to_NA(value, value_type):
'''
Convert None value to an R NA object of the appropriate type.
Returns the value unchanged if it is not none
'''
if value is not None:
return value
value_type_to_NA = {
str: ro.NA_Character,
int: ro.NA_Integer,
bool: ro.NA_Logical,
float: ro.NA_Real,
complex: ro.NA_Complex,
}
return value_type_to_NA[value_type]
def keys_in_dictionary(keys, dictionary):
return set(keys) <= set(dictionary.keys())
def studies_have_raw_data(
studies,
data_type,
data_location,
model,
first_arm_only=False,
):
'''
True iff all the studies in 'studies' have 'raw' data for the currently
selected outcome. If the metric is one-arm, we only check the raw data
corresponding to that arm
'''
if data_type == MEANS_AND_STD_DEVS:
if not keys_in_dictionary(['experimental_mean',
'experimental_std_dev',
'experimental_sample_size'], data_location):
return False
columns_to_check = [data_location['experimental_mean'],
data_location['experimental_std_dev'],
data_location['experimental_sample_size'], ]
if not first_arm_only: # add additional columns to check
if not keys_in_dictionary(['control_mean',
'control_std_dev',
'control_sample_size'], data_location):
return False
columns_to_check.extend([data_location['control_mean'],
data_location['control_std_dev'],
data_location['control_sample_size'], ])
elif data_type == TWO_BY_TWO_CONTINGENCY_TABLE:
if not keys_in_dictionary(['experimental_response',
'experimental_noresponse'], data_location):
return False
columns_to_check = [data_location['experimental_response'],
data_location['experimental_noresponse'], ]
if not keys_in_dictionary(['control_response',
'control_noresponse'], data_location):
return False
columns_to_check.extend([data_location['control_response'],
data_location['control_noresponse'],
])
elif data_type == PROPORTIONS:
if not keys_in_dictionary(['experimental_response',
'experimental_noresponse'], data_location):
return False
columns_to_check = [data_location['experimental_response'],
data_location['experimental_noresponse'], ]
elif data_type == CORRELATION_COEFFICIENTS:
if not keys_in_dictionary(['correlation',
'sample_size'], data_location):
return False
columns_to_check = [data_location['correlation'],
data_location['sample_size'], ]
else:
raise Exception("Unrecognized data type")
if None in columns_to_check:
return False
variables_to_check = [model.get_variable_assigned_to_column(
col) for col in columns_to_check]
for var in variables_to_check:
values = [study.get_var(var) for study in studies]
if None in values:
return False
return True # didn't return false from for loop
def studies_have_point_estimates(studies, data_location, model):
columns_to_check = [data_location[
'effect_size'], data_location['variance']]
variables_to_check = [model.get_variable_assigned_to_column(
col) for col in columns_to_check]
for var in variables_to_check:
values = [study.get_var(var) for study in studies]
if None in values:
return False
return True # didn't return false from for loop
def dataset_to_simple_binary_robj(
model,
included_studies,
data_location,
var_name="tmp_obj",
include_raw_data=True,
covs_to_include=[],
covariate_reference_values={},
one_arm=False,
):
'''
This converts an EETableModel to an OpenMetaData (OMData) R object. We use
type EETableModel rather than a Dataset model directly to access the
current variables.
By 'simple' we mean that this method returns a single outcome single
follow-up (defined as the the currently selected, as indicated by the model
object) data object.
@TODO
- implement methods for more advanced conversions, i.e., for multiple
outcome datasets (althought this will be implemented in some other
method)
'''
r_str = None
# ####study_ids = [study.get_id() for study in included_studies]
# issue #139 -- also grab the years
# this will produce NA ints
none_to_str = lambda n: str(n) if n is not None else ""
study_years = joiner(["as.integer(%s)" % none_to_str(None)
for study in included_studies])
study_names = joiner([
'"{label}"'.format(label=study.get_label(none_to_empty_string=True))
for study in included_studies
])
ests_variable = model.get_variable_assigned_to_column(
data_location['effect_size'])
variance_variable = model.get_variable_assigned_to_column(data_location[
'variance'])
ests = [study.get_var(ests_variable) for study in included_studies]
SEs = [math.sqrt(study.get_var(variance_variable))
for study in included_studies]
ests_str = joiner(_to_strs(ests))
SEs_str = joiner(_to_strs(SEs))
cov_str = list_of_cov_value_objects_str(
studies=included_studies,
cov_list=covs_to_include,
cov_to_ref_var=covariate_reference_values,
)
# first try and construct an object with raw data
if (
include_raw_data
and studies_have_raw_data(
studies=included_studies,
data_type=TWO_BY_TWO_CONTINGENCY_TABLE,
data_location=data_location,
model=model,
first_arm_only=one_arm)
):
print "ok; raw data has been entered for all included studies"
# now figure out the raw data
g1_events_col = data_location['experimental_response']
g1_events_var = model.get_variable_assigned_to_column(g1_events_col)
g1_events = [study.get_var(g1_events_var)
for study in included_studies]
g1_no_events_col = data_location['experimental_noresponse']
g1_no_events_var = model.get_variable_assigned_to_column(
g1_no_events_col)
g1_no_events = [study.get_var(g1_no_events_var)
for study in included_studies]
g1O1_str = joiner(_to_strs(g1_events))
g1O2_str = joiner(_to_strs(g1_no_events))
# now, for group 2; we only set up the string
# for group two if we have a two-arm metric
g2O1_str, g2O2_str = "0", "0" # the 0s are just to satisfy R; not used
if not one_arm:
g2_events_col = data_location['control_response']
g2_no_events_col = data_location['control_noresponse']
g2_events_var = model.get_variable_assigned_to_column(
g2_events_col)
g2_no_events_var = model.get_variable_assigned_to_column(
g2_no_events_col)
g2_events = [study.get_var(g2_events_var)
for study in included_studies]
g2_no_events = [study.get_var(g2_no_events_var)
for study in included_studies]
g2O1_str = joiner(_to_strs(g2_events))
g2O2_str = joiner(_to_strs(g2_no_events))
# actually creating a new object on the R side seems the path of least
# resistance here. The alternative would be to try and create a
# representation of the R object on the python side, but this would
# require more work and I'm not sure what the benefits would be
r_str = '''
%s <- new(
'BinaryData',
g1O1=c(%s),
g1O2=c(%s),
g2O1=c(%s),
g2O2=c(%s),
y=c(%s),
SE=c(%s),
study.names=c(%s),
years=c(%s),
covariates=%s)
''' % (
var_name,
g1O1_str,
g1O2_str,
g2O1_str,
g2O2_str,
ests_str,
SEs_str,
study_names,
study_years,
cov_str,
)
elif studies_have_point_estimates(
studies=included_studies,
data_location=data_location,
model=model,
):
print "not sufficient raw data, but studies have point estimates..."
r_str = "%s <- new('BinaryData', y=c(%s), SE=c(%s), study.names=c(%s), years=c(%s), covariates=%s)" \
% (var_name, ests_str, SEs_str, study_names, study_years, cov_str)
else:
print " ".join([
"Cannot run analysis:",
"there is neither sufficient raw data nor entered effects/CIs."
])
# @TODO complain to the user here
# Relevant for Issue #73
# ok, it seems R uses latin-1 for its unicode encodings,
# whereas QT uses UTF8. this can cause situations where
# rpy2 throws up on this call due to it not being able
# to parse a character; so we sanitize. This isn't great,
# because sometimes characters get garbled...
r_str = _sanitize_for_R(r_str)
exR.execute_in_R(r_str)
print "ok."
print "Executed: %s" % r_str
return r_str
def dataset_to_simple_cont_robj(
model,
included_studies,
data_location,
data_type,
var_name="tmp_obj",
covs_to_include=[],
covariate_reference_values={},
one_arm=False,
generic_effect=False,
):
'''
Convert the dataset into a simple continuous R object
'''
r_str = None
study_names = [
'"{name}"'.format(
name=study.get_label(none_to_empty_string=True),
) for study in included_studies]
study_names = joiner(study_names)
# this will produce NA ints
none_to_str = lambda n: str(n) if n is not None else ""
# study_years = ", ".join([
# "as.integer(%s)" % none_to_str(None) for study in included_studies])
study_years = ["as.integer(%s)" % none_to_str(None)
for study in included_studies]
study_years = joiner(study_years)
ests_variable = model.get_variable_assigned_to_column(
data_location['effect_size'])
variance_variable = model.get_variable_assigned_to_column(
data_location['variance'],
)
ests = [study.get_var(ests_variable) for study in included_studies]
SEs = [math.sqrt(study.get_var(variance_variable))
for study in included_studies]
ests_str = joiner(_to_strs(ests))
SEs_str = joiner(_to_strs(SEs))
cov_str = list_of_cov_value_objects_str(
studies=included_studies,
cov_list=covs_to_include,
cov_to_ref_var=covariate_reference_values,
)
# first try and construct an object with raw data -- note that if
# we're using a one-armed metric for cont. data, we just use y/SE
if (
not generic_effect
and not one_arm
and studies_have_raw_data(
studies=included_studies,
data_type=data_type,
data_location=data_location,
model=model,
first_arm_only=one_arm,
)):
print "we have raw data... parsing, parsing, parsing"
print "data_location: %s" % str(data_location)
Ns1_col = data_location['experimental_sample_size']
means1_col = data_location['experimental_mean']
SDs1_col = data_location['experimental_std_dev']
Ns2_col = data_location['control_sample_size']
means2_col = data_location['control_mean']
SDs2_col = data_location['control_std_dev']
Ns1_var = model.get_variable_assigned_to_column(Ns1_col)
means1_var = model.get_variable_assigned_to_column(means1_col)
SDs1_var = model.get_variable_assigned_to_column(SDs1_col)
Ns2_var = model.get_variable_assigned_to_column(Ns2_col)
means2_var = model.get_variable_assigned_to_column(means2_col)
SDs2_var = model.get_variable_assigned_to_column(SDs2_col)
Ns1 = [study.get_var(Ns1_var) for study in included_studies]
means1 = [study.get_var(means1_var) for study in included_studies]
SDs1 = [study.get_var(SDs1_var) for study in included_studies]
Ns2 = [study.get_var(Ns2_var) for study in included_studies]
means2 = [study.get_var(means2_var) for study in included_studies]
SDs2 = [study.get_var(SDs2_var) for study in included_studies]
Ns1_str = joiner(_to_strs(Ns1))
means1_str = joiner(_to_strs(means1))
SDs1_str = joiner(_to_strs(SDs1))
Ns2_str = joiner(_to_strs(Ns2))
means2_str = joiner(_to_strs(means2))
SDs2_str = joiner(_to_strs(SDs2))
r_str = '''
%s <- new(
'ContinuousData',
N1=c(%s),
mean1=c(%s),
sd1=c(%s),
N2=c(%s),
mean2=c(%s),
sd2=c(%s),
y=c(%s),
SE=c(%s),
study.names=c(%s),
years=c(%s),
covariates=%s)
''' % (
var_name,
Ns1_str,
means1_str,
SDs1_str,
Ns2_str,
means2_str,
SDs2_str,
ests_str,
SEs_str,
study_names,
study_years,
cov_str
)
else:
print "no raw data (or one-arm)... using effects"
r_str = "%s <- new('ContinuousData', \
y=c(%s), SE=c(%s), study.names=c(%s),\
years=c(%s), covariates=%s)" \
% (var_name, ests_str, SEs_str,
study_names, study_years, cov_str)
# character encodings for R
r_str = _sanitize_for_R(r_str)
exR.execute_in_R(r_str)
print "ok."
return r_str
NUMERIC_AND_CATEGORICAL, INT_CONTINUOUS_FACTOR = range(2)
def sort_covariates_by_type(covs, sort_method=NUMERIC_AND_CATEGORICAL):
'''
Sorts covariates in to categories:
if sort_method == NUMERIC_AND_CATEGORICAL:
'numeric' and 'categorical'
elif sort_method == INT_CONTINUOUS_FACTOR:
'int', 'continuous', 'factor'
Then, within those categories, sort the covariates alphabetically
'''
label_of_cov = lambda x: x.get_label()
if sort_method == NUMERIC_AND_CATEGORICAL:
type_cov_num = [COUNT, CONTINUOUS] # Numerical covariate types
type_cov_cat = [CATEGORICAL, ] # Categorical covariate type
cov_num = [cov for cov in covs if cov.get_type() in type_cov_num]
cov_cat = [cov for cov in covs if cov.get_type() in type_cov_cat]
if len(cov_num) + len(cov_cat) != len(covs):
raise Exception("Something is wrong with the covariate types")
# sort the covariates alphabetically in each section
cov_num.sort(key=label_of_cov)
cov_cat.sort(key=label_of_cov)
return {'numeric': cov_num,
'categorical': cov_cat}
elif sort_method == INT_CONTINUOUS_FACTOR:
type_int = [COUNT, ]
type_cont = [CONTINUOUS, ] # continuous
type_factor = [CATEGORICAL, ]
cov_int = [cov for cov in covs if cov.get_type() in type_int]
cov_cont = [cov for cov in covs if cov.get_type() in type_cont]
cov_factor = [cov for cov in covs if cov.get_type() in type_factor]
if len(cov_int) + len(cov_cont) + len(cov_factor) != len(covs):
raise Exception("Something is wrong with the covariate types")
# sort the covariates alphabetically in each section
cov_int.sort(key=label_of_cov)
cov_cont.sort(key=label_of_cov)
cov_factor.sort(key=label_of_cov)
return {'int': cov_int,
'continuous': cov_cont,
'factor': cov_factor}
else:
raise Exception("Unrecognized sorting method")
def dataset_to_dataframe(
model,
included_studies,
data_location,
covariates=[],
cov_ref_values={},
var_name="tmp_obj",
):
'''
Creates an R dataframe with the portion of the dataset of interest as
specified by included_studies and covariates. Categorical variables in the
dataframe are converted to factors with referenece values set as specified
in cov_ref_values
'''
yi_var = model.get_variable_assigned_to_column(
data_location['effect_size'])
vi_var = model.get_variable_assigned_to_column(data_location['variance'])
# For issue #15 (phylogenetics) need a "species" column
include_species = "species" in data_location.keys()
if include_species:
species_var = model.get_variable_assigned_to_column(
data_location['species'])
# Gathers values of the variable from amongst the included studies
var_values = lambda x: [study.get_var(x) for study in included_studies]
# Gather data
yi = var_values(yi_var)
vi = var_values(vi_var)
slab = [study.get_label() for study in included_studies] # study labels
# Covariates sorted into 'numeric' and 'categorical' categories
sorted_covariates = sort_covariates_by_type(covariates)
# Convert covariates to R representation
def cov_to_FloatVector(cov):
values = var_values(cov)
# convert Nones to NA
values = [None_to_NA(x, float) for x in values]
return ro.FloatVector(values)
def cov_to_Factor(cov):
ref_value = cov_ref_values[cov] if cov in cov_ref_values else None
values = var_values(cov)
values = [None_to_NA(x, str) for x in values]
levels = list(set(values))
levels.sort()
if ref_value:
# stick ref_value at the beginning
levels.remove(ref_value)
levels = [ref_value, ] + levels
rfactor = ro.FactorVector(values, levels=ro.StrVector(levels))
return rfactor
numeric_covs = dict([(cov.get_label(), cov_to_FloatVector(cov))
for cov in sorted_covariates['numeric']])
cat_covs = dict([(cov.get_label(), cov_to_Factor(cov))
for cov in sorted_covariates['categorical']])
if include_species:
# species covariate as an R-format factor
species_rcov = cov_to_Factor(species_var)
# Inhibit transformation of vectors upon insertion into dataframe
for name, rvector in numeric_covs.iteritems():
numeric_covs[name] = base.I(rvector)
for name, rvector in cat_covs.iteritems():
cat_covs[name] = base.I(rvector)
cov_labels = numeric_covs.keys() + cat_covs.keys()
if ('yi' in cov_labels) or ('vi' in cov_labels):
raise Exception("Forbidden covariate label present")
init_dict = {
'slab': base.I(ro.StrVector(slab)),
'yi': ro.FloatVector(yi),
'vi': ro.FloatVector(vi),
}
if include_species:
init_dict['species'] = species_rcov
init_dict.update(numeric_covs)
init_dict.update(cat_covs)
dataf = ro.DataFrame(init_dict)
# Only put the dataframe into the workspace if var_name is not None
if var_name:
exR.execute_in_R("%s<-%s" % (var_name, dataf.r_repr())
) # create dataframe in r workspace
return dataf
def dataset_to_simple_fsn_data_robj(
model,
included_studies,
data_location,
var_name="tmp_obj",
):
'''
Package dataset for use with failsafe.wrapper() in R
'''
ests_variable = model.get_variable_assigned_to_column(
data_location['effect_size'])
variance_variable = model.get_variable_assigned_to_column(
data_location['variance'],
)
ests = [study.get_var(ests_variable) for study in included_studies]
variances = [
study.get_var(variance_variable) for study in included_studies]
ests_str = joiner(_to_strs(ests))
variances_str = joiner(_to_strs(variances))
r_str = "%s <- data.frame(yi=c(%s), vi=c(%s))" % (
var_name,
ests_str,
variances_str,
)
# character encodings for R
r_str = _sanitize_for_R(r_str)
exR.execute_in_R(r_str)
print "ok."
return r_str
def run_failsafe_analysis(
model,
included_studies,
data_location,
failsafe_params,
res_name="result",
var_name="tmp_obj",
r_str=None
):
if r_str is None:
make_dataset_r_str = dataset_to_simple_fsn_data_robj(
model,
included_studies,
data_location,
var_name=var_name,
)
# build-up failsafe parameters string
params_as_strs = []
for param, val in failsafe_params.items():
rkey, rval = param, str(val)
if param == "method":
rkey = "type"
rval = '"%s"' % val
if param == "target" and val == "":
rval = 'NULL'
params_as_strs.append("%s=%s" % (rkey, rval))
r_str = "%s <- failsafe.wrapper(%s, %s)" % (
res_name,
var_name,
", ".join(params_as_strs),
)
exR.execute_in_R(r_str)
result = exR.execute_in_R("%s" % res_name)
return parse_out_results(result)
def run_dynamic_data_exploration_analysis(
model,
included_studies,
data_location,
analysis_details,
res_name="result",
var_name="tmp_obj",
):
dataset_to_dataframe(
model=model,
included_studies=included_studies,
data_location=data_location,
var_name=var_name,
)
return _run_dynamic_data_exploration_analysis(
analysis_details=analysis_details,
res_name="result",
var_name="tmp_obj",
)
def _run_dynamic_data_exploration_analysis(