-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwind.py
More file actions
1999 lines (1665 loc) · 69.4 KB
/
wind.py
File metadata and controls
1999 lines (1665 loc) · 69.4 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
"""Methods for working with time-indexed wind data."""
# pylint: disable=E0401
import calendar
import json
import textwrap
import warnings
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
import pandas as pd
from ladybug.dt import DateTime
from ladybug.epw import EPW
from matplotlib.cm import ScalarMappable
from matplotlib.collections import PatchCollection
from matplotlib.colors import Colormap, ListedColormap, Normalize, to_hex
from matplotlib.patches import Rectangle
from pandas.tseries.frequencies import to_offset
from scipy.stats import weibull_min
from .categorical.categories import BEAUFORT_CATEGORIES
from .helpers import (
OpenMeteoVariable,
angle_from_north,
angle_to_vector,
cardinality,
circular_weighted_mean,
scrape_meteostat,
scrape_openmeteo,
wind_speed_at_height,
)
from .ladybug_extension.analysisperiod import (
AnalysisPeriod,
analysis_period_to_boolean,
analysis_period_to_datetimes,
describe_analysis_period,
)
from .bhom.logging import CONSOLE_LOGGER
from python_toolkit.plot.timeseries import timeseries
from python_toolkit.plot.polar import polar
from .plot.utilities import contrasting_color
# pylint: enable=E0401
@dataclass(init=True, eq=True, repr=True)
class Wind:
"""An object containing historic, time-indexed wind data.
Args:
wind_speeds (list[int | float | np.number]):
An iterable of wind speeds in m/s.
wind_directions (list[int | float | np.number]):
An iterable of wind directions in degrees from North (with North at 0-degrees).
datetimes (Union[pd.DatetimeIndex, list[Union[datetime, np.datetime64, pd.Timestamp]]]):
An iterable of datetime-like objects.
height_above_ground (float, optional):
The height above ground (in m) where the input wind speeds and directions were
collected. Defaults to 10m.
source (str, optional):
A source string to describe where the input data comes from. Defaults to None.
"""
wind_speeds: list[float]
wind_directions: list[float]
datetimes: list[datetime] | pd.DatetimeIndex
height_above_ground: float = 10.0
source: str = None
def __post_init__(self):
if self.height_above_ground < 0.1:
raise ValueError("Height above ground must be >= 0.1m.")
if not len(self.wind_speeds) == len(self.wind_directions) == len(self.datetimes):
raise ValueError("wind_speeds, wind_directions and datetimes must be the same length.")
if len(self.wind_speeds) <= 1:
raise ValueError(
"wind_speeds, wind_directions and datetimes must be at least 2 items long."
)
if len(set(self.datetimes)) != len(self.datetimes):
raise ValueError("datetimes contains duplicates.")
# convert to lists
self.wind_speeds = np.array(self.wind_speeds)
self.wind_directions = np.array(self.wind_directions)
self.datetimes = pd.DatetimeIndex(self.datetimes)
# validate wind speeds and directions
if np.any(np.isnan(self.wind_speeds)):
raise ValueError("wind_speeds contains null values.")
if np.any(np.isnan(self.wind_directions)):
raise ValueError("wind_directions contains null values.")
if np.any(self.wind_speeds < 0):
raise ValueError("wind_speeds must be >= 0")
if np.any(self.wind_directions < 0) or np.any(self.wind_directions > 360):
raise ValueError("wind_directions must be within 0-360")
self.wind_directions = self.wind_directions % 360
def __len__(self) -> int:
return len(self.datetimes)
def __repr__(self) -> str:
"""The printable representation of the given object"""
if self.source:
return f"{self.__class__.__name__}(@{self.height_above_ground}m) from {self.source}"
return (
f"{self.__class__.__name__}({min(self.datetimes):%Y-%m-%d} to "
f"{max(self.datetimes):%Y-%m-%d}, n={len(self.datetimes)} @{self.freq}, "
f"@{self.height_above_ground}m) NO SOURCE"
)
def __str__(self) -> str:
"""The string representation of the given object"""
return self.__repr__()
#################
# CLASS METHODS #
#################
def to_dict(self) -> dict:
"""Return the object as a dictionary."""
return {
"_t": "BH.oM.LadybugTools.Wind",
"wind_speeds": [float(i) for i in self.wind_speeds],
"wind_directions": [float(i) for i in self.wind_directions],
"datetimes": [i.isoformat() for i in self.datetimes],
"height_above_ground": self.height_above_ground,
"source": self.source,
}
@classmethod
def from_dict(cls, d: dict) -> "Wind":
"""Create this object from a dictionary."""
return cls(
wind_speeds=d["wind_speeds"],
wind_directions=d["wind_directions"],
datetimes=pd.to_datetime(d["datetimes"]),
height_above_ground=d["height_above_ground"],
source=d["source"],
)
def to_json(self) -> str:
"""Convert this object to a JSON string."""
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_string: str) -> "Wind":
"""Create this object from a JSON string."""
return cls.from_dict(json.loads(json_string))
def to_file(self, path: Path) -> Path:
"""Convert this object to a JSON file."""
if Path(path).suffix != ".json":
raise ValueError("path must be a JSON file.")
with open(Path(path), "w", encoding="utf-8") as fp:
fp.write(self.to_json())
return Path(path)
@classmethod
def from_file(cls, path: Path) -> "Wind":
"""Create this object from a JSON file."""
with open(Path(path), "r", encoding="utf-8") as fp:
return cls.from_json(fp.read())
def to_csv(self, path: Path) -> Path:
"""Save this object as a csv file.
Args:
path (Path):
The path containing the CSV file.
Returns:
Path:
The resultant CSV file.
"""
csv_path = Path(path)
self.df.to_csv(csv_path)
return csv_path
@classmethod
def from_dataframe(
cls,
df: pd.DataFrame,
wind_speed_column: Any,
wind_direction_column: Any,
height_above_ground: float = 10,
source: str = "DataFrame",
) -> "Wind":
"""Create a Wind object from a Pandas DataFrame, with WindSpeed and WindDirection columns.
Args:
df (pd.DataFrame):
A DataFrame object containing speed and direction columns, and a datetime index.
wind_speed_column (str):
The name of the column where wind-speed data exists.
wind_direction_column (str):
The name of the column where wind-direction data exists.
height_above_ground (float, optional):
Defaults to 10m.
source (str, optional):
A source string to describe where the input data comes from.
Defaults to "DataFrame"".
"""
if not isinstance(df, pd.DataFrame):
raise TypeError(f"df must be of type {pd.DataFrame}")
if not isinstance(df.index, pd.DatetimeIndex):
raise TypeError(f"The DataFrame's index must be of type {pd.DatetimeIndex}")
# remove NaN values
df.dropna(axis=0, how="any", inplace=True)
# remove duplicates in input dataframe
df = df.loc[~df.index.duplicated()]
return cls(
wind_speeds=df[wind_speed_column].tolist(),
wind_directions=df[wind_direction_column].tolist(),
datetimes=df.index.tolist(),
height_above_ground=height_above_ground,
source=source,
)
@classmethod
def from_csv(
cls,
csv_path: Path,
wind_speed_column: str,
wind_direction_column: str,
height_above_ground: float = 10,
**kwargs,
) -> "Wind":
"""Create a Wind object from a csv containing wind speed and direction columns.
Args:
csv_path (Path):
The path to the CSV file containing speed and direction columns,
and a datetime index.
wind_speed_column (str):
The name of the column where wind-speed data exists.
wind_direction_column (str):
The name of the column where wind-direction data exists.
height_above_ground (float, optional):
Defaults to 10m.
**kwargs:
Additional keyword arguments passed to pd.read_csv.
"""
csv_path = Path(csv_path)
df = pd.read_csv(csv_path, **kwargs)
df.index = pd.to_datetime(df.index)
return cls.from_dataframe(
df,
wind_speed_column=wind_speed_column,
wind_direction_column=wind_direction_column,
height_above_ground=height_above_ground,
source=csv_path.name,
)
@classmethod
def from_epw(cls, epw: Path | EPW) -> "Wind":
"""Create a Wind object from an EPW file or object.
Args:
epw (Path | EPW):
The path to the EPW file, or an EPW object.
"""
if isinstance(epw, (str, Path)):
source = Path(epw).name
epw = EPW(epw)
else:
source = Path(epw.file_path).name
return cls(
wind_speeds=epw.wind_speed.values,
wind_directions=epw.wind_direction.values,
datetimes=analysis_period_to_datetimes(AnalysisPeriod()),
height_above_ground=10,
source=source,
)
@classmethod
def from_openmeteo(
cls,
latitude: float,
longitude: float,
start_date: datetime | str,
end_date: datetime | str,
) -> "Wind":
"""Create a Wind object from data obtained from the Open-Meteo database
of historic weather station data.
Args:
latitude (float):
The latitude of the target site, in degrees.
longitude (float):
The longitude of the target site, in degrees.
start_date (datetime | str):
The start-date from which records will be obtained.
end_date (datetime | str):
The end-date beyond which records will be ignored.
"""
df = scrape_openmeteo(
latitude=latitude,
longitude=longitude,
start_date=start_date,
end_date=end_date,
variables=[
OpenMeteoVariable.WINDSPEED_10M,
OpenMeteoVariable.WINDDIRECTION_10M,
],
convert_units=True,
)
df.dropna(how="any", axis=0, inplace=True)
wind_speeds = df["Wind Speed (m/s)"].tolist()
wind_directions = df["Wind Direction (degrees)"].tolist()
if len(wind_speeds) == 0 or len(wind_directions) == 0:
raise ValueError(
"OpenMeteo did not return any data for the given latitude, longitude and start/end dates."
)
datetimes = df.index.tolist()
return cls(
wind_speeds=wind_speeds,
wind_directions=wind_directions,
datetimes=datetimes,
height_above_ground=10,
source="OpenMeteo",
)
@classmethod
def from_meteostat(
cls,
latitude: float,
longitude: float,
start_date: datetime | str,
end_date: datetime | str,
altitude: float = 10,
) -> "Wind":
"""Create a Wind object from data obtained from the Meteostat database
of historic weather station data.
Args:
latitude (float):
The latitude of the target site, in degrees.
longitude (float):
The longitude of the target site, in degrees.
start_date (datetime | str):
The start-date from which records will be obtained.
end_date (datetime | str):
The end-date beyond which records will be ignored.
altitude (float, optional):
The altitude of the target site, in meters. Defaults to 10.
"""
df = scrape_meteostat(
latitude=latitude,
longitude=longitude,
start_date=start_date,
end_date=end_date,
altitude=altitude,
convert_units=True,
)[["Wind Speed (m/s)", "Wind Direction (degrees)"]]
df.dropna(axis=0, inplace=True, how="any")
return cls.from_dataframe(
df=df,
wind_speed_column="Wind Speed (m/s)",
wind_direction_column="Wind Direction (degrees)",
height_above_ground=altitude,
source="Meteostat",
)
@classmethod
def from_average(cls, wind_objects: list["Wind"], weights: list[float] = None) -> "Wind":
"""Create an average Wind object from a set of input Wind objects, with optional weighting for each."""
# create default weightings if None
if weights is None:
weights = [1 / len(wind_objects)] * len(wind_objects)
else:
if sum(weights) != 1:
raise ValueError("weights must total 1.")
# create source string
source = []
for src, wgt in list(zip([wind_objects, weights])):
source.append(f"{src.source}|{wgt}")
source = "_".join(source)
# align collections so that intersection only is created
df_ws = pd.concat([i.ws for i in wind_objects], axis=1).dropna()
df_wd = pd.concat([i.wd for i in wind_objects], axis=1).dropna()
# construct the weighted means
wd_avg = np.array([circular_weighted_mean(i, weights) for _, i in df_wd.iterrows()])
ws_avg = np.average(df_ws, axis=1, weights=weights)
dts = df_ws.index
# return the new averaged object
return cls(
wind_speeds=ws_avg.tolist(),
wind_directions=wd_avg.tolist(),
datetimes=dts,
height_above_ground=np.average(
[i.height_above_ground for i in wind_objects], weights=weights
),
source=source,
)
@classmethod
def from_uv(
cls,
u: list[float],
v: list[float],
datetimes: list[datetime],
height_above_ground: float = 10,
source: str = None,
) -> "Wind":
"""Create a Wind object from a set of U, V wind components.
Args:
u (list[float]):
An iterable of U (eastward) wind components in m/s.
v (list[float]):
An iterable of V (northward) wind components in m/s.
datetimes (list[datetime]):
An iterable of datetime-like objects.
height_above_ground (float, optional):
The height above ground (in m) where the input wind speeds and
directions were collected.
Defaults to 10m.
source (str, optional):
A source string to describe where the input data comes from.
Defaults to None.
Returns:
Wind:
A Wind object!
"""
# convert UV into angle and magnitude
wind_direction = angle_from_north(np.stack([u, v]))
wind_speed = np.sqrt(np.square(u) + np.square(v))
if any(wind_direction[wind_speed == 0] == 90):
warnings.warn(
"Some input vectors have velocity of 0. This is not bad, but can mean directions may be misreported."
)
return cls(
wind_speeds=wind_speed.tolist(),
wind_directions=wind_direction.tolist(),
datetimes=datetimes,
height_above_ground=height_above_ground,
source=source,
)
# ##############
# # PROPERTIES #
# ##############
@property
def freq(self) -> str:
"""Return the inferred frequency of the datetimes associated with this object."""
freq = pd.infer_freq(self.datetimes)
if freq is None:
return "inconsistent"
return freq
@property
def index(self) -> pd.DatetimeIndex:
"""Get the datetimes as a pandas DateTimeIndex."""
return pd.to_datetime(self.datetimes)
@property
def ws(self) -> pd.Series:
"""Convenience accessor for wind speeds as a time-indexed pd.Series object."""
return pd.Series(self.wind_speeds, index=self.index, name="Wind Speed (m/s)").sort_index(
ascending=True, inplace=False
)
@property
def wd(self) -> pd.Series:
"""Convenience accessor for wind directions as a time-indexed pd.Series object."""
return pd.Series(
self.wind_directions, index=self.index, name="Wind Direction (degrees)"
).sort_index(ascending=True, inplace=False)
@property
def df(self) -> pd.DataFrame:
"""Convenience accessor for wind direction and speed as a time-indexed
pd.DataFrame object."""
return pd.concat([self.wd, self.ws], axis=1)
@property
def calm_datetimes(self) -> list[datetime]:
"""Return the datetimes where wind speed is < 0.1.
Returns:
list[datetime]:
"Calm" wind datetimes.
"""
return self.ws[self.ws <= 0.1].index.tolist() # pylint: disable=E1136
@property
def uv(self) -> pd.DataFrame:
"""Return the U and V wind components in m/s."""
u, v = angle_to_vector(self.wd)
return pd.concat([u * self.ws, v * self.ws], axis=1, keys=["u", "v"])
@property
def mean_uv(self) -> list[float, float]:
"""Calculate the average U and V wind components in m/s.
Returns:
list[float, float]:
A tuple containing the average U and V wind components.
"""
return self.uv.mean().tolist()
def mean_speed(self, remove_calm: bool = False) -> float:
"""Return the mean wind speed for this object.
Args:
remove_calm (bool, optional):
Remove calm wind speeds before calculating the mean. Defaults to False.
Returns:
float:
Mean wind speed.
"""
return np.linalg.norm(self.filter_by_speed(min_speed=1e-10 if remove_calm else 0).mean_uv)
@property
def mean_direction(self) -> tuple[float, float]:
"""Calculate the average speed and direction for this object.
Returns:
tuple[float, float]:
A tuple containing the average speed and direction.
"""
return angle_from_north(self.mean_uv)
@property
def min_speed(self) -> float:
"""Return the min wind speed for this object."""
return self.ws.min()
@property
def max_speed(self) -> float:
"""Return the max wind speed for this object."""
return self.ws.max()
@property
def median_speed(self) -> float:
"""Return the median wind speed for this object."""
return self.ws.median()
###################
# GENERAL METHODS #
###################
def calm(self, threshold: float = 1e-10) -> float:
"""Return the proportion of timesteps "calm" (i.e. wind-speed ≤ 1e-10)."""
return (self.ws < threshold).sum() / len(self.ws)
def percentile(self, percentile: float) -> float:
"""Calculate the wind speed at the given percentile.
Args:
percentile (float):
The percentile to calculate.
Returns:
float:
Wind speed at the given percentile.
"""
return self.ws.quantile(percentile)
def resample(self, rule: pd.DateOffset | pd.Timedelta | str) -> "Wind":
"""Resample the wind data collection to a different timestep.
This can only be used to downsample.
Args:
rule (Union[pd.DateOffset, pd.Timedelta, str]):
A rule for resampling. This uses the same inputs as a Pandas
Series.resample() method.
Returns:
Wind:
A wind data collection object!
"""
warnings.warn(
(
"Resampling wind speeds and direction is generally not advisable. "
"When input directions are opposing, the average returned is likely inaccurate, "
"and the average speed does not include any outliers. USE WITH CAUTION!"
)
)
common_dt = pd.to_datetime("2000-01-01")
f_a = common_dt + to_offset(self.freq)
f_b = common_dt + to_offset(rule)
if f_a < f_b:
raise ValueError("Resampling can only be used to downsample.")
resampled_speeds = self.ws.resample(rule).mean()
resampled_datetimes = resampled_speeds.index.tolist()
resampled_directions = self.wd.resample(rule).apply(circular_weighted_mean)
return Wind(
wind_speeds=resampled_speeds.tolist(),
wind_directions=resampled_directions.tolist(),
datetimes=resampled_datetimes,
height_above_ground=self.height_above_ground,
source=self.source,
)
def to_height(
self,
target_height: float,
terrain_roughness_length: float = 1,
log_function: bool = True,
) -> "Wind":
"""Translate the object to a different height above ground.
Args:
target_height (float):
Height to translate to (in m).
terrain_roughness_length (float, optional):
Terrain roughness (how big objects are to adjust translation).
Defaults to 1.
log_function (bool, optional):
Whether to use log-function or pow-function. Defaults to True.
Returns:
Wind:
A translated Wind object.
"""
ws = wind_speed_at_height(
reference_value=self.ws,
reference_height=self.height_above_ground,
target_height=target_height,
terrain_roughness_length=terrain_roughness_length,
log_function=log_function,
)
return Wind(
wind_speeds=ws.tolist(),
wind_directions=self.wd.tolist(),
datetimes=self.datetimes,
height_above_ground=target_height,
source=f"{self.source} translated to {target_height}m",
)
def apply_directional_factors(self, directions: int, factors: tuple[float]) -> "Wind":
"""Adjust wind speed values by a set of factors per direction.
Factors start at north, and move clockwise.
Example:
>>> wind = Wind.from_epw(epw_path)
>>> wind.apply_directional_factors(
... directions=4,
... factors=(0.5, 0.75, 1, 0.75)
... )
Where northern winds would be multiplied by 0.5, eastern winds by 0.75,
southern winds by 1, and western winds by 0.75.
Args:
directions (int):
The number of directions to bin wind-directions into.
factors (tuple[float], optional):
Adjustment factors per direction.
Returns:
Wind:
An adjusted Wind object.
"""
factors = np.array(factors).tolist()
if len(factors) != directions:
raise ValueError(
f"number of factors ({len(factors)}) must equal number of directions ({directions})"
)
direction_binned = self.bin_data(directions=directions)
directional_factor_lookup = dict(
zip(*[np.roll(np.unique(direction_binned.iloc[:, 0]), 1), factors])
)
adjusted_wind_speed = self.ws * [
directional_factor_lookup[i] for i in direction_binned.iloc[:, 0]
]
return Wind(
wind_speeds=adjusted_wind_speed.tolist(),
wind_directions=self.wd.tolist(),
datetimes=self.datetimes,
height_above_ground=self.height_above_ground,
source=f"{self.source} adjusted by factors {factors}",
)
def filter_by_analysis_period(
self,
analysis_period: AnalysisPeriod,
) -> "Wind":
"""Filter the current object by a ladybug AnalysisPeriod object.
Args:
analysis_period (AnalysisPeriod):
An AnalysisPeriod object.
Returns:
Wind:
A dataset describing historic wind speed and direction relationship.
"""
if analysis_period == AnalysisPeriod():
return self
if analysis_period.timestep != 1:
raise ValueError("The timestep of the analysis period must be 1 hour.")
# remove 29th Feb dates where present
df = self.df
df = df[~((df.index.month == 2) & (df.index.day == 29))]
# filter available data
possible_datetimes = [DateTime(dt.month, dt.day, dt.hour, dt.minute) for dt in df.index]
lookup = dict(zip(AnalysisPeriod().datetimes, analysis_period_to_boolean(analysis_period)))
mask = [lookup[i] for i in possible_datetimes]
df = df[mask]
if len(df) == 0:
raise ValueError("No data remains within the given analysis_period filter.")
return Wind.from_dataframe(
df,
wind_speed_column="Wind Speed (m/s)",
wind_direction_column="Wind Direction (degrees)",
height_above_ground=self.height_above_ground,
source=f"{self.source} (filtered to {describe_analysis_period(analysis_period)})",
)
def filter_by_boolean_mask(self, mask: tuple[bool]) -> "Wind":
"""Filter the current object by a boolean mask.
Returns:
Wind:
A dataset describing historic wind speed and direction relationship.
"""
if len(mask) != len(self.ws):
raise ValueError(
"The length of the boolean mask must match the length of the current object."
)
if sum(mask) == len(self.ws):
return self
if len(self.ws.values[mask]) == 0:
raise ValueError("No data remains within the given boolean filters.")
return Wind(
wind_speeds=self.ws.values[mask].tolist(),
wind_directions=self.wd.values[mask].tolist(),
datetimes=self.datetimes[mask],
height_above_ground=self.height_above_ground,
source=f"{self.source} (filtered)",
)
def filter_by_time(
self,
months: tuple[float] = tuple(range(1, 13, 1)), # type: ignore
hours: tuple[int] = tuple(range(0, 24, 1)), # type: ignore
years: tuple[int] = tuple(range(1900, 2100, 1)),
) -> "Wind":
"""Filter the current object by month and hour.
Args:
months (list[int], optional):
A list of months. Defaults to all months.
hours (list[int], optional):
A list of hours. Defaults to all hours.
years (tuple[int], optional):
A list of years to include. Default to all years since 1900.
Returns:
Wind:
A dataset describing historic wind speed and direction relationship.
"""
mask = np.all(
[
self.datetimes.year.isin(years),
self.datetimes.month.isin(months),
self.datetimes.hour.isin(hours),
],
axis=0,
).flatten()
if mask.sum() == len(self.ws):
return self
if len(self.ws.iloc[mask]) == 0:
raise ValueError("No data remains within the given time filters.")
filtered_by = []
if len(years) != len(range(1900, 2100, 1)):
filtered_by.append("year")
if len(months) != len(range(1, 13, 1)):
filtered_by.append("month")
if len(hours) != len(range(0, 24, 1)):
filtered_by.append("hour")
filtered_by = ", ".join(filtered_by)
return Wind(
wind_speeds=self.ws.values[mask].tolist(),
wind_directions=self.wd.values[mask].tolist(),
datetimes=self.datetimes[mask],
height_above_ground=self.height_above_ground,
source=f"{self.source} (filtered {filtered_by})",
)
def filter_by_direction(
self, left_angle: float = 0, right_angle: float = 360, inclusive: bool = True
) -> "Wind":
"""Filter the current object by wind direction, based on the angle as
observed from a location.
Args:
left_angle (float):
The left-most angle, to the left of which wind speeds and
directions will be removed.
right_angle (float):
The right-most angle, to the right of which wind speeds and
directions will be removed.
inclusive (bool, optional):
Include values that are exactly the left or right angle values.
Return:
Wind:
A Wind object!
"""
if left_angle < 0 or right_angle > 360:
raise ValueError("Angle limits must be between 0 and 360 degrees.")
if left_angle == 0 and right_angle == 360:
return self
if (left_angle == right_angle) or (left_angle == 360 and right_angle == 0):
raise ValueError("Angle limits cannot be identical.")
if left_angle > right_angle:
if inclusive:
mask = (self.wd >= left_angle) | (self.wd <= right_angle)
else:
mask = (self.wd > left_angle) | (self.wd < right_angle)
else:
if inclusive:
mask = (self.wd >= left_angle) & (self.wd <= right_angle)
else:
mask = (self.wd > left_angle) & (self.wd < right_angle)
if len(self.ws.values[mask]) == 0:
raise ValueError("No data remains within the given direction filter.")
return Wind(
wind_speeds=self.ws.values[mask].tolist(),
wind_directions=self.wd.values[mask].tolist(),
datetimes=self.datetimes[mask],
height_above_ground=self.height_above_ground,
source=f"{self.source} filtered by direction ({left_angle}-{right_angle})",
)
def filter_by_speed(
self, min_speed: float = 0, max_speed: float = 999, inclusive: bool = True
) -> "Wind":
"""Filter the current object by wind speed, based on given low-high limit values.
Args:
min_speed (float):
The lowest speed to include. Values below this wil be removed.
max_speed (float):
The highest speed to include. Values above this wil be removed.
inclusive (bool, optional):
Include values that are exactly the left or right angle values.
Return:
Wind:
A Wind object!
"""
if min_speed < 0:
raise ValueError("min_speed cannot be negative.")
if max_speed <= min_speed:
raise ValueError("min_speed must be less than max_speed.")
if min_speed == 0 and max_speed == 999:
return self
if inclusive:
mask = (self.ws >= min_speed) & (self.ws <= max_speed)
else:
mask = (self.ws > min_speed) & (self.ws < max_speed)
if len(self.ws.values[mask]) == 0:
raise ValueError("No data remains within the given speed filter.")
return Wind(
wind_speeds=self.ws.values[mask].tolist(),
wind_directions=self.wd.values[mask].tolist(),
datetimes=self.datetimes[mask],
height_above_ground=self.height_above_ground,
source=f"{self.source} filtered by speed ({min_speed}-{max_speed})",
)
@staticmethod
def _direction_bin_edges(directions: int) -> list[float]:
"""Calculate the bin edges for a given number of directions.
Args:
directions (int):
The number of directions to calculate bin edges for.
Returns:
list[float]:
A list of bin edges.
"""
if directions <= 2:
raise ValueError("directions must be > 2.")
direction_bin_edges = np.unique(
((np.linspace(0, 360, directions + 1) - ((360 / directions) / 2)) % 360).tolist()
+ [0, 360]
)
return direction_bin_edges
def process_direction_data(self, directions: int) -> tuple[pd.Series, list[tuple[float]]]:
"""Process wind direction data for this object.
Args:
directions (int):
The number of directions to calculate bin edges for.
Returns:
tuple[pd.Series, list[tuple[float]]]:
- A pd.Series containing the processed categorical data.
- A list of tuples containing the bin edges.
"""
# bin the wind directions
categories = pd.cut(
self.wd,
bins=Wind._direction_bin_edges(directions),
include_lowest=True,
)
x = [tuple([i.left, i.right]) for i in categories.cat.categories.tolist()]
bin_tuples = x[1:-1]
bin_tuples.append((bin_tuples[-1][1], bin_tuples[0][0]))
mapper = dict(
zip(
*[
categories.cat.categories.tolist(),
[bin_tuples[-1]] + bin_tuples,
]
)
)
# modify bin tuples and create mapping