-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathhtap-prm.rb
2143 lines (1477 loc) · 64.2 KB
/
htap-prm.rb
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
#!/usr/bin/env ruby
# ************************************************************************************
# This is a rudamentary run-manager developed as a ...
# ************************************************************************************
require 'optparse'
require 'ostruct'
require 'timeout'
require 'fileutils'
require 'pp'
require 'json'
require 'set'
require 'rexml/document'
require_relative 'inc/msgs'
require_relative 'inc/constants'
require_relative 'inc/HTAPUtils.rb'
require_relative 'inc/application_modules.rb'
include REXML # This allows for no "REXML::" prefix to REXML methods
$program = "htap-prm.rb"
HTAPInit()
log_out ("Recovering git version info\n")
$branch_name, $revision_number = HTAPData.getGitInfo()
$gRunUpgrades = Hash.new
$gOptionList = Array.new
$gOptionListLimit = Hash.new
$gOptionListIterators = Hash.new
$gRulesets = Array.new
$gArchetypes = Array.new
$gLocations = Array.new
$gChoiceFileSet = Hash.new
$gArchetypeDir = "C:/HTAP/archetypes"
$gArchetypeHash = Hash.new
$gRulesetHash = Hash.new
$gLocationHash = Hash.new
$gExtendedOutputFlag = ""
$gHourlySimulationFlag = ""
$bufferStatus = {:current_threads => 0,
:total_threads => 0,
:batch =>"",
:action => "",
:err_count => 0,
:processed_count => 0,
:frac_done => 0,
:time_left => "TBD"
}
$gGenChoiceFileBaseName = "sim-X.choices"
$gGenChoiceFileDir = "./gen-choice-files/"
$gGenChoiceFileNum = 0
$gGenChoiceFileList = Array.new
#default: mesh, parametric and sample also supported
$gRunDefMode = "mesh"
#Sample method = default flags
$sample_method = "random" # Doesn't do anything yet
$sample_size = 100
$sample_seeded = false
#Flag for parsing
$RunScopeOpen = false
#Params for JSON output
$gJSONize = false
$gJSONAllData = Array.new
$gHashLoc = 0
$gComputeCosts = false
$snailStart = false
$snailStartWait = 1
$choicesInMemory = true
$ChoiceFileContents = Hash.new
$gDebug = false
=begin rdoc
=========================================================================================
METHODS: Routines called in this file must be defined before use in Ruby
(can't put at bottom of listing).
=========================================================================================
=end
=begin rdoc
# ----------------------------------------------------------------------------
# parse Def file
# This function parses a prm run definition file (such as HTAP-prm-trialmesh.run)
# and loads the attirbute: options info into a hash.
# ----------------------------------------------------------------------------
=end
def parse_def_file(filepath)
#debug_on
bError = false
$runParamsOpen = false;
$runScopeOpen = false;
$UpgradesOpen = false;
$WildCardsInUse = false;
rundefs = File.open(filepath, 'r')
rulesetsHASH = Hash.new
jsonRawOptions = Hash.new
rundefs.each do | line |
$defline = line
$defline.strip!
$defline.gsub!(/\!.*$/, '')
$defline.gsub!(/\s*/, '')
$defline.gsub!(/\^/, '')
if ( $defline !~ /^\s*$/ )
debug_out ("Parsing: #{$defline}\n")
case
# Section star/end in the file
when $defline.match(/RunParameters_START/i)
$RunParamsOpen = true;
when $defline.match(/RunParameters_END/i)
$RunParamsOpen = false;
when $defline.match(/RunScope_START/i)
$RunScopeOpen = true;
when $defline.match(/RunScope_END/i)
$RunScopeOpen = false;
when $defline.match(/Upgrades_START/i)
$UpgradesOpen = true;
when $defline.match(/Upgrades_END/i)
$UpgradesOpen = false;
else
# definitions
$token_values = Array.new
$token_values = $defline.split("=")
debug_out "Token:#{$token_values[0]} = #{$token_values[1]} \n"
if ( $RunParamsOpen && $token_values[0] =~ /archetype-dir/i )
# Where are our .h2k files located?
$gArchetypeDir = $token_values[1]
end
if ( $RunParamsOpen && $token_values[0] =~ /options-file/i )
# Where is our options file located?
$gHTAPOptionsFile = $token_values[1]
debug_out "$gHTAPOptionsFile? : #{$gHTAPOptionsFile}\n"
jsonRawOptions = HTAPData.getOptionsData()
end
if ( $RunParamsOpen && $token_values[0] =~ /substitute-file/i )
# Where is our options file located?
$gSubstitutePath = $token_values[1]
debug_out "$gSubstituteFile? : #{$gSubstitutePath}\n"
end
if ( $RunParamsOpen && $token_values[0] =~ /substitute-file/i )
# Where is our options file located?
$gSubstitutePath = $token_values[1]
debug_out "$gSubstituteFile? : #{$gSubstitutePath}\n"
end
if ( $RunParamsOpen && $token_values[0] =~ /unit-costs-db/i )
# Where is our options file located?
$gCostingFile = $token_values[1]
$gComputeCosts = true
end
if ( $RunParamsOpen && $token_values[0] =~ /rulesets-file/i )
# Where is our options file located?
$gRulesetsFile = $token_values[1]
# Test to see if rulesets file can be parsed
rulesetsHASH = HTAPData.parse_upgrade_file($gRulesetsFile)
debug_out "Rulesets file #{$gRulesetsFile} parsed ok.\n"
end
if ( $RunParamsOpen && $token_values[0] =~ /run-mode/i )
$gRunDefMode = $token_values[1]
if ( ! ( $gRunDefMode =~ /mesh/ ||
$gRunDefMode =~ /parametric/ ||
$gRunDefMode =~ /sample/ ) ) then
fatalerror (" Run mode #{$gRunDefMode} is not supported!")
end
# Sample run mode: Additional arguments may be provided.
if ( $gRunDefMode =~ /sample/ ) then
# parse parameters `n`, `seed` from `sample{ n=###; seed =###}`
$sample_args = $gRunDefMode.clone
$sample_args.gsub!(/.+\{/,'')
$sample_args.gsub!(/\}/,'')
$sample_arg_array = $sample_args.split(";")
$sample_arg_array.each do |arg|
$sample_arg_vals = arg.split(":")
case $sample_arg_vals[0]
when "n"
$sample_size = $sample_arg_vals[1]
when "seed"
$sample_seed_val = $sample_arg_vals[1]
$sample_seeded = true
end
end
$gRunDefMode.gsub!(/\{.*$/,"")
end
end
if ( $RunScopeOpen && $token_values[0] =~ /rulesets/i )
# Rulesets that can be applied.
$gRulesets = $token_values[1].to_s.split(",")
end
if ( $RunScopeOpen && $token_values[0] =~ /archetypes/i )
# archetypes -
$gArchetypes = $token_values[1].to_s.split(",")
end
if ( $RunScopeOpen && $token_values[0] =~ /locations/i )
# locations -
$gLocations = $token_values[1].to_s.split(",")
$WildCardsInUse = true if ($gLocations.grep(/\*/).length > 0 )
end
if ( $UpgradesOpen )
# Check if option has an alias?
option = HTAPData.queryAttribAliases( $token_values[0] )
# Check if option should be ignored
if ( HTAPData.isAttribIgnored(option) )
warn_out ("Legacy option #{option} will be ignored.")
elsif (not HTAPData.isAttribValid(jsonRawOptions,option) ) then
err_out("Attribute #{option} does not match any attribute entry in the options file.")
bError = true
else
choices = $token_values[1].to_s.split(",")
debug_out " #{option} len = #{choices.grep(/\*/).length} \n"
if ( choices.grep(/\*/).length > 0 ) then
$WildCardsInUse = true
end
$gRunUpgrades[option] = choices
$gOptionList.push option
end
end
end #Case
end # if ( $defline !~ /^\s*$/ )
end # rundefs.each do | line |
# Check to see if run options contians wildcards
if ( $WildCardsInUse ) then
debug_out ("Locations\n")
locationIndex = 0
$gLocations.clone.each do | choice |
next unless ( choice =~ /\*/ )
pattern = choice.gsub(/\./, "\.")
pattern.gsub!(/\*/, ".*")
debug_out( " Wildcard Query /#{pattern}/ \n" )
superSet = jsonRawOptions["Opt-Location"]["options"].keys
$gLocations.delete(choice)
$gLocations.concat superSet.grep(/#{pattern}/)
locationIndex += 1
end
$gRunUpgrades.keys.each do |key|
debug_out( " Wildcard search for #{key} => \n" )
# `upgrade-package-list` does not get tested against the options file.
if ( key !~ /upgrade-package-list/ and not HTAPData.isAttribValid(jsonRawOptions,key) ) then
err_out("Attribute #{key} does not match any attribute entry in the options file.")
bError = true
else
$gRunUpgrades[key].clone.each do |choice|
debug_out (" ? #{choice} \n")
if ( choice =~ /\*/ ) then
pattern = choice.gsub(/\*/, ".*")
debug_out " Wildcard matching on #{key} =~ /#{pattern}/\n"
# Matching
if ( key =~ /upgrade-package-list/ ) then
superSet = rulesetsHASH["upgrade-packages"].keys
else
superSet = jsonRawOptions[key]["options"].keys
end
$gRunUpgrades[key].delete(choice)
$gRunUpgrades[key].concat superSet.grep(/#{pattern}/)
end
end
end
end
jsonRawOptions = nil
end
if bError
fatalerror("Could not parse run file (#{filepath})")
end
return
#debug_out ("Final locations: #{$gLocations.pretty_inspect}")
#debug_out ("Final Upgrades: #{$gRunUpgrades.pretty_inspect}")
end # def parse_def_file(filepath)
=begin rdoc
# ----------------------------------------------------------------------------
# cartisian_create_mesh_combinations -
# This function will iterate over all all combinations of choices for all
# attirbutes, and call gen_choice_file to create associated choice files.
# * It calls itself recusrively *
# ----------------------------------------------------------------------------
=end
def create_mesh_cartisian_combos(optIndex)
if ( optIndex == $gOptionList.count )
generated_file = gen_choice_file($gChoiceFileSet)
$gGenChoiceFileList.push generated_file
# Save the name of the archetype that matches this choice file for invoking
# with substitute.h2k.
# "! Opt-Archetype" - choice disabled because prm copies the h2k file into the run directory.
$gArchetypeHash[generated_file] = $gChoiceFileSet["!Opt-Archetype"]
$gLocationHash[generated_file] = $gChoiceFileSet["Opt-Location"]
$gRulesetHash[generated_file] = $gChoiceFileSet["Opt-Ruleset"]
$combosGenerated += 1
$combosSinceLastUpdate += 1
if ( $combosSinceLastUpdate == $comboInterval )
stream_out (" - Creating #{$gRunDefMode} run for #{$combosRequired} combinations --- #{$combosGenerated} combos created so far...\r")
$combosSinceLastUpdate = 0
end
else
case optIndex
when -3
$gLocations.each do |location|
$gChoiceFileSet["Opt-Location"] = location
create_mesh_cartisian_combos(optIndex+1)
end
when -2
$archetypeFiles.each do |file|
debug_out ("test file - #{file}\n")
$h2kfile = File.basename(file)
$gChoiceFileSet["!Opt-Archetype"] = $h2kfile
create_mesh_cartisian_combos(optIndex+1)
end
when -1
$gRulesets.each do |ruleset|
$gChoiceFileSet["Opt-Ruleset"] = ruleset
create_mesh_cartisian_combos(optIndex+1)
end #$gOptionList $gRulesets.each do |ruleset|
else
attribute = $gOptionList[optIndex]
choices = $gRunUpgrades[attribute]
choices.each do | choice |
$gChoiceFileSet[attribute] = choice
# Recursive call for next step in order.
create_mesh_cartisian_combos(optIndex+1)
end
end
end
end
def create_parametric_combos()
#debug_on
$Folder = $gArchetypeDir
startSet = Hash.new
parameterSpace = Hash.new
parameterSpace = $gRunUpgrades.clone
parameterSpace.keys.each do |attribute|
startSet[attribute] = parameterSpace[attribute][0]
end
#debug_out " > START SET:\n#{startSet.pretty_inspect}\n"
$gArchetypes.each do | archetype |
debug_out ("> archatype - #{$gArchetypes}\n")
$archetypeFiles = Dir["#{$Folder}/#{archetype}"]
$archetypeFiles.each do |h2kpath|
$gLocations.each do | location |
$gRulesets.each do | ruleset |
debug_out (" Setting parametric scope for: \n 1 #{archetype} \n 2 #{h2kpath} \n 3 #{location} \n 4 #{ruleset} \n")
# Base point
startSet["!Opt-Archetype"] = File.basename(h2kpath)
startSet["Opt-Location"] = location
startSet["Opt-Ruleset"] = ruleset
thisSet=Hash.new
thisSet = startSet.clone
generated_file = gen_choice_file(thisSet)
$gGenChoiceFileList.push generated_file
$gArchetypeHash[generated_file] = thisSet["!Opt-Archetype"]
$gLocationHash[generated_file] = thisSet["Opt-Location"]
$gRulesetHash[generated_file] = thisSet["Opt-Ruleset"]
$combosGenerated += 1
$combosSinceLastUpdate += 1
# Parametric variations....
parameterSpace.keys.each do |attribute|
debug_out ("PARAMETRIC: #{attribute} has #{parameterSpace[attribute].length} entries\n")
if ( parameterSpace[attribute].length < 1 ) then
fatalerror " #{attribute} has #{parameterSpace[attribute].length} entries"
end
parameterSpace[attribute][1..-1].each do | choice |
debug_out (" + #{choice} \n")
thisSet = startSet.clone
thisSet[attribute] = choice
generated_file = gen_choice_file(thisSet)
$gGenChoiceFileList.push generated_file
# Save the name of the archetype that matches this choice file for invoking
# with substitute.h2k.
# "! Opt-Archetype" - choice disabled because prm copies the h2k file into the run directory.
$gArchetypeHash[generated_file] = thisSet["!Opt-Archetype"]
$gLocationHash[generated_file] = thisSet["Opt-Location"]
$gRulesetHash[generated_file] = thisSet["Opt-Ruleset"]
$combosGenerated += 1
$combosSinceLastUpdate += 1
if ( $combosSinceLastUpdate >= $comboInterval )
stream_out (" - Creating mesh run for #{$combosRequired} combinations --- #{$combosGenerated} combos created so far...\r")
$combosSinceLastUpdate = 0
end
end
end
if ( $combosSinceLastUpdate >= $comboInterval )
stream_out (" - Creating mesh run for #{$combosRequired} combinations --- #{$combosGenerated} combos created so far...\r")
$combosSinceLastUpdate = 0
end
end
end
end
end
debug_out (" ----- PARAMETRIC RUN: PARAMETER SPACE ----\n#{parameterSpace.pretty_inspect}\n")
debug_out( " - gArchetype\n#{$gArchetypeHash.pretty_inspect}\n")
debug_out( " - gLocationH\n#{$gLocationHash.pretty_inspect} \n")
debug_out( " - gRulesetHa\n#{$gRulesetHash.pretty_inspect} \n")
end
=begin rdoc
# ----------------------------------------------------------------------------
# Gen Choice File
# This function generates a choice file from a supplied attirbute:choice hash.
# ----------------------------------------------------------------------------
=end
def gen_choice_file(choices)
# create empty directory to hold choice files
if ( ! Dir.exist?($gGenChoiceFileDir) && ! $choicesInMemory )
if ( ! Dir.mkdir($gGenChoiceFileDir) )
fatalerror( " Fatal Error! Could not create #{$gGenChoiceFileDir} below #{$gMasterPath}!\n MKDir Return code: #{$?}\n" )
end
end
$gGenChoiceFileNum = $gGenChoiceFileNum + 1
choicefilename = $gGenChoiceFileBaseName.gsub(/X/,"#{$gGenChoiceFileNum}")
if ( $choicesInMemory ) then
choicefilepath = "#{choicefilename}"
$ChoiceFileContents[choicefilepath] = "! Choice file for run $gGenChoiceFileNum\n"
choices.each do | attribute, choice |
$ChoiceFileContents[choicefilepath].concat("#{attribute} : #{choice} \n")
end
else
choicefilepath = "#{$gGenChoiceFileDir}#{choicefilename}"
choicefile = File.open(choicefilepath, 'w')
choices.each do | attribute, choice |
choicefile.write(" #{attribute} : #{choice} \n")
end
choicefile.close
end
return choicefilepath
end
=begin rdoc
#======================================================================================================
# This code will process a supplied list of .choice files using the specified number of threads.
#======================================================================================================
=end
def run_these_cases(current_task_files)
$RunResults = Hash.new
$choicefiles = Array.new
$PIDS = Array.new
$FinishedTheseFiles = Hash.new
$RunNumbers = Array.new
lastCount = 0
$CompletedRunCount = 0
$FailedRunCount = 0
## Create working directories
$headerline = ""
if ( $bReadyToResume )
headerOut = true
else
headerOut= false
end
current_task_files.each do |choicefile|
$FinishedTheseFiles[choicefile] = false
end
$choicefileIndex = 0
numberOfFiles = $FinishedTheseFiles.count {|k| k.include?(false)}
stream_out drawRuler("Begin Runs")
stream_out "\n"
$choicefileIndex = 0
$RunsDone = false
$csvColumns = Array.new
# Loop until all files have been processed.
$GiveUp = false
startRunsTime= Time.now
fJSONout = File.open("#{$gOutputJSON}", 'w')
firstJSONLine = true
batchStatusUpdate = Array.new
while ! $RunsDone
$batchCount = $batchCount + 1
batchStatusUpdate.clear
batchStartTime = Time.now
fracCompleted = $choicefileIndex.to_f/numberOfFiles.to_f
debug_out ("> BATCH #{$batchCount}, Index: #{$choicefileIndex}, Complete: #{fracCompleted*100}% \n")
timeMsg = ""
if ( fracCompleted > 0.0 ) then
timeNow = Time.now
timeLapsed = (timeNow - startRunsTime)
timeRemaining = timeLapsed / fracCompleted - timeLapsed
timeMsg = ", ~#{formatTimeInterval(timeRemaining)} remaining"
debug_out "Time Differential = #{(timeNow -startRunsTime)}\n"
update_run_status(time_left: "#{formatTimeInterval(timeRemaining)}")
end
batchLapsedTime = '0'
update_run_status(batch: $batchCount )
update_run_status(action: "Initalizing")
update_run_status(threads_total: $gNumberOfThreads )
update_run_status(run_count: $choicefileIndex.to_i)
update_run_status(frac_done: "#{(fracCompleted*100).round(2)}")
#stream_out (" + Batch #{$batchCount} ( #{(fracCompleted*100).round(4)}% done, #{$choicefileIndex}/#{numberOfFiles} files processed so far#{timeMsg} ...) \n" )
if ( $batchCount == 1 && $snailStart ) then
#stream_out (" |\n")
#stream_out (" +-> NOTE: \"SnailStart\" is active. Waiting for #{$snailStartWait} seconds between threads (on first batch ONLY!) \n\n")
update_run_status(action: "Pausing between threads (Snail Start)")
end
# Empty arrays for current batch.
$choicefiles.clear
$PIDS.clear
$SaveDirs.clear
# Compute the number of threads we will start: lesser of a) files remaining, or b) threads allowed.
$ThreadsNeeded = [$FinishedTheseFiles.count {|k| k.include?(false)}, $gNumberOfThreads].min
debug_out "TOTAL THREADS NEEDED: #{$ThreadsNeeded}"
#=====================================================================================
# Multi-threaded runs - Step 1: Spawn threads.
for thread in 0..$ThreadsNeeded-1
update_run_status(action: "Spawning threads")
# For this thread: Get the next choice file in the batch.
$choicefiles[thread] = current_task_files[$choicefileIndex]
# Get the name of the .h2k file for this thread.
$H2kFile = $gArchetypeHash[$choicefiles[thread]]
$Ruleset = $gRulesetHash[$choicefiles[thread]]
$Location = $gLocationHash[$choicefiles[thread]]
count = thread + 1
#stream_out (" - Starting thread : #{count}/#{$ThreadsNeeded} for file #{$choicefiles[thread]} ")
#stream_out (" - Starting thread #{count}/#{$ThreadsNeeded} for sim ##{$choicefileIndex+1} ")
# For this thread: Get the next choice file in the batch.
#$choicefiles[thread] = $RunTheseFiles[$choicefileIndex]
# Make sure that's a real choice file ( this just duplicates a test above )
if ( $choicefiles[thread] =~ /.*choices$/ )
# Increment run number and create name for unique simulation directory
$RunNumber = $RunNumber + 1
$RunDirectory = $RunDirs[thread]
$SaveDirectory = "#{$SaveDirectoryRoot}-#{$RunNumber}"
# Store run number and directory for this thread
$RunNumbers[thread] = $RunNumber
$SaveDirs[thread] = $SaveDirectory
# create empty run directory
if ( ! Dir.exist?($RunDirectory) )
if ( ! Dir.mkdir($RunDirectory) )
fatalerror( " Fatal Error! Could not create #{$RunDirectory} below #{$gMasterPath}!\n MKDir Return code: #{$?}\n" )
end
else
bCPDone = false
cptries = 0
while ! bCPDone
# Delete contents, but not H2K folder
begin
FileUtils.rm_r Dir.glob("#{$RunDirectory}/*.*")
bCPDone = true
rescue
cptries += 1
warn_out ("Could not delete files from within #{$RunDirectory} (Try # #{cptries}/3)\n")
if ( cptries == 3 )
bCPDone = true
warn_out ( "Trying to run simulation without deleting files in #{$RunDirectory}")
else
sleep 5
end
end
end
end
# Copy choice and options file into intended run directory...
if $choicesInMemory
choicefile = File.open("#{$RunDirectory}/#{$choicefiles[thread]}", 'w')
choicefile.write ($ChoiceFileContents[$choicefiles[thread]])
choicefile.close
else
FileUtils.cp($choicefiles[thread],$RunDirectory)
end
FileUtils.cp($gHTAPOptionsFile,$RunDirectory)
FileUtils.cp("#{$gArchetypeDir}\\#{$H2kFile}",$RunDirectory)
if ( $gComputeCosts || $gLEEPPathwayExport ) then
# Unit cost DB required for cost calcs and LEEP-pathaways export; issue fatal error if not found.
begin
FileUtils.cp($gCostingFile,$RunDirectory)
rescue
err_out("Unit cost database ('#{$gCostingFile}') was not copied successfully.")
fatalerror("Failed to copy unit-cost DB")
end
end
# ... And get base file names for insertion into the substitute-h2k.rb command.
$LocalChoiceFile = File.basename $choicefiles[thread]
$LocalOptionsFile = File.basename $gHTAPOptionsFile
# CD to run directory, spawn substitute-h2k thread and save PID
Dir.chdir($RunDirectory)
if ( $gDebug )
FileUtils.cp("#{$H2kFile}","#{$H2kFile}-p0")
end
# Possibly call another script to modify the .h2k and .choice files
# Perhaps these are depeciated?
case $Ruleset
when /936_2015_AW_HRV/
subcall = "perl C:\\HTAP\\NRC-scripts\\apply936-AW.pl #{$H2kFile} #{$LocalChoiceFile} #{$LocalOptionsFile} #{$Location} 1 "
system (subcall)
when /936_2015_AW_noHRV/
subcall = "perl C:\\HTAP\\NRC-scripts\\apply936-AW.pl #{$H2kFile} #{$LocalChoiceFile} #{$LocalOptionsFile} #{$Location} 0 "
system (subcall)
end
if ( $gDebug )
FileUtils.cp("#{$H2kFile}","#{$H2kFile}-p1")
end
subCostFlag = ""
subRulesetsFlag = ""
if ($gComputeCosts ) then
subCostFlag = "--auto_cost_options --unit-cost-db #{$gCostingFile}"
end
if ( ! $gRulesetsFile.empty? ) then
subRulesetsFlag = "--rulesets #{$gRulesetsFile}"
end
cmdscript = "ruby #{$gSubstitutePath} "+
"-o #{$LocalOptionsFile} "+
"-c #{$LocalChoiceFile} "+
"-b #{$H2kFile} "+
"#{subRulesetsFlag} "+
"#{subCostFlag} "+
"--prm "+
"#{$gExtendedOutputFlag} "+
"#{$gHourlySimulationFlag}"
# Save command for invoking substitute [ useful in debugging ]
$cmdtxt = File.open("run-cmd.ps1", 'w')
$cmdtxt.write "#{cmdscript} -v "
$cmdtxt.close
if ( ! $gLogDebugMsgs ) then
debugflag = "--no-debug"
else
debug_flag = ""
end
# disable debugging in live version for faster runs
# (debugging still enabled in run-cmd.ps1)
pid = Process.spawn(
"#{cmdscript} #{debugflag}",
:err => "substitute-h2k-errors.txt"
)
update_run_status(threads_delta: 1)
$PIDS[thread] = pid
#stream_out("(PID #{$PIDS[thread]})...")
# Cd to root, move to next choice file.
Dir.chdir($gMasterPath)
end
# Snail-Start:
# This patch is a workaround for instability observed with highly-thread (20+) runs on machines with slow I/O.
# On the first batch, the substitute script copies the contents of the h2k folder into the working directories (HTAP-work-X),
# and these folders are subsequently re-used on the following batches. I suspect that windows struggles when 40+ threads are all
# trying to copy 80+ MB simultaneously to a slow disk; some folders are not created correctly, some files are missing. The
# result is a bunch of failed runs.
#
# Specifying command line option '--snailStart X' causes prm to pause for X seconds after spawning a thread - * on the first batch only *
# It seems to give a magnetic disk a fighting chance of keeping up with the copy requests. It doesn't appear to slow the simulation
# down too much, because it only affects the first batch, the H2K folder copy operation appears to be the most expensive part of that first run.
# In tests with 40 threads writing to a magnetic disk, `-- snailStart 6` produces stable runs.
# A future improvement might modify substitute-h2k.rb to take a hash of the h2k directory content, and verify its integrity before proceeding.
if ( $batchCount == 1 && $snailStart ) then
#stream_out (" *SS-Wait")
for wait in 1..5
#stream_out (".")
sleep($snailStartWait/5)
end
#stream_out( "*")
end
#stream_out (" done. \n")
$choicefileIndex = $choicefileIndex + 1
# Create hash to hold results
$RunResults["run-#{thread}"] = Hash.new
$RunResults["run-#{thread}"]["status"] = Hash.new
$RunResults["run-#{thread}"]["status"]["success"] = nil
$RunResults["run-#{thread}"]["status"]["errors"] = Array.new
$RunResults["run-#{thread}"]["status"]["warnings"] = Array.new
$RunResults["run-#{thread}"]["configuration"] = Hash.new
$RunResults["run-#{thread}"]["input"] = Hash.new
$RunResults["run-#{thread}"]["archetype"] = Hash.new