-
Notifications
You must be signed in to change notification settings - Fork 30
/
data_add.py
executable file
·1547 lines (1448 loc) · 49.5 KB
/
data_add.py
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
"""
CLI commands for populating the database
"""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Optional, Type
import json
from pathlib import Path
from io import TextIOBase
from marshmallow import validate
import pandas as pd
import pytz
from flask import current_app as app
from flask.cli import with_appcontext
import click
import getpass
from sqlalchemy.exc import IntegrityError
from sqlalchemy import func
from timely_beliefs.sensors.func_store.knowledge_horizons import x_days_ago_at_y_oclock
import timely_beliefs as tb
import timely_beliefs.utils as tb_utils
from workalendar.registry import registry as workalendar_registry
from flexmeasures.cli.utils import DeprecatedDefaultGroup, MsgStyle
from flexmeasures.data import db
from flexmeasures.data.scripts.data_gen import (
add_transmission_zone_asset,
populate_initial_structure,
add_default_asset_types,
)
from flexmeasures.data.services.data_sources import get_or_create_source
from flexmeasures.data.services.forecasting import create_forecasting_jobs
from flexmeasures.data.services.scheduling import make_schedule, create_scheduling_job
from flexmeasures.data.services.users import create_user
from flexmeasures.data.models.user import Account, AccountRole, RolesAccounts
from flexmeasures.data.models.time_series import (
Sensor,
TimedBelief,
)
from flexmeasures.data.models.validation_utils import (
check_required_attributes,
MissingAttributeException,
)
from flexmeasures.data.models.annotations import Annotation, get_or_create_annotation
from flexmeasures.data.schemas import (
AwareDateTimeField,
DurationField,
LatitudeField,
LongitudeField,
SensorIdField,
)
from flexmeasures.data.schemas.scheduling.storage import EfficiencyField
from flexmeasures.data.schemas.sensors import SensorSchema
from flexmeasures.data.schemas.units import QuantityField
from flexmeasures.data.schemas.generic_assets import (
GenericAssetSchema,
GenericAssetTypeSchema,
)
from flexmeasures.data.models.generic_assets import GenericAsset, GenericAssetType
from flexmeasures.data.models.user import User
from flexmeasures.data.services.data_sources import (
get_source_or_none,
)
from flexmeasures.data.services.utils import get_or_create_model
from flexmeasures.utils import flexmeasures_inflection
from flexmeasures.utils.time_utils import server_now, get_timezone, apply_offset_chain
from flexmeasures.utils.unit_utils import convert_units, ur
from flexmeasures.data.utils import save_to_db
from flexmeasures.data.models.reporting import Reporter
from timely_beliefs import BeliefsDataFrame
@click.group("add")
def fm_add_data():
"""FlexMeasures: Add data."""
@fm_add_data.command("account-role")
@with_appcontext
@click.option("--name", required=True)
@click.option("--description")
def new_account_role(name: str, description: str):
"""
Create an account role.
"""
role = AccountRole.query.filter_by(name=name).one_or_none()
if role is not None:
click.secho(f"Account role '{name}' already exists.", **MsgStyle.ERROR)
raise click.Abort()
role = AccountRole(name=name, description=description)
db.session.add(role)
db.session.commit()
click.secho(
f"Account role '{name}' (ID: {role.id}) successfully created.",
**MsgStyle.SUCCESS,
)
@fm_add_data.command("account")
@with_appcontext
@click.option("--name", required=True)
@click.option("--roles", help="e.g. anonymous,Prosumer,CPO")
def new_account(name: str, roles: str):
"""
Create an account for a tenant in the FlexMeasures platform.
"""
account = db.session.query(Account).filter_by(name=name).one_or_none()
if account is not None:
click.secho(f"Account '{name}' already exists.", **MsgStyle.ERROR)
raise click.Abort()
account = Account(name=name)
db.session.add(account)
if roles:
for role_name in roles.split(","):
role = AccountRole.query.filter_by(name=role_name).one_or_none()
if role is None:
click.secho(f"Adding account role {role_name} ...", **MsgStyle.ERROR)
role = AccountRole(name=role_name)
db.session.add(role)
db.session.flush()
db.session.add(RolesAccounts(role_id=role.id, account_id=account.id))
db.session.commit()
click.secho(
f"Account '{name}' (ID: {account.id}) successfully created.",
**MsgStyle.SUCCESS,
)
@fm_add_data.command("user")
@with_appcontext
@click.option("--username", required=True)
@click.option("--email", required=True)
@click.option(
"--account-id",
type=int,
required=True,
help="Add user to this account. Follow up with the account's ID.",
)
@click.option("--roles", help="e.g. anonymous,Prosumer,CPO")
@click.option(
"--timezone",
"timezone_optional",
help="Timezone as string, e.g. 'UTC' or 'Europe/Amsterdam' (defaults to FLEXMEASURES_TIMEZONE config setting)",
)
def new_user(
username: str,
email: str,
account_id: int,
roles: list[str],
timezone_optional: str | None,
):
"""
Create a FlexMeasures user.
The `users create` task from Flask Security Too is too simple for us.
Use this to add email, timezone and roles.
"""
if timezone_optional is None:
timezone = app.config.get("FLEXMEASURES_TIMEZONE", "UTC")
click.secho(
f"Setting user timezone to {timezone} (taken from FLEXMEASURES_TIMEZONE config setting)...",
**MsgStyle.WARN,
)
else:
timezone = timezone_optional
try:
pytz.timezone(timezone)
except pytz.UnknownTimeZoneError:
click.secho(f"Timezone {timezone} is unknown!", **MsgStyle.ERROR)
raise click.Abort()
account = db.session.query(Account).get(account_id)
if account is None:
click.secho(f"No account with ID {account_id} found!", **MsgStyle.ERROR)
raise click.Abort()
pwd1 = getpass.getpass(prompt="Please enter the password:")
pwd2 = getpass.getpass(prompt="Please repeat the password:")
if pwd1 != pwd2:
click.secho("Passwords do not match!", **MsgStyle.ERROR)
raise click.Abort()
created_user = create_user(
username=username,
email=email,
password=pwd1,
account_name=account.name,
timezone=timezone,
user_roles=roles,
check_email_deliverability=False,
)
db.session.commit()
click.secho(f"Successfully created user {created_user}", **MsgStyle.SUCCESS)
@fm_add_data.command("sensor")
@with_appcontext
@click.option("--name", required=True)
@click.option("--unit", required=True, help="e.g. °C, m/s, kW/m²")
@click.option(
"--event-resolution",
required=True,
type=int,
help="Expected resolution of the data in minutes",
)
@click.option(
"--timezone",
required=True,
help="Timezone as string, e.g. 'UTC' or 'Europe/Amsterdam'",
)
@click.option(
"--asset-id",
"generic_asset_id",
required=True,
type=int,
help="Generic asset to assign this sensor to",
)
@click.option(
"--attributes",
required=False,
type=str,
default="{}",
help='Additional attributes. Passed as JSON string, should be a dict. Hint: Currently, for sensors that measure power, use {"capacity_in_mw": 10} to set a capacity of 10 MW',
)
def add_sensor(**args):
"""Add a sensor."""
check_timezone(args["timezone"])
try:
attributes = json.loads(args["attributes"])
except json.decoder.JSONDecodeError as jde:
click.secho(
f"Error decoding --attributes. Please check your JSON: {jde}",
**MsgStyle.ERROR,
)
raise click.Abort()
del args["attributes"] # not part of schema
check_errors(SensorSchema().validate(args))
args["event_resolution"] = timedelta(minutes=args["event_resolution"])
sensor = Sensor(**args)
if not isinstance(attributes, dict):
click.secho("Attributes should be a dict.", **MsgStyle.ERROR)
raise click.Abort()
sensor.attributes = attributes
if sensor.measures_power:
if "capacity_in_mw" not in sensor.attributes:
click.secho(
"A sensor which measures power needs a capacity (see --attributes).",
**MsgStyle.ERROR,
)
raise click.Abort()
db.session.add(sensor)
db.session.commit()
click.secho(f"Successfully created sensor with ID {sensor.id}", **MsgStyle.SUCCESS)
click.secho(
f"You can access it at its entity address {sensor.entity_address}",
**MsgStyle.SUCCESS,
)
@fm_add_data.command("asset-type")
@with_appcontext
@click.option("--name", required=True)
@click.option(
"--description",
type=str,
help="Description (useful to explain acronyms, for example).",
)
def add_asset_type(**args):
"""Add an asset type."""
check_errors(GenericAssetTypeSchema().validate(args))
generic_asset_type = GenericAssetType(**args)
db.session.add(generic_asset_type)
db.session.commit()
click.secho(
f"Successfully created asset type with ID {generic_asset_type.id}.",
**MsgStyle.SUCCESS,
)
click.secho("You can now assign assets to it.", **MsgStyle.SUCCESS)
@fm_add_data.command("asset")
@with_appcontext
@click.option("--name", required=True)
@click.option(
"--latitude",
type=LatitudeField(),
help="Latitude of the asset's location",
)
@click.option(
"--longitude",
type=LongitudeField(),
help="Longitude of the asset's location",
)
@click.option(
"--account-id",
type=int,
required=False,
help="Add asset to this account. Follow up with the account's ID. If not set, the asset will become public (which makes it accessible to all users).",
)
@click.option(
"--asset-type-id",
"generic_asset_type_id",
required=True,
type=int,
help="Asset type to assign to this asset",
)
def add_asset(**args):
"""Add an asset."""
check_errors(GenericAssetSchema().validate(args))
generic_asset = GenericAsset(**args)
if generic_asset.account_id is None:
click.secho(
"Creating a PUBLIC asset, as no --account-id is given ...",
**MsgStyle.WARN,
)
db.session.add(generic_asset)
db.session.commit()
click.secho(
f"Successfully created asset with ID {generic_asset.id}.", **MsgStyle.SUCCESS
)
click.secho("You can now assign sensors to it.", **MsgStyle.SUCCESS)
@fm_add_data.command("initial-structure")
@with_appcontext
def add_initial_structure():
"""Initialize useful structural data."""
populate_initial_structure(db)
@fm_add_data.command("source")
@with_appcontext
@click.option(
"--name",
required=True,
type=str,
help="Name of the source (usually an organization)",
)
@click.option(
"--model",
required=False,
type=str,
help="Optionally, specify a model (for example, a class name, function name or url).",
)
@click.option(
"--version",
required=False,
type=str,
help="Optionally, specify a version (for example, '1.0'.",
)
@click.option(
"--type",
"source_type",
required=True,
type=str,
help="Type of source (for example, 'forecaster' or 'scheduler').",
)
def add_source(name: str, model: str, version: str, source_type: str):
source = get_or_create_source(
source=name,
model=model,
version=version,
source_type=source_type,
)
db.session.commit()
click.secho(f"Added source {source.__repr__()}", **MsgStyle.SUCCESS)
@fm_add_data.command("beliefs")
@with_appcontext
@click.argument("file", type=click.Path(exists=True))
@click.option(
"--sensor-id",
"sensor",
required=True,
type=SensorIdField(),
help="Sensor to which the beliefs pertain.",
)
@click.option(
"--source",
required=True,
type=str,
help="Source of the beliefs (an existing source id or name, or a new name).",
)
@click.option(
"--unit",
required=False,
type=str,
help="Unit of the data, for conversion to the sensor unit, if possible (a string unit such as 'kW' or 'm³/h').\n"
"Measurements of time itself that are formatted as a 'datetime' or 'timedelta' can be converted to a sensor unit representing time (such as 's' or 'h'),\n"
"where datetimes are represented as a duration with respect to the UNIX epoch."
"Hint: to switch the sign of the data, prepend a minus sign.\n"
"For example, when assigning kW consumption data to a kW production sensor, use '-kW'.",
)
@click.option(
"--horizon",
required=False,
type=int,
help="Belief horizon in minutes (use positive horizon for ex-ante beliefs or negative horizon for ex-post beliefs).",
)
@click.option(
"--cp",
required=False,
type=click.FloatRange(0, 1),
help="Cumulative probability in the range [0, 1].",
)
@click.option(
"--resample/--do-not-resample",
default=True,
help="Resample the data to fit the sensor's event resolution. "
" Only downsampling is currently supported (for example, from hourly to daily data).",
)
@click.option(
"--allow-overwrite/--do-not-allow-overwrite",
default=False,
help="Allow overwriting possibly already existing data.\n"
"Not allowing overwriting can be much more efficient",
)
@click.option(
"--skiprows",
required=False,
default=1,
type=int,
help="Number of rows to skip from the top. Set to >1 to skip additional headers.",
)
@click.option(
"--na-values",
required=False,
multiple=True,
help="Additional strings to recognize as NaN values. This argument can be given multiple times.",
)
@click.option(
"--keep-default-na",
default=False,
type=bool,
help="Whether or not to keep NaN values in the data.",
)
@click.option(
"--nrows",
required=False,
type=int,
help="Number of rows to read (from the top, after possibly skipping rows). Leave out to read all rows.",
)
@click.option(
"--datecol",
required=False,
default=0,
type=int,
help="Column number with datetimes (0 is 1st column, the default)",
)
@click.option(
"--valuecol",
required=False,
default=1,
type=int,
help="Column number with values (1 is 2nd column, the default)",
)
@click.option(
"--beliefcol",
required=False,
type=int,
help="Column number with datetimes",
)
@click.option(
"--timezone",
required=False,
default=None,
help="Timezone as string, e.g. 'UTC' or 'Europe/Amsterdam'",
)
@click.option(
"--filter-column",
"filter_columns",
multiple=True,
help="Set a column number to filter data. Use together with --filter-value.",
)
@click.option(
"--filter-value",
"filter_values",
multiple=True,
help="Set a column value to filter data. Only rows with this value will be added. Use together with --filter-column.",
)
@click.option(
"--delimiter",
required=True,
type=str,
default=",",
help="[For CSV files] Character to delimit columns per row, defaults to comma",
)
@click.option(
"--decimal",
required=False,
default=".",
type=str,
help="[For CSV files] decimal character, e.g. '.' for 10.5",
)
@click.option(
"--thousands",
required=False,
default=None,
type=str,
help="[For CSV files] thousands separator, e.g. '.' for 10.035,2",
)
@click.option(
"--sheet_number",
required=False,
type=int,
help="[For xls or xlsx files] Sheet number with the data (0 is 1st sheet)",
)
def add_beliefs(
file: str,
sensor: Sensor,
source: str,
filter_columns: list[int],
filter_values: list[int],
unit: str | None = None,
horizon: int | None = None,
cp: float | None = None,
resample: bool = True,
allow_overwrite: bool = False,
skiprows: int = 1,
na_values: list[str] | None = None,
keep_default_na: bool = False,
nrows: int | None = None,
datecol: int = 0,
valuecol: int = 1,
beliefcol: int | None = None,
timezone: str | None = None,
delimiter: str = ",",
decimal: str = ".",
thousands: str | None = None,
sheet_number: int | None = None,
**kwargs, # in-code calls to this CLI command can set additional kwargs for use in pandas.read_csv or pandas.read_excel
):
"""Add sensor data from a CSV or Excel file.
To use default settings, structure your CSV file as follows:
- One header line (will be ignored!)
- UTC datetimes in 1st column
- values in 2nd column
For example:
Date,Inflow (cubic meter)
2020-12-03 14:00,212
2020-12-03 14:10,215.6
2020-12-03 14:20,203.8
In case no --horizon is specified and no beliefcol is specified,
the moment of executing this CLI command is taken as the time at which the beliefs were recorded.
"""
_source = parse_source(source)
# Set up optional parameters for read_csv
if file.split(".")[-1].lower() == "csv":
kwargs["infer_datetime_format"] = True
kwargs["delimiter"] = delimiter
kwargs["decimal"] = decimal
kwargs["thousands"] = thousands
if sheet_number is not None:
kwargs["sheet_name"] = sheet_number
if horizon is not None:
kwargs["belief_horizon"] = timedelta(minutes=horizon)
elif beliefcol is None:
kwargs["belief_time"] = server_now().astimezone(pytz.timezone(sensor.timezone))
# Set up optional filters:
if len(filter_columns) != len(filter_values):
raise ValueError(
"The number of filter columns and filter values should be the same."
)
filter_by_column = (
dict(zip(filter_columns, filter_values)) if filter_columns else None
)
bdf = tb.read_csv(
file,
sensor,
source=_source,
cumulative_probability=cp,
resample=resample,
header=None,
skiprows=skiprows,
nrows=nrows,
usecols=[datecol, valuecol]
if beliefcol is None
else [datecol, beliefcol, valuecol],
parse_dates=True,
na_values=na_values,
keep_default_na=keep_default_na,
timezone=timezone,
filter_by_column=filter_by_column,
**kwargs,
)
duplicate_rows = bdf.index.duplicated(keep="first")
if any(duplicate_rows) > 0:
click.secho(
"Duplicates found. Dropping duplicates for the following records:",
**MsgStyle.WARN,
)
click.secho(bdf[duplicate_rows], **MsgStyle.WARN)
bdf = bdf[~duplicate_rows]
if unit is not None:
bdf["event_value"] = convert_units(
bdf["event_value"],
from_unit=unit,
to_unit=sensor.unit,
event_resolution=sensor.event_resolution,
)
try:
TimedBelief.add(
bdf,
expunge_session=True,
allow_overwrite=allow_overwrite,
bulk_save_objects=True,
commit_transaction=True,
)
click.secho(f"Successfully created beliefs\n{bdf}", **MsgStyle.SUCCESS)
except IntegrityError as e:
db.session.rollback()
click.secho(
f"Failed to create beliefs due to the following error: {e.orig}",
**MsgStyle.ERROR,
)
if not allow_overwrite:
click.secho(
"As a possible workaround, use the --allow-overwrite flag.",
**MsgStyle.ERROR,
)
@fm_add_data.command("annotation")
@with_appcontext
@click.option(
"--content",
required=True,
prompt="Enter annotation",
)
@click.option(
"--at",
"start_str",
required=True,
help="Annotation is set (or starts) at this datetime. Follow up with a timezone-aware datetime in ISO 6801 format.",
)
@click.option(
"--until",
"end_str",
required=False,
help="Annotation ends at this datetime. Follow up with a timezone-aware datetime in ISO 6801 format. Defaults to one (nominal) day after the start of the annotation.",
)
@click.option(
"--account-id",
"account_ids",
type=click.INT,
multiple=True,
help="Add annotation to this organisation account. Follow up with the account's ID. This argument can be given multiple times.",
)
@click.option(
"--asset-id",
"generic_asset_ids",
type=int,
multiple=True,
help="Add annotation to this asset. Follow up with the asset's ID. This argument can be given multiple times.",
)
@click.option(
"--sensor-id",
"sensor_ids",
type=int,
multiple=True,
help="Add annotation to this sensor. Follow up with the sensor's ID. This argument can be given multiple times.",
)
@click.option(
"--user-id",
type=int,
required=True,
help="Attribute annotation to this user. Follow up with the user's ID.",
)
def add_annotation(
content: str,
start_str: str,
end_str: str | None,
account_ids: list[int],
generic_asset_ids: list[int],
sensor_ids: list[int],
user_id: int,
):
"""Add annotation to accounts, assets and/or sensors."""
# Parse input
start = pd.Timestamp(start_str)
end = (
pd.Timestamp(end_str)
if end_str is not None
else start + pd.offsets.DateOffset(days=1)
)
accounts = (
db.session.query(Account).filter(Account.id.in_(account_ids)).all()
if account_ids
else []
)
assets = (
db.session.query(GenericAsset)
.filter(GenericAsset.id.in_(generic_asset_ids))
.all()
if generic_asset_ids
else []
)
sensors = (
db.session.query(Sensor).filter(Sensor.id.in_(sensor_ids)).all()
if sensor_ids
else []
)
user = db.session.query(User).get(user_id)
_source = get_or_create_source(user)
# Create annotation
annotation = get_or_create_annotation(
Annotation(
content=content,
start=start,
end=end,
source=_source,
type="label",
)
)
for account in accounts:
account.annotations.append(annotation)
for asset in assets:
asset.annotations.append(annotation)
for sensor in sensors:
sensor.annotations.append(annotation)
db.session.commit()
click.secho("Successfully added annotation.", **MsgStyle.SUCCESS)
@fm_add_data.command("holidays")
@with_appcontext
@click.option(
"--year",
type=click.INT,
help="The year for which to look up holidays",
)
@click.option(
"--country",
"countries",
type=click.STRING,
multiple=True,
help="The ISO 3166-1 country/region or ISO 3166-2 sub-region for which to look up holidays (such as US, BR and DE). This argument can be given multiple times.",
)
@click.option(
"--asset-id",
"generic_asset_ids",
type=click.INT,
multiple=True,
help="Add annotations to this asset. Follow up with the asset's ID. This argument can be given multiple times.",
)
@click.option(
"--account-id",
"account_ids",
type=click.INT,
multiple=True,
help="Add annotations to this account. Follow up with the account's ID. This argument can be given multiple times.",
)
def add_holidays(
year: int,
countries: list[str],
generic_asset_ids: list[int],
account_ids: list[int],
):
"""Add holiday annotations to accounts and/or assets."""
calendars = workalendar_registry.get_calendars(countries)
num_holidays = {}
accounts = (
db.session.query(Account).filter(Account.id.in_(account_ids)).all()
if account_ids
else []
)
assets = (
db.session.query(GenericAsset)
.filter(GenericAsset.id.in_(generic_asset_ids))
.all()
if generic_asset_ids
else []
)
annotations = []
for country, calendar in calendars.items():
_source = get_or_create_source(
"workalendar", model=country, source_type="CLI script"
)
holidays = calendar().holidays(year)
for holiday in holidays:
start = pd.Timestamp(holiday[0])
end = start + pd.offsets.DateOffset(days=1)
annotations.append(
get_or_create_annotation(
Annotation(
content=holiday[1],
start=start,
end=end,
source=_source,
type="holiday",
)
)
)
num_holidays[country] = len(holidays)
db.session.add_all(annotations)
for account in accounts:
account.annotations += annotations
for asset in assets:
asset.annotations += annotations
db.session.commit()
click.secho(
f"Successfully added holidays to {len(accounts)} {flexmeasures_inflection.pluralize('account', len(accounts))} and {len(assets)} {flexmeasures_inflection.pluralize('asset', len(assets))}:\n{num_holidays}",
**MsgStyle.SUCCESS,
)
@fm_add_data.command("forecasts")
@with_appcontext
@click.option(
"--sensor-id",
"sensor_ids",
multiple=True,
required=True,
help="Create forecasts for this sensor. Follow up with the sensor's ID. This argument can be given multiple times.",
)
@click.option(
"--from-date",
"from_date_str",
default="2015-02-08",
help="Forecast from date (inclusive). Follow up with a date in the form yyyy-mm-dd.",
)
@click.option(
"--to-date",
"to_date_str",
default="2015-12-31",
help="Forecast to date (inclusive). Follow up with a date in the form yyyy-mm-dd.",
)
@click.option(
"--resolution",
type=int,
help="Resolution of forecast in minutes. If not set, resolution is determined from the sensor to be forecasted",
)
@click.option(
"--horizon",
"horizons_as_hours",
multiple=True,
type=click.Choice(["1", "6", "24", "48"]),
default=["1", "6", "24", "48"],
help="Forecasting horizon in hours. This argument can be given multiple times. Defaults to all possible horizons.",
)
@click.option(
"--as-job",
is_flag=True,
help="Whether to queue a forecasting job instead of computing directly. "
"To process the job, run a worker (on any computer, but configured to the same databases) to process the 'forecasting' queue. Defaults to False.",
)
def create_forecasts(
sensor_ids: list[int],
from_date_str: str = "2015-02-08",
to_date_str: str = "2015-12-31",
horizons_as_hours: list[str] = ["1"],
resolution: int | None = None,
as_job: bool = False,
):
"""
Create forecasts.
For example:
--from-date 2015-02-02 --to-date 2015-02-04 --horizon 6 --sensor-id 12 --sensor-id 14
This will create forecast values from 0am on May 2nd to 0am on May 5th,
based on a 6-hour horizon, for sensors 12 and 14.
"""
# make horizons
horizons = [timedelta(hours=int(h)) for h in horizons_as_hours]
# apply timezone and set forecast_end to be an inclusive version of to_date
timezone = app.config.get("FLEXMEASURES_TIMEZONE")
forecast_start = pd.Timestamp(from_date_str).tz_localize(timezone)
forecast_end = (pd.Timestamp(to_date_str) + pd.Timedelta("1D")).tz_localize(
timezone
)
event_resolution: timedelta | None
if resolution is not None:
event_resolution = timedelta(minutes=resolution)
else:
event_resolution = None
if as_job:
num_jobs = 0
for sensor_id in sensor_ids:
for horizon in horizons:
# Note that this time period refers to the period of events we are forecasting, while in create_forecasting_jobs
# the time period refers to the period of belief_times, therefore we are subtracting the horizon.
jobs = create_forecasting_jobs(
sensor_id=sensor_id,
horizons=[horizon],
start_of_roll=forecast_start - horizon,
end_of_roll=forecast_end - horizon,
)
num_jobs += len(jobs)
click.secho(
f"{num_jobs} new forecasting job(s) added to the queue.",
**MsgStyle.SUCCESS,
)
else:
from flexmeasures.data.scripts.data_gen import populate_time_series_forecasts
populate_time_series_forecasts( # this function reports its own output
db=app.db,
sensor_ids=sensor_ids,
horizons=horizons,
forecast_start=forecast_start,
forecast_end=forecast_end,
event_resolution=event_resolution,
)
# todo: repurpose `flexmeasures add schedule` (deprecated since v0.12),
# - see https://github.com/FlexMeasures/flexmeasures/pull/537#discussion_r1048680231
# - hint for repurposing to invoke custom logic instead of a default subcommand:
# @fm_add_data.group("schedule", invoke_without_command=True)
# def create_schedule():
# if ctx.invoked_subcommand:
# ...
@fm_add_data.group(
"schedule",
cls=DeprecatedDefaultGroup,
default="storage",
deprecation_message="The command 'flexmeasures add schedule' is deprecated. Please use `flexmeasures add schedule for-storage` instead.",
)
@click.pass_context
@with_appcontext
def create_schedule(ctx):
"""(Deprecated) Create a new schedule for a given power sensor.
THIS COMMAND HAS BEEN RENAMED TO `flexmeasures add schedule for-storage`
"""
pass
@create_schedule.command("for-storage")
@with_appcontext
@click.option(
"--sensor-id",
"power_sensor",
type=SensorIdField(),
required=True,
help="Create schedule for this sensor. Should be a power sensor. Follow up with the sensor's ID.",
)
@click.option(
"--consumption-price-sensor",
"consumption_price_sensor",
type=SensorIdField(),
required=False,
help="Optimize consumption against this sensor. The sensor typically records an electricity price (e.g. in EUR/kWh), but this field can also be used to optimize against some emission intensity factor (e.g. in kg CO₂ eq./kWh). Follow up with the sensor's ID.",
)
@click.option(
"--production-price-sensor",
"production_price_sensor",
type=SensorIdField(),
required=False,
help="Optimize production against this sensor. Defaults to the consumption price sensor. The sensor typically records an electricity price (e.g. in EUR/kWh), but this field can also be used to optimize against some emission intensity factor (e.g. in kg CO₂ eq./kWh). Follow up with the sensor's ID.",
)
@click.option(
"--optimization-context-id",
"optimization_context_sensor",
type=SensorIdField(),
required=False,
help="To be deprecated. Use consumption-price-sensor instead.",
)
@click.option(
"--inflexible-device-sensor",
"inflexible_device_sensors",
type=SensorIdField(),
multiple=True,
help="Take into account the power flow of inflexible devices. Follow up with the sensor's ID."
" This argument can be given multiple times.",
)
@click.option(
"--start",
"start",
type=AwareDateTimeField(format="iso"),
required=True,
help="Schedule starts at this datetime. Follow up with a timezone-aware datetime in ISO 6801 format.",
)
@click.option(
"--duration",
"duration",
type=DurationField(),
required=True,
help="Duration of schedule, after --start. Follow up with a duration in ISO 6801 format, e.g. PT1H (1 hour) or PT45M (45 minutes).",
)
@click.option(
"--soc-at-start",
"soc_at_start",