forked from NatLabRockies/SAM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcase.cpp
More file actions
1670 lines (1407 loc) · 48.1 KB
/
case.cpp
File metadata and controls
1670 lines (1407 loc) · 48.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 Sustainable Energy, 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 <wx/datstrm.h>
#include <wx/wfstream.h>
#include <wex/utils.h>
#include "case.h"
#include "equations.h"
#include "main.h"
#include "library.h"
#include "invoke.h"
#include <lk/stdlib.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h> // for stringify JSON
#include <rapidjson/filereadstream.h>
#include <rapidjson/filewritestream.h>
#define __SAVE_AS_JSON__ 1
#define __LOAD_AS_JSON__ 1
CaseCallbackContext::CaseCallbackContext( Case *cc, const wxString &name )
: m_case(cc), m_name(name)
{
// nothing to do
}
void CaseCallbackContext::SetCase( Case *cc, const wxString &name )
{
m_case = cc;
m_name = name;
}
wxString CaseCallbackContext::GetName() { return m_name; }
VarTable &CaseCallbackContext::GetValues(size_t ndxHybrid) { return GetCase().Values(ndxHybrid); }
Case &CaseCallbackContext::GetCase() { return *m_case; }
void CaseCallbackContext::SetupLibraries( lk::env_t * )
{
/* nothing here - for descendents like UICallbackContext or ResultsCallbackContext */
}
class CaseScriptInterpreter : public VarTableScriptInterpreter
{
Case *m_case;
size_t m_ndxHybrid;
public:
CaseScriptInterpreter( lk::node_t *tree, lk::env_t *env, VarTable *vt, Case *cc, size_t ndxHybrid )
: VarTableScriptInterpreter( tree, env, vt ), m_case( cc ), m_ndxHybrid(ndxHybrid)
{
}
virtual ~CaseScriptInterpreter( ) { /* nothing to do */ };
virtual bool special_set( const lk_string &name, lk::vardata_t &val )
{
if ( VarTableScriptInterpreter::special_set( name, val ) )
{
m_case->VariableChanged( name, m_ndxHybrid );
return true;
}
else
return false;
}
};
bool CaseCallbackContext::Invoke( lk::node_t *root, lk::env_t *parent_env, size_t ndxHybrid )
{
lk::env_t local_env( parent_env );
local_env.register_funcs( lk::stdlib_basic() );
local_env.register_funcs( lk::stdlib_sysio() );
local_env.register_funcs( lk::stdlib_math() );
local_env.register_funcs( lk::stdlib_string() );
local_env.register_funcs( lk::stdlib_wxui(), this );
local_env.register_funcs( invoke_general_funcs(), this );
local_env.register_funcs( invoke_casecallback_funcs(), this );
local_env.register_funcs( invoke_ssc_funcs(), this );
// add other callback environment functions
SetupLibraries( &local_env );
try {
CaseScriptInterpreter e( root, &local_env, &GetValues(ndxHybrid), m_case, ndxHybrid);
if ( !e.run() )
{
wxString text = "Could not evaluate callback function:" + m_name + "\n";
for (size_t i=0;i<e.error_count();i++)
text += e.get_error(i);
wxShowTextMessageDialog( text );
}
} catch(std::exception &e ){
wxShowTextMessageDialog( "Could not evaluate callback function: " + m_name + wxString("\n\n") + e.what());
return false;
}
return true;
}
static void fcall_technology_pCase( lk::invoke_t &cxt )
{
LK_DOC( "technology", "Return the current technology option name", "(void):string" );
if ( Case *cc = static_cast<Case*>( cxt.user_data() ) )
cxt.result().assign( cc->GetTechnology() );
}
static void fcall_financing_pCase( lk::invoke_t &cxt )
{
LK_DOC( "financing", "Return the current financing option name", "(void):string" );
if ( Case *cc = static_cast<Case*>( cxt.user_data() ) )
cxt.result().assign( cc->GetFinancing() );
}
static void fcall_analysis_period_pCase(lk::invoke_t& cxt)
{
LK_DOC("analysis_period", "Gets current analysis period for case, used for analysis period dependent variables.", "():variant");
if (Case* cc = static_cast<Case*>(cxt.user_data()))
cxt.result().assign(cc->m_analysis_period);
}
static void fcall_analysis_period_old_pCase(lk::invoke_t& cxt)
{
LK_DOC("analysis_period_old", "Gets previous analysis period for case, used for analysis period dependent variables.", "():variant");
if (Case* cc = static_cast<Case*>(cxt.user_data()))
cxt.result().assign(cc->m_analysis_period_old);
}
CaseEvaluator::CaseEvaluator( Case *cc, VarTable &vars, EqnFastLookup &efl )
: EqnEvaluator( vars, efl )
{
m_case = cc;
m_vt = &vars;
}
void CaseEvaluator::SetupEnvironment( lk::env_t &env )
{
// call base version first to register standard functions
EqnEvaluator::SetupEnvironment( env );
env.register_func( fcall_technology_pCase, m_case );
env.register_func(fcall_financing_pCase, m_case);
env.register_func(fcall_analysis_period_pCase, m_case);
env.register_func(fcall_analysis_period_old_pCase, m_case);
env.register_funcs( invoke_ssc_funcs() );
env.register_funcs( invoke_equation_funcs() );
}
int CaseEvaluator::CalculateAll(size_t ndxHybrid)
{
int nlibchanges = 0;
/* Check for project file upgrade
If file version < SAM version then skip recalculate all in Case LoadValuesFroExternal Source*/
size_t sam_ver = SamApp::Version();
size_t file_ver = SamApp::Project().GetVersionInfo();
bool update_lib = (sam_ver == file_ver);
if (update_lib) {
for (VarInfoLookup::iterator it = m_case->Variables(ndxHybrid).begin();
it != m_case->Variables(ndxHybrid).end();
++it) {
if (it->second->Flags & VF_LIBRARY
&& it->second->Type == VV_STRING) {
wxArrayString changed;
if (!UpdateLibrary(it->first, changed, ndxHybrid))
return -1;
else
nlibchanges += changed.size();
}
}
}
int nevals = EqnEvaluator::CalculateAll();
if ( nevals >= 0 ) nevals += nlibchanges;
return nevals;
}
int CaseEvaluator::Changed( const wxArrayString &vars, size_t ndxHybrid )
{
int nlibchanges=0;
wxArrayString trigger_list;
for( size_t i=0;i<vars.size();i++ )
{
trigger_list.Add( vars[i] );
wxArrayString changed;
bool ok = UpdateLibrary( vars[i], changed, ndxHybrid );
if ( ok && changed.size() > 0 )
{
for( size_t j=0;j<changed.size();j++ )
{
m_updated.Add( changed[j] );
trigger_list.Add( changed[j] );
nlibchanges++;
}
}
else if ( !ok )
return -1;
}
int nevals = EqnEvaluator::Changed( trigger_list );
if ( nevals > 0 ) nevals += nlibchanges;
return nevals;
}
int CaseEvaluator::Changed( const wxString &trigger, size_t ndxHybrid )
{
wxArrayString list;
list.Add(trigger);
return Changed( list, ndxHybrid );
}
bool CaseEvaluator::UpdateLibrary( const wxString &trigger, wxArrayString &changed, size_t ndxHybrid )
{
size_t nerrors = 0;
VarInfo *vi = m_case->Variables(ndxHybrid).Lookup( trigger );
VarValue *vv = m_vt->Get(trigger);
if (vv && vv->Type() == VV_STRING && vi && vi->Flags & VF_LIBRARY)
{
if ( vi->IndexLabels.size() == 2 )
{
// lookup the library name in vi->IndexLabels
wxString name = vi->IndexLabels[0];
int varindex = wxAtoi( vi->IndexLabels[1] );
if ( Library *lib = Library::Find( name ) )
{
// find the entry
int entry = lib->FindEntry( vv->String() );
if (entry < 0 || !lib->ApplyEntry(entry, varindex, *m_vt, changed))
{
// nerrors++;
// m_errors.Add("Library error: '" + vv->String() + "' is not available in the " + name + " library." );
wxArrayString errs( lib->GetErrors() );
for (size_t k = 0; k < errs.size(); k++)
{
if (!errs[k].IsEmpty())
{
m_errors.Add(errs[k]);
nerrors++;
}
}
}
#ifdef _DEBUG
else
wxLogStatus( "applied " + name + ":" + vv->String() + " = " + wxJoin(changed,',') );
#endif
}
else
{
nerrors++;
m_errors.Add( "Could not locate referenced library: " + name);
}
}
else
{
nerrors++;
m_errors.Add( "invalid library specification: " + wxJoin(vi->IndexLabels, ',') );
}
}
return nerrors == 0;
}
Case::Case()
: m_config(0), m_baseCase( this, wxEmptyString ), m_parametric( this )
{
m_analysis_period = 0;
m_analysis_period_old = 0;
}
Case::~Case()
{
ClearListeners();
}
Object *Case::Duplicate()
{
Case *c = new Case();
c->Copy(this);
return c;
}
bool Case::Copy( Object *obj )
{
if ( Case *rhs = dynamic_cast<Case*>( obj ) )
{
m_config = 0;
if (rhs->m_config) {
SetConfiguration(rhs->m_config->TechnologyFullName, rhs->m_config->Financing);
m_vals.resize(rhs->m_config->Technology.size());
for (size_t i = 0; i < rhs->m_config->Technology.size(); i++)
m_vals[i].Copy(rhs->m_vals[i]);
}
m_baseCase.Copy( rhs->m_baseCase );
m_properties = rhs->m_properties;
m_notes = rhs->m_notes;
m_parametric.Copy(rhs->m_parametric);
m_excelExch.Copy(rhs->m_excelExch);
m_stochastic.Copy(rhs->m_stochastic);
m_pvuncertainty.Copy(rhs->m_pvuncertainty);
m_analysis_period = rhs->m_analysis_period;
m_analysis_period_old = rhs->m_analysis_period_old;
m_graphs.clear();
for( size_t i=0;i<rhs->m_graphs.size();i++ )
m_graphs.push_back( rhs->m_graphs[i] );
return true;
}
else
return false;
}
wxString Case::GetTypeName()
{
return "sam.case";
}
void Case::Write( wxOutputStream &_o )
{
SendEvent( CaseEvent( CaseEvent::SAVE_NOTIFICATION ) );
wxDataOutputStream out(_o);
out.Write8( 0x9b );
out.Write8( 8 ); // include hybrids (multiple m_vals)
wxString tech, fin;
if ( m_config != 0 )
{
tech = m_config->TechnologyFullName;
fin = m_config->Financing;
}
// write data
out.WriteString( tech );
out.WriteString( fin );
out.Write32((wxUint32)m_vals.size());
for (size_t i = 0; i < m_vals.size(); i++)
m_vals[i].Write(_o);
m_baseCase.Write( _o );
m_properties.Write( _o );
m_notes.Write( _o );
m_excelExch.Write( _o );
out.Write32((wxUint32)m_graphs.size() );
for( size_t i=0;i<m_graphs.size();i++ )
m_graphs[i].Write( _o );
m_perspective.Write( _o );
m_parametric.Write( _o );
m_stochastic.Write( _o );
m_pvuncertainty.Write(_o);
out.Write8( 0x9b );
}
bool Case::Read( wxInputStream &_i )
{
wxDataInputStream in(_i);
m_lastError = wxEmptyString;
wxUint8 code = in.Read8();
wxUint8 ver = in.Read8(); // version
// read data
wxString tech = in.ReadString();
wxString fin = in.ReadString();
wxArrayString techary = wxSplit(tech, ' ');
if ( !SetConfiguration( tech, fin ) ) {
wxLogStatus( "Notice: errors occurred while setting configuration during project file read. Continuing...\n\n" + tech + "/" + fin);
return false;
}
size_t i;
for (i = 0; i < m_oldVals.size(); i++)
m_oldVals[i].clear();
m_oldVals.clear();
LoadStatus di;
size_t n = 1;
if (ver >=8)
n = in.Read32();
m_oldVals.resize(n);
for (i = 0; i < n; i++) {
bool ok = LoadValuesFromExternalSource(_i, i, &di, &m_oldVals[i]);
if (!ok || di.not_found.size() > 0 || di.wrong_type.size() > 0 || di.nread != m_vals[i].size()) {
wxLogStatus("discrepancy reading in values from project file: %d not found, %d wrong type, %d read != %d in config",
(int)di.not_found.size(), (int)di.wrong_type.size(), (int)di.nread, (int)m_vals.size());
if (di.not_found.size() > 0) {
wxLogStatus("\not found: " + wxJoin(di.not_found, ','));
}
if (di.wrong_type.size() > 0) {
wxLogStatus("\twrong type: " + wxJoin(di.wrong_type, ','));
}
if (m_vals[i].size() > m_oldVals[i].size()) {
for (auto& newVal : m_vals[i]) {
if (!m_oldVals[i].Get(newVal.first))
wxLogStatus("%s, %s configuration variable %s missing from project file", tech.c_str(), fin.c_str(), newVal.first.c_str());
}
}
if (m_vals[i].size() < m_oldVals[i].size()) {
for (auto& oldVal : m_oldVals[i]) {
if (!m_vals[i].Get(oldVal.first))
wxLogStatus("%s, %s project file variable %s missing from configuration", tech.c_str(), fin.c_str(), oldVal.first.c_str());
}
}
}
}
if ( ver <= 1 )
{
m_baseCase.Clear();
VarTable dum;
if ( !dum.Read( _i ) )
{
wxLogStatus("error reading dummy var table in Case::Read");
m_lastError += "Error reading dummy var table in Case::Read \n";
dum.clear();
}
}
else
if ( !m_baseCase.Read( _i ) )
{
wxLogStatus("error reading m_baseCase in Case::Read");
m_lastError += "Error reading m_baseCase in Case::Read \n";
m_baseCase.Clear();
}
if ( !m_properties.Read( _i ) )
{
wxLogStatus("error reading m_properties in Case::Read");
m_lastError += "Error reading m_properties in Case::Read \n";
m_properties.clear();
}
if ( !m_notes.Read( _i ) )
{
wxLogStatus("error reading m_notes in Case::Read");
m_lastError += "Error reading m_notes in Case::Read \n";
m_notes.clear();
}
if ( ver >= 3 )
{
if (!m_excelExch.Read( _i ))
{
wxLogStatus("error reading excel exchange data in Case::Read");
m_lastError += "Error reading excel exchange data in Case::Read \n";
//m_excelExch.clear();
}
}
if ( ver >= 4 )
{
m_graphs.clear();
size_t n = in.Read32();
for( size_t i=0;i<n;i++)
{
Graph g;
if ( !g.Read( _i ) )
{
wxLogStatus("error reading Graph %d of %d in Case::Read", (int)i, (int)n);
m_lastError += wxString::Format("Error reading Graph %d of %d in Case::Read", (int)i, (int)n);
}
else
m_graphs.push_back( g );
}
if ( !m_perspective.Read( _i ) )
{
wxLogStatus("error reading perspective of results viewer in Case::Read");
m_lastError += "Error reading perspective of results viewer in Case::Read \n";
m_perspective.clear();
}
}
if ( ver >= 5 )
{
if (!m_parametric.Read(_i))
{
wxLogStatus("error reading parametric simulation information in Case::Read");
m_lastError += "Error reading parametric simulation information in Case::Read \n";
m_parametric.ClearRuns();
// m_parametric.clear();
}
}
if ( ver >= 6 )
{
if ( !m_stochastic.Read( _i ) )
{
wxLogStatus("error reading stochastic simulation information in Case::Read");
m_lastError += "Error reading stochastic simulation information in Case::Read \n";
// m_stochastic.clear();
}
}
if (ver >= 7)
{
if (!m_pvuncertainty.Read(_i))
{
wxLogStatus("error reading pvuncertainty simulation information in Case::Read");
m_lastError += "Error reading pvuncertainty simulation information in Case::Read \n";
// m_pvuncertainty.clear();
}
}
return (in.Read8() == code);
}
bool Case::SaveDefaults(bool quiet)
{
if (!m_config)
{
return false;
}
wxString file;
file = SamApp::GetRuntimePath() + "/defaults/"
+ m_config->TechnologyFullName + "_" + m_config->Financing + ".json";
if (!quiet && wxNO == wxMessageBox("Save defaults for configuration:\n\n"
+ m_config->TechnologyFullName + " / " + m_config->Financing,
"Save Defaults", wxYES_NO))
return false;
rapidjson::Document doc;
doc.SetObject();
for (size_t i = 0; i < m_config->Technology.size(); i++) {
// set default library_folder_list blank
VarValue* vv = m_vals[i].Get("library_folder_list");
if (vv) vv->Set(wxString("x"));
wxArrayString asCalculated, asIndicator;
auto& vil = Variables(i);
for (auto& var : vil) {
if (var.second->Flags & VF_CHANGE_MODEL)
continue;
else if (var.second->Flags & VF_CALCULATED)
asCalculated.push_back(var.first);
else if (var.second->Flags & VF_INDICATOR)
asIndicator.push_back(var.first);
}
if (m_config->Technology.size()>1) { //hybrid - write out compute module
rapidjson::Document json_table(&doc.GetAllocator()); // for table inside of json document.
m_vals[i].Write_JSON(json_table, asCalculated, asIndicator);
wxString name = m_config->Technology[i];
doc.AddMember(rapidjson::Value(name.c_str(), (rapidjson::SizeType)name.size(), doc.GetAllocator()).Move(), json_table.Move(), doc.GetAllocator());
}
else {
m_vals[i].Write_JSON(doc, asCalculated, asIndicator);
}
}
rapidjson::StringBuffer os;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(os); // MSPT/MP 64MB JSON, 6.7MB txt, JSON Zip 242kB
doc.Accept(writer);
wxString sfn = file;
wxFileName fn(sfn);
wxFFileOutputStream out(sfn);
out.Write(os.GetString(), os.GetSize());
out.Close();
wxLogStatus("Case: defaults saved for " + file);
return true;
}
bool Case::SaveAsSSCJSON(wxString filename)
{
// similar to CodeGen_json but uses RapidJSON instead of fprintf (prototype for rewriting codegenerator)
// run equations to update calculated values
// write out all inputs for all compute modules
ConfigInfo* cfg = GetConfiguration();
if (!cfg) return false;
char json_string[32256];
// TODO - finish and concatenate based on hybrid compute modules - see test input json for cmod_hybrid
for (size_t i = 0; i < cfg->Technology.size(); i++) {
VarTable inputs = Values(i); // SAM VarTable for the case
CaseEvaluator eval(this, inputs, Equations(i));
int n = eval.CalculateAll(i);
if (n < 0) return false;
// get list of compute modules from case configuration
wxArrayString simlist = cfg->Simulations;
if (simlist.size() == 0) return false;
// go through and translate all SAM UI variables to SSC variables
ssc_data_t p_data = ssc_data_create();
for (size_t kk = 0; kk < simlist.size(); kk++)
{
ssc_module_t p_mod = ssc_module_create(simlist[kk].c_str());
if (!p_mod) 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 ssc_data_type = ssc_info_data_type(p_inf); // SSC_STRING, SSC_NUMBER, SSC_ARRAY, SSC_MATRIX
const char* var_name = ssc_info_name(p_inf);
wxString name(var_name); // assumed to be non-null
wxString reqd(ssc_info_required(p_inf));
if (var_type == SSC_INPUT || var_type == SSC_INOUT) {
int existing_type = ssc_data_query(p_data, ssc_info_name(p_inf));
if (existing_type != ssc_data_type) {
if (VarValue* vv = Values(i).Get(name)) {
if (!VarValueToSSC(vv, p_data, name, true))
wxLogStatus("Error translating data from SAM UI to SSC for " + name);
}
}
}
}
}
strcpy(json_string,ssc_data_to_json(p_data));
}
rapidjson::Document doc;
doc.Parse(json_string);
rapidjson::StringBuffer os;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(os);
doc.Accept(writer);
wxFFileOutputStream out(filename);
out.Write(os.GetString(), os.GetSize());
out.Close();
return true;
}
bool Case::SaveAsJSON(bool quiet, wxString fn, wxString case_name)
{
if (!m_config) return false;
wxFileName filename = wxFileName(fn);
wxString file;
if (filename.IsOk()) {
file = filename.GetLongPath();
if (!quiet && wxNO == wxMessageBox("Save defaults for configuration:\n\n"
+ m_config->TechnologyFullName + " / " + m_config->Financing,
"Save Defaults", wxYES_NO))
return false;
for (size_t i = 0; i < m_config->Technology.size(); i++) {
// set default library_folder_list blank
VarValue* vv = m_vals[i].Get("library_folder_list");
if (vv) vv->Set(wxString("x"));
m_vals[i].Set("Technology", VarValue(m_config->Technology[i]));
m_vals[i].Set("Financing", VarValue(m_config->Financing));
m_vals[i].Set("Case_name", VarValue(case_name));
wxArrayString asCalculated, asIndicator;
auto& vil = Variables(i);
for (auto& var : vil) {
if (var.second->Flags & VF_CHANGE_MODEL)
continue;
else if (var.second->Flags & VF_CALCULATED)
asCalculated.push_back(var.first);
else if (var.second->Flags & VF_INDICATOR)
asIndicator.push_back(var.first);
}
m_vals[i].Write_JSON(file.ToStdString(), asCalculated, asIndicator);
}
wxLogStatus("Case: saved as JSON: " + file);
return true;
}
else {
return false;
}
}
// call SamApp::VarTablesFromJSONFile
/*
bool Case::VarTablesFromJSONFile(std::vector<VarTable>& vt, const std::string& file)
{
if (!m_config ||(vt.size() < 1) || (m_config->Technology.size()<1))
return false;
else if (m_config->Technology.size() < 2)
return vt[0].Read_JSON(file);
else { // hybrid
rapidjson::Document doc, table;
wxFileInputStream fis(file);
if (!fis.IsOk()) {
wxLogError(wxS("Couldn't open the file '%s'."), file);
return false;
}
wxStringOutputStream os;
fis.Read(os);
rapidjson::StringStream is(os.GetString().c_str());
doc.ParseStream(is);
if (doc.HasParseError()) {
wxLogError(wxS("Could not read the json file string conversion '%s'."), file);
return false;
}
else {
bool ret = true;
for (size_t i = 0; i < m_config->Technology.size(); i++) {
table.CopyFrom(doc[m_config->Technology[i].ToStdString().c_str()], doc.GetAllocator());
ret = ret && vt[i].Read_JSON(table);
}
return ret;
}
}
}
*/
bool Case::VarTableFromJSONFile(VarTable* vt, const std::string& file)
{
if (!vt)
return false;
else
return vt->Read_JSON(file);
}
bool Case::LoadValuesFromExternalSource( wxInputStream &in, size_t ndxHybrid, LoadStatus *di, VarTable *oldvals, bool binary)
{
VarTable vt;
// All project files are assumed to be stored as binary
bool read_ok = true;
if (!binary) // text call from LoadDefaults
read_ok = vt.Read_text(in);
else
read_ok = vt.Read(in);
if (!read_ok)
{
wxString e("Error reading inputs from external source");
if ( di ) di->error = e;
wxLogStatus( e );
return false;
}
if ( di ) di->nread = vt.size();
bool ok = (vt.size() == m_vals[ndxHybrid].size());
// copy over values for variables that already exist
// in the configuration
for( VarTable::iterator it = vt.begin();it != vt.end(); ++it ) {
if (VarValue* vv = m_vals[ndxHybrid].Get(it->first))
{
if (vv->Type() == it->second->Type()) {
vv->Copy(*(it->second));
if (oldvals) oldvals->Set(it->first, *(it->second));
}
else
{
if (di) di->wrong_type.Add(it->first + wxString::Format(": expected:%d got:%d", vv->Type(), it->second->Type()));
if (oldvals) oldvals->Set(it->first, *(it->second));
ok = false;
}
}
else
{
if (di) di->not_found.Add(it->first);
if (oldvals) oldvals->Set(it->first, *(it->second));
ok = false;
}
/* TODO: hybrids - turn back on after all vartable dependencies resolved
if (RecalculateAll(ndxHybrid) < 0)
{
wxString e("Error recalculating equations after loading values from external source");
if (di) di->error = e;
wxLogStatus(e);
return false;
}
*/
}
return ok;
}
bool Case::LoadValuesFromExternalSource(const VarTable& vt, size_t ndxHybrid, LoadStatus* di, VarTable* oldvals)
{
bool read_ok = true;
if (!read_ok)
{
wxString e("Error reading inputs from external source");
if ( di ) di->error = e;
wxLogStatus( e );
return false;
}
if ( di ) di->nread = vt.size();
bool ok = (vt.size() == m_vals[ndxHybrid].size());
// copy over values for variables that already exist
// in the configuration
for( VarTable::const_iterator it = vt.begin(); it != vt.end(); ++it ) {
if (VarValue* vv = m_vals[ndxHybrid].Get(it->first))
{
if (vv->Type() == it->second->Type()) {
vv->Copy(*(it->second));
if (oldvals) oldvals->Set(it->first, *(it->second));
}
else
{
if (di) di->wrong_type.Add(it->first + wxString::Format(": expected:%d got:%d", vv->Type(), it->second->Type()));
if (oldvals) oldvals->Set(it->first, *(it->second));
ok = false;
}
}
else
{
if (di) di->not_found.Add(it->first);
if (oldvals) oldvals->Set(it->first, *(it->second));
ok = false;
}
/*
if (RecalculateAll(ndxHybrid, true) < 0) // shj - testing
{
wxString e("Error recalculating equations after loading values from external source");
if (di) di->error = e;
wxLogStatus(e);
return false;
}
*/
}
return ok;
}
bool Case::PreRunSSCJSON(const wxString& tech, const wxString& fin, const wxString& fn, wxString* error_msg)
{
m_baseCase.Clear();
m_config = SamApp::Config().Find(tech, fin);
return m_baseCase.InvokeSSC(false, fn);
}
/* TODO: hybrids - reinstate for loading ssc json modofications in CSP workflows, update similarly to LoadDefaults
bool Case::LoadFromSSCJSON(wxString fn, wxString* pmsg)
{
if (!m_config) return false;
bool binary = true;
LoadStatus di;
wxString message;
bool ok = false;
VarTable vt;
wxString schk = fn;
if (wxFileExists(schk))
{
ok = VarTablesFromJSONFile(&vt, fn.ToStdString());
// TODO - separate into hybrid tables for each hybrid technology
// if no hybrids, then m_config->Technology.size() == 1 and process normally
// else have separate vartables for each technology and one for the remaining variables (financial model, grid and utility rate)
// separated in startup.lk by bin_name
m_oldVals.clear();
ok &= LoadValuesFromExternalSource(vt, &di, &m_oldVals[0]);
message = wxString::Format("JSON file is incomplete: " + wxFileNameFromPath(fn) + "\n\n"
"Variables: %d loaded form JSON file but not in SAM configuration, %d wrong type, JSON file has %d, SAM config has %d\n\n",
(int)di.not_found.size(), (int)di.wrong_type.size(), (int)di.nread, (int)m_vals.size());
if (di.wrong_type.size() > 0)
{
message += "\nWrong data type: " + wxJoin(di.wrong_type, ',');
ok = false;
}
if (di.not_found.size() > 0)
{
message += "\nLoaded but don't exist in config: " + wxJoin(di.not_found, ',');
ok = false;
}
}
else
{
message = "Defaults file does not exist";
ok = false;
}
if (pmsg != 0)
{
*pmsg = message;
}
rapidjson::Document doc;
doc.SetObject();
wxString tech, fin;
GetConfiguration(&tech, &fin);
if (!ok || di.not_found.size() > 0 || di.wrong_type.size() > 0 || di.nread != m_vals.size())
{
wxLogStatus("discrepancy reading in values from project file: %d not found, %d wrong type, %d read != %d in config",
(int)di.not_found.size(), (int)di.wrong_type.size(), (int)di.nread, (int)m_vals.size());
if (di.not_found.size() > 0)
{
wxLogStatus("\not found: " + wxJoin(di.not_found, ','));
}
if (di.wrong_type.size() > 0)
{
wxLogStatus("\twrong type: " + wxJoin(di.wrong_type, ','));
}
if (m_vals[0].size() > m_oldVals[0].size())
{
// create JSON file with list of missing UI inputs (variable name and group)
rapidjson::Value json_val;
wxString x, y;
for (auto& newVal : m_vals[0]) { // only want SAM inputs - not calculated and indicators (m_vals contain all SAM UI inputs, indicators and calculated values)
VarInfo* vi = Variables(0).Lookup(newVal.first);
bool is_input = ((vi != NULL) && !(vi->Flags & VF_INDICATOR) && !(vi->Flags & VF_CALCULATED));
if (!m_oldVals[0].Get(newVal.first) && is_input) {
// example using VarInfo for sscVariableName and sscVariableValue for ssc inputs in JSON e.g. ssc variable rec_htf and SAM UI variable csp.pt.rec.htf_type
wxString sscVariableName = vi->sscVariableName.Trim();
if (sscVariableName.Len() > 0) {
if (VarValue* vv = m_oldVals[0].Get(sscVariableName)) {
int ndx = vi->sscVariableValue.Index(vv->AsString());
newVal.second->Set(ndx);
}
}
/*
// here we can process ssc to UI conversion lk script or do the conversion manually
// manual example for converting rec_htf (SSC input) to csp.pt.rec.htf_type (SAM UI)
if (newVal.first == "csp.pt.rec.htf_type") {
if (VarValue* jsonVal = m_oldVals.Get("rec_htf")) {
if (jsonVal->Value() == 17)
newVal.second->Set(0);
else if (jsonVal->Value() == 10)