/
plant.cpp
5123 lines (4161 loc) · 251 KB
/
plant.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
#include "plant.h"
#include "district.h" //added by Dapeng
// *** Plant class, CitySim *** //
// *** jerome.kaempf@epfl.ch *** //
#pragma GCC diagnostic ignored "-Wunused-parameter"
Polynomial::Polynomial(TiXmlHandle hdl) {
//cout << "Polynomial coefficients: (";
unsigned int index=0;
do {
string attrib = *(hdl.ToElement()->Attribute("c"+toString(index)));
//cout << " " << attrib;
a.push_back(to<float>(attrib));
} while ( hdl.ToElement()->Attribute("c"+toString(++index)) );
//cout << ")" << endl;
}
PhotoVoltaic::PhotoVoltaic(TiXmlHandle hdl, ostream* pLogStr):logStream(std::cout.rdbuf()) {
// logStream is directed by default to the "cout" streambuf
if(pLogStr) // If a logfile stream is provided, redirect logStream to the file stream.
logStream.rdbuf(pLogStr->rdbuf());
if (!logStream.good())
throw(string("Unable to define correctly the logStream."));
//logStream << "PhotoVoltaic constructor from xml " << endl << flush;
if (hdl.ToElement()->Attribute("Pmp") && hdl.ToElement()->Attribute("Ac")) etampref = to<float>(hdl.ToElement()->Attribute("Pmp"))/(to<float>(hdl.ToElement()->Attribute("Ac"))*1000.0);
else if (hdl.ToElement()->Attribute("Etampref")) etampref = to<float>(hdl.ToElement()->Attribute("Etampref"));
else cout << "ERROR PhotoVoltaic: Etampref parameter not defined (nor Pmp & Ac)";
if (hdl.ToElement()->Attribute("Tref")) tref = to<float>(hdl.ToElement()->Attribute("Tref"));
else cout << "ERROR PhotoVoltaic: Tref parameter not defined";
if (hdl.ToElement()->Attribute("Tcnoct")) tcnoct = to<float>(hdl.ToElement()->Attribute("Tcnoct"));
else cout << "ERROR PhotoVoltaic: Tcnoct parameter not defined";
if (hdl.ToElement()->Attribute("muVoc")) muvoc = to<float>(hdl.ToElement()->Attribute("muVoc"));
else cout << "ERROR PhotoVoltaic: muVoc parameter not defined";
if (hdl.ToElement()->Attribute("Vmp")) vmp = to<float>(hdl.ToElement()->Attribute("Vmp"));
else cout << "ERROR PhotoVoltaic: vmp parameter not defined";
if (hdl.ToElement()->Attribute("name")){ hdl.ToElement()->QueryStringAttribute("name",&name);}
if (hdl.FirstChildElement("IAM").ToElement()) iam_polynomial = new Polynomial(hdl.FirstChild("IAM"));
}
void PhotoVoltaic::writeXML(ofstream& file, float ratio, string tab){
file << tab << "<PV pvRatio=\"" << ratio << "\" name=\"" << name <<
"\" Etampref=\"" << etampref << "\" Vmp=\"" << vmp << "\" muVoc=\"" << muvoc <<
"\" Tcnoct=\"" << tcnoct << "\" Tref=\"" << tref << "\"";
if (iam_polynomial) {
file << ">" << endl;
file << tab << "\t<IAM";
for (size_t i=0;i<iam_polynomial->getSize();++i) file << " c" << i << "=\"" << iam_polynomial->get_a(i) << "\"";
file << "/>" << endl;
file << tab << "</PV>" << endl;
}
else file << "/>" << endl;
}
double PhotoVoltaic::getMaxPowerEfficiency(double gt, double tout) {
//cout << "getMaxPowerEfficiency: etampref=" << etampref <<" muvoc="<<muvoc <<" /vmp="<<vmp<<" tout="<<tout << " gt="<< gt <<" tcnoct="<<tcnoct <<" toutsoc="<<toutsoc <<" /gtsoc=" <<gtsoc << " tref=" << tref << endl;
return etampref*(1.0 + (muvoc/vmp)*(tout + gt*(tcnoct-toutsoc)/gtsoc - tref))/(1.0 + etampref*gt*(tcnoct-toutsoc)/gtsoc*(1.0/0.9)*(muvoc/vmp));
}
PhotoVoltaic::~PhotoVoltaic() {
if (iam_polynomial) delete iam_polynomial;
#ifdef DEBUG
fstream output ("iam.txt", ios::out | ios::trunc);
for (size_t i=0;i<iam.size();++i)
output << iam.at(i).first << "\t" << iam.at(i).second << endl;
output.close();
#endif // DEBUG
}
double PhotoVoltaic::getIAM(float elevation) { // elevation is in radians
double iam_value = 1.; // without IAM the value of always 1
if (iam_polynomial) {
iam_value = 0.;
for (size_t i=0;i<iam_polynomial->getSize();++i) {
iam_value += iam_polynomial->get_a(i)*pow(elevation,i);
}
}
else {
// the reference function
iam_value = -1.0410*pow(elevation,6) + 4.0590*pow(elevation,5) - 6.3050*pow(elevation,4) + 4.5308*pow(elevation,3) - 1.4386*pow(elevation,2) + 1.5515e-01*elevation + 9.5204e-01;
//double iam_value_mod = -9.7256E-02*pow(elevation,6) + 2.5487E-01*pow(elevation,5) - 4.0788E-01*pow(elevation,4) + 3.8687E-01*pow(elevation,3) - 1.6502E-01*pow(elevation,2) + 2.2950E-02*elevation + 9.2368E-01;
}
#ifdef DEBUG
iam.push_back(pair<float,double>(elevation,iam_value));
#endif // DEBUG
return iam_value;
}
SolarThermal::SolarThermal(TiXmlHandle hdl, ostream* pLogStr):logStream(std::cout.rdbuf()) {
// logStream is directed by default to the "cout" streambuf
if(pLogStr) // If a logfile stream is provided, redirect logStream to the file stream.
logStream.rdbuf(pLogStr->rdbuf());
if (!logStream.good())
throw(string("Unable to define correctly the logStream."));
//logStream << "SolarHeater constructor from xml " << endl << flush;
if (hdl.ToElement()->Attribute("eta0")) eta0 = to<float>(hdl.ToElement()->Attribute("eta0"));
else if (hdl.ToElement()->Attribute("etaOptical")) eta0 = to<float>(hdl.ToElement()->Attribute("etaOptical"));
else throw("Solar Thermal: eta0 parameter not defined");
if (hdl.ToElement()->Attribute("a1")) a1 = to<float>(hdl.ToElement()->Attribute("a1"));
else if (hdl.ToElement()->Attribute("heatLoss1")) a1 = to<float>(hdl.ToElement()->Attribute("heatLoss1"));
else throw("Solar Thermal: a1 parameter not defined");
if (hdl.ToElement()->Attribute("a2")) a2 = to<float>(hdl.ToElement()->Attribute("a2"));
else if (hdl.ToElement()->Attribute("heatLoss2")) a2 = to<float>(hdl.ToElement()->Attribute("heatLoss2"));
else throw("Solar Thermal: a2 parameter not defined");
if (hdl.ToElement()->Attribute("name")){ hdl.ToElement()->QueryStringAttribute("name",&name);}
}
void SolarThermal::writeXML(ofstream& file, float ratio, string tab){
file << tab << "<ST stRatio=\"" << ratio << "\" name=\"" << name <<
"\" eta0=\"" << eta0 << "\" a1=\"" << a1 << "\" a2=\"" << a2 << "\"/>" << endl;
}
SolarHybrid::SolarHybrid(TiXmlHandle hdl, ostream* pLogStr) : PhotoVoltaic(hdl,pLogStr) {
logStream << "SolarHybrid constructor from xml " << endl << flush;
if (hdl.ToElement()->Attribute("Pth")) Pth = to<float>(hdl.ToElement()->Attribute("Pth"));
else cout << "ERROR PhotoVoltaic: Pth parameter not defined";
// if given by the user, shadow the default value
if (hdl.ToElement()->Attribute("massFlowRate")) massFlowRate = to<float>(hdl.ToElement()->Attribute("massFlowRate"));
}
float SolarHybrid::getThermalSurfacePowerDensity(float gt, float tout, float windspeed, float Tsky, float Tin) {
// Convection naturelle hc_n :
float hc_n = 5.67+3.86*windspeed; // [W/m2.K]
// define the ground temperature (back of the panel)
float Tground = tout + 2.f;
#ifdef DEBUG
ofstream file("debug_PVT.out", ios::app);
file << gt << "\t" << tout << "\t" << hc_n << "\t" << Tsky << "\t" << Tground << "\t" << Tin << "\t";
#endif
// Rayonnement entre ciel et la vitre solAc hrad_sky :
float c_boltz = 5.67e-8;
float hrad_sky = 4.f*c_boltz*epsilon_g*pow((Tg + (Tsky+273.15))/2.,3);
// Verre solAc / cellules pv :
// Conduction :
float hc_g = lambda_g/x_g;
float hc_air = lambda_air/x_air;
float hc_eva = lambda_eva/x_eva;
// Rayonnement entre verre solAc / cellule pv
float E = 1./(1./x_pv + 1./x_g - 1.);
float Tmoy = (Tpv + Tg)/2.;
float hrad_g_pv = 4.*c_boltz*E*pow(Tmoy,3); // [W/m2.K]
// On a 3 résistances en parallèles :
float h1 = hc_g + hc_air + hrad_g_pv; // [W/m2.K]
// Puis 2 résistances en série :
float hpv_g = 1./(1./h1 + 1./hc_eva); // [W/m2.K]
// Cellules pv/absorbeur :
// Conduction :
float hc_bs = lambda_bs/x_bs; // [W/m2.K]
float hc_ab = lambda_ab/x_ab; // [W/m2.K]
float hc_pv = lambda_pv/x_pv; // [W/m2.K]
float hab = 1./(1./hc_eva + 1./hc_bs + 1./hc_ab + 1./hc_pv); // [W/m2.K]
// Absorbeur/air ambiant
// Pertes derriere l'échangeur radiation
float hrad_loss = 4.*c_boltz*epsilon_ab*pow((Tmw + (Tground+273.15))/2.,3); // [W/m2.K]
// Perte totale arrière
float hloss = hc_n + hrad_loss; // [W/m2.K]
// Absorbeur/fluide
// hab_f :
float hab_f = (eff_ab*hloss)/(1.-eff_ab); // [W/m2.K]
float Ac=1.58f;
// initialise the B vector
double b[4];
b[0] = gt*alpha_g + (tout+273.15)*hc_n + (Tsky+273.15f)*hrad_sky;
b[1] = gt*FF*tau_g*(alpha_pv-etampref+etampref*(muvoc/vmp)*(tref+273.15));
b[2] = 0.;
b[3] = ((Tin+273.15f)*(massFlowRate*Cp_w*eta_exch))/Ac + (tout+273.15)*hloss;
// initialise the A matrix
double A[4*4];
A[0+4*0] = hc_n +hrad_sky+hpv_g;
A[0+4*1] = -hpv_g;
A[0+4*2] = 0.;
A[0+4*3] = 0.;
A[1+4*0] = -hpv_g;
A[1+4*1] = hpv_g + hab + gt*FF*etampref*tau_g*(muvoc/vmp);
A[1+4*2] = -hab;
A[1+4*3] = 0.;
A[2+4*0] = 0.;
A[2+4*1] = hab;
A[2+4*2] = hab_f - hab;
A[2+4*3] = -hab_f;
A[3+4*0] = 0.;
A[3+4*1] = 0.;
A[3+4*2] = (massFlowRate*Cp_w*eta_exch)/Ac - hab_f;
A[3+4*3] = hab_f + hloss;
// cout << "matrice A: " << endl;
//
// for (int i=0;i<A.nrows();++i) {
// for (int j=0;j<A.ncols();++j) {
// cout << A[i][j] << "\t";
// }
// cout << endl;
// }
//
// cout << "vecteur b: " << endl;
//
// for (int i=0;i<b.size();++i) {
// cout << b[i] << "\t";
// }
// cout << endl;
solve_Ax_equal_b(A,b,4); // solution A * x = b put in b
Tg = b[0];
Tpv = b[1];
Tab = b[2];
Tmw = b[3];
// Calcul puissance instantannée électrique
//float P_el = Pmp*(gt/1000.)*(1-(Tpv-tref)*0.0044); // [W] - 1000 W/m2 STC
///float rendement = etampref*(1+(muvoc/vmp)*(Tpv-(tref+273.15f))); // [W]
// Avec l'onduleur : P_el_reel = P_el*rend_ond;
// Calcul puissance instantannée thermique
float Tout_ab = (2.*Tmw)-(Tin+273.15f);
float DT = Tout_ab-(Tin+273.15f);
if (DT<0.) DT=0.;
#ifdef DEBUG
file << hloss << "\t" << hab_f << "\t" << Tg << "\t" << Tpv << "\t" << Tab << "\t" << Tmw << "\t" << Tout_ab << "\t" << DT << "\t" << massFlowRate*Cp_w*(DT) << endl;
file.close();
#endif
return massFlowRate*Cp_w*(DT)/Ac;
}
double Equations::solarHeaterEfficiency(SolarThermal *panel, double gt, double xsi) {
return panel->getEta0() - panel->getA1()*xsi - panel->getA2()*gt*xsi*xsi;
}
double Equations::windTurbinePower(WindTurbine *turbine, double v) {
if ( v <= turbine->getvi() ) return 0.0;
else if ( v > turbine->getvm() ) return 0.0;
else if ( v > turbine->getvr() ) return turbine->getPr();
else {
double a = turbine->getPr()*pow(turbine->getvi(), turbine->getc())/(pow(turbine->getvi(), turbine->getc()) - pow(turbine->getvr(), turbine->getc()));
double b = turbine->getPr()/(pow(turbine->getvr(), turbine->getc()) - pow(turbine->getvi(), turbine->getc()));
return a + b * pow(v, turbine->getc());
}
}
double Equations::windSpeedRatio(int type, double height, int typeRef, double heightRef) {
double alpha, alphaprime, gamma, gammaprime;
switch ( type ) {
case 1:
gamma = 0.10;
alpha = 1.30;
break;
case 2:
gamma = 0.15;
alpha = 1.00;
break;
case 3:
gamma = 0.2;
alpha = 0.85;
break;
case 4:
gamma = 0.25;
alpha = 0.67;
break;
case 5:
gamma = 0.35;
alpha = 0.47;
break;
default:
gamma = 0.35;
alpha = 0.47;
break;
}
switch ( typeRef ) {
case 1:
gammaprime = 0.10;
alphaprime = 1.30;
break;
case 2:
gammaprime = 0.15;
alphaprime = 1.00;
break;
case 3:
gammaprime = 0.2;
alphaprime = 0.85;
break;
case 4:
gammaprime = 0.25;
alphaprime = 0.67;
break;
case 5:
gammaprime = 0.35;
alphaprime = 0.47;
break;
default:
gammaprime = 0.35;
alphaprime = 0.47;
break;
}
return (alpha*pow( height/10.0, gamma)) / (alphaprime*pow( heightRef/10.0, gammaprime));
}
double Tank::temperature(double t, double VdotUsed, double Pp2, double Pup2, double T0, double Tinlet, double Tamb) {
return (Pp2 + Pup2 + getCp()*Tinlet*VdotUsed*getRho() + Tamb*getPhi() -
(Pp2 + Pup2 - getCp()*T0*VdotUsed*getRho() + getCp()*Tinlet*VdotUsed*getRho() - T0*getPhi() + Tamb*getPhi())/
std::exp((t*(getCp()*VdotUsed*getRho() + getPhi()))/(getCp()*getVolume()*getRho())))/(getCp()*VdotUsed*getRho() + getPhi());
}
double Tank::power(double t, double Tf, double VdotUsed, double Pup2, double T0, double Tinlet, double Tamb) {
return (Pup2 - std::exp(((getCp()*VdotUsed*getRho() + getPhi())*(t))/(getCp()*getVolume()*getRho()))*Pup2 - getCp()*T0*VdotUsed*getRho() +
getCp()*std::exp(((getCp()*VdotUsed*getRho() + getPhi())*(t))/(getCp()*getVolume()*getRho()))*Tf*VdotUsed*getRho() +
getCp()*Tinlet*VdotUsed*getRho() - getCp()*std::exp(((getCp()*VdotUsed*getRho() + getPhi())*(t))/(getCp()*getVolume()*getRho()))*Tinlet*VdotUsed*
getRho() - T0*getPhi() + Tamb*getPhi() - std::exp(((getCp()*VdotUsed*getRho() + getPhi())*(t))/(getCp()*getVolume()*getRho()))*Tamb*getPhi() +
std::exp(((getCp()*VdotUsed*getRho() + getPhi())*(t))/(getCp()*getVolume()*getRho()))*Tf*getPhi())/
(-1.0 + std::exp(((getCp()*VdotUsed*getRho() + getPhi())*(t))/(getCp()*getVolume()*getRho())));
}
double Tank::time(double Tf, double VdotUsed,double Pp2, double Pup2, double T0, double Tinlet, double Tamb) {
return (Cp*volume*rho)*(log((Pp2 - phi*T0 - Cp*rho*VdotUsed*T0 + Cp*rho*VdotUsed*Tinlet + Pup2 + phi*Tamb)
/(Pp2 - phi*Tf - Cp*rho*VdotUsed*Tf + Cp*rho*VdotUsed*Tinlet + Pup2 + phi*Tamb)))/(phi + Cp*rho*VdotUsed);
}
double TankPCM::temperature(double t, double VdotUsed, double Pp2, double Pup2, double T0, double Tinlet, double Tamb) {
// calcul du crit�re de stabilit�
double deltat = std::min( 300.0, 2.0*(getRho()*getVolume()*getCp() + mass*Cp(T0))/(getPhi() + getRho()*VdotUsed*getCp()) );
std::cerr << "Temperature - explicit stability: " << 2.0*(getRho()*getVolume()*getCp() + mass*Cp(T0))/getPhi() << std::endl;
if ( t < deltat ) return T0 + t*(Pp2 + Pup2 + getPhi()*(Tamb - T0) + getRho()*VdotUsed*getCp()*(Tinlet - T0))/(getRho()*getVolume()*getCp() + mass*Cp(T0));
else {
unsigned int steps = int(std::ceil(t/deltat));
//std::cerr << "Steps: " << steps << std::endl;
vector<double> Tn;
Tn.push_back( T0 + (t/steps)*(Pp2 + Pup2 + getPhi()*(Tamb - T0) + getRho()*VdotUsed*getCp()*(Tinlet - T0))/(getRho()*getVolume()*getCp() + mass*Cp(T0)) );
for (unsigned int i=1; i< steps; i++) {
Tn.push_back( Tn[i-1] + (t/steps)*(Pp2 + Pup2 + getPhi()*(Tamb - Tn[i-1]) + getRho()*VdotUsed*getCp()*(Tinlet - Tn[i-1]))/(getRho()*getVolume()*getCp() + mass*Cp(Tn[i-1])) );
}
return std::min(Tn.back(), getTmax());
}
}
double TankPCM::power(double t, double Tf, double VdotUsed, double Pup2, double T0, double Tinlet, double Tamb) {
std::cerr << "rho: " << getRho() << "\tphi: " << getPhi() << std::endl;
// calcul du crit�re de stabilit�
double deltat = std::min( 300.0, 2.0*(getRho()*getVolume()*getCp() + mass*Cp(T0))/(getPhi()+ getRho()*VdotUsed*getCp()) );
std::cerr << "Heating - explicit stability: " << 2.0*(getRho()*getVolume()*getCp() + mass*Cp(T0))/getPhi() << std::endl;
if ( t < deltat ) return ((Tf-T0)/t)*(getRho()*getVolume()*getCp() + mass*Cp(T0)) - Pup2 - getPhi()*(Tamb - T0) - getRho()*VdotUsed*getCp()*(Tinlet - T0);
else {
unsigned int steps = int(std::ceil(t/deltat));
//std::cerr << "Steps: " << steps << std::endl;
vector<double> Hn;
Hn.push_back( ((Tf-T0)/(t/steps))*(getRho()*getVolume()*getCp() + mass*Cp(T0)) - Pup2 - getPhi()*(Tamb - T0) - getRho()*VdotUsed*getCp()*(Tinlet - T0) );
for (unsigned int i=1; i< steps; i++) {
Hn.push_back( - Pup2 - getPhi()*(Tamb - Tf) - getRho()*VdotUsed*getCp()*(Tinlet - T0) );
}
return accumulate(Hn.begin(), Hn.end(), 0.0)/double(steps);
}
}
double Tank::domesticHotWater(double t, double Tf, double VdotUsedUp, double Pp2, double Pup2, double T0, double Tinlet, double Tamb) {
double VdotUp = VdotUsedUp;
double VdotDown = 0.0;
double VdotMid = 0.5*(VdotUp + VdotDown);
do {
if ( temperature(t, VdotMid, Pp2, Pup2, T0, Tinlet, Tamb) < Tf ) VdotUp = VdotMid;
else VdotDown = VdotMid;
VdotMid = 0.5*(VdotUp + VdotDown);
//std::cerr << "VdotMid: " << VdotMid << std::endl;
}
while ( std::abs(temperature(t, VdotMid, Pp2, Pup2, T0, Tinlet, Tamb)-(Tf-0.01)) > 1e-2 && VdotMid > 1e-20 && VdotMid < (VdotUsedUp - 1e-20) );
if ( VdotMid < 1e-20 ) return 0.0;
else if ( VdotMid > (VdotUsedUp - 1e-20) ) return VdotUsedUp;
else return VdotMid;
}
// Cognet: Start added content.
double Tank::maxSolPowerToNotExceedTcrit(double t, double VdotUsed, double power, double solPower, double T0, double Tinlet, double Tamb){
double solPowerToUse;
double T1 = temperature(t, VdotUsed, power, solPower, T0, Tinlet, Tamb);
if ( T1 < Tcritical ) { // If stay below Tcritical.
solPowerToUse = solPower; // Use all thermal power.
}
else { // If reaches Tcritical, only heat partially.
double powHigh = solPower;
double powLow = 0; //solPower*(Tcritical-T0)/(T1-T0);
double powMid;
int nbLoops = 0;
bool notConverged = true;
while ( notConverged ) {
powMid = (powHigh+powLow)*0.5;
T1 = temperature(t, VdotUsed, power, powMid, T0, Tinlet, Tamb);
if ( T1<Tcritical ) { powLow = powMid; }
else { powHigh = powMid; }
nbLoops++;
notConverged = ( abs(T1-Tcritical)>0.05 and nbLoops<10 );
}
solPowerToUse = powMid;
}
return solPowerToUse;
}
// Cognet: End added content
Boiler::Boiler(TiXmlHandle hdl, unsigned int beginD, unsigned int endD, ostream* pLogStr):EnergyConversionSystem(beginD, endD, pLogStr){
//cout << "Boiler..." << endl << flush;
boilerThermalPower = to<double>(hdl.ToElement()->Attribute("Pmax"));
boilerThermalEfficiency = to<double>(hdl.ToElement()->Attribute("eta_th"));
if (hdl.ToElement()->Attribute("name")){ hdl.ToElement()->QueryStringAttribute("name",&name);}
// if the beginDay and endDay are defined at the level of the EnergyConversionSystem then override
if (hdl.ToElement()->Attribute("beginDay")){ hdl.ToElement()->QueryUnsignedAttribute("beginDay",&beginDay); }
if (hdl.ToElement()->Attribute("endDay")){ hdl.ToElement()->QueryUnsignedAttribute("endDay",&endDay); }
}
void Boiler::writeXML(ofstream& file, string tab=""){
file << tab << "<Boiler name=\"" << name << "\" Pmax=\"" << boilerThermalPower << "\" eta_th=\"" << boilerThermalEfficiency << "\"/>" << endl;
}
void Boiler::writeGML(ofstream& file, string tab="") {
file << tab << "<energy:Boiler>" << endl;
file << tab << "\t<energy:installedNominalPower uom=\"W\">" << this->boilerThermalPower << "</energy:installedNominalPower>" << endl;
file << tab << "\t<energy:nominalEfficiency uom=\"ratio\">" << this->boilerThermalEfficiency << "</energy:nominalEfficiency>" << endl;
file << tab << "</energy:Boiler>" << endl;
}
CoGeneration::CoGeneration(TiXmlHandle hdl, unsigned int beginD, unsigned int endD, ostream* pLogStr):EnergyConversionSystem(beginD, endD, pLogStr) {
coGenThermalPower = to<double>(hdl.ToElement()->Attribute("Pmax"));
coGenElectricalEfficiency = to<double>(hdl.ToElement()->Attribute("eta_el"));
coGenThermalEfficiency = to<double>(hdl.ToElement()->Attribute("eta_th"));
coGenMinPartLoadCoefficient = to<double>(hdl.ToElement()->Attribute("minPartLoadCoeff"));
// if the beginDay and endDay are defined at the level of the EnergyConversionSystem then override
if (hdl.ToElement()->Attribute("beginDay")){ hdl.ToElement()->QueryUnsignedAttribute("beginDay",&beginDay);}
if (hdl.ToElement()->Attribute("endDay")){ hdl.ToElement()->QueryUnsignedAttribute("endDay",&endDay);}
}
CoGeneration::CoGeneration(double coGenThermalPower,double coGenElectricalEfficiency,double coGenThermalEfficiency,double coGenMinPartLoadCoefficient,unsigned int beginDay,unsigned int endDay):
EnergyConversionSystem(beginDay,endDay),
coGenThermalPower(coGenThermalPower),
coGenElectricalEfficiency(coGenElectricalEfficiency),
coGenThermalEfficiency(coGenThermalEfficiency),
coGenMinPartLoadCoefficient(coGenMinPartLoadCoefficient)
{}
void CoGeneration::writeXML(ofstream& file, string tab){
file << tab << "<CoGeneration Pmax=\"" << coGenThermalPower << "\" eta_el=\"" << coGenElectricalEfficiency
<< "\" eta_th=\"" << coGenThermalEfficiency << "\" minPartLoadCoeff=\"" << coGenMinPartLoadCoefficient << "\" />" << endl;
}
//double CoGeneration::getThermalPower(double thermalPowerNeeded, double sourceTemp) { // Cognet: Deleted this.
double CoGeneration::getThermalPower(double sourceTemp) { // Cognet: Added this. thermalPowerNeeded is now a class attribute set beforehand.
if ( thermalPowerNeeded < coGenThermalPower*coGenMinPartLoadCoefficient ) return 0.0; // under the min part load coefficient
else if ( thermalPowerNeeded <= coGenThermalPower ) return thermalPowerNeeded;
else return coGenThermalPower;
}
double CoGeneration::getFuelConsumption(double time, double thermalPower, double sourceTemp) {
if ( thermalPower < coGenThermalPower*coGenMinPartLoadCoefficient ) return 0.0;
else if ( thermalPower <= coGenThermalPower) return (time*thermalPower/coGenThermalEfficiency);
else return (time*coGenThermalPower/coGenThermalEfficiency);
}
double CoGeneration::getElectricConsumption(double time, double thermalPower, double sourceTemp) {
if ( thermalPower < coGenThermalPower*coGenMinPartLoadCoefficient) return 0.0;
else if ( thermalPower <= coGenThermalPower) return -time*(thermalPower/coGenThermalEfficiency)*coGenElectricalEfficiency;
else return -time*(coGenThermalPower/coGenThermalEfficiency)*coGenElectricalEfficiency;
}
HeatPump::HeatPump(TiXmlHandle hdl, unsigned int beginD, unsigned int endD, ostream* pLogStr):EnergyConversionSystem(beginD, endD, pLogStr) {
logStream << "Heat Pump, ";
if (to<double>(hdl.ToElement()->Attribute("Pmax"))) heatPumpElectricPower = to<double>(hdl.ToElement()->Attribute("Pmax"));
etaTech = to<double>(hdl.ToElement()->Attribute("eta_tech"));
targetTemp = to<double>(hdl.ToElement()->Attribute("Ttarget"));
// output of the standard performance
logStream << "COP (2C/" << targetTemp << "C): " << etaTech*fabs(epsilonC(2.,targetTemp)) << ", COP (35C/" << targetTemp << "C): " << etaTech*fabs(epsilonC(35., targetTemp)) << endl;
if (string(hdl.ToElement()->Attribute("Tsource"))==string("ground")) {
logStream << "Ground source." << endl << flush;
ground = true;
z0 = to<double>(hdl.ToElement()->Attribute("depth"));
alpha = to<double>(hdl.ToElement()->Attribute("alpha"));
if (hdl.ToElement()->Attribute("z1")) { // vertical pipes in the ground
z1 = to<double>(hdl.ToElement()->Attribute("z1"));
}
else { // horizontal pipes in the ground
z1 = to<double>(hdl.ToElement()->Attribute("depth"));
}
}
else if (string(hdl.ToElement()->Attribute("Tsource"))==string("air")) { // Cognet: Added this.
logStream << "Air source." << endl << flush;
ground = false;
}
else if (string(hdl.ToElement()->Attribute("Tsource"))==string("network")){ //Added by Max: For the substationHeatPump
logStream << "Network Source." << endl << flush;
ground = false;
}
else {
logStream << "Fixed Temperature Source: ";
ground = false;
if(hdl.ToElement()->QueryFloatAttribute("Tsource",&Tsource)!=TIXML_SUCCESS)
throw string("Error in the XML file: a HeatPump has a Tsource attribute with neither 'ground' nor 'air' nor 'network' nor a numeric value of a fixed temperature.");
logStream << Tsource << " celsius" << endl;
}
// if the beginDay and endDay are defined at the level of the EnergyConversionSystem then override
if (hdl.ToElement()->Attribute("beginDay")){ hdl.ToElement()->QueryUnsignedAttribute("beginDay",&beginDay); }
if (hdl.ToElement()->Attribute("endDay")){ hdl.ToElement()->QueryUnsignedAttribute("endDay",&endDay); }
}
void HeatPump::writeXML(ofstream& file, string tab){
file << tab << "<HeatPump Pmax=\"" << heatPumpElectricPower << "\" eta_tech=\"" << etaTech
<< "\" Ttarget=\"" << targetTemp << "\" ";
if(ground){
file << "Tsource=\"ground\" depth=\""<< z0 << "\" alpha=\"" << alpha << "\" ";
if (z1 != z0) file << "position=\"vertical\" z1=\"" << z1 << "\" ";
}
else if (isnan(Tsource)) file << "Tsource=\"air\"";
else file << "Tsource=\"" << Tsource << "\"";
file << "/>" << endl;
}
void HeatPump::writeGML(ofstream& file, string tab) {
file << tab << "<energy:HeatPump>" << endl;
file << tab << "\t<energy:installedNominalPower uom=\"W\">" << this->heatPumpElectricPower << "</energy:installedNominalPower>" << endl;
file << tab << "\t<energy:nominalEfficiency uom=\"ratio\">" << this->etaTech << "</energy:nominalEfficiency>" << endl;
if (targetTemp >= 35.) {
file << tab << "\t<energy:carnotEfficiency>" << this->epsilonC(2.,targetTemp) << "</energy:carnotEfficiency>" << endl;
}
else {
file << tab << "\t<energy:carnotEfficiency>" << fabs(this->epsilonC(35.,targetTemp)) << "</energy:carnotEfficiency>" << endl;
}
file << tab << "\t<energy:heatSource>";
if (ground) {
if (z0 == z1) file << "HorizontalGroundCollector";
else file << "VerticalGroundCollector";
}
else if (isnan(Tsource)) file << "AmbientAir";
else file << "Aquifer";
file << "</energy:heatSource>" << endl;
file << tab << "</energy:HeatPump>" << endl;
}
HeatPump::HeatPump(double heatPumpElectricPower,double heatPumpCOP,double heatPumpSrcTemp,double heatPumpOutputTemp,unsigned int beginDay,unsigned int endDay):
EnergyConversionSystem(beginDay,endDay),
heatPumpElectricPower(heatPumpElectricPower),
targetTemp(heatPumpOutputTemp)
{
ground = false;
etaTech = heatPumpCOP / epsilonC(heatPumpSrcTemp, heatPumpOutputTemp);
}
HeatPump::HeatPump(double heatPumpElectricPower,double heatPumpEtaTech,double targetTemp,unsigned int beginDay,unsigned int endDay):
EnergyConversionSystem(beginDay,endDay),
heatPumpElectricPower(heatPumpElectricPower),
targetTemp(targetTemp),
etaTech(heatPumpEtaTech)
{ ground = false; }
double HeatPump::getHeatProduced(double work, double sourceTemp, double outputTemp) {
// as epsilonC follows the sign of the heat/cold demand, so does the heat/cold produced
return work*etaTech*epsilonC(sourceTemp, outputTemp);
}
double HeatPump::getWorkNeeded(double thermalPower, double sourceTemp, double outputTemp) {
// the work is always positive
return std::abs(thermalPower/(etaTech*epsilonC(sourceTemp, outputTemp)));
}
double HeatPump::getWorkNeededEvap(double PowerEvap, double sourceTemp, double outputTemp) {
// the work is always positive
return std::abs(PowerEvap/(etaTech*epsilonC(sourceTemp, outputTemp)-1));
}
//double HeatPump::getThermalPower(double thermalPowerNeeded, double sourceTemp) { // Cognet: Deleted this.
double HeatPump::getThermalPower(double sourceTemp) { // Cognet: Added this. thermalPowerNeeded is now a class attribute set beforehand.
if ( getWorkNeeded(thermalPowerNeeded, sourceTemp, targetTemp) <= heatPumpElectricPower ) return thermalPowerNeeded;
else return getHeatProduced(heatPumpElectricPower, sourceTemp, targetTemp);
}
double HeatPump::getElectricConsumption(double time, double thermalPower, double sourceTemp) {
if ( getWorkNeeded(thermalPower, sourceTemp, targetTemp) <= heatPumpElectricPower ) return time*(thermalPower/(etaTech*epsilonC(sourceTemp, targetTemp)));
else return time*heatPumpElectricPower;
}
CoGenerationHeatPump::CoGenerationHeatPump(TiXmlHandle hdl, unsigned int beginD, unsigned int endD, ostream* pLogStr):CoGeneration(hdl,beginD,endD,pLogStr),HeatPump(hdl.FirstChildElement("HeatPump"),beginD,endD,pLogStr) {
logStream << "Cogen + HP." << endl << flush;
// Ignore heatPumpElectricPower read in xml file ? Or keep line bellow only if no value in xml file ?
//if(heatPumpElectricPower==0)
heatPumpElectricPower = coGenThermalPower/coGenThermalEfficiency*coGenElectricalEfficiency;
// if the beginDay and endDay are defined at the level of the EnergyConversionSystem then override
if (hdl.ToElement()->Attribute("beginDay")){ hdl.ToElement()->QueryUnsignedAttribute("beginDay",&beginDay);}
if (hdl.ToElement()->Attribute("endDay")){ hdl.ToElement()->QueryUnsignedAttribute("endDay",&endDay);}
}
CoGenerationHeatPump::CoGenerationHeatPump(double coGenThermalPower, double coGenElectricalEfficiency, double coGenThermalEfficiency, double coGenMinPartLoadCoefficient,
double heatPumpCOP, double heatPumpSrcTemp, double heatPumpOutputTemp,unsigned int beginDay,unsigned int endDay):
CoGeneration(coGenThermalPower, coGenElectricalEfficiency, coGenThermalEfficiency, coGenMinPartLoadCoefficient,beginDay,endDay),
HeatPump(coGenThermalPower/coGenThermalEfficiency*coGenElectricalEfficiency, heatPumpCOP, heatPumpSrcTemp, heatPumpOutputTemp,beginDay,endDay) {}
CoGenerationHeatPump::CoGenerationHeatPump(double coGenThermalPower, double coGenElectricalEfficiency, double coGenThermalEfficiency, double coGenMinPartLoadCoefficient,
double heatPumpEtaTech, double targetTemp,unsigned int beginDay,unsigned int endDay) :
CoGeneration(coGenThermalPower, coGenElectricalEfficiency, coGenThermalEfficiency, coGenMinPartLoadCoefficient,beginDay,endDay),
HeatPump(coGenThermalPower/coGenThermalEfficiency*coGenElectricalEfficiency, heatPumpEtaTech, targetTemp,beginDay,endDay) {}
void CoGenerationHeatPump::writeXML(ofstream& file, string tab){
file << tab << "<CHP-HP Pmax=\"" << coGenThermalPower << "\" eta_el=\"" << coGenElectricalEfficiency
<< "\" eta_th=\"" << coGenThermalEfficiency << "\" minPartLoadCoeff=\"" << coGenMinPartLoadCoefficient << "\">" << endl;
this->HeatPump::writeXML(file, tab+"\t");
file << tab << "</CHP-HP>" << endl;
}
//double CoGenerationHeatPump::getThermalPower(double thermalPowerNeeded, double sourceTemp) { // Cognet: Deleted this.
double CoGenerationHeatPump::getThermalPower(double sourceTemp) { // Cognet: Added this. thermalPowerNeeded is now a class attribute set beforehand.
double COP = etaTech*epsilonC(sourceTemp, targetTemp);
double Pgross = thermalPowerNeeded/(coGenElectricalEfficiency*COP+coGenThermalEfficiency); // gross energy needed to satisfy the needs
double PgrossMax = coGenThermalPower/coGenThermalEfficiency; // maximal gross energy taken by the machine
if ( Pgross > PgrossMax ) return PgrossMax*(coGenElectricalEfficiency*COP+coGenThermalEfficiency);
else if ( (Pgross/PgrossMax) < coGenMinPartLoadCoefficient ) return 0.0;
else return thermalPowerNeeded;
}
double CoGenerationHeatPump::getFuelConsumption(double time, double thermalPower, double sourceTemp) {
double COP = etaTech*epsilonC(sourceTemp, targetTemp);
double Pgross = thermalPower/(coGenElectricalEfficiency*COP+coGenThermalEfficiency);
double PgrossMax = coGenThermalPower/coGenThermalEfficiency;
if ( Pgross > PgrossMax ) return time*PgrossMax;
else if ( (Pgross/PgrossMax) < coGenMinPartLoadCoefficient ) return 0.0;
else return time*Pgross;
}
Pump::Pump(TiXmlHandle hdl) {
string name = "efficiencyPump";
float effPump=0.f;
if ( hdl.ToElement()->QueryFloatAttribute(name.c_str(), &effPump) ) {
// no efficiency in the attributes, check if a child exists
if (hdl.FirstChildElement("EfficiencyPump").ToElement()) {// Changed by Max
efficiencyPump = EfficiencyPump::createNewEfficiencyPump(hdl.FirstChildElement("EfficiencyPump")); // Dynamical allocation.
}
else throw string("Error in the XML file: a Pump is missing attribute or child element: '"+name+"'.");
}
else { // efficiency is defined in the attributes, check its value
if ( effPump<=0 ) { throw string("Error in the XML file: a Pump has "+name+"<=0."); }
else { // create the pump with given efficiency
efficiencyPump = new ConstantEfficiencyPump(effPump);
}
}
name = "n0";
if ( hdl.ToElement()->QueryFloatAttribute(name.c_str(), &n0) ) { throw string("Error in the XML file: a Pump doesn't have attribute: '"+name+"'."); }
if ( n0<=0 ) { throw string("Error in the XML file: a Pump has "+name+"<=0."); }
name = "a0";
if ( hdl.ToElement()->QueryFloatAttribute(name.c_str(), &a0) ) { throw string("Error in the XML file: a Pump doesn't have attribute: '"+name+"'."); }
if ( a0<=0 ) { throw string("Error in the XML file: a Pump "+name+"<=0."); }
name = "a1";
if ( hdl.ToElement()->QueryFloatAttribute(name.c_str(), &a1) ) { throw string("Error in the XML file: a Pump doesn't have attribute: '"+name+"'."); }
name = "a2";
if ( hdl.ToElement()->QueryFloatAttribute(name.c_str(), &a2) ) { throw string("Error in the XML file: a Pump doesn't have attribute: '"+name+"'."); }
if ( a2>0 ) { throw string("Error in the XML file: a Pump has "+name+">0."); }
n = 0.5f*n0; // TODO improve this?
}
void Pump::computeElectricAndThermalPower(float const& pressureDiff, float const& massFlow, float const& rho, float& electricPow, float& thermalPow) {
float effPump = efficiencyPump->computeEfficiency(massFlow);
if (massFlow>=0.f and pressureDiff<=0.f) { // Normal conditions, mass flow in correct direction and pump increases the pressure and temperature.
// Hydraulic power needed is pressureDiff*massFlow/rho
electricPow = -pressureDiff*massFlow/(rho*effPump); //Added by Max
thermalPow = electricPow*(1.f-effPump); // Since pumpPower = hydraulicPower+thermalPower = hydraulicPower/efficiency (Added by Max)
} else { // Pump is resisting the flow (similar to a valve), dissipating heat.
electricPow = 0.f; // For simplifications, this no electricity, only heat dissipation (even if it could technically generate electricity, like a turbine).
thermalPow = pressureDiff*massFlow/rho; // Should always be positive.
}
}
//Added by Max
float Pump::cpdT(float const& pressureDiff, float const& rho, float const& massFlow){
// We suppose that the mass flow should be always positive
if(pressureDiff<=0.f){
return -pressureDiff*(1-efficiencyPump->computeEfficiency(massFlow))/rho/efficiencyPump->computeEfficiency(massFlow); // For now we suppose an arbitrary massflow because we don't know it as we trying to compute it. (Solution to say that the slave has necessary a constant efficiency)
}else{
return pressureDiff*(1-efficiencyPump->computeEfficiency(massFlow))/rho/efficiencyPump->computeEfficiency(massFlow);
}
}
void Pump::computePressureDiff(float const& massFlow, float& deltaP, float& dDeltaP_dm) {
float x = n/n0;
if (massFlow>=0.f) {
deltaP = -(a0*x*x + a1*x*massFlow + a2*massFlow*massFlow);
dDeltaP_dm = -(a1*x + 2.f*a2*massFlow);
} else {
// deltaP = -a0*x*x;
// dDeltaP_dm = 0.f;
deltaP = -a0*x*x + a2*massFlow*massFlow*100000.f; // TODO: improve this. This is to ensure that the friction increases if flow goes backwards through the pump.
dDeltaP_dm = 2.f*a2*massFlow*100000.f;
}
}
float Pump::computeIdealN(float const& massFlow, float const& pressureDiff) {
float a = -a0;
float b = -a1*massFlow;
float c = -a2*massFlow*massFlow - pressureDiff;
float delta = abs(b*b-4*a*c); // SHould always be positive even without abs.
float idealN = n0 * ( -b-sqrt(delta) )/(2.f*a);
return idealN;
}
void Pump::updateRpms(float& sumDeltaRpm, float& sumRpm, float const& learningRate, float const& targetMassFlow, float const& targetPressureDiff) {
float nMax = n0;
float nMin = computeNMin();
float nPrev = n;
n = computeIdealN(targetMassFlow, targetPressureDiff);
if (n<nMin) { n = nMin; }
else if (n>nMax) { n = nMax; }
n = nPrev*(1.f-learningRate)+n*learningRate;
sumDeltaRpm += abs(n-nPrev);
sumRpm += n;
}
void Pump::setNToMax(float& sumDeltaRpm, float& sumRpm, float const& learningRate) {
float nPrev = n;
n = nPrev*(1.f-learningRate)+n0*learningRate;
sumDeltaRpm += abs(n-nPrev);
sumRpm += n;
}
float Valve::deltaP0_invRho0_36002 = 1296000000.f ; // deltaP0=1e5, invRho0=1/1e3, 3600^2=12960000, multiply them.
void Valve::computePressureDiffAndDerivative(float const& m, float const& rho, float& deltaP, float& dDeltaP_dm) {
dDeltaP_dm = deltaP0_invRho0_36002*2.f*abs(m)/(rho*kv*kv);
deltaP = 0.5f*m*dDeltaP_dm;
}
float Valve::computeIdealKv(float const& rho, float const& massFlow, float const& pressureDiff) {
return massFlow*sqrt(abs(deltaP0_invRho0_36002/(rho*pressureDiff)));
}
void Valve::updateKv(float const& rho, float& sumDeltaKv, float& sumKv, float const& learningRate, float const& targetMassFlow, float const& targetPressureDiff, PIDControllerValve& pid, float& Targetkv, bool& ImposedValve) {
float kvMin = computeKvMin();
float kvPrev = kv;
float ratio(0);
// if (massFlow<=0.f or pressureDiff<=0.f) { // If the pressure drops the wrong way, or if the supply temperatures don't match : close the valve.
// kv = kvMin;
// }
// else {
if (ImposedValve) {
ratio = pid.computeControlVariable(Targetkv,kvPrev/kvMax);
kv = ratio*kvMax;
}else{
kv = computeIdealKv(rho, targetMassFlow, targetPressureDiff/*-50000*/);
if (kv<kvMin) { kv = kvMin; }
else if (kv>kvMax) { kv = kvMax; }
kv = kvPrev*(1.f-learningRate)+kv*learningRate;
}
// }
sumDeltaKv += abs(kv-kvPrev);
sumKv += kv;
}
void Valve::setKvToMin(float& sumDeltaKv, float& sumKv, float const& learningRate) {
float kvPrev = kv;
kv = kvPrev*(1.f-learningRate)+computeKvMin()*learningRate;
sumDeltaKv += abs(kv-kvPrev);
sumKv += kv;
}
float PIDController::computeControlVariable(float const& desiredSetpoint, float const& processVariable, float const& kp, float const& ki, float const& kd) {
float err = desiredSetpoint-processVariable;
integralErr += err;
float deriv = err-prevErr;
prevErr = err;
float controlVariable = kp*err + ki*integralErr + kd*deriv;
return controlVariable;
}
float Carla::integrate(vector<float> const& f, float const& xmin, float const& xmax) {
float integ = -0.5f*(f.front()+f.back());
for (auto const& el : f) { integ += el; }
integ *= (xmax-xmin)/(f.size()-1);
return integ;
}
float Carla::selectAction() {
float z = randomUniform(0,1);
float cumulProba = 0.f;
float probaToNextStep = 0.f;
size_t i = 0;
do {
probaToNextStep = 0.5f*(probaDensity_fx[i]+probaDensity_fx[i+1])*(position_x[i+1]-position_x[i]);
cumulProba += probaToNextStep;
i++;
} while (cumulProba<z and i<probaDensity_fx.size()-1);
float newAction;
cumulProba -= probaToNextStep;
if (cumulProba<z) {
i--;
newAction = solveQuadratic(position_x[i], position_x[i+1], probaDensity_fx[i], probaDensity_fx[i+1], z-cumulProba);
} else {
newAction = xmax(); // Somehow the integral is bigger than one, just take xmax.
}
return newAction;
}
float Carla::solveQuadratic(float const& xi, float const& xip1, float const& fi, float const& fip1, float const& area) {
float slope = (fip1-fi)/(xip1-xi);
float a = slope*0.5f;
float b = fi-xi*slope;
float c = -( area + xi*b + xi*xi*a );
float sol;
if (a==0.f) { // Not quadratic equation.
if (b==0.f) { // The affine function is zero everywhere (should not happen).
sol = xi;
} else {
sol = -c/b;
}
}
else { // Quadratic equation.
float tmp = sqrt(b*b-4*a*c);
sol = ( -b+tmp )/(2.f*a);
if (sol<xi or sol>xip1) { // Check whether this root is the correct solution.
sol = ( -b-tmp )/(2.f*a);
}
}
return sol;
}