forked from NatLabRockies/SAM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulation.cpp
More file actions
2156 lines (1804 loc) · 58.1 KB
/
simulation.cpp
File metadata and controls
2156 lines (1804 loc) · 58.1 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
/*
BSD 3-Clause License
Copyright (c) Alliance for Energy Innovation, LLC. See also https://github.com/NREL/SAM/blob/develop/LICENSE
All rights reserved.
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, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder 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.
*/
#include <algorithm>
#include <iostream>
#include <fstream>
#include <wx/datstrm.h>
#include <wx/gauge.h>
#include <wx/progdlg.h>
#include <wx/thread.h>
#include <wx/statline.h>
#include <wx/stattext.h>
#include <wx/file.h>
#include <wx/ffile.h>
#include <wx/filedlg.h>
#include <wx/filefn.h>
#include <wex/metro.h>
#include <wex/utils.h>
#include <lk/absyn.h>
#include <lk/stdlib.h>
#include <lk/eval.h>
#include <ssc/sscapi.h>
#include "simulation.h"
#include "main.h"
#include "equations.h"
#include "case.h"
#include "codegenerator.h" // write out ssc inputs for generating tests from SAM simulations
bool VarValueToSSC( VarValue *vv, ssc_data_t pdata, const wxString &sscname, bool match_case )
{
auto var = ssc_var_create();
if (!vv->AsSSCVar(var)){
ssc_var_free(var);
return false;
}
if (match_case)
ssc_data_set_var_match_case(pdata, sscname.c_str(), var);
else
ssc_data_set_var(pdata, sscname.c_str(), var);
ssc_var_free(var);
return true;
}
Simulation::Simulation( Case *cc, const wxString &name )
: m_case( cc ), m_name( name )
{
m_totalElapsedMsec = 0;
m_sscElapsedMsec = 0;
m_bSscTestsGeneration = false;
}
static void write_array_string( wxDataOutputStream &out, wxArrayString &list )
{
out.Write32( list.size() );
for( size_t i=0;i<list.size();i++ )
out.WriteString( list[i] );
}
static void read_array_string( wxDataInputStream &in, wxArrayString &list )
{
list.Clear();
size_t n = in.Read32();
for( size_t i=0;i<n;i++ )
list.Add( in.ReadString() );
}
void Simulation::Write( wxOutputStream &os )
{
size_t i;
wxDataOutputStream out( os );
out.Write8( 0x9c );
out.Write8( 4 ); // version - update to 4 for hybrids m_inputs and m_overrides
out.WriteString( m_name );
out.Write8(m_overrides.size());
for (i = 0; i < m_overrides.size(); i++)
write_array_string( out, m_overrides[i]);
out.Write8(m_inputs.size());
for (i=0; i < m_inputs.size(); i++)
m_inputs[i].Write(os);
m_outputs.Write( os, SamApp::Project().GetSaveHourlyData() ? 0 : 1024 );
write_array_string( out, m_errors );
write_array_string( out, m_warnings );
write_array_string( out, m_notices );
m_outputLabels.Write( os );
m_outputUnits.Write( os );
m_uiHints.Write(os);
out.Write8( 0x9c );
}
bool Simulation::Read(wxInputStream& is)
{
size_t i;
Clear();
wxDataInputStream in(is);
wxUint8 code = in.Read8(); // code
wxUint8 ver = in.Read8(); // ver
m_name = in.ReadString();
if (ver > 3) {
size_t n = in.Read8();
m_overrides.resize(n);
for (i = 0; i < m_overrides.size(); i++)
read_array_string(in, m_overrides[i]);
n = in.Read8();
m_inputs.resize(n);
for (i = 0; i < m_inputs.size(); i++)
m_inputs[i].Read(is);
}
else {
m_overrides.resize(1);
read_array_string(in, m_overrides[0]);
m_inputs.resize(1);
m_inputs[0].Read(is);
}
m_outputs.Read(is);
read_array_string( in, m_errors );
read_array_string( in, m_warnings );
if ( ver > 1 ) read_array_string( in, m_notices );
m_outputLabels.Read( is );
m_outputUnits.Read( is );
if (ver > 2)
m_uiHints.Read( is );
return ( code == in.Read8() );
}
void Simulation::Copy( const Simulation &rh )
{
Clear();
m_name = rh.m_name;
m_overrides = rh.m_overrides;
m_inputs = rh.m_inputs;
m_outputs = rh.m_outputs;
m_errors = rh.m_errors;
m_warnings = rh.m_warnings;
m_notices = rh.m_notices;
m_outputLabels = rh.m_outputLabels;
m_outputUnits = rh.m_outputUnits;
m_uiHints = rh.m_uiHints;
}
void Simulation::Clear()
{
size_t i;
for (i = 0; i < m_overrides.size(); i++)
m_overrides[i].clear();
m_overrides.clear();
for (i = 0; i < m_inputs.size(); i++)
m_inputs[i].clear();
m_inputs.clear();
m_outputList.clear();
m_outputs.clear();
m_errors.clear();
m_warnings.clear();
m_notices.clear();
m_outputLabels.clear();
m_outputUnits.clear();
m_uiHints.clear();
Setup(); // resize after clearing
}
void Simulation::Override( const wxString &name, const VarValue &val, size_t ndxHybrid)
{
if ( VarValue *vv = m_inputs[ndxHybrid].Create(name, val.Type()))
{
m_overrides[ndxHybrid].Add(name);
vv->Copy( val );
}
}
wxString Simulation::GetOverridesLabel(size_t ndxHybrid, bool with_labels )
{
wxString tag;
for( size_t i=0;i<m_overrides[ndxHybrid].size(); i++)
{
if ( VarValue *vv = m_inputs[ndxHybrid].Get(m_overrides[ndxHybrid][i]))
{
wxString label = m_overrides[ndxHybrid][i];
if ( with_labels )
if ( VarInfo *vi = m_case->Variables(ndxHybrid).Lookup( m_overrides[ndxHybrid][i] ) )
if ( !vi->Label.IsEmpty() )
label = vi->Label;
tag += label + "=" + vv->AsString();
if ( i < m_overrides.size()-1 )
tag += ";";
}
}
return tag;
}
VarValue *Simulation::GetInput( const wxString &name, size_t ndxHybrid)
{
if ( VarValue *val = m_inputs[ndxHybrid].Get(name))
return val;
if (VarValue* val = m_case->Values(ndxHybrid).Get(name))
return val;
return NULL;
}
void Simulation::SetInput(const wxString & , lk::vardata_t) {
//if (VarValue *vv = m_inputs.Get(name)) {
// if (vv->Type == VV_NUMBER && val.type == 3) {
// }
// else if (vv->Type == VV_STRING && val.type == 4) {
// }
// else if (vv->Type == VV_ARRAY && val.type == 5) {
// }
//}
}
bool Simulation::Ok()
{
return m_errors.size() == 0;
}
wxArrayString &Simulation::GetErrors()
{
return m_errors;
}
void Simulation::SetErrors(wxArrayString &_errors)
{
m_errors = _errors;
}
wxArrayString &Simulation::GetWarnings()
{
return m_warnings;
}
wxArrayString &Simulation::GetNotices()
{
return m_notices;
}
VarTable &Simulation::Outputs()
{
return m_outputs;
}
wxArrayString Simulation::ListOutputs()
{
return m_outputList;
}
VarValue *Simulation::GetOutput( const wxString &var )
{
return Outputs().Get( var );
}
VarValue *Simulation::GetValue( const wxString &name )
{
if ( VarValue *vv = Outputs().Get( name ) )
return vv;
else {
// search from last to first vartable for hybrids i=ndxHybrid and name is variable name in vorrect vartable - may report incorrect value for same names in different vartables
bool found = false;
for (int i = m_inputs.size() - 1; i>=0 && !found; i--) {
if (vv = GetInput(name, i))
found = true;
}
if (!found) {
for (int i = m_case->GetConfiguration()->Technology.size() - 1; i >= 0 && !found; i--) {
if (vv = m_case->Values(i).Get(name))
found = true;
}
}
return vv;
}
}
wxString Simulation::GetLabel( const wxString &var )
{
if ( m_outputLabels.find( var ) != m_outputLabels.end() )
return m_outputLabels[ var ];
else {
bool found = false;
wxString label = wxEmptyString;
for (int i = m_inputs.size() - 1; i >= 0 && !found; i--) {
label = m_case->Variables(i).Label(var);
found = (label.Left(11) != "<not found:");
}
return label;
}
}
wxString Simulation::GetUnits( const wxString &var )
{
if ( m_outputUnits.find( var ) != m_outputUnits.end() )
return m_outputUnits[ var ];
else {
bool found = false;
wxString units = wxEmptyString;
for (int i = m_inputs.size() - 1; i >= 0 && !found; i--) {
units = m_case->Variables(i).Units(var);
found = (units != wxEmptyString);
}
return units;
}
}
StringHash Simulation::GetUIHints(const wxString &var)
{
StringHash tmp;
if (m_uiHints.find(var) != m_uiHints.end())
{
wxString value = m_uiHints[var];
value.UpperCase();
tmp.Split(value, ',', '=');
}
return tmp;
}
class SingleThreadHandler : public ISimulationHandler
{
wxProgressDialog *progdlg;
wxString save_folder;
public:
SingleThreadHandler() {
progdlg = 0;
save_folder = wxGetHomeDir();
};
void SetProgressDialog( wxProgressDialog *d ) { progdlg = d; }
virtual void Update( float percent, const wxString &s ) {
if( progdlg) progdlg->Update( (int)percent, s );
}
virtual bool IsCancelled() {
if ( progdlg) return progdlg->WasCancelled();
else return false;
}
virtual bool WriteDebugFile( const wxString &sim, ssc_module_t p_mod, ssc_data_t p_data )
{
return Simulation::WriteDebugFile(sim, p_mod, p_data);
}
};
class SingleThreadHandlerWithDebugOutput : public ISimulationHandler
{
wxProgressDialog* progdlg;
wxString save_folder;
public:
SingleThreadHandlerWithDebugOutput() {
progdlg = 0;
save_folder = wxGetHomeDir();
};
void SetProgressDialog(wxProgressDialog* d) { progdlg = d; }
virtual void Update(float percent, const wxString& s) {
if (progdlg) progdlg->Update((int)percent, s);
}
virtual bool IsCancelled() {
if (progdlg) return progdlg->WasCancelled();
else return false;
}
virtual bool WriteDebugFile(const wxString& sim, ssc_module_t p_mod, ssc_data_t p_data)
{
// folder prompting
wxString fn = "ssc-" + sim + ".lk";
wxFileDialog dlg(SamApp::Window(), "Save inputs as...",
save_folder,
fn,
"SAM Script Files (*.lk)|*.lk", wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
if (dlg.ShowModal() == wxID_OK)
{
save_folder = wxPathOnly(dlg.GetPath());
return Simulation::WriteDebugFile(dlg.GetPath(), p_mod, p_data);
}
else
return false;
}
};
static ssc_bool_t ssc_invoke_handler( ssc_module_t , ssc_handler_t ,
int action_type, float f0, float ,
const char *s0, const char *,
void *user_data )
{
ISimulationHandler *hh = (ISimulationHandler*) user_data;
if (!hh) return 0;
if (action_type == SSC_LOG)
{
switch( (int)f0 )
{
case SSC_NOTICE:
hh->Notice( s0 );
break;
case SSC_WARNING:
hh->Warn( s0 );
break;
case SSC_ERROR:
hh->Error( s0 );
break;
}
return hh->IsCancelled() ? 0 : 1;
}
else if (action_type == SSC_UPDATE)
{
hh->Update( f0, s0 );
return hh->IsCancelled() ? 0 : 1;
}
else
return 0;
}
bool Simulation::InvokeSSC(bool silent, const wxString& fn)
{
SingleThreadHandler sc;
wxProgressDialog* prog = 0;
ConfigInfo* cfg = m_case->GetConfiguration();
if (!cfg)
{
m_errors.Add("no valid configuration for this case");
return false;
}
m_simlist = cfg->Simulations;
if (!silent)
{
prog = new wxProgressDialog("Simulation", "in progress", 100,
SamApp::GetMainTopWindow(),
wxPD_SMOOTH | wxPD_AUTO_HIDE );
prog->Show();
sc.SetProgressDialog(prog);
}
// Warning - be careful here if threading!
std::ifstream test(fn.ToStdString().c_str());
std::string json_str((std::istreambuf_iterator<char>(test)), std::istreambuf_iterator<char>());
auto p_data = json_to_ssc_data(json_str.c_str());
bool ok = InvokeSSCWithHandler(&sc, p_data);
if (!ok) {
wxMessageBox("ssc simulation failed " + wxJoin(m_errors, '\n'));
}
ssc_data_free(p_data);
if (prog) prog->Destroy();
return ok;
}
bool Simulation::Invoke( bool silent, bool prepare, wxString folder )
{
SingleThreadHandler sc;
// SingleThreadHandlerWithDebugOutput sc;
wxProgressDialog *prog = 0;
if (!folder.IsEmpty())
{
// set folder before progress dialog to prevent hiding
}
if ( !silent )
{
prog = new wxProgressDialog("SAM Simulation", "Simulation running...", 100,
SamApp::CurrentActiveWindow(), // progress dialog parent is current active window - works better when invoked scripting
wxPD_APP_MODAL | wxPD_SMOOTH | wxPD_CAN_ABORT | wxPD_AUTO_HIDE );
prog->Show();
sc.SetProgressDialog( prog );
}
if ( prepare && !Prepare() )
return false;
bool ok = InvokeWithHandler( &sc, folder );
if ( prog ) prog->Destroy();
return ok;
}
bool Simulation::Setup()
{
ConfigInfo* cfg = m_case->GetConfiguration();
if (!cfg)
{
m_errors.Add("no valid configuration for this case");
return false;
}
// resize vectors
size_t nHybrids = cfg->Technology.size();
m_inputs.resize(nHybrids);
m_overrides.resize(nHybrids);
return true;
}
bool Simulation::Prepare()
{
ConfigInfo *cfg = m_case->GetConfiguration();
if ( !cfg )
{
m_errors.Add("no valid configuration for this case");
return false;
}
m_simlist = cfg->Simulations;
m_outputList.clear();
m_outputLabels.clear();
m_outputUnits.clear();
m_uiHints.clear();
size_t nHybrids = cfg->Technology.size();
for (size_t ndx_hybrid = 0; ndx_hybrid < nHybrids; ndx_hybrid++) {
// transfer all the values except for ones that have been 'overriden'
for (VarTableBase::const_iterator it = m_case->Values(ndx_hybrid).begin();
it != m_case->Values(ndx_hybrid).end();
++it)
if (0 == m_inputs[ndx_hybrid].Get(it->first))
m_inputs[ndx_hybrid].Set(it->first, *(it->second));
// recalculate all the equations
CaseEvaluator eval(m_case, m_inputs[ndx_hybrid], m_case->Equations(ndx_hybrid));// update m_inputs for hybrids
int n = eval.CalculateAll(ndx_hybrid);
if (n < 0)
{
wxArrayString& errs = eval.GetErrors();
for (size_t i = 0; i < errs.size(); i++)
m_errors.Add(errs[i]);
return false;
}
//wxLogStatus("Simulation preparation time: %d copy, %d eval", (int)time_copy, (int)time_eval);
}
return true;
}
static void dump_variable( FILE *fp, ssc_data_t p_data, const char *name )
{ // .17g to .17g for full double precision.
ssc_number_t value;
ssc_number_t *p;
int len, nr, nc;
wxString str_value;
double dbl_value;
int type = ::ssc_data_query( p_data, name );
switch( type )
{
case SSC_STRING:
str_value = wxString::FromUTF8(::ssc_data_get_string( p_data, name ));
str_value.Replace("\\", "/" );
fprintf(fp, "var( '%s', '%s' );\n", name, (const char*)str_value.c_str() );
break;
case SSC_NUMBER:
::ssc_data_get_number( p_data, name, &value );
dbl_value = (double)value;
if ( dbl_value > 1e38 ) dbl_value = 1e38;
fprintf(fp, "var( '%s', %.17g );\n", name, dbl_value );
break;
case SSC_ARRAY:
p = ::ssc_data_get_array( p_data, name, &len );
fprintf(fp, "var( '%s', [", name);
for ( int i=0;i<(len-1);i++ )
{
dbl_value = (double)p[i];
if ( dbl_value > 1e38 ) dbl_value = 1e38;
fprintf(fp, " %.17g,", dbl_value );
}
dbl_value = (double)p[len-1];
if ( dbl_value > 1e38 ) dbl_value = 1e38;
fprintf(fp, " %.17g ] );\n", dbl_value );
break;
case SSC_MATRIX:
p = ::ssc_data_get_matrix( p_data, name, &nr, &nc );
len = nr*nc;
fprintf( fp, "var( '%s', \n[ [", name );
for (int k=0;k<(len-1);k++)
{
dbl_value = (double)p[k];
if ( dbl_value > 1e38 ) dbl_value = 1e38;
if ( (k+1)%nc == 0 )
fprintf(fp, " %.17g ], \n[", dbl_value);
else
fprintf(fp, " %.17g,", dbl_value);
}
dbl_value = (double)p[len-1];
if ( dbl_value > 1e38 ) dbl_value = 1e38;
fprintf(fp, " %.17g ] ] );\n", dbl_value);
}
}
bool Simulation::WriteDebugFile( const wxString &file, ssc_module_t p_mod, ssc_data_t p_data )
{
if( FILE *fp = fopen( file.c_str(), "w" ) )
{
fprintf(fp, "clear();\n");
int dbgidx = 0;
while( const ssc_info_t p_inf = ssc_module_var_info( p_mod, dbgidx++ ) )
{
const char *name = ::ssc_info_name( p_inf );
dump_variable( fp, p_data, name );
}
wxString name = wxFileName(file).GetName();
name = name.Right(name.length() - 4); // skip "ssc-"
fprintf(fp, "run('%s');\n", (const char *)name.c_str());
fclose(fp);
return true;
}
else
return false;
}
bool Simulation::WriteDebugFile( const wxString &file, ssc_data_t p_data )
{
if( FILE *fp = fopen( file.c_str(), "w" ) )
{
const char *name = ssc_data_first( p_data );
while( name )
{
dump_variable( fp, p_data, name );
name = ssc_data_next( p_data );
}
fclose( fp );
return true;
}
else
return false;
}
bool Simulation::Generate_lk(FILE *fp)
{
SingleThreadHandler ih;
if (!Prepare())
return false;
ssc_data_t p_data = ssc_data_create();
if (m_simlist.size() == 0)
ih.Error("No simulation compute modules defined for this configuration.");
for (size_t kk = 0; kk < m_simlist.size(); kk++)
{
ssc_module_t p_mod = ssc_module_create(m_simlist[kk].c_str());
if (!p_mod)
{
ih.Error("could not create ssc module: " + m_simlist[kk]);
continue;
}
int pidx = 0;
while (const ssc_info_t p_inf = ssc_module_var_info(p_mod, pidx++))
{
int var_type = ssc_info_var_type(p_inf); // SSC_INPUT, SSC_OUTPUT, SSC_INOUT
int data_type = ssc_info_data_type(p_inf); // SSC_STRING, SSC_NUMBER, SSC_ARRAY, SSC_MATRIX
wxString name(ssc_info_name(p_inf)); // assumed to be non-null
wxString reqd(ssc_info_required(p_inf));
if (var_type == SSC_INPUT || var_type == SSC_INOUT)
{
// handle ssc variable names
// that are explicit field accesses"shading:mxh"
wxString field;
int pos = name.Find(':');
if (pos != wxNOT_FOUND)
{
field = name.Mid(pos + 1);
name = name.Left(pos);
}
int existing_type = ssc_data_query(p_data, ssc_info_name(p_inf));
if (existing_type != data_type)
{
if (VarValue *vv = GetInput(name, 0)) // TODO: hybrid update
{
if (!field.IsEmpty())
{
if (vv->Type() != VV_TABLE)
ih.Error("SSC variable has table:field specification, but '" + name + "' is not a table in SAM");
bool do_copy_var = false;
if (reqd.Left(1) == "?")
{
// if the SSC variable is optional, check for the 'en_<field>' element in the table
if (VarValue *en_flag = vv->Table().Get("en_" + field))
if (en_flag->Boolean())
do_copy_var = true;
}
else do_copy_var = true;
if (do_copy_var)
{
if (VarValue *vv_field = vv->Table().Get(field))
{
if (!VarValueToSSC(vv_field, p_data, name + ":" + field))
ih.Error("Error translating table:field variable from SAM UI to SSC for '" + name + "':" + field);
}
}
}
if (!VarValueToSSC(vv, p_data, name))
ih.Error("Error translating data from SAM UI to SSC for " + name);
}
else if (reqd == "*")
ih.Error("SSC requires input '" + name + "', but was not found in the SAM UI or from previous simulations");
}
}
}
const char *name = ssc_data_first(p_data);
while (name)
{
dump_variable(fp, p_data, name);
name = ssc_data_next(p_data);
}
fprintf(fp, "run('%s');\n", (const char*)m_simlist[kk].c_str());
}
return true;
}
bool Simulation::WriteSSCTestInputs(wxString& cmod_name, ssc_module_t p_mod, ssc_data_t p_data) {
// can filter on compute module name
// if (cmod_name != "cashloan") return false;
if (std::find(std::begin(m_asSscTestsComputeModules),std::end(m_asSscTestsComputeModules), cmod_name) == std::end(m_asSscTestsComputeModules))
return false;
auto cfg = m_case->GetConfiguration();
wxString casename = SamApp::Project().GetCaseName( m_case );
wxString fn = m_sSscTestsJSONFolder; //SamApp::GetUserLocalDataDir();
wxString tech = cfg->TechnologyFullName;
tech.Replace(" ", "_");
wxString fin = cfg->Financing;
fin.Replace(" ", "_");
fn += "/" + casename + "_" + tech + "_" + fin + "_" + "cmod_" + cmod_name + ".json";
auto cg = std::make_shared<CodeGen_json>(m_case, fn);
cg->Header();
int pidx = 0;
while (const ssc_info_t p_inf = ssc_module_var_info(p_mod, pidx++)) {
int var_type = ssc_info_var_type(p_inf); // SSC_INPUT, SSC_OUTPUT, SSC_INOUT
wxString name(ssc_info_name(p_inf)); // assumed to be non-null
// wxString reqd(ssc_info_required(p_inf)); // optional if want required inputs only
if (var_type == SSC_INPUT || var_type == SSC_INOUT) { // all SSC_INPUT and SSC_INOUT without checking required
if (!cg->Input(p_data, name.c_str(), "", 0)) {
wxString err = "SSC requires input '" + name +
"', but was not found in the SAM UI or from previous simulations";
ssc_data_set_string(p_data, "error", err.c_str());
return false;
}
}
}
cg->Footer();
return true;
}
bool Simulation::WriteSSCTestOutputs(wxString& cmod_name, ssc_module_t p_mod, ssc_data_t p_data) {
// can filter on compute module name
// if (cmod_name != "cashloan") return false;
if (std::find(std::begin(m_asSscTestsComputeModules),std::end(m_asSscTestsComputeModules), cmod_name) == std::end(m_asSscTestsComputeModules))
return false;
auto cfg = m_case->GetConfiguration();
wxString casename = SamApp::Project().GetCaseName( m_case );
wxString fn = m_sSscTestsJSONFolder; //SamApp::GetUserLocalDataDir();
wxString tech = cfg->TechnologyFullName;
tech.Replace(" ", "_");
wxString fin = cfg->Financing;
fin.Replace(" ", "_");
fn += "/" + casename + "_" + tech + "_" + fin + "_" + "cmod_" + cmod_name + "_outputs.json";
auto cg = std::make_shared<CodeGen_json>(m_case, fn);
cg->Header();
int pidx = 0;
while (const ssc_info_t p_inf = ssc_module_var_info(p_mod, pidx++)) {
int var_type = ssc_info_var_type(p_inf); // SSC_INPUT, SSC_OUTPUT, SSC_INOUT
wxString name(ssc_info_name(p_inf)); // assumed to be non-null
// wxString reqd(ssc_info_required(p_inf)); // optional if want required inputs only
if (var_type == SSC_OUTPUT || var_type == SSC_INOUT) { // all SSC_OUTPUT and SSC_INOUT without checking required
if (!cg->Input(p_data, name.c_str(), "", 0)) {
// if (!cg->Output(p_data)) {
wxString err = "SSC requires output '" + name +
"', but was not found in the SAM UI or from previous simulations";
ssc_data_set_string(p_data, "error", err.c_str());
return false;
}
}
}
cg->Footer();
return true;
}
bool Simulation::JSONInputsToSSCData(wxString& fn, ssc_data_t p_data) {
bool ret = false;
std::ifstream test(fn.ToStdString().c_str());
std::string json_str((std::istreambuf_iterator<char>(test)), std::istreambuf_iterator<char>());
p_data = json_to_ssc_data(json_str.c_str());
ret = true;
return ret;
}
bool Simulation::CmodInputsToSSCData(ssc_module_t p_mod, ssc_data_t p_data) {
int pidx = 0;
while (const ssc_info_t p_inf = ssc_module_var_info(p_mod, pidx++)) {
int var_type = ssc_info_var_type(p_inf); // SSC_INPUT, SSC_OUTPUT, SSC_INOUT
int data_type = ssc_info_data_type(p_inf); // SSC_STRING, SSC_NUMBER, SSC_ARRAY, SSC_MATRIX
wxString name(ssc_info_name(p_inf)); // assumed to be non-null
wxString reqd(ssc_info_required(p_inf));
if (var_type == SSC_INPUT || var_type == SSC_INOUT) {
// handle ssc variable names
// that are explicit field accesses"shading:mxh"
wxString field;
int pos = name.Find(':');
if (pos != wxNOT_FOUND) {
field = name.Mid(pos + 1);
name = name.Left(pos);
wxLogStatus("Table value, table %s, field %s", name.c_str(), field.c_str());
}
int existing_type = ssc_data_query(p_data, ssc_info_name(p_inf));
if (existing_type != data_type) {
if (VarValue *vv = GetInput(name, 0)) { // TODO:hybrids
if (!field.IsEmpty()) {
if (vv->Type() != VV_TABLE) {
wxString err = "SSC variable has table:field specification, but '" + name +
"' is not a table in SAM";
ssc_data_set_string(p_data, "error", err.c_str());
return false;
}
bool do_copy_var = false;
if (reqd.Left(1) == "?") {
// if the SSC variable is optional, check for the 'en_<field>' element in the table
if (VarValue *en_flag = vv->Table().Get("en_" + field))
if (en_flag->Boolean())
do_copy_var = true;
} else do_copy_var = true;
if (do_copy_var) {
if (VarValue *vv_field = vv->Table().Get(field)) {
if (!VarValueToSSC(vv_field, p_data, name + ":" + field)) {
wxString err =
"Error translating table:field variable from SAM UI to SSC for '" +
name + "':" + field;
ssc_data_set_string(p_data, "error", err.c_str());
return false;
}
}
}
}
if (!VarValueToSSC(vv, p_data, name)) {
wxString err = "Error translating data from SAM UI to SSC for " + name;
ssc_data_set_string(p_data, "error", err.c_str());
return false;
}
} else if (reqd == "*") {
wxString err = "SSC requires input '" + name +
"', but was not found in the SAM UI or from previous simulations";
ssc_data_set_string(p_data, "error", err.c_str());
return false;
}
}
}
}
return true;
}
bool Simulation::SetModels()
{
ConfigInfo* cfg = m_case->GetConfiguration();
if (!cfg)
{
m_errors.Add("no valid configuration for this case");
return false;
}
m_simlist = cfg->Simulations;
return true;
}
bool Simulation::InvokeSSCWithHandler(ISimulationHandler* ih, ssc_data_t p_data)
{
assert(0 != ih);
m_totalElapsedMsec = 0;
m_sscElapsedMsec = 0;
wxStopWatch sw;
if (m_simlist.size() == 0)
ih->Error("No simulation compute modules defined for this configuration.");
// // Warning - be careful here if threading!
// std::ifstream test(fn.ToStdString().c_str());
// std::string json_str((std::istreambuf_iterator<char>(test)), std::istreambuf_iterator<char>());
// auto p_data = json_to_ssc_data(json_str.c_str());
// if (!JSONInputsToSSCData(fn, p_data)) {
// ih->Error(ssc_data_get_string(p_data, "error"));
// }
for (size_t kk = 0; kk < m_simlist.size(); kk++)
{
ssc_module_t p_mod = ssc_module_create(m_simlist[kk].c_str());
if (!p_mod) {
wxString err = "could not create ssc module: " + m_simlist[kk];
ssc_data_set_string(p_data, "error", err.c_str());