-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathinit.py
2332 lines (1925 loc) · 110 KB
/
init.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
# -*- coding: latin-1 -*-
###############################################################################
# # Contact: [email protected]
# #
# # This file is part of the Software for Assisted Habitat Modeling package
# # for VisTrails.
# #
# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
# #
# # Although this program has been used by the U.S. Geological Survey (USGS),
# # no warranty, expressed or implied, is made by the USGS or the
# # U.S. Government as to the accuracy and functioning of the program and
# # related program material nor shall the fact of distribution constitute
# # any such warranty, and no responsibility is assumed by the USGS
# # in connection therewith.
# #
# # Any use of trade, firm, or product names is for descriptive purposes only
# # and does not imply endorsement by the U.S. Government.
###############################################################################
import csv
import os, sys
import shutil
import subprocess
import copy
import time
from vistrails.core.modules.vistrails_module import Module, ModuleError, ModuleSuspended
from vistrails.core.modules.basic_modules import File, Path, Constant
from vistrails.gui.modules.module_configure import StandardModuleConfigurationWidget
from vistrails.core.packagemanager import get_package_manager
import vistrails.core.upgradeworkflow as upgradeworkflow
UpgradeModuleRemap = upgradeworkflow.UpgradeModuleRemap
from vistrails.core import system
from PyQt4 import QtCore, QtGui
from widgets import get_predictor_widget, get_predictor_config
from SelectPredictorsLayers import SelectListDialog
from SelectAndTestFinalModel import SelectAndTestFinalModel
import utils
import GenerateModuleDoc as GenModDoc
import pySAHM.utilities as utilities
import pySAHM.FieldDataAggreagateAndWeight as FDAW
import pySAHM.MDSBuilder as MDSB
import pySAHM.PARC as parc
import pySAHM.RasterFormatConverter as RFC
import pySAHM.SpatialUtilities as SpatialUtilities
from SahmOutputViewer import ModelOutputViewer, ResponseCurveExplorer
from SahmSpatialOutputViewer import ModelMapViewer
from spatial_modules import BaseGeoViewerCell, GeoSpatialViewerCell, RasterLayer, \
VectorLayer, PolyLayer, PointLayer
from utils import writetolog
from pySAHM.utilities import TrappedError
identifier = 'gov.usgs.sahm'
doc_file = os.path.abspath(os.path.join(os.path.dirname(__file__), "documentation.xml"))
GenModDoc.load_documentation(doc_file)
def menu_items():
""" Add a menu item which allows users to specify their session directory
and select and test the final model
"""
def change_session_folder():
global session_dir
path = str(QtGui.QFileDialog.getExistingDirectory(None,
'Browse to new session folder -', utils.getrootdir()))
if path == '':
return None
session_dir = path
utils.setrootdir(path)
utils.createLogger(session_dir, True)
package_manager = get_package_manager()
package = package_manager.get_package(identifier)
configuration.set_deep_value('cur_session_folder', path)
package.persist_configuration()
writetolog("*" * 79 + "\n" + "*" * 79)
writetolog(" output directory: " + session_dir)
writetolog("*" * 79 + "\n" + "*" * 79)
def select_test_final_model():
global session_dir
STFM = SelectAndTestFinalModel(session_dir, utils.get_r_path())
retVal = STFM.exec_()
def selectProcessingMode():
selectDialog = QtGui.QDialog()
global groupBox
groupBox = QtGui.QGroupBox("Processing mode:")
vbox = QtGui.QVBoxLayout()
for mode in [("multiple models simultaneously (1 core each)", True),
("single models sequentially (n - 1 cores each)", True)]:
radio = QtGui.QRadioButton(mode[0])
radio.setChecked(mode[0] == configuration.cur_processing_mode)
radio.setEnabled(mode[1])
QtCore.QObject.connect(radio, QtCore.SIGNAL("toggled(bool)"), selectProcessingMode_changed)
vbox.addWidget(radio)
groupBox.setLayout(vbox)
layout = QtGui.QVBoxLayout()
layout.addWidget(groupBox)
selectDialog.setLayout(layout)
selectDialog.exec_()
def selectProcessingMode_changed(e):
if e:
global groupBox
qvbl = groupBox.layout()
for i in range(0, qvbl.count()):
widget = qvbl.itemAt(i).widget()
if (widget != 0) and (type(widget) is QtGui.QRadioButton):
if widget.isChecked():
package_manager = get_package_manager()
package = package_manager.get_package(identifier)
configuration.set_deep_value('cur_processing_mode', str(widget.text()))
package.persist_configuration()
utilities.start_new_pool(utilities.get_process_count(widget.text()))
lst = []
lst.append(("Change session folder", change_session_folder))
lst.append(("Change processing mode", selectProcessingMode))
lst.append(("Select and test the Final Model", select_test_final_model))
return(lst)
class SAHMDocumentedModule(object):
@classmethod
def provide_input_port_documentation(cls, port_name):
return GenModDoc.construct_port_doc(cls, port_name, 'in')
@classmethod
def provide_output_port_documentation(cls, port_name):
return GenModDoc.construct_port_doc(cls, port_name, 'out')
class SAHMPathModule(Module, SAHMDocumentedModule):
'''The base class that all Path modules in SAHM inherit from
'''
_input_ports = [('file', '(edu.utah.sci.vistrails.basic:File)', {'optional':True}), ]
def compute(self):
self.set_output('value', utils.get_relative_path(self.get_input("file"), module=self))
class FieldData(SAHMPathModule):
'''
'''
__doc__ = GenModDoc.construct_module_doc('FieldData')
_output_ports = [('value', '(gov.usgs.sahm:FieldData:DataInput)'), ]
class TemplateLayer(SAHMPathModule):
'''
'''
__doc__ = GenModDoc.construct_module_doc('TemplateLayer')
_output_ports = [('value', '(gov.usgs.sahm:TemplateLayer:DataInput)'), ]
class Predictor(Module, SAHMDocumentedModule):
'''
'''
__doc__ = GenModDoc.construct_module_doc('Predictor')
_input_ports = [('categorical', '(edu.utah.sci.vistrails.basic:Boolean)', {'optional': True}),
('ResampleMethod', '(edu.utah.sci.vistrails.basic:String)',
{'entry_types': "['enum']",
'values': "[['NearestNeighbor', 'Bilinear', 'Cubic', 'CubicSpline', 'Lanczos']]",
'defaults':'["Bilinear"]', 'optional': True}),
('AggregationMethod', '(edu.utah.sci.vistrails.basic:String)',
{'entry_types': "['enum']",
'values': "[['Mean', 'Max', 'Min', 'STD', 'Majority', 'None']]", 'optional': True,
'defaults':'["Mean"]', 'optional': True}),
('file', '(edu.utah.sci.vistrails.basic:Path)', {'optional': True})]
_output_ports = [('value', '(gov.usgs.sahm:Predictor:DataInput)'), ]
def compute(self):
if (self.has_input("ResampleMethod")):
resample_method = self.get_input("ResampleMethod")
if resample_method.lower() not in ['nearestneighbor', 'bilinear', 'cubic', 'cubicspline', 'lanczos']:
raise ModuleError(self,
"Resample Method not one of 'nearestneighbor', 'bilinear', 'cubic', 'cubicspline', or 'lanczos'")
else:
resample_method = 'Bilinear'
if (self.has_input("AggregationMethod")):
aggregation_method = self.get_input("AggregationMethod")
if self.get_input("AggregationMethod").lower() not in ['mean', 'max', 'min', 'std', 'majority', 'none']:
raise ModuleError(self, "No Aggregation Method specified")
else:
aggregation_method = "Mean"
if (self.has_input("categorical")):
if self.get_input("categorical") == True:
categorical = '1'
else:
categorical = '0'
else:
categorical = '0'
if (self.has_input("file")):
out_fname = utils.get_relative_path(self.get_input("file"), self)
inFile = utils.get_raster_name(out_fname)
else:
raise ModuleError(self, "No input file specified")
self.set_output('value', (inFile, categorical, resample_method, aggregation_method))
class PredictorList(Constant):
'''
This module is a required class for other modules and scripts within the
SAHM package. It is not intended for direct use or incorporation into
the VisTrails workflow by the user.
'''
_input_ports = [('value', '(gov.usgs.sahm:PredictorList:Other)'),
('addPredictor', '(gov.usgs.sahm:Predictor:DataInput)')]
_output_ports = [('value', '(gov.usgs.sahm:PredictorList:Other)')]
@staticmethod
def translate_to_string(v):
return str(v)
@staticmethod
def translate_to_python(v):
v_list = eval(v)
return v_list
@staticmethod
def validate(x):
return type(x) == list
def compute(self):
p_list = self.force_get_input_list("addPredictor")
v = self.force_get_input("value", [])
b = self.validate(v)
if not b:
raise ModuleError(self, "Internal Error: Constant failed validation")
if len(v) > 0 and type(v[0]) == tuple:
f_list = [utils.get_relative_path(v_elt[0], module=self) for v_elt in v]
else:
f_list = v
p_list += f_list
# self.set_output("value", p_list)
self.set_output("value", v)
class PredictorListFile(SAHMDocumentedModule, Module):
'''
copies the input predictor list csv to our working directory
and appends any additionally added predictors
'''
__doc__ = GenModDoc.construct_module_doc('PredictorListFile')
_input_ports = [('csvFileList', '(edu.utah.sci.vistrails.basic:File)', {'optional': True})]
_output_ports = [('RastersWithPARCInfoCSV', '(gov.usgs.sahm:RastersWithPARCInfoCSV:Other)')]
def compute(self):
if not self.has_input("csvFileList"):
raise ModuleError(self, "No CSV file provided")
output_file = utils.get_relative_path(self.get_input("csvFileList"), module=self)
self.set_output('RastersWithPARCInfoCSV', output_file)
# ##Internal class definitions, used for port connection enforcement
class MergedDataSet(File):
'''
This module is a required class for other modules and scripts within the
SAHM package. It is not intended for direct use or incorporation into
the VisTrails workflow by the user.
'''
_input_ports = [('mdsFile', '(edu.utah.sci.vistrails.basic:File)'), ]
_output_ports = [('value', '(gov.usgs.sahm:MergedDataSet:Other)'), ]
pass
class RastersWithPARCInfoCSV(File):
'''
This module is a required class for other modules and scripts within the
SAHM package. It is not intended for direct use or incorporation into
the VisTrails workflow by the user.
'''
_input_ports = [('mdsFile', '(edu.utah.sci.vistrails.basic:File)'), ]
_output_ports = [('value', '(gov.usgs.sahm:MergedDataSet:Other)'), ]
pass
# ##End of Internal class definitions, used for port connection enforcement
class Model(SAHMDocumentedModule, Module):
'''
This module is a required class for other modules and scripts within the
SAHM package. It is not intended for direct use or incorporation into
the VisTrails workflow by the user.
'''
_input_ports = [('ThresholdOptimizationMethod', '(edu.utah.sci.vistrails.basic:String)',
{'entry_types': "['enum']",
'values': '[["Threshold=0.5", "Sensitivity=Specificity", "Maximizes (sensitivity+specificity)/2", "Maximizes Cohen\'s Kappa","Maximizes PCC (percent correctly classified)","Predicted prevalence=observed prevalence","Threshold=observed prevalence","Mean predicted probability","Minimizes distance between ROC plot and (0,1)",]]', 'optional': True,
'defaults':'["Sensitivity=Specificity"]', 'optional':True}),
('mdsFile', '(gov.usgs.sahm:MergedDataSet:Other)'),
('makeBinMap', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["True"]', 'optional':True}),
('makeProbabilityMap', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["True"]', 'optional':True}),
('makeMESMap', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["False"]', 'optional':True}),
('outputFolderName', '(edu.utah.sci.vistrails.basic:String)', {'optional':True}),
('run_name_info', '(gov.usgs.sahm:OutputNameInfo:Other)', {'optional':False}), ]
_output_ports = [('modelWorkspace', '(edu.utah.sci.vistrails.basic:Directory)'),
('BinaryMap', '(edu.utah.sci.vistrails.basic:File)', {'optional':True}),
('ProbabilityMap', '(edu.utah.sci.vistrails.basic:File)', {'optional':True}),
('ResidualsMap', '(edu.utah.sci.vistrails.basic:File)', {'optional':True}),
('MessMap', '(edu.utah.sci.vistrails.basic:File)', {'optional':True}),
('MoDMap', '(edu.utah.sci.vistrails.basic:File)', {'optional':True}),
('modelEvalPlot', '(edu.utah.sci.vistrails.basic:File)', {'optional':True}),
('Text_Output', '(edu.utah.sci.vistrails.basic:File)', {'optional':True}),
('ModelVariableImportance', '(edu.utah.sci.vistrails.basic:File)', {'optional': True}),]
port_map = {'mdsFile':('c', None, True), # These ports are for all Models
'makeProbabilityMap':('mpt', utils.R_boolean, True),
'makeBinMap':('mbt', utils.R_boolean, True),
'makeMESMap':('mes', utils.R_boolean, True),
'ThresholdOptimizationMethod':('om', None, False),
}
def __init__(self):
self.suspended_completed = False
self.pywrapper = "runRModel.py"
self.port_map = copy.deepcopy(Model.port_map)
self.output_dname = None
Module.__init__(self)
def compute(self):
out_folder = self.force_get_input("outputFolderName", "")
self.args_dict = utils.map_ports(self, self.port_map)
mdsFile = utils.get_relative_path(self.args_dict['c'], self)
if self.has_input('run_name_info'):
runinfo = self.force_get_input('run_name_info')
if not type(runinfo) == dict:
runinfo = runinfo.contents
subfolder = runinfo.get('subfolder_name', "")
runname = runinfo.get('runname', "")
else:
subfolder, runname = utils.get_previous_run_info(mdsFile)
prefix = self.abbrev
if prefix == "ApplyModel":
prefix = "Apply"
if not os.path.isdir(self.args_dict['ws']):
orig_ws = os.path.split(self.args_dict['ws'])[0]
else:
orig_ws = self.args_dict['ws']
prefix += os.path.split(orig_ws)[1].replace('_', '').upper()
name_items = filter(None, [prefix, runname, out_folder])
prefix = "_".join(name_items)
# convert threshold optimization string to the expected integer
thresholds = {"Threshold=0.5":1,
"Sensitivity=Specificity":2,
"Maximizes (sensitivity+specificity)/2":3,
"Maximizes Cohen's Kappa":4,
"Maximizes PCC (percent correctly classified)":5,
"Predicted prevalence=observed prevalence":6,
"Threshold=observed prevalence":7,
"Mean predicted probability":8,
"Minimizes distance between ROC plot and (0,1)":9}
self.args_dict["om"] = thresholds.get(self.args_dict.get("om", "Sensitivity=Specificity"))
if not utils.checkModelCovariatenames(mdsFile):
msg = "These R models do not work with covariate names begining with non-letter characters or \n"
msg += "covariate names that contain non-alphanumeric characters other than '.' or '_'.\n"
msg += "Please check your covariate names and rename any that do not meet these constraints.\n"
msg += "Covaraiate names are found in the first line of the mds file: \n"
msg += "\t\t" + mdsFile
writetolog(msg, False, True)
raise ModuleError(self, msg)
if self.abbrev == "Maxent":
self.args_dict['maxent_path'] = configuration.maxent_path
self.args_dict['java_path'] = utils.find_java_exe(configuration.java_path)
self.args_dict['maxent_args'] = self.maxent_args
self.args_dict['rc'] = utils.MDSresponseCol(mdsFile)
self.args_dict['cur_processing_mode'] = configuration.cur_processing_mode
self.output_dname, signature, already_run = utils.make_next_file_complex(self, prefix, key_inputs=[mdsFile],
file_or_dir='dir', subfolder=subfolder)
copy_mds_fname = os.path.join(self.output_dname, os.path.split(mdsFile)[1])
if not os.path.exists(copy_mds_fname):
shutil.copyfile(mdsFile, copy_mds_fname)
expanded_output_dname = os.path.join(self.output_dname, "ExpandedOutput")
if not os.path.exists(expanded_output_dname):
os.makedirs(expanded_output_dname)
self.args_dict["c"] = copy_mds_fname
# self.output_dname = utils.find_model_dir(prefix, self.args_dict)
if self.abbrev == 'brt' or \
self.abbrev == 'rf':
if not "seed" in self.args_dict.keys():
self.args_dict['seed'] = utils.get_seed()
writetolog(" seed used for " + self.abbrev + " = " + str(self.args_dict['seed']))
self.args_dict['o'] = self.output_dname
# This give previously launched models time to finish writing their
# logs so we don't get a lock
time.sleep(0.5)
utils.write_hash_entry_pickle(signature, self.output_dname)
try:
utils.run_model_script(self.name, self.args_dict, self, self.pywrapper)
except ModuleSuspended:
raise
except:
utils.delete_hash_entry_pickle(signature)
raise
self.set_model_results()
def set_model_results(self,):
# set our output ports
# if an output is expected and we're running in syncronously then throw
# an error
if not self.args_dict.has_key('mes'):
self.args_dict['mes'] = 'FALSE'
self.outputRequired = configuration.cur_processing_mode == "single models sequentially (n - 1 cores each)"
self.setModelResult("_prob_map.tif", 'ProbabilityMap', self.abbrev)
self.setModelResult("_bin_map.tif", 'BinaryMap', self.abbrev)
self.setModelResult("_resid_map.tif", 'ResidualsMap', self.abbrev)
self.setModelResult("_mess_map.tif", 'MessMap', self.abbrev)
self.setModelResult("_MoD_map.tif", 'MoDMap', self.abbrev)
self.setModelResult("_output.txt", 'Text_Output', self.abbrev)
self.setModelResult("_modelEvalPlot.png", 'modelEvalPlot', self.abbrev)
self.setModelResult("_variable.importance.png", 'ModelVariableImportance', self.abbrev)
writetolog("Finished " + self.abbrev + " builder\n", True, True)
self.set_output("modelWorkspace", self.output_dname)
def setModelResult(self, filename, portname, abbrev):
'''sets a single output port value
'''
out_fname = os.path.join(self.output_dname, abbrev + filename)
self.set_output(portname, out_fname)
class GLM(Model):
__doc__ = GenModDoc.construct_module_doc('GLM')
_input_ports = list(Model._input_ports)
_input_ports.extend([('SelectBestPredSubset', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["True"]', 'optional':True}),
('SimplificationMethod', '(edu.utah.sci.vistrails.basic:String)', {'defaults':'["AIC"]', 'optional':True}),
('SquaredTerms', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["True"]', 'optional':True}),
])
def __init__(self):
global models_path
Model.__init__(self)
self.name = 'FIT_GLM_pluggable.r'
self.abbrev = 'glm'
self.port_map.update({'SimplificationMethod':('sm', None, False), # This is a GLM specific port
'SquaredTerms':('sqt', utils.R_boolean, False), # This is a GLM specific port
'SelectBestPredSubset':('pst', utils.R_boolean, False), # This is a GLM specific port
})
class RandomForest(Model):
__doc__ = GenModDoc.construct_module_doc('RandomForest')
_input_ports = list(Model._input_ports)
_input_ports.extend([('Seed', '(edu.utah.sci.vistrails.basic:Integer)', {'defaults':'["{}"]'.format(utils.get_seed()), 'optional':True}),
('mTry', '(edu.utah.sci.vistrails.basic:Integer)', {'defaults':'["1"]', 'optional':True}),
('nTrees', '(edu.utah.sci.vistrails.basic:Integer)', {'optional':True}),
('nodesize', '(edu.utah.sci.vistrails.basic:Integer)', {'optional':True}),
('replace', '(edu.utah.sci.vistrails.basic:Boolean)', {'optional':True}),
('maxnodes', '(edu.utah.sci.vistrails.basic:Integer)', {'optional':True}),
('importance', '(edu.utah.sci.vistrails.basic:Boolean)', {'optional':True}),
('localImp', '(edu.utah.sci.vistrails.basic:Boolean)', {'optional':True}),
('proximity', '(edu.utah.sci.vistrails.basic:Boolean)', {'optional':True}),
('oobProx', '(edu.utah.sci.vistrails.basic:Boolean)', {'optional':True}),
('normVotes', '(edu.utah.sci.vistrails.basic:Boolean)', {'optional':True}),
])
def __init__(self):
global models_path
Model.__init__(self)
self.name = 'FIT_RF_pluggable.r'
self.abbrev = 'rf'
self.port_map.update({'Seed':('seed', utils.get_seed, True), # This is a BRT specific port
'mTry': ('mtry', None, False), # This is a Random Forest specific port
'nTrees': ('ntree', None, False), # MMF 02/22/2016 - nTrees was not getting passed
'nodesize': ('nodeS', None, False), # This is a Random Forest specific port
'replace': ('sampR', utils.R_boolean, False), # This is a Random Forest specific port
'maxnodes': ('maxN', None, False), # This is a Random Forest specific port
'importance': ('impt', utils.R_boolean, False), # This is a Random Forest specific port
'localImp': ('locImp', utils.R_boolean, False), # This is a Random Forest specific port
'proximity': ('prox', utils.R_boolean, False), # This is a Random Forest specific port
'oobPorx': ('oopp', utils.R_boolean, False), # This is a Random Forest specific port
'normVotes': ('nVot', utils.R_boolean, False), # This is a Random Forest specific port
'doTrace': ('Trce', utils.R_boolean, False), # This is a Random Forest specific port
'keepForest': ('kf', utils.R_boolean, False), # This is a Random Forest specific port
})
class MARS(Model):
__doc__ = GenModDoc.construct_module_doc('MARS')
_input_ports = list(Model._input_ports)
_input_ports.extend([('MarsDegree', '(edu.utah.sci.vistrails.basic:Integer)', {'defaults':'["1"]', 'optional':True}),
('MarsPenalty', '(edu.utah.sci.vistrails.basic:Float)', {'defaults':'["2.0"]', 'optional':True}),
])
def __init__(self):
global models_path
Model.__init__(self)
self.name = 'FIT_MARS_pluggable.r'
self.abbrev = 'mars'
self.port_map.update({'MarsDegree':('deg', None, False), # This is a MARS specific port
'MarsPenalty':('pen', None, False), # This is a MARS specific port
})
class ApplyModel(Model):
__doc__ = GenModDoc.construct_module_doc('ApplyModel')
_input_ports = list(Model._input_ports)
_input_ports.insert(0, ('modelWorkspace', '(edu.utah.sci.vistrails.basic:Directory)'))
# _input_ports.insert(1, ('evaluateHoldout', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["False"]', 'optional':False}))
# _input_ports.extend([('modelWorkspace', '(edu.utah.sci.vistrails.basic:Directory)')])
def __init__(self):
global models_path
Model.__init__(self)
self.name = 'EvaluateNewData.r'
self.abbrev = 'ApplyModel'
self.port_map.update({'modelWorkspace':('ws',
lambda x: os.path.join(utils.dir_path_value(x), "modelWorkspace"), True), })
def compute(self):
# if the suplied mds has rows, observations then
# pass r code the flag to produce metrics
mdsfname = utils.get_relative_path(self.force_get_input('mdsFile'), self)
workspace = utils.get_relative_path(self.force_get_input('modelWorkspace'), self)
mdsfile = open(mdsfname, "r")
lines = mdsfile.readlines()
if len(lines) > 3:
# we have rows R will need to recreate metrics.
self.args = 'pmt=TRUE '
else:
self.args = 'pmt=FALSE '
# make sure all the covariates in the original model are in the new csv
# if not raise an exception alerting the user
orig_mds = utils.get_mdsfname(workspace)
orig_mdsfile = open(orig_mds, "r")
orig_lines = orig_mdsfile.readlines()
skip_list = ['Split', 'EvalSplit', 'Weights']
orig_covariates = [item.strip() for item in orig_lines[0].split(",")[3:]
if item.strip() not in skip_list]
orig_used = [item.strip() for item in orig_lines[1].split(",")[3:]]
missing_covariates = []
new_covariates = [item.strip() for item in lines[0].split(",")[3:]
if item.strip() not in skip_list]
for orig_covariate in orig_covariates:
i = orig_covariates.index(orig_covariate)
if orig_used[i] == "1" and \
new_covariates.count(orig_covariate) == 0:
missing_covariates.append(orig_covariate)
if len(missing_covariates) > 0:
msg = 'One or more of the covariates used in the original model are not specified in the apply model mds file\n'
msg += 'Specfically the following covariates were not found:'
msg += '\n\t'.join(missing_covariates)
raise RuntimeError(msg)
Model.compute(self)
class BoostedRegressionTree(Model):
__doc__ = GenModDoc.construct_module_doc('BoostedRegressionTree')
_input_ports = list(Model._input_ports)
_input_ports.extend([('Seed', '(edu.utah.sci.vistrails.basic:Integer)', {'defaults':'["{}"]'.format(utils.get_seed()), 'optional':True}),
('TreeComplexity', '(edu.utah.sci.vistrails.basic:Integer)', {'optional':True}),
('BagFraction', '(edu.utah.sci.vistrails.basic:Float)', {'defaults':'["0.75"]', 'optional':True}),
('NumberOfFolds', '(edu.utah.sci.vistrails.basic:Integer)', {'defaults':'["3"]', 'optional':True}),
('Alpha', '(edu.utah.sci.vistrails.basic:Float)', {'defaults':'["1"]', 'optional':True}),
('PrevalenceStratify', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["True"]', 'optional':True}),
('ToleranceMethod', '(edu.utah.sci.vistrails.basic:String)', {'defaults':'["auto"]', 'optional':True}),
('Tolerance', '(edu.utah.sci.vistrails.basic:Float)', {'defaults':'["0.001"]', 'optional':True}),
('LearningRate', '(edu.utah.sci.vistrails.basic:Float)', {'optional':True}),
('SelectBestPredSubset', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["True"]', 'optional':True}),
('NumberOfTrees', '(edu.utah.sci.vistrails.basic:Integer)', {'optional':True}),
])
def __init__(self):
global models_path
Model.__init__(self)
self.name = 'FIT_BRT_pluggable.r'
self.abbrev = 'brt'
self.port_map.update({'Seed':('seed', None, False), # This is a BRT specific port
'TreeComplexity':('tc', None, False), # This is a BRT specific port
'BagFraction':('bf', None, False), # This is a BRT specific port
'NumberOfFolds':('nf', None, False), # This is a BRT specific port
'Alpha':('alp', None, False), # This is a BRT specific port
'PrevalenceStratify':('ps', None, False), # This is a BRT specific port
'ToleranceMethod':('tolm', None, False), # This is a BRT specific port
'Tolerance':('tol', None, False), # This is a BRT specific port
'LearningRate':('lr', None, False), # This is a BRT specific port
'NumberOfTrees':('ntr', None, False), # This is a BRT specific port
'SelectBestPredSubset':('pst', utils.R_boolean, False), # This is a BRT specific port
})
class MAXENT(Model):
'''
'''
_input_ports = list(Model._input_ports)
_input_ports.extend([('UseRMetrics', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["True"]', 'optional':True}),
])
_output_ports = list(Model._output_ports)
_output_ports.extend([("lambdas", "(edu.utah.sci.vistrails.basic:File)", {'optional':True}),
("report", "(edu.utah.sci.vistrails.basic:File)", {'optional':True}),
("roc", "(edu.utah.sci.vistrails.basic:File)", {'optional':True}),])
def __init__(self):
global models_path
Model.__init__(self)
self.name = 'WrapMaxent.r'
self.pywrapper = "runMaxent.py"
self.abbrev = 'Maxent'
self.port_map.update({'species_name':('species_name', None, True), # This is a Maxent specific port
})
def compute(self):
self.maxent_args = {}
for port in self._input_ports:
if not port in list(Model._input_ports) and \
port[0] <> 'projectionlayers' and \
port[0] <> 'UseRMetrics' and \
port[0] <> 'species_name':
if self.has_input(port[0]):
port_val = self.get_input(port[0])
if port[1] == "(edu.utah.sci.vistrails.basic:Boolean)":
port_val = str(port_val).lower()
elif (port[1] == "(edu.utah.sci.vistrails.basic:Path)" or \
port[1] == "(edu.utah.sci.vistrails.basic:File)" or \
port[1] == "(edu.utah.sci.vistrails.basic:Directory)"):
port_val = port_val.name
self.maxent_args[port[0]] = port_val
else:
kwargs = port[2]
try:
if port[1] == "(edu.utah.sci.vistrails.basic:Boolean)":
default = kwargs['defaults'][1:-1].lower()
elif port[1] == "(edu.utah.sci.vistrails.basic:String)":
default = kwargs['defaults'][1:-1]
else:
default = kwargs['defaults'][1:-1]
# args[port[0]] = default
self.maxent_args[port[0]] = default[1:-1]
except KeyError:
pass
if self.has_input('projectionlayers'):
value = self.force_get_input_list('projectionlayers')
projlayers = ','.join([path.name for path in value])
self.maxent_args['projectionlayers'] = projlayers
Model.compute(self)
# set some Maxent specific outputs
self.args_dict['species_name'] = self.args_dict['species_name'].replace(' ', '_')
lambdasfile = self.args_dict["species_name"] + ".lambdas"
self.setModelResult(lambdasfile, "lambdas", "")
rocfile = "plots" + os.sep + self.args_dict["species_name"] + "_roc.png"
self.setModelResult(rocfile, "roc", "")
htmlfile = self.args_dict["species_name"] + ".html"
self.setModelResult(htmlfile, "report", "")
writetolog("Finished Maxent", True)
class UserDefinedCurve(Model):
__doc__ = GenModDoc.construct_module_doc('UserDefinedCurve')
_input_ports = list(Model._input_ports)
_input_ports.extend([("curves_json", "(edu.utah.sci.vistrails.basic:File)", {'optional':True}),])
_output_ports = list(Model._output_ports)
_output_ports.extend([("curves_json", "(edu.utah.sci.vistrails.basic:File)", {'optional':True}),])
def __init__(self):
global models_path
Model.__init__(self)
self.name = 'FIT_UDC.r'
self.pywrapper = "runRModel.py"
self.abbrev = 'udc'
self.port_map.update({'curves_json':('curves_json', None, False), # This is a Maxent specific port
})
def compute(self):
Model.compute(self)
self.setModelResult("udc.json", "curves_json", "")
writetolog("Finished UserDefinedCurves", True)
class EnsembleBuilder(SAHMDocumentedModule, Module):
'''
'''
__doc__ = GenModDoc.construct_module_doc('EnsembleBuilder')
_input_ports = [('ModelWorkspaces', '(edu.utah.sci.vistrails.basic:Directory)'),
('ThresholdMetric', '(edu.utah.sci.vistrails.basic:String)',
{'entry_types': "['enum']",
'values': '[["None", "AUC", "Percent Correctly Classified", "Sensitivity", "Specificity", "Kappa", "True Skill Statistic"]]',
'defaults':'["None"]', 'optional':True}),
('ThresholdValue', '(edu.utah.sci.vistrails.basic:Float)', {'defaults':'["0.75"]', 'optional':True}),
('run_name_info', '(gov.usgs.sahm:OutputNameInfo:Other)', {'optional':True}), ]
_output_ports = [("AverageProbability", "(edu.utah.sci.vistrails.basic:File)"),
("BinaryCount", "(edu.utah.sci.vistrails.basic:File)"),]
def compute(self):
port_map = {'ThresholdMetric': ('ThresholdMetric', None, True),
'ThresholdValue': ('ThresholdValue', None, False),
'run_name_info': ('run_name_info', None, False), }
params = utils.map_ports(self, port_map)
model_workspaces = self.get_input_list("ModelWorkspaces")
if len(model_workspaces) < 2:
raise RuntimeError('2 or more ModelWorkspaces must be supplied!')
# TODO add in check to make sure all models finished successfully
# if still running raise module suspended
workspaces = []
for model_workspace in model_workspaces:
rel_workspace = utils.get_relative_path(model_workspace, self)
if params['ThresholdMetric'] != 'None':
model_results = utils.get_model_results(rel_workspace)
param_key = params['ThresholdMetric'].replace(' ', '').lower()
if float(model_results[param_key]) >= float(params['ThresholdValue']):
workspaces.append(os.path.normpath(rel_workspace))
else:
msg = "Model below threshold, Removed from ensemble! :\n"
msg += os.path.normpath(rel_workspace)
msg += "\n model {} value of {} below threshold of {}".format(params['ThresholdMetric'], model_results[param_key], params['ThresholdValue'])
writetolog(msg, True)
else:
workspaces.append(os.path.normpath(rel_workspace))
run_name_info = params.get('run_name_info')
if run_name_info:
if not type(run_name_info) == dict:
run_name_info = run_name_info.contents
subfolder = run_name_info.get('subfolder_name', "")
runname = run_name_info.get('runname', "")
else:
# If all subfolders are the same we'll but the model output in the same subfolder
subfolders = []
for model_workspace in model_workspaces:
subfolder, runname = utils.get_previous_run_info(utils.get_relative_path(model_workspace))
subfolders.append(subfolder)
if all(x == subfolders[0] for x in subfolders):
subfolder = subfolders[0]
else:
subfolder = ''
runname = ''
prefix = "ensemble_prob"
suffix = ".tif"
prob_tifs = [os.path.join(ws, utils.find_file(ws, '_prob_map.tif')) for ws in workspaces]
bin_tifs = [os.path.join(ws, utils.find_file(ws, '_bin_map.tif')) for ws in workspaces]
output_fname, signature, already_run = utils.make_next_file_complex(self,
prefix=prefix, suffix=suffix,
key_inputs=prob_tifs,
subfolder=subfolder, runname=runname)
output_fname_bin = output_fname.replace("ensemble_prob", "ensemble_count")
if already_run:
writetolog("No change in inputs or parameters using previous run of EnsembleBuilder", True)
else:
SpatialUtilities.average_geotifs(prob_tifs, output_fname, None, False, SpatialUtilities.average_nparrays)
SpatialUtilities.average_geotifs(bin_tifs, output_fname_bin, None, False, SpatialUtilities.sum_nparrays)
if os.path.exists(utils.get_relative_path(output_fname, self)):
writetolog("Finished Ensemble generation ", True)
else:
msg = "Problem encountered building ensemble maps. Expected output file not found."
writetolog(msg, False)
raise ModuleError(self, msg)
utils.write_hash_entry_pickle(signature, output_fname)
self.set_output("AverageProbability", utils.get_relative_path(output_fname, self))
self.set_output("BinaryCount", utils.get_relative_path(output_fname_bin, self))
class BackgroundSurfaceGenerator(SAHMDocumentedModule, Module):
'''
'''
__doc__ = GenModDoc.construct_module_doc('BackgroundSurfaceGenerator')
_input_ports = [('templateLayer', '(gov.usgs.sahm:TemplateLayer:DataInput)'),
('fieldData', '(gov.usgs.sahm:FieldData:DataInput)'),
('method', '(edu.utah.sci.vistrails.basic:String)', {'defaults':'["KDE"]', 'optional':True}),
('bandwidthOptimizationMethod', '(edu.utah.sci.vistrails.basic:String)', {'defaults':'["adhoc"]', 'optional':True}),
('isopleth', '(edu.utah.sci.vistrails.basic:Integer)', {'defaults':'["95"]', 'optional':True}),
('continuous', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["False"]', 'optional':True}),
('run_name_info', '(gov.usgs.sahm:OutputNameInfo:Other)', {'optional':False}), ]
_output_ports = [("KDE", "(edu.utah.sci.vistrails.basic:File)")]
def compute(self):
port_map = {'templateLayer': ('templatefName', None, True),
'fieldData': ('fieldData', None, False),
'method': ('method', None, True),
'bandwidthOptimizationMethod': ('bandOptMeth', None, True),
'isopleth': ('isopleth', None, True),
'continuous': ('continuous', utils.R_boolean, True),
'run_name_info': ('run_name_info', None, False), }
kde_params = utils.map_ports(self, port_map)
run_name_info = kde_params.get('run_name_info')
if run_name_info:
if not type(runinfo) == dict:
runinfo = runinfo.contents
subfolder = run_name_info.get('subfolder_name', "")
runname = run_name_info.get('runname', "")
else:
subfolder, runname = utils.get_previous_run_info(kde_params['fieldData'])
global models_path
prefix = os.path.splitext(os.path.split(kde_params["fieldData"])[1])[0]
suffix = kde_params["method"]
if kde_params["method"] == "KDE":
suffix += kde_params["bandOptMeth"]
if kde_params["continuous"] == "TRUE":
suffix += "_continuous"
else:
suffix += "_iso" + str(kde_params["isopleth"])
suffix += ".tif"
output_fname, signature, already_run = utils.make_next_file_complex(self,
prefix=prefix, suffix=suffix,
key_inputs=[kde_params['fieldData'], utils.get_raster_files(kde_params['templatefName'])],
subfolder=subfolder, runname=runname)
if already_run:
writetolog("No change in inputs or parameters using previous run of BackgroundSurfaceGenerator", True)
else:
args = {"tmplt":kde_params["templatefName"],
"i":kde_params["fieldData"],
"o":output_fname,
"mth":kde_params["method"],
"bwopt":kde_params["bandOptMeth"],
"ispt":str(kde_params["isopleth"]),
"continuous":kde_params["continuous"]}
utils.run_R_script("PseudoAbs.r", args, self, new_r_path=configuration.r_path)
if os.path.exists(output_fname):
output_file = utils.get_relative_path(output_fname, module=self)
writetolog("Finished KDE generation ", True)
else:
msg = "Problem encountered generating KDE. Expected output file not found."
writetolog(msg, False)
raise ModuleError(self, msg)
utils.write_hash_entry_pickle(signature, output_fname)
self.set_output("KDE", output_file)
class OutputNameInfo(Constant):
contents = {}
@staticmethod
def translate_to_python(x):
try:
runinfo = OutputNameInfo()
runinfo.contents = {'runname':'',
'subfolder_name':str(x),
'delete_previous':False}
return runinfo
except:
return None
class OutputName(SAHMDocumentedModule, Module):
__doc__ = GenModDoc.construct_module_doc('OutputName')
_input_ports = [('run_name', '(edu.utah.sci.vistrails.basic:String)', {'defaults':'[""]', 'optional':True}),
('subfolder_name', '(edu.utah.sci.vistrails.basic:String)', {'defaults':'[""]', 'optional':True}),
('delete_previous', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["False"]', 'optional':True}), ]
_output_ports = [('run_name_info', '(gov.usgs.sahm:OutputNameInfo:Other)')]
def compute(self):
port_map = {'run_name': ('runname', None, True),
'subfolder_name': ('subfolder_name', None, True),
'delete_previous': ('delete_previous', None, True), }
name_info = utils.map_ports(self, port_map)
if not name_info.has_key('runname') and not name_info.has_key('subfolder_name'):
raise ModuleError(self, "either 'run_name' or 'subfolder_name' must be supplied")
if name_info['runname'] and not name_info['runname'].isalnum():
raise ModuleError(self, "run_name cannot contain spaces or any characters other than letters and numbers")
if name_info['delete_previous']:
# do our best to clear out any previous contents with this name
if name_info['subfolder_name'] != "":
subfolder = os.path.join(utils.getrootdir(), name_info['subfolder_name'])
shutil.rmtree(subfolder, ignore_errors=True)
if name_info['runname'] != "":
for fname in os.listdir(utils.getrootdir()):
if "_" + name_info['runname'] + "_" in fname:
fname = os.path.join(utils.getrootdir(), name_info['runname'])
os.unlink(fname)
subfolder = os.path.join(utils.getrootdir(), name_info['subfolder_name'])
if name_info['subfolder_name'] != "" and not os.path.exists(subfolder):
os.makedirs(subfolder)
self.set_output('run_name_info', name_info)
class MDSBuilder(SAHMDocumentedModule, Module):
'''
'''
__doc__ = GenModDoc.construct_module_doc('MDSBuilder')
_input_ports = [('RastersWithPARCInfoCSV', '(gov.usgs.sahm:RastersWithPARCInfoCSV:Other)'),
('fieldData', '(gov.usgs.sahm:FieldData:DataInput)'),
('backgroundPointCount', '(edu.utah.sci.vistrails.basic:Integer)', {'optional':True}),
('backgroundProbSurf', '(edu.utah.sci.vistrails.basic:File)'),
('Seed', '(edu.utah.sci.vistrails.basic:Integer)', {'defaults':'["{}"]'.format(utils.get_seed()), 'optional':True}),
('run_name_info', '(gov.usgs.sahm:OutputNameInfo:Other)', {'optional':False}), ]
_output_ports = [('mdsFile', '(gov.usgs.sahm:MergedDataSet:Other)')]
def compute(self):
port_map = {'fieldData': ('fieldData', None, False),
'backgroundPointCount': ('pointCount', None, False),
'backgroundProbSurf': ('probSurfacefName', None, False),
'Seed': ('seed', utils.get_seed, True),
'run_name_info': ('run_name_info', None, False), }
MDSParams = utils.map_ports(self, port_map)
inputs_csvs = self.force_get_input_list('RastersWithPARCInfoCSV')
if len(inputs_csvs) == 0:
raise ModuleError(self, "Must supply at least one 'RastersWithPARCInfoCSV'/nThis is the output from the PARC module")
if not type(inputs_csvs[0]) == str:
inputs_csvs = [i.name for i in inputs_csvs]
run_name_info = MDSParams.get('run_name_info')
if run_name_info:
if not type(run_name_info) == dict:
run_name_info = run_name_info.contents
subfolder = run_name_info.get('subfolder_name', "")
runname = run_name_info.get('runname', "")
else:
subfolder, runname = utils.get_previous_run_info(
MDSParams.get('fieldData', ''))
if subfolder == '' and runname == '':