forked from ColinTalbert/sahm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.py
More file actions
2421 lines (2043 loc) · 112 KB
/
init.py
File metadata and controls
2421 lines (2043 loc) · 112 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
# -*- coding: latin-1 -*-
###############################################################################
##
## Copyright (C) 2010-2012, USGS Fort Collins Science Center.
## All rights reserved.
## Contact: talbertc@usgs.gov
##
## This file is part of the Software for Assisted Habitat Modeling package
## for VisTrails.
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##
## - Redistributions of source code must retain the above copyright notice,
## this list of conditions and the following disclaimer.
## - Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## - Neither the name of the University of Utah nor the names of its
## contributors may be used to endorse or promote products derived from
## this software without specific prior written permission.
##
## 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
from datetime import datetime
import glob
import itertools
import os
import shutil
import sys
import subprocess
import traceback
import random
import copy
import multiprocessing
import time
import core.system
from core.modules.vistrails_module import Module, ModuleError, ModuleConnector
from core.modules.basic_modules import File, Directory, Path, new_constant, Constant
from packages.spreadsheet.basic_widgets import SpreadsheetCell, CellLocation
from packages.spreadsheet.spreadsheet_cell import QCellWidget, QCellToolBar
from core.modules.module_configure import StandardModuleConfigurationWidget
from core.modules.basic_modules import String
from core.packagemanager import get_package_manager
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 our python SAHM Processing files
import pySAHM.FieldDataAggreagateAndWeight as FDAW
import pySAHM.MDSBuilder as MDSB
import pySAHM.MDSBuilder_vector as MDSB_V
import pySAHM.PARC as parc
import pySAHM.RasterFormatConverter as RFC
import pySAHM.runMaxent as MaxentRunner
import pySAHM.utilities as utilities
from SahmOutputViewer import SAHMModelOutputViewerCell
from SahmSpatialOutputViewer import SAHMSpatialOutputViewerCell
from GeneralSpatialViewer import GeneralSpatialViewer
from sahm_picklists import ResponseType, AggregationMethod, \
ResampleMethod, PointAggregationMethod, ModelOutputType, RandomPointType, \
OutputRaster, mpl_colormap, T_O_M
from utils import writetolog
from pySAHM.utilities import TrappedError
global utilities
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
if configuration.cur_processing_mode == "FORT Condor" and \
not utilities.checkIfFolderIsOnNetwork(path):
return None
session_dir = path
utils.setrootdir(path)
utils.createLogger(session_dir, True)
configuration.cur_session_folder = path
package_manager = get_package_manager()
package = package_manager.get_package(identifier)
dom, element = package.find_own_dom_element()
configuration.write_to_dom(dom, element)
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),
("FORT Condor", isFortCondorAvailible())]:
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():
configuration.cur_processing_mode = str(widget.text())
package_manager = get_package_manager()
package = package_manager.get_package(identifier)
dom, element = package.find_own_dom_element()
if configuration.cur_processing_mode == "FORT Condor":
if not utilities.checkIfFolderIsOnNetwork(configuration.cur_session_folder):
widget = qvbl.itemAt(i - 1).widget()
widget.setChecked(True)
return
configuration.write_to_dom(dom, element)
utilities.start_new_pool(utilities.get_process_count(widget.text()))
def isFortCondorAvailible():
try:
cmd = ["condor_store_cred", "-n", "IGSKBACBWSCDRS3", "query"]
p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
ret = p.communicate()
return ret[0].find("A credential is stored and is valid") != -1
except:
return False
def checkAsyncModels():
utils.launch_RunMonitorApp()
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))
lst.append(("Check Asynchronous model runs", checkAsyncModels))
return(lst)
#
#def expand_ports(port_list):
# new_port_list = []
# for port in port_list:
# port_spec = port[1]
# if type(port_spec) == str: # or unicode...
# if port_spec.startswith('('):
# port_spec = port_spec[1:]
# if port_spec.endswith(')'):
# port_spec = port_spec[:-1]
# new_spec_list = []
# for spec in port_spec.split(','):
# spec = spec.strip()
# parts = spec.split(':', 1)
## print 'parts:', parts
# namespace = None
# if len(parts) > 1:
# mod_parts = parts[1].rsplit('|', 1)
# if len(mod_parts) > 1:
# namespace, module_name = mod_parts
# else:
# module_name = parts[1]
# if len(parts[0].split('.')) == 1:
# id_str = 'edu.utah.sci.vistrails.' + parts[0]
# else:
# id_str = parts[0]
# else:
# mod_parts = spec.rsplit('|', 1)
# if len(mod_parts) > 1:
# namespace, module_name = mod_parts
# else:
# module_name = spec
# id_str = identifier
# if namespace:
# new_spec_list.append(id_str + ':' + module_name + ':' + \
# namespace)
# else:
# new_spec_list.append(id_str + ':' + module_name)
# port_spec = '(' + ','.join(new_spec_list) + ')'
# new_port_list.append((port[0], port_spec) + port[2:])
## print new_port_list
# return new_port_list
class FieldData(Path):
'''
'''
__doc__ = GenModDoc.construct_module_doc('FieldData')
# _input_ports = [('csvFile', '(edu.utah.sci.vistrails.basic:File)')]
_output_ports = [('value', '(gov.usgs.sahm:FieldData:DataInput)'),
('value_as_string', '(edu.utah.sci.vistrails.basic:String)', True)]
@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')
def compute(self):
out_fname = utils.getFileRelativeToCurrentVT(self.getInputFromPort("value").name, self)
output_file = utils.create_file_module(out_fname, module=self)
self.setResult('value', output_file)
class Predictor(Constant):
'''
'''
__doc__ = GenModDoc.construct_module_doc('Predictor')
_input_ports = [('categorical', '(edu.utah.sci.vistrails.basic:Boolean)'),
('ResampleMethod', '(gov.usgs.sahm:ResampleMethod:Other)', {'defaults':'["Bilinear"]'}),
('AggregationMethod', '(gov.usgs.sahm:AggregationMethod:Other)', {'defaults':'["Mean"]'}),
('file', '(edu.utah.sci.vistrails.basic:Path)')]
_output_ports = [('value', '(gov.usgs.sahm:Predictor:DataInput)'),
('value_as_string', '(edu.utah.sci.vistrails.basic:String)', True)]
@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')
def compute(self):
if (self.hasInputFromPort("ResampleMethod")):
resampleMethod = self.getInputFromPort("ResampleMethod")
if resampleMethod.lower() not in ['nearestneighbor', 'bilinear', 'cubic', 'cubicspline', 'lanczos']:
raise ModuleError(self,
"Resample Method not one of 'nearestneighbor', 'bilinear', 'cubic', 'cubicspline', or 'lanczos'")
else:
resampleMethod = 'Bilinear'
if (self.hasInputFromPort("AggregationMethod")):
aggregationMethod = self.getInputFromPort("AggregationMethod")
if self.getInputFromPort("AggregationMethod").lower() not in ['mean', 'max', 'min', 'std', 'majority', 'none']:
raise ModuleError(self, "No Aggregation Method specified")
else:
aggregationMethod = "Mean"
if (self.hasInputFromPort("categorical")):
if self.getInputFromPort("categorical") == True:
categorical = '1'
else:
categorical = '0'
else:
categorical = '0'
if (self.hasInputFromPort("file")):
out_fname = utils.getFileRelativeToCurrentVT(self.getInputFromPort("file").name, self)
inFile = utils.getRasterName(out_fname)
else:
raise ModuleError(self, "No input file specified")
self.setResult('value', (inFile, categorical, resampleMethod, aggregationMethod))
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.forceGetInputListFromPort("addPredictor")
v = self.forceGetInputFromPort("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.create_file_module(v_elt[0], module=self) for v_elt in v]
else:
f_list = v
p_list += f_list
#self.setResult("value", p_list)
self.setResult("value", v)
class PredictorListFile(Module):
'''
'''
__doc__ = GenModDoc.construct_module_doc('PredictorListFile')
_input_ports = [('csvFileList', '(edu.utah.sci.vistrails.basic:File)'),
('predictor', "(gov.usgs.sahm:Predictor:DataInput)")]
_output_ports = [('RastersWithPARCInfoCSV', '(gov.usgs.sahm:RastersWithPARCInfoCSV:Other)')]
#copies the input predictor list csv to our working directory
#and appends any additionally added predictors
@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')
@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):
if not (self.hasInputFromPort("csvFileList") or
self.hasInputFromPort("addPredictor")):
raise ModuleError(self, "No inputs or CSV file provided")
output_fname = utils.mknextfile(prefix='PredictorList_', suffix='.csv')
if self.hasInputFromPort("csvFileList"):
csv_input = utils.getFileRelativeToCurrentVT(self.getInputFromPort("csvFileList").name, self)
if os.path.exists(csv_input):
shutil.copy(csv_input, output_fname)
output_file = open(output_fname, 'ab')
csv_writer = csv.writer(output_file)
else:
#create an empty file to start with.
output_file = open(output_fname, 'wb')
csv_writer = csv.writer(output_file)
csv_writer.writerow(["file", "Resampling", "Aggregation"])
else:
#create an empty file to start with.
output_file = open(output_fname, 'wb')
csv_writer = csv.writer(output_file)
csv_writer.writerow(["file", "Resampling", "Aggregation"])
if self.hasInputFromPort("addPredictor"):
p_list = self.forceGetInputListFromPort("addPredictor")
for p in p_list:
if p.hasInputFromPort('resampleMethod'):
resMethod = p.getInputFromPort('resampleMethod')
else:
resMethod = "NearestNeighbor"
if p.hasInputFromPort('aggregationMethod'):
aggMethod = p.getInputFromPort('aggregationMethod')
else:
aggMethod = "Mean"
csv_writer.writerow([os.path.normpath(p.name), resMethod, aggMethod])
output_file.close()
del csv_writer
output_file = utils.create_file_module(output_fname, module=self)
self.setResult('RastersWithPARCInfoCSV', output_file)
class TemplateLayer(Path):
'''
'''
__doc__ = GenModDoc.construct_module_doc('TemplateLayer')
# _input_ports = [('FilePath', '(edu.utah.sci.vistrails.basic:File)')]
_output_ports = [('value', '(gov.usgs.sahm:TemplateLayer:DataInput)'),
('value_as_string', '(edu.utah.sci.vistrails.basic:String)', True)]
@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')
def compute(self):
out_fname = utils.getFileRelativeToCurrentVT(self.getInputFromPort("value").name, self)
output_file = utils.create_file_module(out_fname, module=self)
self.setResult('value', output_file)
#class SingleInputPredictor(Predictor):
# pass
#
#class SpatialDef(Module):
# _output_ports = [('spatialDef', '(gov.usgs.sahm:SpatialDef:DataInput)')]
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
class Model(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', '(gov.usgs.sahm:T_O_M:Other)', {'defaults':'["Sensitivity=Specificity"]', 'optional':False}),
('mdsFile', '(gov.usgs.sahm:MergedDataSet:Other)'),
('makeBinMap', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["True"]', 'optional':False}),
('makeProbabilityMap', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["True"]', 'optional':False}),
('makeMESMap', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["False"]', 'optional':False}),
('outputFolderName', '(edu.utah.sci.vistrails.basic:String)'),]
_output_ports = [('modelWorkspace', '(edu.utah.sci.vistrails.basic:Directory)'),
('BinaryMap', '(edu.utah.sci.vistrails.basic:File)'),
('ProbabilityMap', '(edu.utah.sci.vistrails.basic:File)'),
('ResidualsMap', '(edu.utah.sci.vistrails.basic:File)'),
('MessMap', '(edu.utah.sci.vistrails.basic:File)'),
('MoDMap', '(edu.utah.sci.vistrails.basic:File)'),
('modelEvalPlot', '(edu.utah.sci.vistrails.basic:File)'),
('Text_Output', '(edu.utah.sci.vistrails.basic:File)'),
('ModelVariableImportance', '(edu.utah.sci.vistrails.basic:File)')]
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),
}
@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')
def __init__(self):
self.suspended_completed = False
self.pywrapper = "runRModel.py"
self.port_map = copy.deepcopy(Model.port_map)
Module.__init__(self)
def compute(self):
out_folder = self.forceGetInputFromPort("outputFolderName", "")
prefix = self.abbrev + ("_" + out_folder + "_" if out_folder else "_")
self.args_dict = utils.map_ports(self, self.port_map)
mdsFile = utils.getFileRelativeToCurrentVT(self.args_dict['c'], self)
#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":
global maxent_path
self.args_dict['maxent_path'] = maxent_path
self.args_dict['maxent_args'] = self.maxent_args
self.output_dname = utils.mknextdir(prefix)
#make a copy of the mds file used in the output folder
copy_mds_fname = os.path.join(self.output_dname, os.path.split(mdsFile)[1])
shutil.copyfile(mdsFile, copy_mds_fname)
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'] = random.randint(-1 * ((2**32)/2 - 1), (2**32)/2 - 1)
writetolog(" seed used for " + self.abbrev + " = " + str(self.args_dict['seed']))
self.args_dict['o'] = self.output_dname
self.args_dict['rc'] = utils.MDSresponseCol(mdsFile)
self.args_dict['cur_processing_mode'] = configuration.cur_processing_mode
#This give previously launched models time to finish writing their
#logs so we don't get a lock
time.sleep(2)
utils.run_model_script(self.name, self.args_dict, self, self.pywrapper)
utils.launch_RunMonitorApp()
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.jpg", 'modelEvalPlot', self.abbrev)
self.setModelResult("_variable.importance.jpg", 'ModelVariableImportance', self.abbrev)
writetolog("Finished " + self.abbrev + " builder\n", True, True)
modelWorkspace = utils.create_dir_module(self.output_dname)
self.setResult("modelWorkspace", modelWorkspace)
def setModelResult(self, filename, portname, abbrev):
'''sets a single output port value
'''
outFileName = os.path.join(self.output_dname, abbrev + filename)
output_file = File()
output_file.name = outFileName
output_file.upToDate = True
self.setResult(portname, output_file)
class GLM(Model):
__doc__ = GenModDoc.construct_module_doc('GLM')
_input_ports = list(Model._input_ports)
_input_ports.extend([('UsePseudoAbs', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["False"]', 'optional':False}),
('SimplificationMethod', '(edu.utah.sci.vistrails.basic:String)', {'defaults':'["AIC"]', 'optional':True}),
('SquaredTerms', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["False"]', '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
})
class RandomForest(Model):
__doc__ = GenModDoc.construct_module_doc('RandomForest')
_input_ports = list(Model._input_ports)
_input_ports.extend([('UsePseudoAbs', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["False"]', 'optional':False}),
('Seed', '(edu.utah.sci.vistrails.basic:Integer)', {'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', None, False), #This is a BRT specific port
'mTry': ('mtry', None, False), #This is a Random Forest specific port
'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([('UsePseudoAbs', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["False"]', 'optional':False}),
('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.getFileRelativeToCurrentVT(self.forceGetInputFromPort('mdsFile').name, self)
mdsfile = open(mdsfname, "r")
lines = 0
readline = mdsfile.readline
while readline():
lines += 1
if lines > 4:
break
if lines > 3:
#we have rows R will need to recreate metrics.
self.args = 'pmt=TRUE '
else:
self.args = 'pmt=FALSE '
Model.compute(self)
class BoostedRegressionTree(Model):
__doc__ = GenModDoc.construct_module_doc('BoostedRegressionTree')
_input_ports = list(Model._input_ports)
_input_ports.extend([('UsePseudoAbs', '(edu.utah.sci.vistrails.basic:Boolean)', {'defaults':'["False"]', 'optional':False}),
('Seed', '(edu.utah.sci.vistrails.basic:Integer)', {'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}),
('MaximumTrees', '(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
'MaximumTrees':('mt', None, 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)"),
("report", "(edu.utah.sci.vistrails.basic:File)"),
("roc", "(edu.utah.sci.vistrails.basic:File)")])
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.hasInputFromPort(port[0]):
port_val = self.getInputFromPort(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.hasInputFromPort('projectionlayers'):
value = self.forceGetInputListFromPort('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 BackgroundSurfaceGenerator(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})]
_output_ports = [("KDE", "(edu.utah.sci.vistrails.basic:File)")]
@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')
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)}
kde_params = utils.map_ports(self, port_map)
global models_path
outfName = os.path.splitext(os.path.split(kde_params["fieldData"])[1])[0]
outfName += "_" + kde_params["method"]
if kde_params["method"] == "KDE":
outfName += "_" + kde_params["bandOptMeth"]
if kde_params["continuous"] == "TRUE":
outfName += "_continuous"
else:
outfName += "_iso" + str(kde_params["isopleth"])
outputfName = os.path.join(utils.getrootdir(), outfName + ".tif")
if os.path.exists(outputfName):
os.unlink(outputfName)
args = {"tmplt":kde_params["templatefName"],
"i":kde_params["fieldData"],
"o":outputfName,
"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(outputfName):
output_file = utils.create_file_module(outputfName, 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)
self.setResult("KDE", output_file)
class MDSBuilder(Module):
'''
'''
__doc__ = GenModDoc.construct_module_doc('MDSBuilder')
_input_ports = [('RastersWithPARCInfoCSV', '(gov.usgs.sahm:RastersWithPARCInfoCSV:Other)'),
('fieldData', '(gov.usgs.sahm:FieldData:DataInput)'),
# ('backgroundPointType', '(gov.usgs.sahm:RandomPointType:Other)', {'defaults':'["Background"]'}),
('backgroundPointCount', '(edu.utah.sci.vistrails.basic:Integer)'),
('backgroundProbSurf', '(edu.utah.sci.vistrails.basic:File)'),
('Seed', '(edu.utah.sci.vistrails.basic:Integer)')]
_output_ports = [('mdsFile', '(gov.usgs.sahm:MergedDataSet:Other)')]
@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')
def compute(self):
port_map = {'fieldData': ('fieldData', None, False),
# 'backgroundPointType': ('pointType', None, False),
'backgroundPointCount': ('pointCount', None, False),
'backgroundProbSurf': ('probSurfacefName', None, False),
'Seed': ('seed', None, False)}
MDSParams = utils.map_ports(self, port_map)
MDSParams['outputMDS'] = utils.mknextfile(prefix='MergedDataset_', suffix='.csv')
#allow multiple CSV of inputs to be provided.
#if more than one then combine into a single CSV before sending to MDSBuilder
inputs_csvs = self.forceGetInputListFromPort('RastersWithPARCInfoCSV')
if len(inputs_csvs) == 0:
raise ModuleError(self, "Must supply at least one 'RastersWithPARCInfoCSV'/nThis is the output from the PARC module")
if len(inputs_csvs) > 1:
inputs_csv = utils.mknextfile(prefix='CombinedPARCFiles_', suffix='.csv')
inputs_names = [utils.getFileRelativeToCurrentVT(f.name, self) for f in inputs_csvs]
utils.merge_inputs_csvs(inputs_names, inputs_csv)
else:
inputs_csv = utils.getFileRelativeToCurrentVT(inputs_csvs[0].name, self)
MDSParams['inputsCSV'] = inputs_csv
#inputsCSV = utils.path_port(self, 'RastersWithPARCInfoCSV')
ourMDSBuilder = MDSB.MDSBuilder()
utils.PySAHM_instance_params(ourMDSBuilder, MDSParams)
writetolog(" inputsCSV=" + ourMDSBuilder.inputsCSV, False, False)
writetolog(" fieldData=" + ourMDSBuilder.fieldData, False, False)
writetolog(" outputMDS=" + ourMDSBuilder.outputMDS, False, False)
try:
ourMDSBuilder.run()
except TrappedError as e:
raise ModuleError(self, e.message)
except:
utils.informative_untrapped_error(self, "MDSBuilder")
output_file = utils.create_file_module(ourMDSBuilder.outputMDS, module=self)
self.setResult('mdsFile', output_file)
class MDSBuilder_vector(Module):
'''
'''
__doc__ = GenModDoc.construct_module_doc('MDSBuilder')
_input_ports = [('RastersWithPARCInfoCSV', '(gov.usgs.sahm:RastersWithPARCInfoCSV:Other)'),
('VectorFieldData', '(gov.usgs.sahm:FieldData:DataInput)'),
('KeyField', '(edu.utah.sci.vistrails.basic:String)'),
('Statistic', '(edu.utah.sci.vistrails.basic:String)', {'defaults':'["Mean"]', 'optional':True}),
('ResponseType', '(edu.utah.sci.vistrails.basic:String)', {'defaults':'["Binary"]', 'optional':True})]
_output_ports = [('mdsFile', '(gov.usgs.sahm:MergedDataSet:Other)')]
@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')
def compute(self):
port_map = {'VectorFieldData': ('VectorFieldData', None, True),
'KeyField': ('KeyField', None, True),
'Statistic': ('Statistic', None, False)}
MDSParams = utils.map_ports(self, port_map)
MDSParams['outputMDS'] = utils.mknextfile(prefix='MergedDataset_', suffix='.csv')
#allow multiple CSV of inputs to be provided.
#if more than one then combine into a single CSV before sending to MDSBuilder
inputs_csvs = self.forceGetInputListFromPort('RastersWithPARCInfoCSV')
if len(inputs_csvs) == 0:
raise ModuleError(self, "Must supply at least one 'RastersWithPARCInfoCSV'/nThis is the output from the PARC module")
if len(inputs_csvs) > 1:
inputs_csv = utils.mknextfile(prefix='CombinedPARCFiles_', suffix='.csv')
inputs_names = [utils.getFileRelativeToCurrentVT(f.name, self) for f in inputs_csvs]
utils.merge_inputs_csvs(inputs_names, inputs_csv)