forked from NRCan-IETS-CE-O-HBC/HTAP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtap-prm.rb
More file actions
1516 lines (946 loc) · 44.7 KB
/
htap-prm.rb
File metadata and controls
1516 lines (946 loc) · 44.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ruby
# ************************************************************************************
# This is a really rudamentary run-manager developed as a ...
# ************************************************************************************
require 'optparse'
require 'ostruct'
require 'timeout'
require 'fileutils'
require 'pp'
require 'json'
$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 = ""
$gGenChoiceFileBaseName = "sim-X.choices"
$gGenChoiceFileDir = "./gen-choice-files/"
$gGenChoiceFileNum = 0
$gGenChoiceFileList = Array.new
#default (and only supported mode)
$gRunDefMode = "mesh"
$RunScopeOpen = false
#Params for JSON output
$gJSONize = false
$gJSONAllData = Array.new
$gHashLoc = 0
$gComputeCosts = false
$snailStart = false
$snailStartWait = 1
$choicesInMemory = true
$ChoiceFileContents = Hash.new
=begin rdoc
=========================================================================================
METHODS: Routines called in this file must be defined before use in Ruby
(can't put at bottom of listing).
=========================================================================================
=end
def fatalerror( err_msg )
# Display a fatal error and quit. -----------------------------------
if ($gTest_params["logfile"])
$fLOG.write("\nsubstitute-h2k.rb -> Fatal error: \n")
$fLOG.write("#{err_msg}\n")
end
print "\n=========================================================\n"
print "substitute-h2k.rb -> Fatal error: \n\n"
print " #{err_msg}\n"
print "\n\n"
print "substitute-h2k.rb -> Other Error or warning messages:\n\n"
print "#{$ErrorBuffer}\n"
exit() # Run stopped
end
# =========================================================================================
# Optionally write text to buffer -----------------------------------
# =========================================================================================
def stream_out(msg)
if ($gTest_params["verbosity"] != "quiet")
print msg
end
if ($gTest_params["logfile"])
$fLOG.write(msg)
end
end
# =========================================================================================
# Write debug output ------------------------------------------------
# =========================================================================================
def debug_out(debmsg)
if $gDebug
puts debmsg
end
if ($gTest_params["logfile"])
$fLOG.write(debmsg)
end
end
# =========================================================================================
# Write warning output ------------------------------------------------
# =========================================================================================
def warn_out(debmsg)
if $gWarn
puts debmsg
end
if ($gTest_params["logfile"])
$fLOG.write(debmsg)
end
end
# =========================================================================================
# Does this do anything? ------------------------------------------------
# =========================================================================================
def parse_output_data(filepath)
# NOPE!
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)
$runParamsOpen = false;
$runScopeOpen = false;
$UpgradesOpen = false;
$WildCardsInUse = false;
rundefs = File.open(filepath, 'r')
rundefs.each do | line |
$defline = line
$defline.strip!
$defline.gsub!(/\!.*$/, '')
$defline.gsub!(/\s*/, '')
$defline.gsub!(/\^/, '')
if ( $defline !~ /^\s*$/ )
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("=")
if ( $RunParamsOpen && $token_values[0] =~ /archetype-dir/i )
# Where are our .h2k files located?
$gArchetypeDir = $token_values[1]
end
if ( $RunParamsOpen && $token_values[0] =~ /run-mode/i )
# This does nothing only 'mesh' supported for now!!!
$gRunDefMode = $token_values[1]
if ( ! ( $gRunDefMode =~ /mesh/ || $gRunDefMode =~ /parametric/ ) ) then
fatalerror (" Run mode #{$gRunDefMode} is not supported!")
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(",")
end
if ( $UpgradesOpen )
option = $token_values[0]
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 #Case
end # if ( $defline !~ /^\s*$/ )
end # rundefs.each do | line |
# Check to see if run options contians wildcards
if ( $WildCardsInUse ) then
if ( ! $gOptionFile =~ /\.json/i ) then
fatalerror ("Wildcard matching is only supported with .json option files")
end
fOPTIONS = File.new($gOptionFile, "r")
if fOPTIONS == nil then
fatalerror(" Could not read #{filename}.\n")
end
$OptionsContents = fOPTIONS.read
fOPTIONS.close
$JSONRawOptions = JSON.parse($OptionsContents)
$OptionsContents = nil
$gRunUpgrades.keys.each do |key|
debug_out( " Wildcard search for #{key} => \n" )
$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
$SuperSet = $JSONRawOptions[key]["options"].keys
$gRunUpgrades[key].delete(choice)
$gRunUpgrades[key].concat $SuperSet.grep(/#{$pattern}/)
end
end
end
$JSONRawOptions = nil
end
# What if archetypes are defined using a wildcard?
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"]
else
case optIndex
when -3
$gLocations.each do |location|
$gChoiceFileSet["Opt-Location"] = location
create_mesh_cartisian_combos(optIndex+1)
end
when -2
$gArchetypes.each do |archentry|
$Folder = $gArchetypeDir
# Allow wildcards; expand list!
$ArchetypeFiles = Dir["#{$Folder}/#{archentry}"]
$ArchetypeFiles.each do |h2kpath|
$h2kfile = File.basename(h2kpath)
$gChoiceFileSet["!Opt-Archetype"] = $h2kfile
create_mesh_cartisian_combos(optIndex+1)
end
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()
$Folder = $gArchetypeDir
$StartSet = Hash.new
$gParameterSpace = Hash.new
$gParameterSpace = $gRunUpgrades.clone
$gParameterSpace["Opt-Ruleset"] = Array.new
$gParameterSpace["Opt-Ruleset"] = $gRulesets
$gParameterSpace["Opt-Location"] = Array.new
$gParameterSpace["Opt-Location"] = $gLocations
$gParameterSpace["!Opt-Archetype"] = Array.new
$gArchetypes.each do |archetype|
$ArchetypeFiles = Dir["#{$Folder}/#{archetype}"]
$ArchetypeFiles.each do |h2kpath|
$gParameterSpace["!Opt-Archetype"].push File.basename(h2kpath)
end
end
$gParameterSpace.keys.each do |attribute|
$StartSet[attribute] = $gParameterSpace[attribute][0]
end
# Base point -
generated_file = gen_choice_file($StartSet)
$gGenChoiceFileList.push generated_file
$gArchetypeHash[generated_file] = $StartSet["!Opt-Archetype"]
$gLocationHash[generated_file] = $StartSet["Opt-Location"]
$gRulesetHash[generated_file] = $StartSet["Opt-Ruleset"]
$gParameterSpace.keys.each do |attribute|
debug_out ("PARAMETRIC: #{attribute} has #{$gParameterSpace[attribute].length} entries\n")
$gParameterSpace[attribute][1..-1].each do | choice |
debug_out (" + #{choice} \n")
$gChoiceFileSet = $StartSet.clone
$gChoiceFileSet[attribute] = choice
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"]
end
end
if ( $gDebug ) then
debug_out (" ----- PARAMETRIC RUN: PARAMETER SPACE ---- \n ")
pp $gParameterSpace
end
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
$CompletedRunCount = 0
$FailedRunCount = 0
## Create working directories
$headerline = ""
$outputHeaderPrinted = false
current_task_files.each do |choicefile|
$FinishedTheseFiles[choicefile] = false
end
$choicefileIndex = 0
numberOfFiles = $FinishedTheseFiles.count {|k| k.include?(false)}
stream_out (" - HTAP-prm: begin runs ----------------------------\n\n")
$choicefileIndex = 0
$RunsDone = false
$csvColumns = Array.new
# Loop until all files have been processed.
$GiveUp = false
while ! $RunsDone
$batchCount = $batchCount + 1
stream_out (" + Batch #{$batchCount} ( #{$choicefileIndex}/#{numberOfFiles} files processed so far...) \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")
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
#=====================================================================================
# Multi-threaded runs - Step 1: Spawn threads.
for thread in 0..$ThreadsNeeded-1
# 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
# Delete contents, but not H2K folder
FileUtils.rm_r Dir.glob("#{$RunDirectory}/*.*")
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($gOptionFile,$RunDirectory)
FileUtils.cp("#{$gArchetypeDir}\\#{$H2kFile}",$RunDirectory)
if ( $gComputeCosts ) then
# Think about error handling.
FileUtils.cp($gCostingFile,$RunDirectory)
end
# ... And get base file names for insertion into the substitute-h2k.rb command.
$LocalChoiceFile = File.basename $choicefiles[thread]
$LocalOptionsFile = File.basename $gOptionFile
# 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
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 = ""
if ($gComputeCosts ) then
$SubCostFlag = "--auto_cost_options"
end
cmdscript = "ruby #{$gSubstitutePath} -o #{$LocalOptionsFile} -c #{$LocalChoiceFile} -b #{$H2kFile} --report-choices --prm #{$gExtendedOutputFlag} #{$SubCostFlag}"
# Save command for invoking substitute [ useful in debugging ]
$cmdtxt = File.open("cmd.txt", 'w')
$cmdtxt.write cmdscript
$cmdtxt.close
#debug_out(" ( cmd: #{cmdscript} | \n")
pid = Process.spawn( cmdscript, :out => File::NULL, :err => "substitute-h2k-errors.txt" )
$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
end
# Multi-threaded runs - Step 2: Monitor thread progress
#=====================================================================================
# Wait for threads to complete
for thread2 in 0..$ThreadsNeeded-1
count = thread2 + 1
stream_out (" - Waiting on PID: #{$PIDS[thread2]} (#{count}/#{$ThreadsNeeded})...")
Process.wait($PIDS[thread2], 0)
status = $?.exitstatus
if ( status == 0 )
stream_out (" done.\n")
else
stream_out (" FAILED! (Exit status: #{status})\n")
$RunResults["run-#{thread2}"]["s.success"] = "false"
$RunResults["run-#{thread2}"]["s.errors@99"] = " Run failed - substitute-h2k.rb returned status #{status}"
end
end
#=====================================================================================
# Multi-threaded runs - Step 3: Post-process and clean up.
for thread3 in 0..$ThreadsNeeded-1
count = thread3 + 1
stream_out (" - Reading results files from PID: #{$PIDS[thread3]} (#{count}/#{$ThreadsNeeded})...")
Dir.chdir($RunDirs[thread3])
$RunResults["run-#{thread3}"]["c.RunNumber"] = "#{$RunNumbers[thread3].to_s}"
$RunResults["run-#{thread3}"]["c.RunDirectory"] = "#{$RunDirs[thread3].to_s}"
$RunResults["run-#{thread3}"]["c.SaveDirectory"] = "#{$SaveDirs[thread3].to_s}"
$RunResults["run-#{thread3}"]["c.ChoiceFile"] = "#{$choicefiles[thread3].to_s}"
$runFailed = false
# Parse contents of substitute-h2k-errors.txt, which may contain ruby errors if substitute-h2k.rb did
# not execute correctly.
$RunResults["run-#{thread3}"]["s.substitute-h2k-err-msgs"] = "nil"
if ( File.exist?("substitute-h2k-errors.txt") )
$errmsgs= File.read("substitute-h2k-errors.txt")
$errmsgs_chk = $errmsgs
if ( ! $errmsgs_chk.gsub(/\n*/,"").gsub( / */, "").empty? )
$RunResults["run-#{thread3}"]["s.substitute-h2k-err-msgs"] = $errmsgs
end
end
if ( File.exist?($RunResultFilename) )
contents = File.open($RunResultFilename, 'r')
ec=0
wc=0
lineCount = 0
contents.each do |line|
lineCount = lineCount + 1
line_clean = line.gsub(/ /, '')
line_clean = line.gsub(/\n/, '')
if ( ! line_clean.to_s.empty? )
$contents = Array.new
$contents = line_clean.split('=')
token = $contents[0].gsub(/\s*/,'')
value = $contents[1].gsub(/^\s*/,'')
value = $contents[1].gsub(/^ /,'')
value = $contents[1].gsub(/ +$/,'')
# add prefix to
case token
when /s.error/
token.concat("@#{ec}")
ec = ec + 1
when /s.warning/
token.concat("@#{wc}")
wc=wc+1
end
$RunResults["run-#{thread3}"][token] = value
end
end
contents.close
if $RunResults["run-#{thread3}"]["s.success"] =~ /false/ then
$runFailed = true
stream_out (" done (with errors).\n")
else
stream_out (" done.\n")
end
else
stream_out (" Output couldn't be found! \n")
$runFailed = true
#stream_out (" RUN FAILED! (see dir: #{$SaveDirs[thread3]}) \n")
$failures.write "#{$choicefiles[thread3]} (dir: #{$SaveDirs[thread3]}) - no output from substitute-h2k.rb\n"
$FailedRuns.push "#{$choicefiles[thread3]} (dir: #{$SaveDirs[thread3]}) - no output from substitute-h2k.rb"
$FailedRunCount = $FailedRunCount + 1
$RunResults["run-#{thread3}"]["s.success"] = "false"
$RunResults["run-#{thread3}"]["s.errors@99"] = " Run failed - no output generated"
$LocalChoiceFile = File.basename $gOptionFile
if ( ! FileUtils.rm_rf("#{$RunDirs[thread3]}/#{$LocalChoiceFile}") )
warn_out(" Warning! Could delete #{$RunDirs[thread3]} rm_fr Return code: #{$?}\n" )
end
end
Dir.chdir($gMasterPath)
# Save files from runs that failed, or possibly all runs.
if ( $gSaveAllRuns || $runFailed )
if ( ! Dir.exist?($SaveDirs[thread3]) )
Dir.mkdir($SaveDirs[thread3])
else
FileUtils.rm_rf Dir.glob("#{$SaveDirs[thread3]}/*.*")
end
FileUtils.mv( Dir.glob("#{$RunDirs[thread3]}/*.*") , "#{$SaveDirs[thread3]}" )
FileUtils.rm_rf ("#{$RunDirs[thread3]}/sim-output")
end
#Update status of this thread.
$FinishedTheseFiles[$choicefiles[thread3]] = true
end
errs = ""
stream_out (" - Post-processing results... ")
$outputlines = ""
row = 0
# Alternative output in JSON format. Can be memory-intensive
if ( $gJSONize )
$RunResults.each do |run,data|
$gJSONAllData[$gHashLoc] = Hash.new
$gJSONAllData[$gHashLoc] = { "result-number" => $gHashLoc+1,
"status" => Hash.new,
"archetype" => Hash.new,
"input" => Hash.new,
"output" => Hash.new,
"configuration" => Hash.new,
"miscellaneous_info" => Hash.new }
# Storage for arrays.
$gJSONAllData[$gHashLoc]["status"] = { "warnings" => Array.new, "errors" => Array.new }
# Storage for binned data
if ( $gExtendedOutputFlag =~ /-e/ )
$gJSONAllData[$gHashLoc]["output"] = { "BinnedData" => Hash.new }
$gJSONAllData[$gHashLoc]["output"]["BinnedData"] = Array.new
for counter in 0..31
$gJSONAllData[$gHashLoc]["output"]["BinnedData"][counter] = Hash.new
$gJSONAllData[$gHashLoc]["output"]["BinnedData"][counter]["bin"] = counter+1
end
else
$gJSONAllData[$gHashLoc]["output"] = { "BinnedData" => "No binned data to report for run ##{$gHashLoc}. Run htap-prm with '-e' to enable" }
end
data.each do |token,value|
#Detect the type of this token from prefix
$col_tmp = token.to_s.gsub(/\s*/, '')
case $col_tmp
when /^input\./ , /^i\./
$col_type = "input"
when /^output\./ , /^o\./
$col_type = "output"
when /^arch\./ , /^a\./
$col_type = "archetype"
when /^config\./ , /^c\./
$col_type = "configuration"
when /^status\./ , /^s\./