-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmodels.py
More file actions
1517 lines (1304 loc) · 49.7 KB
/
models.py
File metadata and controls
1517 lines (1304 loc) · 49.7 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
import datetime as dt
from enum import Enum
from typing import Union, List, Optional, Any, Tuple, Dict
import pandas as pd
import pvlib # type: ignore
from pvlib.ivtools.sdm import pvsyst_temperature_coeff # type: ignore
from pydantic import BaseModel, Field, PrivateAttr, validator, root_validator
from pydantic.fields import Undefined
from pydantic.types import UUID
import pytz
SYSTEM_ID = "6b61d9ac-2e89-11eb-be2a-4dc7a6bcd0d9"
SYSTEM_EXAMPLE = dict(
name="Test PV System",
latitude=33.98,
longitude=-115.323,
elevation=2300,
inverters=[
dict(
name="Inverter 1",
make_model="ABB__MICRO_0_25_I_OUTD_US_208__208V_",
inverter_parameters=dict(
Pso=2.08961,
Paco=250,
Pdco=259.589,
Vdco=40,
C0=-4.1e-05,
C1=-9.1e-05,
C2=0.000494,
C3=-0.013171,
Pnt=0.075,
),
losses={},
arrays=[
dict(
name="Array 1",
make_model="Canadian_Solar_Inc__CS5P_220M",
albedo=0.2,
modules_per_string=7,
strings=5,
tracking=dict(
tilt=20.0,
azimuth=180.0,
),
temperature_model_parameters=dict(
u_c=29.0, u_v=0.0, eta_m=0.1, alpha_absorption=0.9
),
module_parameters=dict(
alpha_sc=0.004539,
gamma_ref=1.2,
mu_gamma=-0.003,
I_L_ref=5.11426,
I_o_ref=8.10251e-10,
R_sh_ref=381.254,
R_s=1.06602,
R_sh_0=400.0,
cells_in_series=96,
),
)
],
airmass_model="kastenyoung1989",
aoi_model="physical",
clearsky_model="ineichen",
spectral_model="no_loss",
transposition_model="haydavies",
)
],
)
# all compatible with luxon 1.25.0, most commen + Etc/GMT+offset
TIMEZONES = [
tz
for tz in pytz.common_timezones
if not tz.startswith("US/") and tz not in ("America/Nuuk", "Antarctica/McMurdo")
] + [tz for tz in pytz.all_timezones if tz.startswith("Etc/GMT") and tz != "Etc/GMT0"]
SURFACE_ALBEDOS = pvlib.irradiance.SURFACE_ALBEDOS
TEMPERATURE_PARAMETERS = pvlib.temperature.TEMPERATURE_MODEL_PARAMETERS
# allows word chars, space, comma, apostrophe, hyphen, parentheses, underscore
# and empty string
def UserString(default: Any = Undefined, *, title: str = None, description: str = None):
return Field(
default,
title=title,
description=description,
max_length=128,
regex=r"^(?!\W+$)(?![_ ',\-\(\)]+$)[\w ',\-\(\)]*$",
)
class SPIBase(BaseModel):
class Config:
extra = "forbid"
class PVLibBase(SPIBase):
"""Provide a `pvlib_dict` method to convert parameters if needed
for using in pvlib. Child classes may implement model-specific conversions
as needed."""
def pvlib_dict(self):
return self.dict()
class FixedTracking(SPIBase):
"""Parameters for a fixed tilt array"""
tilt: float = Field(
..., description="Tilt of modules in degrees from horizontal", ge=0, le=180
)
azimuth: float = Field(
...,
description="Azimuth of modules relative to North in degrees",
ge=0,
lt=360.0,
)
class SingleAxisTracking(SPIBase):
"""Parameters for a single axis tracking array"""
axis_tilt: float = Field(
...,
title="Axis Tilt",
description="Tilt of tracker axis in degrees from horizontal",
ge=0,
le=90,
)
axis_azimuth: float = Field(
...,
title="Axis Azimiuth",
description="Azimuth of tracker axis clockwise from North in degrees",
ge=0,
lt=360.0,
)
gcr: float = Field(
...,
title="GCR",
description=(
"Ground coverage ratio: ratio of module length to the spacing"
" between trackers"
),
ge=0,
)
backtracking: bool = Field(
..., description="True if the tracking system supports backtracking"
)
class PVsystModuleParameters(PVLibBase):
"""Parameters for the modules that make up an array in a PVsyst-like model"""
alpha_sc: float = Field(
...,
description=(
"Short-circuit current temperature coefficient of the module "
"in units of A/C"
),
)
gamma_ref: float = Field(..., description="Diode ideality factor", ge=0)
mu_gamma: float = Field(
...,
description="Temperature coefficient for the diode ideality factor, 1/K",
)
I_L_ref: float = Field(
...,
description=(
"Light-generated current (or photocurrent) at reference conditions,"
"in amperes"
),
)
I_o_ref: float = Field(
...,
description=(
"Dark or diode reverse saturation current at reference conditions,"
"in amperes"
),
)
R_sh_ref: float = Field(
...,
description="Shunt resistance at reference conditions, in ohms",
)
R_sh_0: float = Field(
..., description="Shunt resistance at zero irradiance conditions, in ohms"
)
R_s: float = Field(
..., description="Series resistance at reference conditions, in ohms"
)
cells_in_series: int = Field(
..., description="Number of cells connected in series in a module", ge=0
)
R_sh_exp: float = Field(
5.5, description="Exponent in the equation for shunt resistance, unitless"
)
EgRef: float = Field(
1.121,
description=(
"Energy bandgap at reference temperature in units of eV. "
"1.121 eV for crystsalline silicon."
),
gt=0,
)
_modelchain_dc_model: str = PrivateAttr("pvsyst")
_gamma: float = PrivateAttr()
@root_validator(skip_on_failure=True)
def validate_diode_params(cls, values):
# and set _gamma here since it could raise an error with bad params
err = ValueError(
"Unable to calculate single diode parameters from parameters supplied."
)
try:
pvlib.pvsystem.calcparams_pvsyst(
effective_irradiance=1000, temp_cell=25, **values
)
except Exception:
raise err
try:
cls._gamma = pvsyst_temperature_coeff(**values)
except Exception:
raise err
return values
class PVWattsModuleParameters(PVLibBase):
"""Parameters for the modules that make up an array in a PVWatts-like model"""
pdc0: float = Field(
...,
description="Power of the modules at 1000 W/m^2 and cell reference temperature",
)
gamma_pdc: float = Field(
...,
description=(
"Temperature coefficient of power in units of %/C. "
"Typically -0.2 to -0.5 % per degree C"
),
)
_modelchain_dc_model: str = PrivateAttr("pvwatts")
_gamma: float = PrivateAttr()
def __init__(self, **data):
super().__init__(**data)
self._gamma = self.gamma_pdc / 100
def pvlib_dict(self):
"""Convert to a dict pvlib understands for `module_parameters`
i.e. scale gamma_pdc to 1/C"""
return {k: v / 100 if k == "gamma_pdc" else v for k, v in self.dict().items()}
class CECModuleParameters(PVLibBase):
"""Parameters for the modules that make up an array in a SAM-like model"""
alpha_sc: float = Field(
...,
description=(
"Short-circuit current temperature coefficient of the module "
"in units of A/C"
),
)
a_ref: float = Field(
...,
description=(
"Product of number of cells in series, diode ideality factor, "
"and thermal voltage at reference conditions"
),
ge=0,
)
I_L_ref: float = Field(
...,
description=(
"Light-generated current (or photocurrent) at reference "
"conditions, in amperes"
),
)
I_o_ref: float = Field(
...,
description=(
"Dark or diode reverse saturation current at reference conditions,"
"in amperes"
),
)
R_sh_ref: float = Field(
...,
description="Shunt resistance at reference conditions, in ohms",
)
R_s: float = Field(
..., description="Series resistance at reference conditions, in ohms"
)
gamma_r: float = Field(
...,
description=(
"Temperature coefficient of power in units of %/C. "
"Typically -0.2 to -0.5 % per degree C"
),
)
cells_in_series: int = Field(
..., description="Number of cells connected in series in a module", ge=0
)
Adjust: float = Field(
0.0,
description=(
"Factor used to adjust temperature coefficients for voltage "
"and current to match temperature coefficient for power, percent"
),
)
EgRef: float = Field(
1.121,
description=(
"Energy bandgap at reference temperature in units of eV. "
"1.121 eV for all modules in the CEC database."
),
gt=0,
)
dEgdT: float = Field(
-0.0002677,
description=(
"The temperature dependence of the energy bandgap at reference "
"conditions in units of 1/K. -0.0002677 1/K for all modules in "
"the CEC database."
),
)
_modelchain_dc_model: str = PrivateAttr("cec")
_gamma: float = PrivateAttr()
def __init__(self, **data):
super().__init__(**data)
self._gamma = self.gamma_r / 100
@root_validator(skip_on_failure=True)
def validate_diode_params(cls, values):
try:
pvlib.pvsystem.calcparams_cec(
effective_irradiance=1000,
temp_cell=25,
**{
k: v
for k, v in values.items()
if k not in ("gamma_r", "cells_in_series")
},
)
except Exception: # pragma: no cover
raise ValueError(
"Unable to calculate single diode parameters from parameters supplied."
)
return values
def pvlib_dict(self):
"""Convert to a dict pvlib understands for `module_parameters` by removing
gamma_r"""
return {k: v for k, v in self.dict().items() if k != "gamma_r"}
class PVsystTemperatureParameters(SPIBase):
"""Parameters for the cell temperature model of the modules in a
PVSyst-like model"""
u_c: float = Field(
29.0, description="Combined heat loss factor coefficient, units of W/m^2/C"
)
u_v: float = Field(
0.0,
description=(
"Combined heat loss factor influenced by wind, units of (W/m^2)/(C m/s)"
),
)
eta_m: float = Field(0.1, description="Module external efficiency as a fraction")
alpha_absorption: float = Field(0.9, description="Absorption coefficient")
_modelchain_temperature_model: str = PrivateAttr("pvsyst")
class SAPMTemperatureParameters(SPIBase):
"""Parameters for the cell temperature model of the modules in the
Sandia Array Performance Model"""
a: float = Field(
..., description="Parameter a of the Sandia Array Performance Model"
)
b: float = Field(
..., description="Parameter b of the Sandia Array Performance Model"
)
deltaT: float = Field(
..., description="Parameter delta T of the Sandia Array Performance Model"
)
_modelchain_temperature_model: str = PrivateAttr("sapm")
class NOCTSAMTemperatureParameters(SPIBase):
"""Parameters for the NOCT SAM temperature model"""
noct: float = Field(
...,
description=(
"Nominal operating cell temperature [C], determined at conditions of "
"800 W/m^2 irradiance, 20 C ambient air temperature and 1 m/s wind."
),
)
eta_m_ref: float = Field(
...,
description=(
"Module external efficiency [unitless] at reference conditions of "
"1000 W/m^2 and 20C."
),
)
transmittance_absorptance: float = Field(
0.9,
description=(
"Coefficient for combined transmittance and absorptance effects. [unitless]"
),
)
array_height: int = Field(
1,
description=(
"Height of array above ground in stories (one story is about 3m). Must "
"be either 1 or 2. For systems elevated less than one story, use 1. "
"If system is elevated more than two stories, use 2."
),
ge=1,
le=2,
)
mount_standoff: float = Field(
4,
description=(
"Distance between array mounting and mounting surface. Use default "
"if system is ground-mounted. [inches]"
),
)
_modelchain_temperature_model: str = PrivateAttr("noct_sam")
class PVArray(SPIBase):
"""Parameters of a PV array that feeds into one inverter"""
name: str = UserString("", description="Name of this array")
make_model: str = UserString(
"",
title="Module Make & Model",
description="Make and model of the PV modules in this array",
)
module_parameters: Union[
PVsystModuleParameters, PVWattsModuleParameters, CECModuleParameters
] = Field(
...,
title="Module Parameters",
description="Parameters describing PV modules in this array",
)
temperature_model_parameters: Union[
PVsystTemperatureParameters,
SAPMTemperatureParameters,
NOCTSAMTemperatureParameters,
] = Field(
...,
title="Temperature Model Parameters",
description=(
"Parameters describing the temperature characteristics of the modules"
),
)
tracking: Union[FixedTracking, SingleAxisTracking] = Field(
..., description="Parameters describing single-axis tracking or fixed mounting"
)
albedo: float = Field(
..., description="Albedo of the surface around the array", ge=0
)
modules_per_string: int = Field(
...,
title="Modules Per String",
description="Number of PV modules per string",
gt=0,
)
strings: int = Field(
..., description="Number of parallel strings in the array", gt=0
)
_modelchain_models: Tuple[Tuple[str, str], ...] = PrivateAttr()
def __init__(self, **data):
super().__init__(**data)
self._modelchain_models = (
("dc_model", self.module_parameters._modelchain_dc_model),
(
"temperature_model",
self.temperature_model_parameters._modelchain_temperature_model,
),
("dc_ohmic_model", "no_loss"),
)
class PVWattsLosses(SPIBase):
"""Parameters describing the PVWatts system loss model"""
soiling: float = Field(2.0, description="Soiling loss, %")
shading: float = Field(3.0, description="Shading loss, %")
snow: float = Field(0.0, description="Snow loss, %")
mismatch: float = Field(2.0, description="Mismatch loss, %")
wiring: float = Field(2.0, description="Wiring loss, %")
connections: float = Field(0.5, description="Connections loss, %")
lid: float = Field(1.5, title="LID", description="Light induced degradation, %")
nameplate_rating: float = Field(1.0, description="Nameplate Rating loss, %")
age: float = Field(0.0, description="Age loss, %")
availability: float = Field(3.0, description="Availability loss, %")
_modelchain_losses_model: str = PrivateAttr("pvwatts")
class PVWattsInverterParameters(SPIBase):
"""DC-AC power conversion parameters of an inverter for the PVWatts model"""
pdc0: float = Field(
...,
description=(
"DC power input which produces the rated AC output power at the "
"nominal DC voltage of the inverter, W"
),
)
eta_inv_nom: float = Field(
0.96, description="Nominal inverter efficiency, unitless"
)
eta_inv_ref: float = Field(
0.9637, description="Reference inverter efficiency, unitless"
)
_modelchain_ac_model: str = PrivateAttr("pvwatts")
_pac0: float = PrivateAttr()
def __init__(self, **data):
super().__init__(**data)
self._pac0 = self.pdc0 * self.eta_inv_nom
class SandiaInverterParameters(SPIBase):
"""DC-AC power conversion parameters of an inverter for Sandia's
Grid-Connected PV Inverter model"""
Paco: float = Field(..., description="AC power rating of the inverter, W")
Pdco: float = Field(
...,
description=(
"DC power which produces the rated AC output power at the "
"nominal DC voltage of the inverter, W"
),
)
Vdco: float = Field(
...,
description=(
"Nominal DC voltage at which the AC power rating is determined, V"
),
)
Pso: float = Field(
...,
description=(
"DC power required to start the inversion process, assumed equal "
"to self consumption by the inverter, W"
),
)
C0: float = Field(
...,
description=(
"Parameter defining the curvature of the relationship between AC "
"power and DC power at reference operating conditions, 1/W"
),
)
C1: float = Field(
...,
description=(
"Empirical coefficient allowing Pdco to vary linearly with DC "
"voltage input, 1/V"
),
)
C2: float = Field(
...,
description=(
"Empirical coefficient allowing Pso to vary linearly with DC "
"voltage input, 1/V"
),
)
C3: float = Field(
...,
description=(
"Empirical coefficient allowing C0 to vary linearly with DC "
"voltage input, 1/V"
),
)
Pnt: float = Field(
...,
description=(
"AC power consumed by the inverter when no AC power is exported "
" (i.e., night tare), W"
),
)
_modelchain_ac_model: str = PrivateAttr("sandia")
_pac0: float = PrivateAttr()
def __init__(self, **data):
super().__init__(**data)
self._pac0 = self.Paco
class AOIModelEnum(str, Enum):
"""Model to calculate the incidence angle modifier"""
no_loss = "no_loss"
physical = "physical"
ashrae = "ashrae"
sapm = "sapm"
martin_ruiz = "martin_ruiz"
class SpectralModelEnum(str, Enum):
"""Spectral losses model"""
no_loss = "no_loss"
class ClearskyModelEnum(str, Enum):
"""Model to estimate clear sky GHI, DNI, DHI"""
ineichen = "ineichen"
haurwitz = "haurwitz"
simplified_solis = "simplified_solis"
class AirmassModelEnum(str, Enum):
"""Model to estimate relative airmass at sea level"""
simple = "simple"
kasten1966 = "kasten1966"
youngirvine1967 = "youngirvine1967"
kastenyoung1989 = "kastenyoung1989"
gueymard1993 = "gueymard1993"
young1994 = "young1994"
pickering2002 = "pickering2002"
class TranspositionModelEnum(str, Enum):
"""Transposition model to determine total in-plane irradiance and the
beam, sky diffuse, and ground reflected components"""
isotropic = "isotropic"
klucher = "klucher"
haydavies = "haydavies"
reindl = "reindl"
king = "king"
perez = "perez"
class Inverter(SPIBase):
"""Parameters for a single inverter feeding into a PV system"""
name: str = UserString("", description="Name of this inverter")
make_model: str = UserString(
"",
title="Inverter Make & Model",
description="Make and model of the inverter",
)
arrays: List[PVArray] = Field(
...,
description="List of PV arrays that are connected to this inverter",
min_items=1,
)
losses: Optional[PVWattsLosses] = Field(
{}, description="Parameters describing the array losses"
)
inverter_parameters: Union[
PVWattsInverterParameters, SandiaInverterParameters
] = Field(
...,
title="Inverter Parameters",
description="Power conversion parameters for the inverter",
)
airmass_model: AirmassModelEnum = AirmassModelEnum.kastenyoung1989
aoi_model: AOIModelEnum = AOIModelEnum.physical
clearsky_model: ClearskyModelEnum = ClearskyModelEnum.ineichen
spectral_model: SpectralModelEnum = SpectralModelEnum.no_loss
transposition_model: TranspositionModelEnum = TranspositionModelEnum.haydavies
_modelchain_models: Tuple[Tuple[str, str], ...] = PrivateAttr()
def __init__(self, **data):
super().__init__(**data)
self._modelchain_models = self.arrays[0]._modelchain_models + (
("ac_model", self.inverter_parameters._modelchain_ac_model),
(
"losses_model",
getattr(self.losses, "_modelchain_losses_model", "no_loss"),
),
("airmass_model", self.airmass_model),
("aoi_model", self.aoi_model),
("clearsky_model", self.clearsky_model),
("spectral_model", self.spectral_model),
("transposition_model", self.transposition_model),
)
@root_validator
def check_only_one_array_for_tracker(cls, values):
arrays = values.get("arrays")
if arrays is not None and len(arrays) > 1:
for arr in arrays:
if isinstance(arr.tracking, SingleAxisTracking):
raise ValueError(
"Multiple arrays per inverter with any single axis "
"trackers is not supported"
)
return values
class PVSystem(SPIBase):
"""Parameters for an entire PV system at some location"""
name: str = UserString(
...,
title="PV System Name",
description="Name of the system",
)
latitude: float = Field(
...,
description=(
"Latitude of the system in degrees NORTH of the equator. Use a NEGATIVE sign "
"for all systems in the southern hemisphere."
),
ge=-90,
le=90,
)
longitude: float = Field(
...,
description="Longitude of the system in degrees EAST of the prime meridian (zero degrees).",
ge=-180,
le=180,
)
elevation: float = Field(
...,
description=(
"Elevation of the system in METERS above sea level. Use a NEGATIVE sign if the system "
"is below sea level."
),
ge=-300,
)
inverters: List[Inverter] = Field(
..., description="List of inverters that make up this system", min_items=1
)
class Config:
schema_extra = {"example": SYSTEM_EXAMPLE}
class StoredObjectID(SPIBase):
object_id: UUID = Field(..., description="Unique identifier of the object")
object_type: str = Field("system", description="Type of the object")
class Config:
# allow extra fields to go into Stored objects as they are
# removed when serializing. Eases putting DB objects into models
extra = "ignore"
schema_extra = {
"example": {
"object_id": "6b61d9ac-2e89-11eb-be2a-4dc7a6bcd0d9",
"object_type": "system",
}
}
class StoredObject(StoredObjectID):
created_at: dt.datetime = Field(..., description="Datetime the object was created")
modified_at: dt.datetime = Field(
..., description="Datetime the object was last modified"
)
class Config:
schema_extra = {
"example": {
"object_id": "6b61d9ac-2e89-11eb-be2a-4dc7a6bcd0d9",
"object_type": "system",
"created_at": "2020-12-01T01:23:00+00:00",
"modified_at": "2020-12-01T01:23:00+00:00",
}
}
class StoredPVSystem(StoredObject):
definition: PVSystem
class Config:
schema_extra = {
"example": {
"object_id": "6b61d9ac-2e89-11eb-be2a-4dc7a6bcd0d9",
"object_type": "system",
"created_at": "2020-12-01T01:23:00+00:00",
"modified_at": "2020-12-01T01:23:00+00:00",
"definition": SYSTEM_EXAMPLE,
}
}
class UserInfo(StoredObject):
"""Information about the current user"""
auth0_id: str = Field(..., description="User ID from Auth 0")
class JobTimeindex(SPIBase):
"""Parameters for a time index that all data uploads must conform to.
Data is assumed to time-averaged and closed and labeled at the left endpoint, i.e.
a datapoint at 23:00 of data with a 1 hour time step is assumed be the
average of data from 23:00 to 23:59.
"""
start: dt.datetime = Field(
...,
description=(
"Start of the time range that data will be uploaded for. "
"String values in the format YYYY-MM-DD[T]HH:MM:SS[Z or +-HH[:]MM] "
"may be provided. "
"Integers/floats may be provided and are assumed to be Unix time."
),
)
end: dt.datetime = Field(
...,
description="End (exclusive) of the time range that data will be uploaded for",
)
step: dt.timedelta = Field(
...,
description=(
"Time step between each data point in whole minutes, "
"from 1 to 60 minutes. Acceptable formats include ISO 8601 timedeltas,"
" strings formatted like HH:MM, and integers/float assumed as seconds."
),
)
timezone: Optional[str] = Field(
...,
description="Timezone data will be converted to before computation. "
"Unlocalized data will be localized to this timezone. If timezone is "
"null, the timezone will be inferred from start/end.",
)
_time_range: List[dt.datetime] = PrivateAttr()
def __init__(self, **data):
super().__init__(**data)
tr = pd.date_range(start=self.start, end=self.end, freq=self.step)
if tr[-1] == self.end:
tr = tr[:-1]
if tr.tzinfo is None:
self._time_range = tr.tz_localize(
self.timezone, ambiguous=True, nonexistent="NaT"
)
self._time_range = self._time_range[
~(self._time_range.duplicated() | self._time_range.isna())
]
else:
if self.timezone is not None:
self._time_range = tr.tz_convert(self.timezone)
else:
self.timezone = str(tr.tzinfo)
self._time_range = tr
@root_validator(pre=True)
def restrict_timedelta_number(cls, values):
# restrict size of step if int/float and avoid overflowerror
step = values.get("step")
if isinstance(step, (int, float)):
if abs(step) > 1e8:
raise ValueError("Step much too large")
return values
@root_validator(skip_on_failure=True)
def check_start_end_tz(cls, values):
start = values.get("start")
end = values.get("end")
tz = values.get("timezone")
if start is not None and end is not None and start > end:
raise ValueError("'start' is after 'end'")
if start.tzinfo != end.tzinfo:
raise ValueError("'start' and 'end' must have the same timezone")
if tz is None and start.tzinfo is None:
raise ValueError("Could not infer timezone")
return values
@validator("step")
def check_step(cls, v):
secs = v.total_seconds()
if secs < 60:
raise ValueError("The minimum time step is 1 minute")
elif secs > 3600:
raise ValueError("The maximum time step is 60 minutes")
if secs % 60 != 0:
raise ValueError("The time step must be in whole minutes")
return v
@validator("timezone")
def check_tz(cls, v):
if v is not None and v not in TIMEZONES:
raise ValueError("Unrecognized timezone")
return v
class WeatherGranularityEnum(str, Enum):
"""Level of granularity of uploaded weather data"""
system = "system"
inverter = "inverter"
array = "array"
class PerformanceGranularityEnum(str, Enum):
"""Level of granularity of uploaded performance data"""
system = "system"
inverter = "inverter"
class IrradianceTypeEnum(str, Enum):
"""Type of irradiance included in weather files"""
standard = "standard"
poa = "poa"
effective = "effective"
class TemperatureTypeEnum(str, Enum):
"""Type of temperature included in weather files"""
air = "air"
module = "module"
cell = "cell"
class JobDataTypeEnum(str, Enum):
reference_weather = "reference weather data"
actual_weather = "actual weather data"
reference_performance = "reference performance data"
reference_performance_dc = "reference DC performance data"
modeled_performance = "modeled performance data"
actual_performance = "actual performance data"
monthly_actual_weather = "actual monthly weather data"
monthly_reference_weather = "reference monthly weather data"
monthly_actual_performance = "actual monthly performance data"
monthly_reference_performance = "reference monthly performance data"
class JobDataItem(SPIBase):
schema_path: str = Field(
..., description="Relative to PV system definition, i.e. /inverters/0/arrays/0"
)
type: JobDataTypeEnum
_data_cols: List[str] = PrivateAttr()
@classmethod
def from_types(
cls,
schema_path: str,
type_: JobDataTypeEnum,
irradiance_type: Optional[IrradianceTypeEnum] = None,
temperature_type: Optional[TemperatureTypeEnum] = None,
**kwargs,
):
"""Intialization that also sets _data_cols for ease of use later when adding
data_columns to StoredJobDataMetadata"""
cols = [
"time",
]
if type_ in (JobDataTypeEnum.reference_weather, JobDataTypeEnum.actual_weather):
if irradiance_type == IrradianceTypeEnum.effective:
cols += ["effective_irradiance"]
elif irradiance_type == IrradianceTypeEnum.poa:
cols += ["poa_global", "poa_direct", "poa_diffuse"]
else:
cols += ["ghi", "dni", "dhi"]
if temperature_type == TemperatureTypeEnum.cell:
cols += ["cell_temperature"]
elif temperature_type == TemperatureTypeEnum.module:
cols += ["module_temperature"]
else:
cols += ["temp_air", "wind_speed"]
elif type_ in (
JobDataTypeEnum.reference_performance,
JobDataTypeEnum.actual_performance,
JobDataTypeEnum.modeled_performance,
JobDataTypeEnum.reference_performance_dc,
):
cols += ["performance"]
elif type_ in (
JobDataTypeEnum.monthly_actual_weather,
JobDataTypeEnum.monthly_reference_weather,
):
cols = [
"month",
"total_poa_insolation",
"average_daytime_cell_temperature",
]
elif type_ in (
JobDataTypeEnum.monthly_actual_performance,
JobDataTypeEnum.monthly_reference_performance,
):
cols = ["month", "total_energy"]
out = cls(schema_path=schema_path, type=type_, **kwargs)
out._data_cols = cols
return out
class JobParametersBase(SPIBase):