-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSolution.cpp
4416 lines (3940 loc) · 160 KB
/
Solution.cpp
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
#pragma hdrstop
#include <chrono>
#include "Solution.h"
#include "SolutionAlgs.h"
#include "DSSClassDefs.h"
#include "DSSGlobals.h"
#include "CmdForms.h"
#include "PDElement.h"
#include "ControlElem.h"
#include "Fault.h"
#include "AutoAdd.h"
#include "YMatrix.h"
#include "Load.h"
#include "CktTree.h"
#include "ParserDel.h"
#include "generator.h"
#include "Capacitor.h"
//#include "ImplGlobals.h" // to fire events
#include <math.h>
#include "Circuit.h"
#include "Utilities.h"
#include "klusolve.h"
#include "PointerList.h"
#include "Line.h"
#include "Transformer.h"
#include "Reactor.h"
#include "Diakoptics.h"
#include "d2c_structures.h"
#include "ExecHelper.h"
#include "dirsep.h"
TSolutionObj* ActiveSolutionObj = NULL;
const int NumPropsThisClass = 1;
namespace Solution
{
// ===========================================================================================
TSolutionObj* ActiveSolutionObj;
EControlProblem::EControlProblem(const String &Msg) : inherited(Msg) {}
ESolveError::ESolveError(const String &Msg) : inherited(Msg) {}
TDSSSolution::TDSSSolution( ) // Collection of all solution objects
{
;
Class_Name = "Solution";
DSSClassType = DSS_OBJECT + HIDDEN_ELEMENT;
ActiveElement = 0;
DefineProperties();
std::string* slc = Slice( PropertyName, NumProperties );
CommandList = TCommandList(slc , NumProperties);
delete[] slc;
CommandList.set_AbbrevAllowed(true);
}
// ===========================================================================================
TDSSSolution::~TDSSSolution( )
{
// ElementList and CommandList freed in inherited destroy
// todo check: inherited::Destroy;
}
// ===========================================================================================
void TDSSSolution::DefineProperties( )
{
NumProperties = NumPropsThisClass;
CountProperties(); // Get inherited property count
AllocatePropertyArrays();
// Define Property names
PropertyName[1 - 1] = "-------";
// define Property help values
PropertyHelp[1 - 1] = "Use Set Command to set Solution properties.";
ActiveProperty = NumPropsThisClass - 1;
inherited::DefineProperties(); // Add defs of inherited properties to bottom of list
}
// ===========================================================================================
int TDSSSolution::NewObject( const String ObjName )
{
int result = 0;
// Make a new Solution Object and add it to Solution class list
ActiveSolutionObj = new TSolutionObj( this, ObjName );
// this one is different than the rest of the objects.
result = AddObjectToList( ActiveSolutionObj );
return result;
}
// ===========================================================================================
// ===========================================================================================
TSolutionObj::TSolutionObj( TDSSClass* ParClass, const String solutionname )
: inherited(ParClass),
dV(NULL),
nNZ_yii(0),
Algorithm(0),
ControlActionsDone(false),
ControlIteration(0),
ControlMode(0),
ConvergenceTolerance(0.0),
ConvergedFlag(false),
DefaultControlMode(0),
DefaultLoadModel(0),
DoAllHarmonics(false),
DynamicsAllowed(false),
FirstIteration(false),
FrequencyChanged(false),
Fyear(0),
Harmonic(0.0),
HarmonicListSize(0),
IntervalHrs(0.0),
Iteration(0),
LoadModel(0),
VoltageBaseChanged(false),
SampleTheMeters(false),
SeriesYInvalid(false),
SolutionInitialized(false),
DynamicsInitialized(false),
SystemYChanged(false),
UseAuxCurrents(false),
PreserveNodeVoltages(false),
IsDynamicModel(false),
IsHarmonicModel(false),
LastSolutionWasDirect(false),
LoadsNeedUpdating(false),
ActorVIdx(0),
NumberOfTimes(0),
RandomType(0),
SolutionCount(0),
MaxIterations(0),
MinIterations(0),
MostIterationsDone(0),
MaxControlIterations(0),
MaxError(0.0),
NodeYiiEmpty(false),
clstr_num_hghst(0),
clstr_num_lwst(0),
bCurtl(false),
Total_Time_Elapsed(0.0),
Solve_Time_Elapsed(0.0),
Total_Solve_Time_Elapsed(0.0),
Step_Time_Elapsed(0.0),
temp_counter(0),
ADiakoptics_ready(false),
ADiakoptics_Actors(0)
{
Set_Name(LowerCase( solutionname ));
// i := SetLogFile ('c:\\temp\\KLU_Log.txt', 1);
SolveStartTime = { 0 };
SolveEndtime = { 0 };
GStartTime = { 0 };
Gendtime = { 0 };
LoopEndtime = { 0 };
Fyear = 0;
DynaVars.intHour = 0;
DynaVars.T = 0.0;
DynaVars.dblHour = 0.0;
DynaVars.tstart = 0.0;
DynaVars.tstop = 0.0;
//duration := 0.0;
DynaVars.h = 0.001; // default for dynasolve
LoadsNeedUpdating = true;
VoltageBaseChanged = true; // Forces Building of convergence check arrays
MaxIterations = 15;
MinIterations = 2;
MaxControlIterations = 10;
ConvergenceTolerance = 0.0001;
ConvergedFlag = false;
SampleTheMeters = false; // Flag to tell solution algorithm to sample the Energymeters
IsDynamicModel = false;
IsHarmonicModel = false;
if (DefaultBaseFreq == 0)
DefaultBaseFreq = 60;
Set_Frequency(DefaultBaseFreq);
/*Fundamental := 60.0; Moved to Circuit and used as default base frequency*/
Harmonic = 1.0;
FrequencyChanged = true; // Force Building of YPrim matrices
DoAllHarmonics = true;
FirstIteration = true;
DynamicsAllowed = false;
SystemYChanged = true;
SeriesYInvalid = true;
NodeV.clear();
Currents.clear();
Node_dV.clear();
Ic_Local.clear();
NodeYii.clear();
/*Define default harmonic list*/
HarmonicListSize = 5;
HarmonicList = new double[ HarmonicListSize ];
HarmonicList[0] = 1.0;
HarmonicList[1] = 5.0;
HarmonicList[2] = 7.0;
HarmonicList[3] = 11.0;
HarmonicList[4] = 13.0;
SolutionInitialized = false;
LoadModel = POWERFLOW;
DefaultLoadModel = LoadModel;
LastSolutionWasDirect = false;
hYseries = 0;
hYsystem = 0;
hY = 0;
Jacobian = 0;
NodeV.clear();
dV = NULL;
Currents.clear();
AuxCurrents = NULL;
VmagSaved.clear();
ErrorSaved.clear();
NodeVbase.clear();
UseAuxCurrents = false;
SolutionCount = 0;
DynaVars.SolutionMode = SNAPSHOT;
ControlMode = CTRLSTATIC;
DefaultControlMode = ControlMode;
Algorithm = NORMALSOLVE;
RandomType = GAUSSIAN; // default to gaussian
NumberOfTimes = 100;
IntervalHrs = 1.0;
InitPropertyValues( 0 );
ADiakoptics_ready = false; // A-Diakoptics needs to be initialized
/* --pending to implement--DM
if ( !( ActorMA_Msg[ActiveActor] != NULL ) )
ActorMA_Msg[ActiveActor] = TEvent( NULL, true, false, "" ); */
pColIdx_Yii.clear();
pRowIdx_Yii.clear();
pcVals_Yii.clear();
deltaF.clear();
deltaZ.clear();
NCIMY.clear();
NCIMYRow.clear();
NCIMYCol.clear();
NCIMRdy = false;
PV2PQList.clear();
IgnoreQLimit = false;
GenGainNCIM = 1.0;
InitGenQ = true;
}
// ===========================================================================================
TSolutionObj::~TSolutionObj( )
{
AuxCurrents = (pComplexArray) realloc(AuxCurrents,0);
Currents.clear();
//dV = (pNodeVarray) realloc(dV, 0);
free(dV);
ErrorSaved.clear();
NodeV.clear();
NodeVbase.clear();
VmagSaved.clear();
if ( hYsystem != 0 )
DeleteSparseSet( hYsystem );
if ( hYseries != 0 )
DeleteSparseSet( hYseries );
/*by Dahei: */
NodeYii.clear(); // for bii
pColIdx_Yii.clear();
pRowIdx_Yii.clear();
pcVals_Yii.clear();
/*---------------------------*/
// SetLogFile ('c:\\temp\\KLU_Log.txt', 0);
delete[] HarmonicList;
//ActorMA_Msg[ActiveActor].SetEvent;
// Sends a message to the working actor
if ( ActorHandle[ActiveActor] != NULL )
{
delete ActorHandle[ActiveActor];
ActorHandle[ActiveActor] = NULL;
}
//free(ActorMA_Msg[ActiveActor]);
ActorMA_Msg[ActiveActor] = 0;
// todo check: inherited::Destroy;
Node_dV.clear();
Ic_Local.clear();
NCIMY.clear();
NCIMYRow.clear();
NCIMYCol.clear();
}
// ===========================================================================================
int TDSSSolution::Edit( int ActorID )
{
int result = 0;
result = 0;
ActiveSolutionObj = ActiveCircuit[ActorID]->Solution;
/*# with ActiveSolutionObj do */
{
// This is all we do here now...
ActiveSolutionObj->Solve( ActorID );
} /*WITH*/
return result;
}
// ===========================================================================================
void TSolutionObj::Solve( int ActorID )
{
//TScriptEdit ScriptEd;
ActiveCircuit[ActorID]->Issolved = false;
SolutionWasAttempted[ActorID] = true;
/*Check of some special conditions that must be met before executing solutions*/
if ( ActiveCircuit[ActorID]->EmergMinVolts >= ActiveCircuit[ActorID]->NormalMinVolts )
{
DoThreadSafeMsg( "Error: Emergency Min Voltage Must Be Less Than Normal Min Voltage!" + CRLF + "Solution Not Executed.", 480 );
return;
}
if ( SolutionAbort )
{
GlobalResult = "Solution aborted.";
CmdResult = SOLUTION_ABORT;
ErrorNumber = CmdResult;
return;
}
try
{
/*Main solution Algorithm dispatcher*/
/*# with ActiveCircuit[ActorID] do */
{
TDSSCircuit* with0 = ActiveCircuit[ActorID];
{
switch ( get_Fyear() )
{
case 0:
with0->DefaultGrowthFactor = 1.0;
break; // RCD 8-17-00
default:
with0->DefaultGrowthFactor = pow(with0->DefaultGrowthRate, ( get_Fyear() - 1 ) );
}
}
}
// Creates the actor again in case of being terminated due to an error before
if ((!ActorHandle[ActorID]->ActorActive) || (ActorHandle[ActorID] == NULL))
{
if ( !ActorHandle[ActorID]->ActorActive)
free(ActorHandle[ActorID]);
New_Actor( ActorID );
}
// Resets the event for receiving messages from the active actor
// Updates the status of the Actor in the GUI
ActorStatus[ActorID] = 0; // Global to indicate that the actor is busy
//ActorMA_Msg[ActorID]->ResetEvent;
QueryPerformanceCounter( &GStartTime );
if ( ! NoFormsAllowed )
{
if ( ! IsProgressON && DSSProgressFrm )
{
switch ( DynaVars.SolutionMode )
{
case YEARLYMODE: case DUTYCYCLE: case LOADDURATION1: case LOADDURATION2: case HARMONICMODE: case HARMONICMODET:
{
if ( Progress_Actor[ActorID] != NULL )
{
//Progress_Actor[ActorID]->Terminate;
Progress_Actor[ActorID] = NULL;
}
//Progress_Actor = TProgressActor.Create( );
}
break;
default:
{
// Just other simulation modes, nothing to do
}
}
}
}
// Sends message to start the Simulation
ActorHandle[ActorID]->Send_Message( SIMULATE );
// If the parallel mode is not active, Waits until the actor finishes
if (!Parallel_enabled)
{
Wait4Actors( ALL_ACTORS );
}
}
catch( std::exception & E )
{
DoThreadSafeMsg( "Error Encountered in Solve: " + (std::string) E.what(), 482 );
SolutionAbort = true;
}
}
// ===========================================================================================
bool TSolutionObj::Converged( int ActorID )
{
bool result = false;
int i = 0;
double VMag = 0.0;
if (ActiveCircuit[ActorID]->Solution->Algorithm != NCIMSOLVE)
{
// base convergence on voltage magnitude
MaxError = 0.0;
for (int stop = ActiveCircuit[ActorID]->NumNodes, i = 1; i <= stop; i++)
{
if (!ADiakoptics || (ActorID == 1))
VMag = cabs(NodeV[i]);
else
VMag = cabs(VoltInActor1(i));
/* If base specified, use it; otherwise go on present magnitude */
if (NodeVbase[i] > 0.0)
ErrorSaved[i] = Abs(VMag - VmagSaved[i]) / NodeVbase[i];
else
if (VMag != 0.0)
ErrorSaved[i] = Abs(1.0 - (VmagSaved[i] / VMag));
VmagSaved[i] = VMag; // for next go-'round
MaxError = max(MaxError, ErrorSaved[i]); // update max error
}
if (MaxError <= ConvergenceTolerance)
result = true;
}
else
{
for (i = 0; i < deltaF.size(); i++)
{
result = Abs(deltaF[i].re) <= ConvergenceTolerance;
if (!result)
break;
}
}
ConvergedFlag = result;
return result;
}
// ===========================================================================================
void TSolutionObj::GetSourceInjCurrents( int ActorID )
// Add in the contributions of all source type elements to the global solution vector InjCurr
{
TDSSCktElement* pElem;
/*# with ActiveCircuit[ActorID] do */
{
auto with0 = ActiveCircuit[ActorID];
{
pElem = (TDSSCktElement*) with0->Sources.Get_First();
while ( pElem != NULL )
{
if ( pElem->Get_Enabled() )
pElem->InjCurrents( ActorID ); // uses NodeRef to add current into InjCurr Array;
pElem = (TDSSCktElement*) with0->Sources.Get_Next();
}
// Adds GFM PCE as well
GetPCInjCurr(ActorID, true);
}
}
}
// ===========================================================================================
void TSolutionObj::SetGeneratorDispRef( int ActorID )
// Set the global generator dispatch reference
{
/*# with ActiveCircuit[ActorID] do */
{
TDSSCircuit* with0 = ActiveCircuit[ActorID];
switch ( DynaVars.SolutionMode )
{
case SNAPSHOT:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor;
break;
case YEARLYMODE:
with0->GeneratorDispatchReference = with0->DefaultGrowthFactor * with0->DefaultHourMult.re;
break;
case DAILYMODE:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor * with0->DefaultHourMult.re;
break;
case DUTYCYCLE:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor * with0->DefaultHourMult.re;
break;
case GENERALTIME:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor * with0->DefaultHourMult.re;
break;
case DYNAMICMODE:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor;
break;
case EMPMODE:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor;
break;
case EMPDAILYMODE:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor;
break;
case HARMONICMODE:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor;
break;
case MONTECARLO1:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor;
break;
case MONTECARLO2:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor * with0->DefaultHourMult.re;
break;
case MONTECARLO3:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor * with0->DefaultHourMult.re;
break;
case PEAKDAY:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor * with0->DefaultHourMult.re;
break;
case LOADDURATION1:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor * with0->DefaultHourMult.re;
break;
case LOADDURATION2:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor * with0->DefaultHourMult.re;
break;
case DIRECT:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor;
break;
case MONTEFAULT:
with0->GeneratorDispatchReference = 1.0;
break; // Monte Carlo Fault Cases solve at peak load only base case
case FAULTSTUDY:
with0->GeneratorDispatchReference = 1.0;
break;
case AUTOADDFLAG:
with0->GeneratorDispatchReference = with0->DefaultGrowthFactor;
break; // peak load only
case HARMONICMODET:
with0->GeneratorDispatchReference = with0->get_FLoadMultiplier() * with0->DefaultGrowthFactor * with0->DefaultHourMult.re;
break;
default:
DoSimpleMsg( "Unknown solution mode.", 483 );
}
}
}
// ===========================================================================================
void TSolutionObj::SetGeneratordQdV( int ActorID )
{
TGeneratorObj* pGen;
bool Did_One = false;
double GenDispSave = 0.0;
Did_One = false;
// Save the generator dispatch level and set on high enough to
// turn all generators on
GenDispSave = ActiveCircuit[ActorID]->GeneratorDispatchReference;
ActiveCircuit[ActorID]->GeneratorDispatchReference = 1000.0;
/*# with ActiveCircuit[ActorID] do */
{
TDSSCircuit* with0 = ActiveCircuit[ActorID];
{
pGen = (TGeneratorObj*) with0->Generators.Get_First();
while ( pGen != NULL )
{
if ( ( (TDSSCktElement*) pGen )->Get_Enabled() )
{
// for PV generator models only ...
if ( pGen->GenModel == 3 )
{
pGen->InitDQDVCalc();
// solve at base var setting
Iteration = 0;
do
{
Iteration++;
ZeroInjCurr( ActorID );
GetSourceInjCurrents( ActorID );
pGen->InjCurrents( ActorID ); // get generator currents with nominal vars
SolveSystem( &NodeV[0], ActorID);
}
while ( ! ( Converged( ActorID ) || ( Iteration >= MaxIterations ) ) );
pGen->RememberQV( ActorID ); // Remember Q and V
pGen->BumpUpQ();
// solve after changing vars
Iteration = 0;
do
{
Iteration++;
ZeroInjCurr( ActorID );
GetSourceInjCurrents( ActorID );
pGen->InjCurrents( ActorID ); // get generator currents with nominal vars
SolveSystem( &NodeV[0], ActorID);
}
while ( ! ( Converged( ActorID ) || ( Iteration >= MaxIterations ) ) );
pGen->CalcDQDV( ActorID ); // bssed on remembered Q and V and present values of same
pGen->ResetStartPoint();
Did_One = true;
}
}
pGen = (TGeneratorObj*)with0->Generators.Get_Next();
}
}
}
// Restore generator dispatch reference
ActiveCircuit[ActorID]->GeneratorDispatchReference = GenDispSave;
try
{
if // Reset Initial Solution
( Did_One )
SolveZeroLoadSnapShot( ActorID );
}
catch( std::exception & E )
{
{
DoThreadSafeMsg( "From SetGenerator DQDV, SolveZeroLoadSnapShot: " + CRLF + (std::string) E.what() + CheckYMatrixforZeroes( ActorID ), 7071 );
//throw @ESolveError ::( "Aborting" );
}
}
}
// ===========================================================================================
void TSolutionObj::SendCmd2Actors( int Msg )
{
int i = 0;
for ( int stop = NumOfActors, i = 2; i <= stop; i++)
{
ActorStatus[i] = 0;
ActorHandle[i]->Send_Message( Msg );
}
Wait4Actors( AD_ACTORS );
}
// ===========================================================================================
void TSolutionObj::DoNormalSolution( int ActorID )
/* Normal fixed-point solution
Vn+1 = [Y]-1 Injcurr
Where Injcurr includes only PC elements (loads, generators, etc.)
i.e., the shunt elements.
Injcurr are the current injected INTO the NODE
(need to reverse current direction for loads)
*/
{
int i = 0;
Iteration = 0;
/***** Main iteration loop *****/
{
auto with0 = ActiveCircuit[ActorID];
// DOForceFlatStart(ActorID);
do
{
Iteration++;
if ( with0->LogEvents )
LogThisEvent( "Solution Iteration " + IntToStr( Iteration ), ActorID );
if ( ( ! ADiakoptics ) || ( ActorID != 1 ) ) // Normal simulation
{ // In A-Diakoptics, all other actors do normal solution
/* Get injcurrents for all PC devices */
ZeroInjCurr( ActorID );
GetSourceInjCurrents( ActorID ); // sources
GetPCInjCurr( ActorID ); // Get the injection currents from all the power conversion devices and feeders
// The above call could change the primitive Y matrix, so have to check
if ( SystemYChanged )
{
BuildYMatrix( WHOLEMATRIX, false, ActorID ); // Does not realloc V, I
}
/*by Dahei*/
if ( NodeYiiEmpty )
Get_Yiibus();
if ( UseAuxCurrents )
AddInAuxCurrents( NORMALSOLVE, ActorID );
// Solve for voltages {Note:NodeV[0] = 0 + j0 always}
if ( with0->LogEvents )
LogThisEvent( "Solve Sparse Set DoNormalSolution ...", ActorID );
SolveSystem( &NodeV[0], ActorID);
LoadsNeedUpdating = false;
}
else
{
ADiak_PCInj = true;
Solve_Diakoptics( ); // A-Diakoptics
}
}
while ( ! ( ( Converged( ActorID ) && ( Iteration >= MinIterations ) ) || ( Iteration >= MaxIterations ) ) );
}
}
// ===========================================================================================
void TSolutionObj::DoNCIMSolution(int ActorID)
{
/* Implements the N conductor current injection method (NCIM) for solving the power flow problem.
This mehtod is a Newton-Raphson like solution method, and is implemented here to address
transmission system-like simulations. For more info, check:
https://www.sciencedirect.com/science/article/abs/pii/S0142061512004310
*/
auto with0 = ActiveCircuit[ActorID];
bool Solved = false;
complex dV = CZero;
Iteration = 0; // Initializes iteration counter
if (InitGenQ) // If the system needs to be initialized
{
InitPQGen(ActorID); // Initialize PQ like generators
PV2PQList.clear();
}
if (SystemYChanged || !NCIMRdy)
NCIMNodes = InitNCIM(ActorID, InitGenQ); // Initializes the NCIM environment vars and structures (takes time)
/***** Main iteration loop *****/
do
{
Iteration++;
CalcInjCurr(ActorID, InitGenQ); // Calc Injection currents using the latest solution ( I = Y * V )
BuildJacobian(ActorID); // Resets the jacobian's diagonal for the next iteration
GetNCIMPowers(ActorID); // Populate the total power vector
ApplyCurrNCIM(ActorID); // Adjust Jacobian and populate the currents vector
if (with0->LogEvents)
LogThisEvent("Solve Power flow DoNCIMSolution ...", ActorID);
// Solves the Jacobian
SolveSparseSet(Jacobian, &(deltaZ[0]), &(deltaF[0]));
//Updates the Voltage vector
int dVIdx = 0;
dV = CZero;
for (int i = 1; i <= with0->NumNodes; i++)
{
dVIdx = (i - 1) * 2;
dV = cmplx(deltaZ[dVIdx].re, deltaZ[dVIdx + 1].re);
NodeV[i] = csub(NodeV[i], dV);
}
Solved = Converged(ActorID);
// Updates the Generator's Q using the calculated deltaQ
UpdateGenQ(ActorID);
InitGenQ = false;
} while (!((Solved && (Iteration >= MinIterations)) || (Iteration >= MaxIterations)));
DistGenClusters(ActorID); // Distributes the power among all the clustered generators (if any)
// To reverse what we did for the next simulation step
// ReversePQ2PV(ActorID); - not needed for now (04/01/2024)
}
// ===========================================================================================
void TSolutionObj::DoNewtonSolution( int ActorID )
/* Newton Iteration
Vn+1 = Vn - [Y]-1 Termcurr
Where Termcurr includes currents from all elements and we are
attempting to get the currents to sum to zero at all nodes.
Termcurr is the sum of all currents going INTO THE TERMINALS of
the elements.
For PD Elements, Termcurr = Yprim*V
For Loads, Termcurr = (Sload/V)*
For Generators, Termcurr = -(Sgen/V)*
*/
{
int i = 0;
/*# with ActiveCircuit[ActorID] do */
{
auto with0 = ActiveCircuit[ActorID];
{
ReallocMem( dV, sizeof( dV[1] ) * ( with0->NumNodes + 1 ) ); // Make sure this is always big enough
if ( ControlIteration == 1 )
GetPCInjCurr( ActorID ); // Update the load multipliers for this solution
Iteration = 0;
do
{
Iteration++;
SolutionCount++; // SumAllCurrents Uses ITerminal So must force a recalc
// Get sum of currents at all nodes for all devices
ZeroInjCurr( ActorID );
SumAllCurrents( ActorID );
// Call to current calc could change YPrim for some devices
if ( SystemYChanged )
{
BuildYMatrix( WHOLEMATRIX, false, ActorID ); // Does not realloc V, I
}
/*by Dahei*/
if ( NodeYiiEmpty )
Get_Yiibus(); //
if ( UseAuxCurrents )
AddInAuxCurrents( NEWTONSOLVE, ActorID );
// Solve for change in voltages
SolveSystem( dV, ActorID );
LoadsNeedUpdating = false;
// Compute new guess at voltages
for ( int stop = with0->NumNodes, i = 1; i <= stop; i++) // 0 node is always 0
/*# with NodeV^[i] do */
{
complex with1 = NodeV[i];
{
with1.re = with1.re - dV[i].re;
with1.im = with1.im - dV[i].im;
}
}
}
while ( ! ( ( Converged( ActorID ) && ( Iteration >= MinIterations ) ) || ( Iteration >= MaxIterations ) ) );
}
}
}
// ===========================================================================================
/* Populates the current injections vector and updates the jacobian matrix as needed */
void TSolutionObj::ApplyCurrNCIM(int ActorID)
{
auto with0 = ActiveCircuit[ActorID]->Solution;
for (int i = 1; i < pNodePower.size(); i++)
{
if ((pNodePower[i].re != 0) || (pNodePower[i].im != 0))
{
if (pNodeType[i] == PV_Node)
DoPVBusNCIM(ActorID, i, pNodePVTarget[i], pNodePower[i]);
else
DoPQBusNCIM(ActorID, i, with0->NodeV[i], pNodePower[i]);
}
}
}
// ===========================================================================================
/* Populates the total power vector before solving the NCIM algorithm */
void TSolutionObj::GetNCIMPowers(int ActorID)
{
TDSSCktElement* pElem = nullptr;
TCapacitorObj* pCap = nullptr;
TReactorObj* pReact = nullptr;
bool valid = false;
int NodeIdx = 0;
auto with0 = ActiveCircuit[ActorID];
/* Get inj currents from all enabled PC devices */
{
{
complex LdPower = CZero,
LdVolt = CZero,
GenS = CZero;
pElem = (TDSSCktElement*)with0->PCElements.Get_First();
while (pElem != NULL)
{
/*# with pElem do */
if (pElem->Get_Enabled())
{
for (int idx = 1; idx <= pElem->Fnphases; idx++)
{
NodeIdx = pElem->NodeRef[idx - 1];
switch (pElem->DSSObjType & CLASSMASK)
{
case LOAD_ELEMENT:
{
LdPower = cmplx(((TLoadObj*)pElem)->WNominal, ((TLoadObj*)pElem)->varNominal);
LdVolt = with0->Solution->NodeV[NodeIdx];
if (((TLoadObj*)pElem)->FLoadModel == 2)
DoZBusNCIM(ActorID, NodeIdx, LdVolt, ((TLoadObj*)pElem)->YPrim);
else
{
if (pNodeType[NodeIdx] == PV_Node)
pNodePower[NodeIdx] = csub(pNodePower[NodeIdx], LdPower);
else
pNodePower[NodeIdx] = cadd(pNodePower[NodeIdx], LdPower);
for (int idx = 0; idx < pElem->Get_NPhases(); idx++)
pElem->Iterminal[idx] = conjg(cdiv(LdPower, LdVolt));
}
}
break;
case GEN_ELEMENT:
{
auto with2 = (TGeneratorObj*)pElem;
auto& with1 = with2->GenVars;
// Checks the reactive power limits in this node
switch (with2->GenModel)
{
case 3: // Generator is a PV bus
{
with1.Qnominalperphase = with1.deltaQNom[idx - 1];
GenS = cmplx(with1.Pnominalperphase, with1.Qnominalperphase);
if (pNodeType[NodeIdx] == PQ_Node)
pNodePower[NodeIdx] = cnegate(pNodePower[NodeIdx]);
pNodeType[NodeIdx] = PV_Node; // Forces the node to be PV
pNodePower[NodeIdx] = cadd(GenS, pNodePower[NodeIdx]);
pGenPower[NodeIdx] = cadd(GenS, pGenPower[NodeIdx]);
pNodePVTarget[NodeIdx] = with1.VTarget; // Updates the target for the Bus, just in case
PVBusIdx[NodeIdx] = with2->NCIMIdx + idx; // Stores the generator IDX in the NCIM array
}
break;
case 4: // Generator acts like PQ bus
{
LdVolt = with0->Solution->NodeV[NodeIdx];
if (with1.deltaQNom.empty())
GenS = cmplx(with1.Pnominalperphase, with1.Qnominalperphase);
else
GenS = cmplx(with1.Pnominalperphase, with1.deltaQNom[0]);
if (pNodeType[NodeIdx] == PQ_Node)
pNodePower[NodeIdx] = csub(pNodePower[NodeIdx], GenS);
else
pNodePower[NodeIdx] = cadd(pNodePower[NodeIdx], GenS);
pGenPower[NodeIdx] = cadd(GenS, pGenPower[NodeIdx]);
}
break;
default: // Constant impedance
{
LdVolt = with0->Solution->NodeV[NodeIdx];
DoZBusNCIM(ActorID, NodeIdx, LdVolt, with2->YPrim);
}
break;
}
}
break;
case FAULTOBJECT:
{
auto with2 = (TFaultObj*)pElem;
LdVolt = with0->Solution->NodeV[NodeIdx];
DoZBusNCIM(ActorID, NodeIdx, LdVolt, with2->YPrim);
}
break;
default:
{
// Ignore the others
}
break;
}
}
}
pElem = (TDSSCktElement*)with0->PCElements.Get_Next();
}