enerdata 1.1.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1278 @@
1
+ # -*- coding: utf-8 -*-
2
+ import calendar
3
+ from datetime import datetime, timedelta
4
+ from .normalized_power import NormalizedPower
5
+ from ..datetime.station import get_station
6
+ from ..datetime.holidays import get_holidays
7
+ from ..datetime.timezone import TIMEZONE
8
+ from ..datetime.work_and_holidays import get_num_of_workdays_holidays
9
+ from .electrical_seasons import PERIODS_2x_BY_ELECTRIC_ZONE_CIR03_2020, \
10
+ PERIODS_3x_BY_ELECTRIC_ZONE_CIR03_2020, PERIODS_6x_BY_ELECTRIC_ZONE, DAYTYPE_BY_ELECTRIC_ZONE, \
11
+ DAYTYPE_BY_ELECTRIC_ZONE_CIR03_2020, TARIFFS_START_DATE_STR, PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020
12
+ from ..profiles import my_round
13
+
14
+
15
+ def check_range_hours(hours):
16
+ before = (0, 0)
17
+ for range_hours in sorted(hours):
18
+ start, end = range_hours
19
+ if start >= end:
20
+ return False
21
+ if start < 0 or start > 24:
22
+ return False
23
+ if end < 1 or end > 24:
24
+ return False
25
+ if start < before[1]:
26
+ return False
27
+ before = (start, end)
28
+ return True
29
+
30
+
31
+ def are_powers_ascending(powers):
32
+ power_ant = 0
33
+ for power_new in powers:
34
+ if power_new < power_ant:
35
+ return False
36
+ power_ant = power_new
37
+
38
+ return True
39
+
40
+
41
+ def set_day_type_electric_zone(current_date):
42
+ if current_date.strftime('%Y-%m-%d') >= TARIFFS_START_DATE_STR:
43
+ day_type_by_zone = DAYTYPE_BY_ELECTRIC_ZONE_CIR03_2020
44
+ else:
45
+ day_type_by_zone = DAYTYPE_BY_ELECTRIC_ZONE
46
+ return day_type_by_zone
47
+
48
+ def get_daytype_by_date_and_zone(date_time, zone='1', holidays=None):
49
+ """
50
+ Calcultes daytype from date and zone.
51
+ :param date_time in datetime format
52
+ :param zone in ['1', '2', '3' ,'4', '5']
53
+ :param holidays list of holidays
54
+ :returns char ('A', 'A1', 'B', 'B1', 'C', 'D')
55
+ """
56
+ is_weekend = (
57
+ calendar.weekday(
58
+ date_time.year,
59
+ date_time.month,
60
+ date_time.day
61
+ ) in (5, 6)
62
+ )
63
+ if is_weekend or date_time.date() in holidays:
64
+ return 'D'
65
+
66
+ day_type_by_zone = set_day_type_electric_zone(date_time)
67
+
68
+ monthday = date_time.strftime('%m/%d')
69
+ for daytype, periods in day_type_by_zone[zone].items():
70
+ for period in periods:
71
+ if period[0] <= monthday <= period[1]:
72
+ return daytype
73
+
74
+
75
+ class Tariff(object):
76
+ """Energy DSO Tariff.
77
+ """
78
+ def __init__(self, code=None, **kwargs):
79
+ self.code = code
80
+ self._periods = tuple()
81
+ self.cof = None
82
+ self.require_powers_above_min_power = False
83
+ self.require_summer_winter_hours = True
84
+ self.periods_validation = True
85
+
86
+ @property
87
+ def periods(self):
88
+ return self._periods
89
+
90
+ @periods.setter
91
+ def periods(self, value):
92
+ self._periods = value
93
+ validate = self.periods_validation
94
+ hours = {
95
+ 'holidays': [],
96
+ 'no_holidays': []
97
+ }
98
+ for period in self.energy_periods.values():
99
+ if period.holiday:
100
+ hours['holidays'].append(period)
101
+ else:
102
+ hours['no_holidays'].append(period)
103
+
104
+ for station in ('summer', 'winter'):
105
+ for holiday in (False, True):
106
+ total_hours = 0
107
+ range_hours = []
108
+ for period in self.energy_periods.values():
109
+ if period.holiday == holiday:
110
+ total_hours += getattr(period, 'total_%s_hours' % station)
111
+ range_hours += getattr(period, '%s_hours' % station)
112
+ range_hours = sorted(range_hours)
113
+ if total_hours != 24 and validate:
114
+ if (holiday and total_hours) or not holiday:
115
+ raise ValueError(
116
+ 'The sum of hours in %s%s must be 24h: %s'
117
+ % (station, holiday and ' (in holidays)' or '',
118
+ range_hours)
119
+ )
120
+ if not check_range_hours(range_hours) and validate:
121
+ raise ValueError(
122
+ 'Invalid range of hours in %s%s: %s'
123
+ % (station, holiday and ' (in holidays)' or '',
124
+ range_hours)
125
+ )
126
+
127
+ @property
128
+ def energy_periods(self):
129
+ return dict((p.code, p) for p in self.periods if p.type == 'te')
130
+
131
+ @property
132
+ def power_periods(self):
133
+ return dict((p.code, p) for p in self.periods if p.type == 'tp')
134
+
135
+ def get_number_of_periods(self):
136
+ return len([p for p in self.periods if p.type == 'te'])
137
+
138
+ def get_min_power(self):
139
+ return self.min_power
140
+
141
+ def get_max_power(self):
142
+ return self.max_power
143
+
144
+ def get_period_by_date(self, date_time, holidays=None, magn='te'):
145
+ station = get_station(date_time)
146
+ if not holidays:
147
+ holidays = get_holidays(date_time.year)
148
+ date = date_time.date()
149
+ if (calendar.weekday(date.year, date.month, date.day) in (5, 6)
150
+ or date in holidays):
151
+ holiday = True
152
+ else:
153
+ holiday = False
154
+ periods = self.energy_periods
155
+ if magn == 'tp':
156
+ periods = self.power_periods
157
+ for period in periods.values():
158
+ if period.holiday == holiday or not self.has_holidays_periods:
159
+ if period.daytype:
160
+ zone = period.geom_zone
161
+ daytype = get_daytype_by_date_and_zone(
162
+ date_time, zone, holidays
163
+ )
164
+ periods_ranges = period.periods_by_zone_and_day[zone][daytype]
165
+ range_list = periods_ranges[int(period.code[-1]) - 1]
166
+ else:
167
+ range_list = getattr(period, '%s_hours' % station)
168
+ for range_h in range_list:
169
+ if range_h[0] <= date_time.hour < range_h[1]:
170
+ return period
171
+ elif magn == 'tp':
172
+ if period.daytype:
173
+ zone = period.geom_zone
174
+ daytype = get_daytype_by_date_and_zone(
175
+ date_time, zone, holidays
176
+ )
177
+ periods_ranges = period.periods_by_zone_and_day[zone][daytype]
178
+ range_list = periods_ranges[int(period.code[-1]) - 1]
179
+ else:
180
+ if holiday and self.has_holidays_hours_in_periods:
181
+ if period.holiday_hours:
182
+ range_list = getattr(period, 'holiday_hours')
183
+ else:
184
+ continue
185
+ else:
186
+ range_list = getattr(period, '%s_hours' % station)
187
+ for range_h in range_list:
188
+ if range_h[0] <= date_time.hour < range_h[1]:
189
+ return period
190
+ return None
191
+
192
+ def get_hours_by_period(self, start_time, end_time, holidays=None,
193
+ zone='1'):
194
+ hours_by_period = {}
195
+ for period in self.energy_periods.values():
196
+ hours_by_period[period.code] = period.get_hours_between_dates(
197
+ start_time, end_time, holidays, zone
198
+ )
199
+ return hours_by_period
200
+
201
+ def get_period_by_timestamp(self, timestamp):
202
+ """
203
+ Gets the number of energy period
204
+ :param timestamp: datetime in format 'YYYY-MM-DD HH'
205
+ :return: period number
206
+ """
207
+ day, hours = timestamp.split(' ')
208
+ dt_tz = TIMEZONE.normalize(TIMEZONE.localize(datetime.strptime(day, '%Y-%m-%d')) + timedelta(hours=int(hours)))
209
+ # "get_period_by_date" expects a local timestamp without timezone
210
+ # decreases 1 minute because is final datetime open interval (not included)
211
+ dt = dt_tz.replace(tzinfo=None) - timedelta(minutes=1)
212
+ return self.get_period_by_date(dt).code
213
+
214
+ @property
215
+ def has_holidays_periods(self):
216
+ return any(p.holiday for p in self.energy_periods.values())
217
+
218
+ @property
219
+ def has_holidays_hours_in_periods(self):
220
+ return any(p.holiday_hours for p in self.periods)
221
+
222
+ @property
223
+ def has_holidays_periods(self):
224
+ return any(p.holiday for p in self.energy_periods.values())
225
+
226
+ def is_maximum_power_correct(self, max_pow):
227
+ return self.min_power < max_pow <= self.max_power
228
+
229
+ def is_minimum_powers_correct(self, min_pow):
230
+ if self.require_powers_above_min_power:
231
+ return self.min_power < min_pow <= self.max_power
232
+ else:
233
+ return True
234
+
235
+ @staticmethod
236
+ def are_powers_normalized(powers, allow_zero_power=False):
237
+ np = NormalizedPower()
238
+ for power in powers:
239
+ if allow_zero_power and power == 0:
240
+ continue
241
+ if not np.is_normalized(int(power * 1000)):
242
+ return False
243
+
244
+ return True
245
+
246
+ def evaluate_powers_all_checks(self, powers):
247
+ """
248
+
249
+ :param powers: [pow1, pow2,...]
250
+ :return: [Error1, Error2] if errors else []
251
+ """
252
+ errors = []
253
+ if min(powers) <= 0:
254
+ errors.append(NotPositivePower())
255
+ if not len(self.power_periods) == len(powers):
256
+ errors.append(IncorrectPowerNumber(len(powers), len(self.power_periods)))
257
+ if not self.is_maximum_power_correct(max(powers)):
258
+ errors.append(IncorrectMaxPower(max(powers), self.min_power, self.max_power))
259
+ if not self.is_minimum_powers_correct(min(powers)):
260
+ errors.append(IncorrectMinPower(min(powers), self.min_power, self.max_power))
261
+ if not self.are_powers_normalized(powers):
262
+ errors.append(NotNormalizedPower())
263
+
264
+ return errors
265
+
266
+ def evaluate_powers(self, powers, allow_zero_power=False):
267
+ if not allow_zero_power and min(powers) <= 0:
268
+ raise NotPositivePower()
269
+ if allow_zero_power and min(powers) < 0:
270
+ raise NotPositivePower()
271
+ if not len(self.power_periods) == len(powers):
272
+ raise IncorrectPowerNumber(len(powers), len(self.power_periods))
273
+ if not self.is_maximum_power_correct(max(powers)):
274
+ raise IncorrectMaxPower(max(powers), self.min_power, self.max_power)
275
+ if not self.is_minimum_powers_correct(min(powers)):
276
+ raise IncorrectMinPower(min(powers), self.min_power, self.max_power)
277
+ if not self.are_powers_normalized(powers, allow_zero_power=allow_zero_power):
278
+ raise NotNormalizedPower()
279
+
280
+ return True
281
+
282
+ def correct_powers(self, powers):
283
+ raise NotImplementedError
284
+
285
+
286
+ class TariffPreTD(Tariff):
287
+ """Energy DSO Tariff.
288
+ """
289
+ def __init__(self, code=None, **kwargs):
290
+ self.code = code
291
+ self._periods = tuple()
292
+ self.cof = None
293
+ self.require_powers_above_min_power = False
294
+ self.require_summer_winter_hours = True
295
+
296
+ @property
297
+ def periods(self):
298
+ return self._periods
299
+
300
+ @periods.setter
301
+ def periods(self, value):
302
+ self._periods = value
303
+ if self.require_summer_winter_hours:
304
+ hours = {
305
+ 'holidays': [],
306
+ 'no_holidays': []
307
+ }
308
+ for period in self.energy_periods.values():
309
+ if period.holiday:
310
+ hours['holidays'].append(period)
311
+ else:
312
+ hours['no_holidays'].append(period)
313
+
314
+ for station in ('summer', 'winter'):
315
+ for holiday in (False, True):
316
+ total_hours = 0
317
+ range_hours = []
318
+ for period in self.energy_periods.values():
319
+ if period.holiday == holiday:
320
+ total_hours += getattr(period, 'total_%s_hours' % station)
321
+ range_hours += getattr(period, '%s_hours' % station)
322
+ range_hours = sorted(range_hours)
323
+ if total_hours != 24:
324
+ if (holiday and total_hours) or not holiday:
325
+ raise ValueError(
326
+ 'The sum of hours in %s%s must be 24h: %s'
327
+ % (station, holiday and ' (in holidays)' or '',
328
+ range_hours)
329
+ )
330
+ if not check_range_hours(range_hours):
331
+ raise ValueError(
332
+ 'Invalid range of hours in %s%s: %s'
333
+ % (station, holiday and ' (in holidays)' or '',
334
+ range_hours)
335
+ )
336
+
337
+ @property
338
+ def energy_periods(self):
339
+ return dict((p.code, p) for p in self.periods if p.type == 'te')
340
+
341
+ @property
342
+ def power_periods(self):
343
+ return dict((p.code, p) for p in self.periods if p.type == 'tp')
344
+
345
+ def get_number_of_periods(self):
346
+ return len([p for p in self.periods if p.type == 'te'])
347
+
348
+ def get_min_power(self):
349
+ return self.min_power
350
+
351
+ def get_max_power(self):
352
+ return self.max_power
353
+
354
+ def get_period_by_date(self, date_time):
355
+ datetime_previous_hour = date_time - timedelta(hours=1)
356
+ station = get_station(datetime_previous_hour)
357
+ date = datetime_previous_hour.date()
358
+ holidays = get_holidays(date.year)
359
+ if (calendar.weekday(date.year, date.month, date.day) in (5, 6) or
360
+ date in holidays):
361
+ holiday = True
362
+ else:
363
+ holiday = False
364
+
365
+ # Map hour 0 to 24
366
+ hour = date_time.hour or 24
367
+ for period in self.periods:
368
+ if period.holiday == holiday or not self.has_holidays_periods:
369
+ for range_h in getattr(period, '%s_hours' % station):
370
+ if range_h[0] < hour <= range_h[1]:
371
+ return period
372
+ return None
373
+
374
+
375
+ @property
376
+ def has_holidays_periods(self):
377
+ return any(p.holiday for p in self.energy_periods.values())
378
+
379
+ def is_maximum_power_correct(self, max_pow):
380
+ return self.min_power < max_pow <= self.max_power
381
+
382
+ def is_minimum_powers_correct(self, min_pow):
383
+ if self.require_powers_above_min_power:
384
+ return self.min_power < min_pow <= self.max_power
385
+ else:
386
+ return True
387
+
388
+ @staticmethod
389
+ def are_powers_normalized(powers):
390
+ np = NormalizedPower()
391
+ for power in powers:
392
+ if not np.is_normalized(int(power * 1000)):
393
+ return False
394
+
395
+ return True
396
+
397
+ def evaluate_powers_all_checks(self, powers):
398
+ """
399
+
400
+ :param powers: [pow1, pow2,...]
401
+ :return: [Error1, Error2] if errors else []
402
+ """
403
+ errors = []
404
+ if min(powers) <= 0:
405
+ errors.append(NotPositivePower())
406
+ if not len(self.power_periods) == len(powers):
407
+ errors.append(IncorrectPowerNumber(len(powers), len(self.power_periods)))
408
+ if not self.is_maximum_power_correct(max(powers)):
409
+ errors.append(IncorrectMaxPower(max(powers), self.min_power, self.max_power))
410
+ if not self.is_minimum_powers_correct(min(powers)):
411
+ errors.append(IncorrectMinPower(min(powers), self.min_power, self.max_power))
412
+ if not self.are_powers_normalized(powers):
413
+ errors.append(NotNormalizedPower())
414
+
415
+ return errors
416
+
417
+ def evaluate_powers(self, powers, allow_zero_power=False):
418
+ if min(powers) <= 0:
419
+ raise NotPositivePower()
420
+ if not len(self.power_periods) == len(powers):
421
+ raise IncorrectPowerNumber(len(powers), len(self.power_periods))
422
+ if not self.is_maximum_power_correct(max(powers)):
423
+ raise IncorrectMaxPower(max(powers), self.min_power, self.max_power)
424
+ if not self.is_minimum_powers_correct(min(powers)):
425
+ raise IncorrectMinPower(min(powers), self.min_power, self.max_power)
426
+ if not self.are_powers_normalized(powers):
427
+ raise NotNormalizedPower()
428
+
429
+ return True
430
+
431
+ def correct_powers(self, powers):
432
+ raise NotImplementedError
433
+
434
+
435
+ class TariffPeriod(object):
436
+ """Tariff period.
437
+ """
438
+ def __init__(self, code, ptype, **kwargs):
439
+ assert ptype in ('te', 'tp')
440
+ self.code = code
441
+ self.type = ptype
442
+ winter_hours = kwargs.pop('winter_hours', [(0, 24)])
443
+ if not check_range_hours(winter_hours):
444
+ raise ValueError('Invalid winter hours')
445
+ self.winter_hours = winter_hours
446
+ summer_hours = kwargs.pop('summer_hours', [(0, 24)])
447
+ if not check_range_hours(summer_hours):
448
+ raise ValueError('Invalid summer hours')
449
+ self.summer_hours = summer_hours
450
+ holiday_hours = kwargs.pop('holiday_hours', [])
451
+ if holiday_hours:
452
+ if not check_range_hours(holiday_hours):
453
+ raise ValueError('Invalid holiday hours')
454
+ self.holiday = kwargs.pop('holiday', False)
455
+ self.tariff_has_holiday_periods = kwargs.pop(
456
+ 'tariff_has_holiday_periods', self.holiday
457
+ )
458
+ # daytype tariffs (6.x)
459
+ self.periods_by_zone_and_day = kwargs.pop('periods_by_zone_and_day', PERIODS_6x_BY_ELECTRIC_ZONE)
460
+ self.daytype = kwargs.pop('daytype', False)
461
+ if self.daytype:
462
+ self.geom_zone = kwargs.pop('geom_zone', '1')
463
+ periods_dict = self.periods_by_zone_and_day[self.geom_zone]
464
+ for daytype in periods_dict.keys():
465
+ hours = [p for lp in periods_dict[daytype] if lp for p in lp]
466
+ if not check_range_hours(hours):
467
+ raise ValueError(
468
+ 'Invalid {0} hours for {1} '
469
+ 'geographic zone '.format(daytype, self.geom_zone)
470
+ )
471
+
472
+ @property
473
+ def total_summer_hours(self):
474
+ hours = 0
475
+ for range_h in self.summer_hours:
476
+ hours += (range_h[1] - range_h[0])
477
+ return hours
478
+
479
+ @property
480
+ def total_winter_hours(self):
481
+ hours = 0
482
+ for range_h in self.winter_hours:
483
+ hours += (range_h[1] - range_h[0])
484
+ return hours
485
+
486
+
487
+ class T20A(TariffPreTD):
488
+ def __init__(self, **kwargs):
489
+ super(T20A, self).__init__(**kwargs)
490
+ self.code = '2.0A'
491
+ self.cof = 'A'
492
+ self.periods = (
493
+ TariffPeriod('P1', 'te'),
494
+ TariffPeriod('P1', 'tp')
495
+ )
496
+ self.min_power = 0
497
+ self.max_power = 10
498
+ self.type = 'BT'
499
+
500
+ # set subsystem and periods by zone
501
+ self.geom_zone = kwargs.pop('geom_zone', '1')
502
+
503
+ def correct_powers(self, powers):
504
+ try:
505
+ if self.evaluate_powers(powers):
506
+ return powers
507
+ except:
508
+ pass
509
+
510
+ norm_power = next(NormalizedPower().get_norm_powers(
511
+ int(self.min_power * 1000), int(self.max_power * 1000)
512
+ ))
513
+
514
+ return [norm_power / 1000.0] * len(self.power_periods)
515
+
516
+
517
+ class T20DHA(T20A):
518
+ def __init__(self, **kwargs):
519
+ super(T20DHA, self).__init__(**kwargs)
520
+ self.code = '2.0DHA'
521
+ self.cof = 'B'
522
+ self.periods = (
523
+ TariffPeriod(
524
+ 'P1', 'te',
525
+ winter_hours=[(12, 22)],
526
+ summer_hours=[(13, 23)]
527
+ ),
528
+ TariffPeriod(
529
+ 'P2', 'te',
530
+ winter_hours=[(0, 12), (22, 24)],
531
+ summer_hours=[(0, 13), (23, 24)]
532
+ ),
533
+ TariffPeriod(
534
+ 'P1', 'tp'
535
+ )
536
+ )
537
+
538
+
539
+ class T20DHS(T20DHA):
540
+ def __init__(self, **kwargs):
541
+ super(T20DHS, self).__init__(**kwargs)
542
+ self.code = '2.0DHS'
543
+ self.cof = 'D'
544
+ self.periods = (
545
+ TariffPeriod(
546
+ 'P1', 'te',
547
+ winter_hours=[(13, 23)],
548
+ summer_hours=[(13, 23)]
549
+ ),
550
+ TariffPeriod(
551
+ 'P2', 'te',
552
+ winter_hours=[(0, 1), (7, 13), (23, 24)],
553
+ summer_hours=[(0, 1), (7, 13), (23, 24)]
554
+ ),
555
+ TariffPeriod(
556
+ 'P3', 'te',
557
+ winter_hours=[(1, 7)],
558
+ summer_hours=[(1, 7)]
559
+ ),
560
+ TariffPeriod(
561
+ 'P1', 'tp'
562
+ )
563
+ )
564
+
565
+
566
+ class T21A(T20A):
567
+ def __init__(self, **kwargs):
568
+ super(T21A, self).__init__(**kwargs)
569
+ self.code = '2.1A'
570
+ self.cof = 'A'
571
+ self.min_power = 10
572
+ self.max_power = 15
573
+
574
+
575
+ class T21DHA(T20DHA):
576
+ def __init__(self, **kwargs):
577
+ super(T21DHA, self).__init__(**kwargs)
578
+ self.code = '2.1DHA'
579
+ self.cof = 'B'
580
+ self.min_power = 10
581
+ self.max_power = 15
582
+
583
+
584
+ class T21DHS(T20DHS):
585
+ def __init__(self, **kwargs):
586
+ super(T21DHS, self).__init__(**kwargs)
587
+ self.code = '2.1DHS'
588
+ self.cof = 'D'
589
+ self.min_power = 10
590
+ self.max_power = 15
591
+
592
+
593
+ class T30A(TariffPreTD):
594
+ def __init__(self, **kwargs):
595
+ super(T30A, self).__init__(**kwargs)
596
+ self.code = '3.0A'
597
+ self.cof = 'C'
598
+ self.min_power = 15
599
+ self.max_power = 1000000
600
+ self.require_powers_above_min_power = True
601
+ self.type = 'BT'
602
+ self.periods = (
603
+ TariffPeriod(
604
+ 'P1', 'te',
605
+ winter_hours=[(18, 22)],
606
+ summer_hours=[(11, 15)]
607
+ ),
608
+ TariffPeriod(
609
+ 'P2', 'te',
610
+ winter_hours=[(8, 18), (22, 24)],
611
+ summer_hours=[(8, 11), (15, 24)]
612
+ ),
613
+ TariffPeriod(
614
+ 'P3', 'te',
615
+ winter_hours=[(0, 8)],
616
+ summer_hours=[(0, 8)]
617
+ ),
618
+ TariffPeriod(
619
+ 'P4', 'te',
620
+ holiday=True,
621
+ winter_hours=[(18, 22)],
622
+ summer_hours=[(11, 15)]
623
+ ),
624
+ TariffPeriod(
625
+ 'P5', 'te',
626
+ holiday=True,
627
+ winter_hours=[(8, 18), (22, 24)],
628
+ summer_hours=[(8, 11), (15, 24)]
629
+ ),
630
+ TariffPeriod(
631
+ 'P6', 'te',
632
+ holiday=True,
633
+ winter_hours=[(0, 8)],
634
+ summer_hours=[(0, 8)]
635
+ ),
636
+ TariffPeriod(
637
+ 'P1', 'tp'
638
+ ),
639
+ TariffPeriod(
640
+ 'P2', 'tp'
641
+ ),
642
+ TariffPeriod(
643
+ 'P3', 'tp'
644
+ )
645
+ )
646
+
647
+ # set subsystem and periods by zone
648
+ self.geom_zone = kwargs.pop('geom_zone', '1')
649
+
650
+
651
+ class T30ANoFestivos(T30A):
652
+ def __init__(self, **kwargs):
653
+ super(T30ANoFestivos, self).__init__(**kwargs)
654
+ self.periods = (
655
+ TariffPeriod(
656
+ 'P1', 'te',
657
+ winter_hours=[(18, 22)],
658
+ summer_hours=[(11, 15)]
659
+ ),
660
+ TariffPeriod(
661
+ 'P2', 'te',
662
+ winter_hours=[(8, 18), (22, 24)],
663
+ summer_hours=[(8, 11), (15, 24)]
664
+ ),
665
+ TariffPeriod(
666
+ 'P3', 'te',
667
+ winter_hours=[(0, 8)],
668
+ summer_hours=[(0, 8)]
669
+ ),
670
+ TariffPeriod(
671
+ 'P1', 'tp'
672
+ ),
673
+ TariffPeriod(
674
+ 'P2', 'tp'
675
+ ),
676
+ TariffPeriod(
677
+ 'P3', 'tp'
678
+ )
679
+ )
680
+
681
+ class T30A_one_period(T30A):
682
+ """
683
+ A 3.0A with one unique period
684
+ """
685
+ def __init__(self, **kwargs):
686
+ super(T30A_one_period, self).__init__(**kwargs)
687
+ self.periods = (
688
+ TariffPeriod('P1', 'te'),
689
+ TariffPeriod('P1', 'tp')
690
+ )
691
+
692
+
693
+ class T31A(T30A):
694
+ """
695
+ 3.1A Tariff patched with 3.1ALB
696
+ """
697
+ def __init__(self, kva=None, **kwargs):
698
+ super(T31A, self).__init__(**kwargs)
699
+ self.code = '3.1A'
700
+ self.cof = 'C'
701
+ self.min_power = 1
702
+ self.max_power = 450
703
+ self.losses = 0.04
704
+ self.type = 'AT'
705
+ self.require_powers_above_min_power = False
706
+ if kva:
707
+ if not isinstance(kva, (int, float)):
708
+ raise ValueError('kva must be an enter value')
709
+ self.low_voltage_measure = True
710
+ self.kva = kva
711
+ else:
712
+ self.low_voltage_measure = False
713
+ self.hours_by_period = {
714
+ 'P1': 6,
715
+ 'P2': 10,
716
+ 'P3': 8,
717
+ 'P4': 0,
718
+ 'P5': 6,
719
+ 'P6': 18
720
+ }
721
+ self.periods = (
722
+ TariffPeriod(
723
+ 'P1', 'te',
724
+ winter_hours=[(17, 23)],
725
+ summer_hours=[(10, 16)]
726
+ ),
727
+ TariffPeriod(
728
+ 'P2', 'te',
729
+ winter_hours=[(8, 17), (23, 24)],
730
+ summer_hours=[(8, 10), (16, 24)]
731
+ ),
732
+ TariffPeriod(
733
+ 'P3', 'te',
734
+ winter_hours=[(0, 8)],
735
+ summer_hours=[(0, 8)]
736
+ ),
737
+ TariffPeriod(
738
+ 'P5', 'te',
739
+ holiday=True,
740
+ winter_hours=[(18, 24)],
741
+ summer_hours=[(18, 24)]
742
+ ),
743
+ TariffPeriod(
744
+ 'P6', 'te',
745
+ holiday=True,
746
+ winter_hours=[(0, 18)],
747
+ summer_hours=[(0, 18)]
748
+ ),
749
+ TariffPeriod(
750
+ 'P1', 'tp'
751
+ ),
752
+ TariffPeriod(
753
+ 'P2', 'tp'
754
+ ),
755
+ TariffPeriod(
756
+ 'P3', 'tp'
757
+ )
758
+ )
759
+
760
+ @staticmethod
761
+ def are_powers_normalized(powers):
762
+ # 3.1A doesn't need to have normalized powers
763
+ return True
764
+
765
+ def apply_31A_LB_cof(self, balance, start_date, end_date):
766
+ consumptions = balance.copy()
767
+ period_hours = self.hours_by_period
768
+ holidays_list = get_holidays(start_date.year)
769
+ (workdays, holidays) = get_num_of_workdays_holidays(
770
+ start_date, end_date, holidays_list
771
+ )
772
+
773
+ cofs = {}
774
+ for period in period_hours:
775
+ if period > 'P3':
776
+ cofs[period] = period_hours.get(period, 0) * holidays
777
+ else:
778
+ cofs[period] = period_hours.get(period, 0) * workdays
779
+ for period, consumption in balance.items():
780
+ consumptions[period] = my_round(
781
+ consumption * (1 + self.losses), 2
782
+ ) + my_round(0.01 * cofs[period] * self.kva, 2)
783
+
784
+ return consumptions
785
+
786
+ def apply_curve_losses(self, measures):
787
+ for idx, measure in enumerate(measures):
788
+ values = measure._asdict()
789
+ consumption = my_round(measure.measure * (1 + self.losses), 2) + my_round(0.01 * self.kva, 2)
790
+ values['measure'] = consumption
791
+ measures[idx] = measure._replace(**values)
792
+ return measures
793
+
794
+ def evaluate_powers(self, powers, allow_zero_power=False):
795
+ super(T31A, self).evaluate_powers(powers, allow_zero_power=allow_zero_power)
796
+
797
+ if not are_powers_ascending(powers):
798
+ raise NotAscendingPowers()
799
+
800
+ return True
801
+
802
+ def evaluate_powers_all_checks(self, powers):
803
+ errors = super(T31A, self).evaluate_powers_all_checks(powers)
804
+ if not are_powers_ascending(powers):
805
+ errors.append(NotAscendingPowers())
806
+
807
+ return errors
808
+
809
+
810
+ class T31A_one_period(T31A):
811
+ """
812
+ A 3.1A with one unique period
813
+ """
814
+ def __init__(self, **kwargs):
815
+ super(T31A_one_period, self).__init__(**kwargs)
816
+ self.periods = (
817
+ TariffPeriod('P1', 'te'),
818
+ TariffPeriod('P1', 'tp')
819
+ )
820
+
821
+
822
+ class T31ANoFestivos(T31A):
823
+ def __init__(self, kva=None, **kwargs):
824
+ super(T31ANoFestivos, self).__init__(kva=kva, **kwargs)
825
+ self.hours_by_period = {
826
+ 'P1': 6,
827
+ 'P2': 10,
828
+ 'P3': 8,
829
+ }
830
+ self.periods = (
831
+ TariffPeriod(
832
+ 'P1', 'te',
833
+ winter_hours=[(17, 23)],
834
+ summer_hours=[(10, 16)]
835
+ ),
836
+ TariffPeriod(
837
+ 'P2', 'te',
838
+ winter_hours=[(8, 17), (23, 24)],
839
+ summer_hours=[(8, 10), (16, 24)]
840
+ ),
841
+ TariffPeriod(
842
+ 'P3', 'te',
843
+ winter_hours=[(0, 8)],
844
+ summer_hours=[(0, 8)]
845
+ ),
846
+ TariffPeriod(
847
+ 'P1', 'tp'
848
+ ),
849
+ TariffPeriod(
850
+ 'P2', 'tp'
851
+ ),
852
+ TariffPeriod(
853
+ 'P3', 'tp'
854
+ )
855
+ )
856
+
857
+
858
+ class T61A(TariffPreTD):
859
+ """
860
+ 6.1A Tariff
861
+ """
862
+ def __init__(self, **kwargs):
863
+ super(T61A, self).__init__(**kwargs)
864
+ self.code = '6.1A'
865
+ self.cof = 'C'
866
+ self.min_power = 450
867
+ self.max_power = 1000000
868
+ self.type = 'AT'
869
+ self.periods = (
870
+ #
871
+ # TODO: Implement correct energy periods
872
+ #
873
+ TariffPeriod('P1', 'te'),
874
+ TariffPeriod(
875
+ 'P1', 'tp'
876
+ ),
877
+ TariffPeriod(
878
+ 'P2', 'tp'
879
+ ),
880
+ TariffPeriod(
881
+ 'P3', 'tp'
882
+ ),
883
+ TariffPeriod(
884
+ 'P4', 'tp'
885
+ ),
886
+ TariffPeriod(
887
+ 'P5', 'tp'
888
+ ),
889
+ TariffPeriod(
890
+ 'P6', 'tp'
891
+ ),
892
+ )
893
+
894
+ # set subsystem and periods by zone
895
+ self.geom_zone = kwargs.pop('geom_zone', '1')
896
+
897
+ @staticmethod
898
+ def are_powers_normalized(powers):
899
+ # 6.1A doesn't need to have normalized powers
900
+ return True
901
+
902
+ def evaluate_powers(self, powers, allow_zero_power=False):
903
+ super(T61A, self).evaluate_powers(powers, allow_zero_power=allow_zero_power)
904
+
905
+ if not are_powers_ascending(powers):
906
+ raise NotAscendingPowers()
907
+
908
+ return True
909
+
910
+ def evaluate_powers_all_checks(self, powers):
911
+ errors = super(T61A, self).evaluate_powers_all_checks(powers)
912
+ if not are_powers_ascending(powers):
913
+ errors.append(NotAscendingPowers())
914
+
915
+ return errors
916
+
917
+
918
+ class T61B(T61A):
919
+ """
920
+ 6.1B Tariff
921
+ """
922
+ def __init__(self, **kwargs):
923
+ super(T61B, self).__init__(**kwargs)
924
+ self.code = '6.1B'
925
+
926
+
927
+ class T62(T61A):
928
+ """
929
+ 6.2 Tariff
930
+ """
931
+ def __init__(self, **kwargs):
932
+ super(T62, self).__init__(**kwargs)
933
+ self.code = '6.2'
934
+
935
+
936
+ class T63(T61A):
937
+ """
938
+ 6.3 Tariff
939
+ """
940
+ def __init__(self, **kwargs):
941
+ super(T63, self).__init__(**kwargs)
942
+ self.code = '6.3'
943
+
944
+
945
+ class T64(T61A):
946
+ """
947
+ 6.4 Tariff
948
+ """
949
+ def __init__(self, **kwargs):
950
+ super(T64, self).__init__(**kwargs)
951
+ self.code = '6.4'
952
+
953
+
954
+ class TRE(TariffPreTD):
955
+ def __init__(self, **kwargs):
956
+ super(TRE, self).__init__(**kwargs)
957
+ self.code = 'RE'
958
+ self.cof = 'A'
959
+
960
+ self.periods = (
961
+ TariffPeriod('P0', 'te'),
962
+ TariffPeriod('P0', 'tp')
963
+ )
964
+
965
+
966
+ # Tariffs from BOE-A-2020-1066 (https://www.boe.es/eli/es/cir/2020/01/15/3)
967
+ class T20TD(Tariff):
968
+ """Classe que implementa la Tarifa 2.0TD."""
969
+ def __init__(self, **kwargs):
970
+ super(T20TD, self).__init__(**kwargs)
971
+ self.code = '2.0TD'
972
+ self.cof = '2.0TD'
973
+ self.min_power = 0
974
+ self.max_power = 15
975
+ self.require_summer_winter_hours = False
976
+
977
+ self.type = 'BT'
978
+
979
+ # set subsystem and periods by zone
980
+ self.geom_zone = kwargs.pop('geom_zone', '1')
981
+ self.periods_by_zone_and_day = PERIODS_3x_BY_ELECTRIC_ZONE_CIR03_2020
982
+
983
+ self.periods_validation = False
984
+
985
+ self.periods = (
986
+ TariffPeriod('P1', 'te',
987
+ tariff_has_holiday_periods=True,
988
+ periods_by_zone_and_day=PERIODS_3x_BY_ELECTRIC_ZONE_CIR03_2020,
989
+ daytype=True,
990
+ geom_zone=self.geom_zone
991
+ ),
992
+ TariffPeriod('P2', 'te',
993
+ tariff_has_holiday_periods=True,
994
+ periods_by_zone_and_day=PERIODS_3x_BY_ELECTRIC_ZONE_CIR03_2020,
995
+ daytype=True,
996
+ geom_zone=self.geom_zone
997
+ ),
998
+ TariffPeriod('P3', 'te',
999
+ tariff_has_holiday_periods=True,
1000
+ periods_by_zone_and_day=PERIODS_3x_BY_ELECTRIC_ZONE_CIR03_2020,
1001
+ daytype=True,
1002
+ geom_zone=self.geom_zone
1003
+ ),
1004
+ TariffPeriod('P1', 'tp',
1005
+ tariff_has_holiday_periods=True,
1006
+ periods_by_zone_and_day=PERIODS_2x_BY_ELECTRIC_ZONE_CIR03_2020,
1007
+ daytype=True,
1008
+ geom_zone=self.geom_zone
1009
+ ),
1010
+ TariffPeriod('P2', 'tp',
1011
+ tariff_has_holiday_periods=True,
1012
+ periods_by_zone_and_day=PERIODS_2x_BY_ELECTRIC_ZONE_CIR03_2020,
1013
+ daytype=True,
1014
+ geom_zone=self.geom_zone
1015
+ )
1016
+ )
1017
+
1018
+
1019
+ class T30TD(Tariff):
1020
+ """Classe que implementa la Tarifa 3.0TD."""
1021
+ def __init__(self, **kwargs):
1022
+ super(T30TD, self).__init__(**kwargs)
1023
+ self.code = '3.0TD'
1024
+ self.cof = '3.0TD'
1025
+ self.min_power = 15
1026
+ self.max_power = 100000
1027
+ self.require_summer_winter_hours = False
1028
+
1029
+ self.type = 'BT'
1030
+ self.geom_zone = kwargs.pop('geom_zone', '1')
1031
+
1032
+ self.periods_validation = False
1033
+ self.periods = (
1034
+ TariffPeriod('P1', 'te',
1035
+ tariff_has_holiday_periods=True,
1036
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1037
+ daytype=True,
1038
+ geom_zone=self.geom_zone),
1039
+ TariffPeriod('P2', 'te',
1040
+ tariff_has_holiday_periods=True,
1041
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1042
+ daytype=True,
1043
+ geom_zone=self.geom_zone),
1044
+ TariffPeriod('P3', 'te',
1045
+ tariff_has_holiday_periods=True,
1046
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1047
+ daytype=True,
1048
+ geom_zone=self.geom_zone),
1049
+ TariffPeriod('P4', 'te',
1050
+ tariff_has_holiday_periods=True,
1051
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1052
+ daytype=True,
1053
+ geom_zone=self.geom_zone),
1054
+ TariffPeriod('P5', 'te',
1055
+ tariff_has_holiday_periods=True,
1056
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1057
+ daytype=True,
1058
+ geom_zone=self.geom_zone),
1059
+ TariffPeriod('P6', 'te',
1060
+ tariff_has_holiday_periods=True,
1061
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1062
+ daytype=True,
1063
+ geom_zone=self.geom_zone),
1064
+ TariffPeriod('P1', 'tp',
1065
+ tariff_has_holiday_periods=True,
1066
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1067
+ daytype=True,
1068
+ geom_zone=self.geom_zone),
1069
+ TariffPeriod('P2', 'tp',
1070
+ tariff_has_holiday_periods=True,
1071
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1072
+ daytype=True,
1073
+ geom_zone=self.geom_zone),
1074
+ TariffPeriod('P3', 'tp',
1075
+ tariff_has_holiday_periods=True,
1076
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1077
+ daytype=True,
1078
+ geom_zone=self.geom_zone),
1079
+ TariffPeriod('P4', 'tp',
1080
+ tariff_has_holiday_periods=True,
1081
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1082
+ daytype=True,
1083
+ geom_zone=self.geom_zone),
1084
+ TariffPeriod('P5', 'tp',
1085
+ tariff_has_holiday_periods=True,
1086
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1087
+ daytype=True,
1088
+ geom_zone=self.geom_zone),
1089
+ TariffPeriod('P6', 'tp',
1090
+ tariff_has_holiday_periods=True,
1091
+ periods_by_zone_and_day=PERIODS_6x_BY_ELECTRIC_ZONE_CIR03_2020,
1092
+ daytype=True,
1093
+ geom_zone=self.geom_zone)
1094
+ )
1095
+
1096
+
1097
+ class T61TD(T30TD):
1098
+ """Classe que implementa la Tarifa 6.1TD."""
1099
+ def __init__(self, **kwargs):
1100
+ super(T61TD, self).__init__(**kwargs)
1101
+ self.code = '6.1TD'
1102
+ self.cof = '3.0TD'
1103
+ self.min_power = 0
1104
+ self.max_power = 100000
1105
+ self.require_summer_winter_hours = False
1106
+ self.type = 'AT'
1107
+ self.losses = 0.04
1108
+ kva = kwargs.pop('kva', False)
1109
+ if kva:
1110
+ if not isinstance(kva, (int, float)):
1111
+ raise ValueError('kva must be an enter value')
1112
+ self.low_voltage_measure = True
1113
+ self.kva = kva
1114
+ else:
1115
+ self.low_voltage_measure = False
1116
+
1117
+ def apply_curve_losses(self, measures):
1118
+ for idx, measure in enumerate(measures):
1119
+ values = measure._asdict()
1120
+ consumption = my_round(measure.measure * (1 + self.losses), 2) + my_round(0.01 * self.kva, 2)
1121
+ values['measure'] = consumption
1122
+ measures[idx] = measure._replace(**values)
1123
+ return measures
1124
+
1125
+
1126
+ class T62TD(T61TD):
1127
+ """Classe que implementa la Tarifa 6.2TD."""
1128
+ def __init__(self, **kwargs):
1129
+ super(T62TD, self).__init__(**kwargs)
1130
+ self.code = '6.2TD'
1131
+ self.cof = None
1132
+
1133
+
1134
+ class T63TD(T61TD):
1135
+ """Classe que implementa la Tarifa 6.3TD."""
1136
+ def __init__(self, **kwargs):
1137
+ super(T63TD, self).__init__(**kwargs)
1138
+ self.code = '6.3TD'
1139
+ self.cof = None
1140
+
1141
+
1142
+ class T64TD(T61TD):
1143
+ """Classe que implementa la Tarifa 6.4TD."""
1144
+ def __init__(self, **kwargs):
1145
+ super(T64TD, self).__init__(**kwargs)
1146
+ self.code = '6.4TD'
1147
+ self.cof = None
1148
+
1149
+
1150
+ # Vehículo Eléctrico
1151
+ class T30TDVE(T30TD):
1152
+ """Classe que implementa la Tarifa 3.0TDVE."""
1153
+ def __init__(self, **kwargs):
1154
+ super(T30TDVE, self).__init__(**kwargs)
1155
+ self.code = '3.0TDVE'
1156
+ self.cof = '3.0TDVE'
1157
+
1158
+
1159
+ class T61TDVE(T61TD):
1160
+ """Classe que implementa la Tarifa 6.1TDVE."""
1161
+ def __init__(self, **kwargs):
1162
+ super(T61TDVE, self).__init__(**kwargs)
1163
+ self.code = '6.1TDVE'
1164
+ self.cof = '3.0TDVE'
1165
+
1166
+
1167
+ class T62TDVE(T62TD):
1168
+ """Classe que implementa la Tarifa 6.2TDVE."""
1169
+ def __init__(self, **kwargs):
1170
+ super(T62TDVE, self).__init__(**kwargs)
1171
+ self.code = '6.2TDVE'
1172
+ self.cof = None
1173
+
1174
+
1175
+ class T1P(Tariff):
1176
+ def __init__(self):
1177
+ super(T1P, self).__init__()
1178
+ self.code = '1P'
1179
+ self.cof = '2.0TD'
1180
+ self.periods = (
1181
+ TariffPeriod('P1', 'te'),
1182
+ TariffPeriod('P1', 'tp')
1183
+ )
1184
+
1185
+
1186
+ class NotPositivePower(Exception):
1187
+ def __init__(self):
1188
+ super(NotPositivePower, self).__init__(
1189
+ 'Power should allways be higher than 0'
1190
+ )
1191
+
1192
+
1193
+ class NotNormalizedPower(Exception):
1194
+ def __init__(self):
1195
+ super(NotNormalizedPower, self).__init__(
1196
+ 'One or more of the powers doen\'t have a normalized value'
1197
+ )
1198
+
1199
+
1200
+ class IncorrectPowerNumber(Exception):
1201
+ def __init__(self, power_number, expected_number):
1202
+ super(IncorrectPowerNumber, self).__init__(
1203
+ 'Expected {0} power(s) and got {1}'.format(
1204
+ expected_number, power_number
1205
+ )
1206
+ )
1207
+ self.power_number = power_number
1208
+ self.expected_number = expected_number
1209
+
1210
+
1211
+ class IncorrectMaxPower(Exception):
1212
+ def __init__(self, power, min_power, max_power):
1213
+ super(IncorrectMaxPower, self).__init__(
1214
+ 'Power {0} is not between {1} and {2}'.format(
1215
+ power, min_power, max_power
1216
+ )
1217
+ )
1218
+ self.power = power
1219
+ self.min_power = min_power
1220
+ self.max_power = max_power
1221
+
1222
+
1223
+ class IncorrectMinPower(Exception):
1224
+ def __init__(self, power, min_power, max_power):
1225
+ super(IncorrectMinPower, self).__init__(
1226
+ 'Power {0} is not between {1} and {2}'.format(
1227
+ power, min_power, max_power
1228
+ )
1229
+ )
1230
+ self.power = power
1231
+ self.min_power = min_power
1232
+ self.max_power = max_power
1233
+
1234
+
1235
+ class NotAscendingPowers(Exception):
1236
+ def __init__(self):
1237
+ super(NotAscendingPowers, self).__init__(
1238
+ 'For this tariff powers should go in an ascending order (Pn+1>=Pn)'
1239
+ )
1240
+
1241
+
1242
+ def get_tariff_by_code(code):
1243
+ """Get tariff class by code
1244
+
1245
+ :param code: Tariff code
1246
+ :return: Tariff
1247
+ """
1248
+ available = {
1249
+ '2.0A': T20A,
1250
+ '2.0DHA': T20DHA,
1251
+ '2.0DHS': T20DHS,
1252
+ '2.1A': T21A,
1253
+ '2.1DHA': T21DHA,
1254
+ '2.1DHS': T21DHS,
1255
+ '3.0A': T30A,
1256
+ '3.0A C2': T30ANoFestivos,
1257
+ '3.1A': T31A,
1258
+ '3.1A LB': T31A,
1259
+ '3.1A C2': T31ANoFestivos,
1260
+ '6.1A': T61A,
1261
+ '6.1B': T61B,
1262
+ '6.2': T62,
1263
+ '6.3': T63,
1264
+ '6.4': T64,
1265
+ 'RE': TRE,
1266
+ '1P': T1P,
1267
+ # New access tariffs 2021
1268
+ '2.0TD': T20TD,
1269
+ '3.0TD': T30TD,
1270
+ '6.1TD': T61TD,
1271
+ '6.2TD': T62TD,
1272
+ '6.3TD': T63TD,
1273
+ '6.4TD': T64TD,
1274
+ '3.0TDVE': T30TDVE,
1275
+ '6.1TDVE': T61TDVE,
1276
+ '6.2TDVE': T62TDVE
1277
+ }
1278
+ return available.get(code, None)