forked from NatLabRockies/SAM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstochastic.cpp
More file actions
2435 lines (2077 loc) · 70.6 KB
/
stochastic.cpp
File metadata and controls
2435 lines (2077 loc) · 70.6 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
/*******************************************************************************************************
* Copyright 2017 Alliance for Sustainable Energy, LLC
*
* NOTICE: This software was developed at least in part by Alliance for Sustainable Energy, LLC
* (“Alliance”) under Contract No. DE-AC36-08GO28308 with the U.S. Department of Energy and the U.S.
* The Government retains for itself and others acting on its behalf a nonexclusive, paid-up,
* irrevocable worldwide license in the software to reproduce, prepare derivative works, distribute
* copies to the public, perform publicly and display publicly, and to permit others to do so.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, the above government
* rights notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, the above government
* rights notice, this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. The entire corresponding source code of any redistribution, with or without modification, by a
* research entity, including but not limited to any contracting manager/operator of a United States
* National Laboratory, any institution of higher learning, and any non-profit organization, must be
* made publicly available under this license for as long as the redistribution is made available by
* the research entity.
*
* 4. Redistribution of this software, without modification, must refer to the software by the same
* designation. Redistribution of a modified version of this software (i) may not refer to the modified
* version by the same designation, or by any confusingly similar designation, and (ii) must refer to
* the underlying software originally provided by Alliance as “System Advisor Model” or “SAM”. Except
* to comply with the foregoing, the terms “System Advisor Model”, “SAM”, or any confusingly similar
* designation may not be used to refer to any modified version of this software or any modified
* version of the underlying software originally provided by Alliance without the prior written consent
* of Alliance.
*
* 5. The name of the copyright holder, contributors, the United States Government, the United States
* Department of Energy, or any of their employees may not 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,
* CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR
* EMPLOYEES, 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.
*******************************************************************************************************/
#include <wx/filefn.h>
#include <wx/stopwatch.h>
#include <wx/tokenzr.h>
#include <wx/utils.h>
#include <wx/filename.h>
#include <wx/progdlg.h>
#include <wx/dir.h>
#include <wex/metro.h>
#include <wex/utils.h>
#include "main.h"
#include "casewin.h"
#include "stochastic.h"
char *lhs_dist_names[LHS_NUMDISTS] = {
"Uniform,Min,Max",
"Normal,Mean (mu),Std. Dev. (sigma)",
"Lognormal,Mean,ErrorF",
"Lognormal-N,Mean,Std. Dev.",
"Triangular,A,B,C",
"Gamma,Alpha,Beta",
"Poisson,Lambda",
"Binomial,P,N",
"Exponential,Lambda",
"Weibull,Alpha or k (shape parameter),Beta or lambda (scale parameter)",
"UserCDF,N"
};
LHS::LHS()
{
m_npoints = 500;
m_seedval = 0;
}
void LHS::Reset()
{
m_dist.clear();
m_corr.clear();
m_npoints = 500;
m_errmsg.Empty();
}
void LHS::SeedVal(int sv)
{
m_seedval =sv;
}
#ifdef __WXMSW__
#define LHSBINARY "lhs.exe"
#else
#define LHSBINARY "lhs.bin"
#endif
bool LHS::Exec()
{
wxString workdir(wxFileName::GetTempDir());
wxString lhsexe( SamApp::GetRuntimePath() + "/bin/" + wxString(LHSBINARY) );
if (!wxFileExists(lhsexe))
{
m_errmsg = "Sandia LHS executable does not exist: " + lhsexe;
return false;
}
// write lhsinputs.lhi file
wxString inputfile = workdir + "/SAMLHS.LHI";
FILE *fp = fopen(inputfile.c_str(), "w");
if (!fp)
{
m_errmsg = "Could not write to LHS input file " + inputfile;
return false;
}
int sv = wxGetLocalTime();
if (m_seedval > 0)
sv = m_seedval;
fprintf(fp, "LHSTITL SAM LHS RUN\n");
fprintf(fp, "LHSOBS %d\n", m_npoints);
fprintf(fp, "LHSSEED %d\n", sv);
fprintf(fp, "LHSRPTS CORR DATA\n");
fprintf(fp, "LHSSCOL\n");
fprintf(fp, "LHSOUT samlhs.lsp\n");
fprintf(fp, "LHSPOST samlhs.msp\n");
fprintf(fp, "LHSMSG samlhs.lmo\n");
fprintf(fp, "DATASET:\n");
for (size_t i=0;i<m_dist.size();i++)
{
int ncdfpairs;
int nminparams = wxStringTokenize(lhs_dist_names[ m_dist[i].type ], ",").Count()-1;
if ( (int)m_dist[i].params.size() < nminparams)
{
m_errmsg.Printf("Dist '%s' requires minimum %d params, only %d specified.",
(const char*)m_dist[i].name.c_str(), nminparams, (int)m_dist[i].params.size());
fclose(fp);
return false;
}
switch(m_dist[i].type)
{
case LHS_UNIFORM:
fprintf(fp, "%s UNIFORM %lg %lg\n", (const char*)m_dist[i].name.c_str(),
m_dist[i].params[0],
m_dist[i].params[1]);
break;
case LHS_NORMAL:
fprintf(fp, "%s NORMAL %lg %lg\n", (const char*)m_dist[i].name.c_str(),
m_dist[i].params[0],
m_dist[i].params[1]);
break;
case LHS_LOGNORMAL:
fprintf(fp, "%s LOGNORMAL %lg %lg\n", (const char*)m_dist[i].name.c_str(),
m_dist[i].params[0],
m_dist[i].params[1]);
break;
case LHS_LOGNORMAL_N:
fprintf(fp, "%s LOGNORMAL-N %lg %lg\n", (const char*)m_dist[i].name.c_str(),
m_dist[i].params[0],
m_dist[i].params[1]);
break;
case LHS_TRIANGULAR:
fprintf(fp, "%s %lg TRIANGULAR %lg %lg %lg\n", (const char*)m_dist[i].name.c_str(), m_dist[i].params[1],
m_dist[i].params[0],
m_dist[i].params[1],
m_dist[i].params[2]);
break;
case LHS_GAMMA:
fprintf(fp, "%s GAMMA %lg %lg\n", (const char*)m_dist[i].name.c_str(),
m_dist[i].params[0],
m_dist[i].params[1]);
break;
case LHS_POISSON:
fprintf(fp, "%s POISSON %lg\n", (const char*)m_dist[i].name.c_str(),
m_dist[i].params[0]);
break;
case LHS_BINOMIAL:
fprintf(fp, "%s BINOMIAL %lg %lg\n", (const char*)m_dist[i].name.c_str(),
m_dist[i].params[0],
m_dist[i].params[1]);
break;
case LHS_EXPONENTIAL:
fprintf(fp, "%s EXPONENTIAL %lg\n", (const char*)m_dist[i].name.c_str(),
m_dist[i].params[0]);
break;
case LHS_WEIBULL:
fprintf(fp, "%s WEIBULL %lg %lg\n", (const char*)m_dist[i].name.c_str(),
m_dist[i].params[0],
m_dist[i].params[1]);
break;
case LHS_USERCDF:
ncdfpairs = (int) m_dist[i].params[0];
fprintf(fp, "%s DISCRETE CUMULATIVE %d #\n", (const char*)m_dist[i].name.c_str(), ncdfpairs);
// update for uniform discrete distributions initially
if (ncdfpairs <= 0)
{
m_errmsg.Printf("user defined CDF error: too few [value,cdf] pairs in list: %d pairs should exist.", ncdfpairs);
fclose(fp);
return false;
}
/*
for (int j = 0; j<ncdfpairs; j++)
{
double cdf = (j + 1);
cdf /= (double)ncdfpairs;
if (cdf > 1.0) cdf = 1.0;
fprintf(fp, " %d %lg", j, cdf);
if (j == ncdfpairs - 1) fprintf(fp, "\n");
else fprintf(fp, " #\n");
}
*/
for (int j=0;j<ncdfpairs;j++)
{
if (2+2*j >= (int)m_dist[i].params.size())
{
m_errmsg.Printf("user defined CDF error: too few [value,cdf] pairs in list: %d pairs should exist.", ncdfpairs);
fclose(fp);
return false;
}
fprintf(fp, " %lg %lg", m_dist[i].params[ 1+2*j ], m_dist[i].params[ 2+2*j ] );
if (j==ncdfpairs-1) fprintf(fp, "\n");
else fprintf(fp, " #\n");
}
break;
}
}
for (size_t i=0;i<m_corr.size();i++)
{
if (Find(m_corr[i].name1)>=0 && Find(m_corr[i].name2)>=0)
fprintf(fp, "CORRELATE %s %s %lg\n", (const char*)m_corr[i].name1.c_str(), (const char*)m_corr[i].name2.c_str(), m_corr[i].corr);
}
fclose(fp);
// now run using the callback provided or 'system' function
// delete any output or error that may exist
if( wxFileExists( workdir + "/SAMLHS.LSP" ) )
wxRemoveFile( workdir + "/SAMLHS.LSP" );
if( wxFileExists( workdir + "/LHS.ERR" ) )
wxRemoveFile( workdir + "/LHS.ERR" );
// run the executable synchronously
wxString curdir = wxGetCwd();
wxSetWorkingDirectory( workdir );
wxString execstr = wxString('"' + lhsexe + "\" SAMLHS.LHI");
bool exe_ok = ( 0 == wxExecute( execstr, wxEXEC_SYNC|wxEXEC_HIDE_CONSOLE ) );
wxSetWorkingDirectory(curdir);
exe_ok = true;
if (wxFileExists(workdir + "/LHS.ERR"))
{
m_errmsg = "LHS error. There could be a problem with the input setup.";
FILE *ferr = fopen( wxString(workdir + "/LHS.ERR").c_str(), "r");
if (ferr)
{
char buf[256];
m_errmsg += "\n\n";
wxString line;
while ( !feof(ferr) )
{
fgets( buf, 255, ferr );
m_errmsg += wxString(buf) + "\n";
}
fclose(ferr);
}
return false;
}
if (!exe_ok)
{
m_errmsg = "Failed to run LHS executable";
return false;
}
// read the lsp output file
wxString outputfile = workdir + "/SAMLHS.LSP";
fp = fopen( outputfile.c_str(), "r");
if (!fp)
{
m_errmsg = "Could not read output file " + outputfile;
return false;
}
for (size_t i=0;i<m_dist.size();i++)
{
m_dist[i].values.clear();
m_dist[i].values.reserve( m_npoints );
}
int nline = 0;
char cbuf[1024];
int n_runs = 0;
bool found_data = false;
while ( !feof(fp) )
{
fgets(cbuf, 1023, fp);
wxString buf( cbuf );
nline++;
if (buf.Trim() == "@SAMPLEDATA")
{
found_data = true;
continue;
}
if (found_data)
{
if ( n_runs == m_npoints )
break;
n_runs++;
int n = atoi(buf.c_str());
if (n != n_runs)
{
m_errmsg = wxString::Format("output file formatting error (run count %d!=%d) at line %d: ",n, n_runs, nline) + buf;
fclose(fp);
return false;
}
fgets(cbuf, 1023, fp);
wxString buf( cbuf );
nline++;
n = atoi(buf.c_str());
if (n != (int) m_dist.size())
{
m_errmsg = "output file formatting error (ndist count) at line " + wxString::Format("%d",nline);
fclose(fp);
return false;
}
for (size_t i=0;i<m_dist.size();i++)
{
fgets(cbuf, 1023, fp);
wxString buf( cbuf );
nline++;
m_dist[i].values.push_back( wxAtof( buf ) );
}
}
}
fclose( fp );
return true;
}
wxString LHS::ErrorMessage()
{
return m_errmsg;
}
void LHS::Points(int n)
{
if (n > 0 && n < 50000)
m_npoints = n;
}
void LHS::Correlate(const wxString &name1, const wxString &name2, double corr)
{
if (corr > -1 && corr < 1)
{
CorrInfo x;
x.name1 = name1;
x.name2 = name2;
x.corr = corr;
m_corr.push_back(x);
}
}
void LHS::Distribution(int type, const wxString &name, const std::vector<double> ¶ms)
{
int idx = Find(name);
if (idx >= 0)
{
m_dist[idx].type = type;
m_dist[idx].name = name;
m_dist[idx].params = params;
}
else
{
DistInfo x;
x.type = type;
x.name = name;
x.params = params;
m_dist.push_back( x );
}
}
bool LHS::Retrieve(const wxString &name, std::vector<double> &values)
{
int idx = Find(name);
if (idx < 0)
return false;
values = m_dist[idx].values;
return true;
}
wxArrayString LHS::ListAll()
{
wxArrayString list;
for (size_t i=0;i<m_dist.size();i++)
list.Add(m_dist[i].name);
return list;
}
void LHS::Remove(const wxString &name)
{
int idx = Find(name);
if (idx < 0) return;
m_dist.erase( m_dist.begin() + idx );
}
void LHS::RemoveCorrelation(const wxString &name1, const wxString &name2)
{
for (size_t i=0;i<m_corr.size();i++)
{
if (m_corr[i].name1 == name1 && m_corr[i].name2 == name2)
{
m_corr.erase( m_corr.begin() + i );
return;
}
}
}
int LHS::Find(const wxString &name)
{
for (size_t i=0;i<m_dist.size();i++)
if (m_dist[i].name == name)
return i;
return -1;
}
#ifdef __WXMSW__
#define STWBINARY "stepwise.exe"
#else
#define STWBINARY "stepwise.bin"
#endif
Stepwise::Stepwise()
{
/* nothing to do */
}
void Stepwise::Reset()
{
m_inputs.clear();
m_output_vec.clear();
m_err.Empty();
}
bool Stepwise::Exec( )
{
wxString workdir( wxFileName::GetTempDir() );
wxString exe( SamApp::GetRuntimePath() + "/bin/" + STWBINARY );
if (!wxFileExists(exe))
{
m_err = "STEPWISE executable does not exist: " + exe;
return false;
}
// check inputs and outputs
int datalen = -1;
for (size_t i=0;i<m_inputs.size();i++)
{
if (datalen < 0) datalen = m_inputs[i].vec.size();
if ((int)m_inputs[i].vec.size() != datalen)
{
m_err = "Inconsistent input data vector lengths.";
return false;
}
}
if ((int)m_output_vec.size() != datalen)
{
m_err = "Inconsistent output data vector length.";
return false;
}
// write input vector file
wxString input_data = workdir + "/input_data.txt";
FILE *fp = fopen(input_data.c_str(), "w");
if (!fp)
{
m_err = "Could not open input_data.txt for writing.";
return false;
}
// write headers
for (size_t i=0;i<m_inputs.size();i++)
fprintf(fp, "%s%c", (const char*)m_inputs[i].name.c_str(), i<m_inputs.size()-1 ? '\t' : '\n');
// write data columns
for (int i=0;i<datalen;i++)
for (size_t j=0;j<m_inputs.size();j++)
fprintf(fp, "%lg%c", m_inputs[j].vec[i], j<m_inputs.size()-1 ? '\t' : '\n');
fclose(fp);
// write output vector file
wxString output_data = workdir + "/output.txt";
fp = fopen(output_data.c_str(), "w");
if (!fp)
{
m_err = "Could not open output.txt for writing.";
return false;
}
for(int i=0;i<datalen;i++)
fprintf(fp, "%lg\n", m_output_vec[i]);
fclose(fp);
// write control file
wxString control_file = workdir + "/stepin.txt";
fp = fopen(control_file.c_str(), "w");
if (!fp)
{
m_err = "Could not open stepin.txt for writing.";
return false;
}
fprintf(fp, "stp_test_usr.inp ! user file name\n");
fprintf(fp, "stp_test_ind.dat ! independent (input) data file name\n");
fprintf(fp, "stp_test_dep.dat ! dependent (output) data file name\n");
fprintf(fp, "stp_test_out.out ! result file name\n");
fprintf(fp, "1 ! TITLE - 1: include title ; 0 : do not include title\n");
fprintf(fp, "First_Analysis ! title if included: up to 30 characters\n");
fprintf(fp, "%d ! number of input parameters\n", (int)m_inputs.size());
fprintf(fp, "1 ! number of timesteps (not implemented yet)\n");
fprintf(fp, "1 ! LABEL - 0: no label, 1: label following, 2: input label in input file\n");
fprintf(fp, "Y ! output label (for option 1 in label) \n");
fprintf(fp, "0 ! BACKWARD regression ; 0= do not include ; 1 = include\n");
fprintf(fp, "1 ! STEPWISE regression ; 0= do not include ; 1 = include\n");
fprintf(fp, "0.05 ! SIGIN for STEPWISE regression (option 1 in Stepwise)\n");
fprintf(fp, "0.05 ! SIGOUT for STEPWISE regression (option 1 in Stepwise)\n");
fprintf(fp, "0 ! Forced variables - 1: include - 0: do not include\n");
fprintf(fp, "0 ! Dropped variables - 1: include - 0: do not include\n");
fprintf(fp, "0 ! PRESS - 1: include - 0: do not include\n");
fprintf(fp, "1 ! RANK - 1: include - 0: do not include\n");
fprintf(fp, "0 ! WEIGHT - 1: include - 0: do not include\n");
fclose(fp);
/*
-------- EXAMPLE INPUT FILE FROM C.Sallaberry August 2010 for STEPWISE 2.21a WIPP -----------
stp_test.inp ! user file name
stp_test_z_ind.dat ! independent (input) data file name
stp_test_z_dep.dat ! dependent (output) data file name
stp_test_z_out.out ! result file name
1 ! TITLE - 1: include title ; 0 : do not include title
Stepwise_Test_#1 ! title if included: up to 30 characters
18 ! number of input parameters
1 ! number of timesteps (not implemented yet)
1 ! LABEL - 0: no label, 1: label following, 2: input label in input file
Y ! output label (for option 1 in label)
0 ! BACKWARD regression ; 0= do not include ; 1 = include
1 ! STEPWISE regression ; 0= do not include ; 1 = include
0.1 ! SIGIN for STEPWISE regression (option 1 in Stepwise)
0.1 ! SIGOUT for STEPWISE regression (option 1 in Stepwise)
1 ! Forced variables - 1: include - 0: do not include
1 ! number of forced variables
6 ! Forced variable #
1 ! Dropped variables - 1: include - 0: do not include
1 ! Number of dropped variables
16 ! Dropped variables #
1 ! PRESS - 1: include - 0: do not include
1 ! RANK - 1: include - 0: do not include
0 ! WEIGHT - 1: include - 0: do not include
*/
// all files written, now change folders and run STEPWISE
// delete any output file that may exist
if ( wxFileExists( workdir + "/result.txt" ) ) wxRemoveFile( workdir + "/result.txt" );
if ( wxFileExists( workdir + "/stp_test_usr.inp" ) ) wxRemoveFile( workdir + "/stp_test_usr.inp" );
if ( wxFileExists( workdir + "/stp_test_ind.dat" ) ) wxRemoveFile( workdir + "/stp_test_ind.dat" );
if ( wxFileExists( workdir + "/stp_test_dep.dat" ) ) wxRemoveFile( workdir + "/stp_test_dep.dat" );
if ( wxFileExists( workdir + "/stp_test_out.out" ) ) wxRemoveFile( workdir + "/stp_test_out.out" );
wxString curdir = wxGetCwd();
wxSetWorkingDirectory( workdir );
wxExecute( '"' + exe + '"', wxEXEC_SYNC|wxEXEC_HIDE_CONSOLE );
wxSetWorkingDirectory(curdir);
wxString results_file = workdir + "/result.txt";
fp = fopen(results_file.c_str(), "r");
if (!fp)
{
m_err = "Could not open result.txt file for reading.";
return false;
}
char cbuf[2048];
fgets(cbuf,2047, fp); // header line
fgets(cbuf,2047, fp); // delimiter line ==========
int nlines=0;
while ( !feof( fp ) )
{
if (nlines++ > (int)m_inputs.size())
break;
fgets( cbuf, 2047, fp );
wxArrayString parts = wxStringTokenize( cbuf, " \t:", wxTOKEN_STRTOK);
if (parts.Count() != 4)
continue;
bool assigned = false;
for (size_t i=0;i<m_inputs.size();i++)
{
if (m_inputs[i].name.Lower() == parts[0].Lower())
{
m_inputs[i].R2 = atof( parts[1].c_str() );
m_inputs[i].R2inc = atof( parts[2].c_str() );
m_inputs[i].SRC = atof( parts[3].c_str() );
m_inputs[i].calculated = true;
assigned = true;
}
}
}
fclose(fp);
return true;
}
wxString Stepwise::ErrorMessage()
{
return m_err;
}
// set simulation inputs and results
void Stepwise::SetInputVector(const wxString &name, const std::vector<double> &data)
{
if (name.IsEmpty()) return;
bool found = false;
for (size_t i=0;i<m_inputs.size();i++)
{
if (m_inputs[i].name == name)
{
m_inputs[i].vec = data;
found = true;
}
}
if (!found)
{
m_inputs.push_back( datavec() );
datavec &x = m_inputs[m_inputs.size()-1];
x.name = name;
x.vec = data;
x.calculated = false;
x.R2 = 0;
x.SRC = 0;
}
}
void Stepwise::SetOutputVector(const std::vector<double> &data)
{
m_output_vec = data;
}
bool Stepwise::GetStatistics(const wxString &name, double *R2, double *R2inc, double *SRC)
{
for (size_t i=0;i<m_inputs.size();i++)
{
if (m_inputs[i].name == name && m_inputs[i].calculated )
{
if (R2) *R2 = m_inputs[i].R2;
if (R2inc) *R2inc = m_inputs[i].R2inc;
if (SRC) *SRC = m_inputs[i].SRC;
return true;
}
}
return false;
}
StochasticData::StochasticData()
{
Seed = 0;
N = 100;
}
void StochasticData::Copy( StochasticData &stat )
{
Seed = stat.Seed;
N = stat.N;
Outputs = stat.Outputs;
InputDistributions = stat.InputDistributions;
Correlations = stat.Correlations;
}
void StochasticData::Write( wxOutputStream &_o )
{
wxDataOutputStream out(_o);
out.Write8( 0x8f );
out.Write8( 1 );
out.Write32( N );
out.Write32( Seed );
out.WriteString( wxJoin( Outputs, '|' ) );
out.WriteString( wxJoin( InputDistributions, '|' ) );
out.WriteString( wxJoin( Correlations, '|' ) );
out.Write8( 0x8f );
}
bool StochasticData::Read( wxInputStream &_i )
{
wxDataInputStream in(_i);
wxUint8 code = in.Read8();
in.Read8(); // ver
N = in.Read32();
Seed = in.Read32();
Outputs = wxStringTokenize( in.ReadString(), "|" );
InputDistributions = wxStringTokenize( in.ReadString(), "|" );
Correlations = wxStringTokenize( in.ReadString(), "|" );
return in.Read8() == code;
}
enum { ID_cboDistribution = wxID_HIGHEST+394 };
class InputDistDialog : public wxDialog
{
public:
wxChoice *cboDistribution;
wxStaticText *lblVarName;
wxStaticText *lblVarValue;
wxStaticText *lbls[4];
wxNumericCtrl *nums[4];
wxFlexGridSizer *grid;
wxExtGridCtrl *cdf_grid;
int m_disttype;
InputDistDialog(wxWindow *parent, const wxString &title)
: wxDialog( parent, wxID_ANY, title, wxDefaultPosition, wxScaleSize(450,350), wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER )
{
cboDistribution = new wxChoice(this, ID_cboDistribution);
//for (int i = 0; i<LHS_NUMDISTS && i < LHS_USERCDF; i++)
for (int i = 0; i<LHS_NUMDISTS ; i++)
cboDistribution->Append(wxString(::lhs_dist_names[i]).BeforeFirst(','));
cboDistribution->Select(LHS_NORMAL);
lblVarName = new wxStaticText(this, wxID_ANY, "VarName");
lblVarValue = new wxStaticText(this, wxID_ANY, "VarValue");
// wxFlexGridSizer *grid = new wxFlexGridSizer(2);
grid = new wxFlexGridSizer(2);
grid->Add(new wxStaticText(this, wxID_ANY, "Variable name:"), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5);
grid->Add( lblVarName, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
grid->Add( new wxStaticText( this, wxID_ANY, "Variable value:" ), 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
grid->Add( lblVarValue, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
for( size_t i=0;i<4;i++ )
{
lbls[i] = new wxStaticText( this, wxID_ANY, "-----" );
nums[i] = new wxNumericCtrl( this, wxID_ANY );
grid->Add( lbls[i], 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
grid->Add( nums[i], 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
}
cdf_grid = new wxExtGridCtrl(this, wxID_ANY);
cdf_grid->CreateGrid(5, 2);
cdf_grid->EnableEditing(true);
wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL );
sizer->Add( cboDistribution, 0, wxALL|wxEXPAND, 5 );
sizer->Add(grid, 1, wxALL | wxEXPAND, 0);
sizer->Add(cdf_grid, 1, wxALL | wxEXPAND, 0);
sizer->Add(CreateButtonSizer(wxOK | wxCANCEL), 0, wxALL | wxEXPAND, 10);
SetSizer( sizer );
lbls[2]->Hide(); nums[2]->Hide();
lbls[3]->Hide(); nums[3]->Hide();
}
void Setup(const wxString &name, const wxString &value,
int DistType, double p0, double p1, double p2, double p3)
{
lblVarName->SetLabel(name);
lblVarValue->SetLabel(value);
m_disttype = DistType;
cboDistribution->SetSelection(DistType);
nums[0]->SetValue(p0);
nums[1]->SetValue(p1);
nums[2]->SetValue(p2);
nums[3]->SetValue(p3);
UpdateLabels();
}
// void Setup(const wxString &name, const wxString &value,
// int DistType, wxArrayString listValues, wxArrayString cdf_values)
void Setup( int DistType, wxArrayString listValues, wxArrayString cdf_values)
{
//lblVarName->SetLabel(name);
//lblVarValue->SetLabel(value);
m_disttype = DistType;
cboDistribution->SetSelection(DistType);
cdf_grid->ClearGrid();
int num_rows = listValues.Count();
if ((num_rows == 0) || ((int)cdf_values.Count() != num_rows))
{
wxMessageBox("Error setting up user CDF");
return;
}
cdf_grid->Freeze();
cdf_grid->ResizeGrid(num_rows, 2);
cdf_grid->HideRowLabels();
cdf_grid->SetColLabelValue(0, "Value");
cdf_grid->SetColLabelValue(1, "CDF");
for (int i = 0; i < num_rows; i++)
{
cdf_grid->SetCellValue(i, 0, listValues[i]);
cdf_grid->SetReadOnly(i, 0, true);
cdf_grid->SetCellValue(i, 1, cdf_values[i]);
}
cdf_grid->AutoSize();
cdf_grid->Thaw();
UpdateLabels();
}
void UpdateLabels()
{
int cur_selection = cboDistribution->GetSelection();
wxArrayString parts = wxStringTokenize(::lhs_dist_names[cur_selection], ",");
int i;
if (m_disttype == LHS_USERCDF)
{
cdf_grid->Show(true);
grid->Show(false);
cboDistribution->SetSelection(LHS_USERCDF);
}
else
{
if (cur_selection == LHS_USERCDF)
{
cur_selection = LHS_NORMAL;
cboDistribution->SetSelection(LHS_NORMAL);
parts = wxStringTokenize(::lhs_dist_names[cur_selection], ",");
}
cdf_grid->Show(false);
grid->Show(true);
for (i = 0; i<4; i++)
{
lbls[i]->Hide();
nums[i]->Hide();
}
for (i = 1; i < (int)parts.Count(); i++)
{
lbls[i - 1]->SetLabel(parts[i] + ":");
lbls[i - 1]->Show();
nums[i - 1]->Show();
}
}
Layout();
Refresh();
}
void OnDistChange(wxCommandEvent &)
{
UpdateLabels();
}
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE( InputDistDialog, wxDialog )
EVT_CHOICE( ID_cboDistribution, InputDistDialog::OnDistChange )
END_EVENT_TABLE()
#include "case.h"
#include "casewin.h"
#include "simulation.h"
enum {
ID_lstOutputMetrics = wxID_HIGHEST+414,
ID_btnRemoveInput,
ID_btnAddInput,
ID_btnAddOutput,
ID_btnRemoveOutput,
ID_m_seed,
ID_btnAddCorr,
ID_btnEditCorr,
ID_btnRemoveCorr,
ID_m_corrList,
ID_m_inputList,
ID_m_N,
ID_btnComputeSamples,
ID_btnEditInput,
ID_Simulate,
ID_Select_Folder,
ID_Check_Weather,
ID_Combo_Weather,
ID_Show_Weather_CDF
};
BEGIN_EVENT_TABLE( StochasticPanel, wxPanel )
EVT_NUMERIC( ID_m_N, StochasticPanel::OnNChange)
EVT_NUMERIC( ID_m_seed, StochasticPanel::OnSeedChange)
EVT_BUTTON( ID_btnAddInput, StochasticPanel::OnAddInput)
EVT_BUTTON( ID_btnRemoveInput, StochasticPanel::OnRemoveInput)
EVT_BUTTON( ID_btnEditInput, StochasticPanel::OnEditInput)
EVT_LISTBOX_DCLICK( ID_m_inputList, StochasticPanel::OnEditInput)
EVT_BUTTON( ID_btnAddOutput, StochasticPanel::OnAddOutput)
EVT_BUTTON( ID_btnRemoveOutput, StochasticPanel::OnRemoveOutput)
EVT_BUTTON( ID_btnAddCorr, StochasticPanel::OnAddCorr)
EVT_BUTTON( ID_btnRemoveCorr, StochasticPanel::OnRemoveCorr)
EVT_BUTTON( ID_btnEditCorr, StochasticPanel::OnEditCorr)
EVT_LISTBOX_DCLICK( ID_m_corrList, StochasticPanel::OnEditCorr)
EVT_BUTTON( ID_btnComputeSamples, StochasticPanel::OnComputeSamples)
EVT_BUTTON( ID_Simulate, StochasticPanel::OnSimulate )
EVT_BUTTON(ID_Select_Folder, StochasticPanel::OnSelectFolder)
EVT_CHECKBOX(ID_Check_Weather, StochasticPanel::OnCheckWeather)
EVT_COMBOBOX(ID_Combo_Weather, StochasticPanel::OnComboWeather)
EVT_BUTTON(ID_Show_Weather_CDF, StochasticPanel::OnShowWeatherCDF)
END_EVENT_TABLE()
StochasticPanel::StochasticPanel(wxWindow *parent, Case *cc)
: wxPanel( parent ), m_case( cc ), m_sd( m_case->Stochastic() )
{
wxBoxSizer *sizer_main = new wxBoxSizer( wxVERTICAL );
wxPanel *top_panel = new wxPanel( this );
top_panel->SetBackgroundColour( wxMetroTheme::Colour( wxMT_FOREGROUND ) );
wxSize sz;
m_N = new wxNumericCtrl(top_panel, ID_m_N, 100, wxNUMERIC_INTEGER);
sz = m_N->GetBestSize();
m_N->SetInitialSize( wxSize( sz.x/2, sz.y ) );
m_seed = new wxNumericCtrl(top_panel, ID_m_seed, -1, wxNUMERIC_INTEGER);
sz = m_seed->GetBestSize();
m_seed->SetInitialSize( wxSize( sz.x/2,sz.y ) );
wxBoxSizer *top_sizer = new wxBoxSizer( wxHORIZONTAL );
top_sizer->Add( new wxMetroButton(top_panel, ID_Simulate, "Run simulations", wxNullBitmap, wxDefaultPosition, wxDefaultSize, wxMB_RIGHTARROW), 0, wxALL|wxEXPAND, 0 );
top_sizer->Add( m_useThreads = new wxCheckBox( top_panel, wxID_ANY, "Use threads"), 0, wxLEFT|wxRIGHT|wxEXPAND, 3);
m_useThreads->SetValue( true );
m_useThreads->Hide();
top_sizer->AddStretchSpacer();
wxStaticText *lbl;
top_sizer->Add( lbl = new wxStaticText(top_panel, wxID_ANY, "Number of samples:"), 0, wxLEFT|wxRIGHT|wxALIGN_CENTER_VERTICAL, 3 );
lbl->SetForegroundColour( *wxWHITE );
top_sizer->Add( m_N, 0, wxLEFT|wxRIGHT|wxALIGN_CENTER_VERTICAL, 3 );
top_sizer->Add( lbl = new wxStaticText(top_panel, wxID_ANY, "Seed value (0 for random):"), 0, wxLEFT|wxRIGHT|wxALIGN_CENTER_VERTICAL, 3 );
lbl->SetForegroundColour( *wxWHITE );
top_sizer->Add( m_seed, 0, wxLEFT|wxRIGHT|wxALIGN_CENTER_VERTICAL, 3 );
top_sizer->Add( new wxMetroButton(top_panel, ID_btnComputeSamples, "Compute samples"), 0, wxALL, 0 );