-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathcommon.py
More file actions
1890 lines (1560 loc) · 62.1 KB
/
Copy pathcommon.py
File metadata and controls
1890 lines (1560 loc) · 62.1 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
#!/usr/bin/env python3
"""
Linopy common module.
This module contains commonly used functions.
"""
from __future__ import annotations
import operator
import os
from collections.abc import Callable, Generator, Hashable, Iterable, Mapping, Sequence
from functools import cached_property, partial, reduce, wraps
from pathlib import Path
from typing import TYPE_CHECKING, Any, Generic, TypeVar, overload
from warnings import warn
import numpy as np
import pandas as pd
import polars as pl
from numpy import arange, nan, signedinteger
from polars.datatypes import DataTypeClass
from xarray import Coordinates, DataArray, Dataset, apply_ufunc, broadcast
from xarray import align as xr_align
from xarray.core import dtypes, indexing
from xarray.core.coordinates import CoordinateValidationError
from xarray.core.types import JoinOptions, T_Alignable
from xarray.namedarray.utils import is_dict_like
from linopy.config import options
from linopy.constants import (
HELPER_DIMS,
SIGNS,
SIGNS_alternative,
SIGNS_pretty,
sign_replace_dict,
)
from linopy.types import (
CoordsLike,
DimsLike,
SideLike,
)
if TYPE_CHECKING:
from linopy.constraints import ConstraintBase
from linopy.expressions import LinearExpression, QuadraticExpression
from linopy.variables import Variable
def set_int_index(series: pd.Series) -> pd.Series:
"""
Convert string index to int index.
"""
if not series.empty and not pd.api.types.is_integer_dtype(series.index):
cutoff = count_initial_letters(str(series.index[0]))
try:
series.index = series.index.str[cutoff:].astype(int)
except ValueError:
series.index = series.index.str.replace(".*#", "", regex=True).astype(int)
return series
def maybe_replace_sign(sign: str) -> str:
"""
Replace the sign with an alternative sign if available.
Parameters
----------
sign (str): The sign to be replaced.
Returns
-------
str: The replaced sign.
Raises
------
ValueError: If the sign is not in the available signs.
"""
if sign in SIGNS_alternative:
return sign_replace_dict[sign]
elif sign in SIGNS:
return sign
else:
raise ValueError(f"Sign {sign} not in {SIGNS} or {SIGNS_alternative}")
def maybe_replace_signs(sign: DataArray) -> DataArray:
"""
Replace signs with alternative signs if available.
Parameters
----------
sign (np.ndarray): The signs to be replaced.
Returns
-------
np.ndarray: The replaced signs.
"""
func = np.vectorize(maybe_replace_sign)
return apply_ufunc(func, sign, dask="parallelized", output_dtypes=[sign.dtype])
def format_string_as_variable_name(name: Hashable) -> str:
"""
Format a string to a valid python variable name.
Parameters
----------
name (str): The name to be converted.
Returns
-------
str: The formatted name.
"""
return str(name).replace(" ", "_").replace("-", "_")
def get_from_iterable(lst: DimsLike | None, index: int) -> Any | None:
"""
Returns the element at the specified index of the list, or None if the index
is out of bounds.
"""
if lst is None:
return None
if isinstance(lst, Sequence | Iterable):
lst = list(lst)
else:
lst = [lst]
return lst[index] if 0 <= index < len(lst) else None
def pandas_to_dataarray(
arr: pd.DataFrame | pd.Series,
coords: CoordsLike | None = None,
dims: DimsLike | None = None,
**kwargs: Any,
) -> DataArray:
"""
Convert a pandas DataFrame or Series to a DataArray.
As pandas objects already have a concept of coordinates, the
coordinates (index, columns) will be used as coordinates for the DataArray.
Solely the dimension names can be specified.
Parameters
----------
arr (Union[pd.DataFrame, pd.Series]):
The input pandas DataFrame or Series.
coords (Union[dict, list, None]):
The coordinates for the DataArray. If None, default coordinates will be used.
dims (Union[list, None]):
The dimensions for the DataArray. If None, the column names of the DataFrame or the index names of the Series will be used.
**kwargs:
Additional keyword arguments to be passed to the DataArray constructor.
Returns
-------
DataArray:
The converted DataArray.
"""
dims = [
axis.name or get_from_iterable(dims, i) or f"dim_{i}"
for i, axis in enumerate(arr.axes)
]
return DataArray(arr, coords=None, dims=dims, **kwargs)
def numpy_to_dataarray(
arr: np.ndarray,
coords: CoordsLike | None = None,
dims: DimsLike | None = None,
**kwargs: Any,
) -> DataArray:
"""
Convert a numpy array to a DataArray.
Parameters
----------
arr (np.ndarray):
The input numpy array.
coords (Union[dict, list, None]):
The coordinates for the DataArray. If None, default coordinates will be used.
dims (Union[list, None]):
The dimensions for the DataArray. If None, the dimensions will be automatically generated.
**kwargs:
Additional keyword arguments to be passed to the DataArray constructor.
Returns
-------
DataArray:
The converted DataArray.
"""
# fallback case for zero dim arrays
if arr.ndim == 0:
if dims is None and is_dict_like(coords):
dims = list(coords.keys())
return DataArray(arr.item(), coords=coords, dims=dims, **kwargs)
if isinstance(dims, Iterable | Sequence):
dims = list(dims)
elif dims is not None:
dims = [dims]
if dims is not None and len(dims):
dims = [get_from_iterable(dims, i) or f"dim_{i}" for i in range(arr.ndim)]
if dims is not None and len(dims) and coords is not None:
if isinstance(coords, list):
coords = dict(zip(dims, coords[: arr.ndim]))
elif is_dict_like(coords):
coords = {k: v for k, v in coords.items() if k in dims}
return DataArray(arr, coords=coords, dims=dims, **kwargs)
def _as_dataarray_lax(
arr: Any,
coords: CoordsLike | None = None,
dims: DimsLike | None = None,
**kwargs: Any,
) -> DataArray:
"""
Type-dispatched DataArray conversion without any coords validation.
This is the conversion primitive used by ``as_dataarray``: it picks the
right constructor for each supported input type but does not check the
result against ``coords``. Callers that need ``coords`` to govern the
output (dim order, shared-dim values, missing-dim expansion) should use
``as_dataarray`` instead.
"""
if isinstance(arr, pd.Series | pd.DataFrame):
arr = pandas_to_dataarray(arr, coords=coords, dims=dims, **kwargs)
elif isinstance(arr, np.ndarray):
arr = numpy_to_dataarray(arr, coords=coords, dims=dims, **kwargs)
elif isinstance(arr, pl.Series):
arr = numpy_to_dataarray(arr.to_numpy(), coords=coords, dims=dims, **kwargs)
elif isinstance(arr, np.number | int | float | str | bool | list):
if isinstance(arr, np.number):
arr = float(arr)
if dims is None:
if isinstance(coords, Coordinates):
dims = coords.dims
elif is_dict_like(coords) and np.ndim(arr) == 0:
dims = list(coords.keys())
arr = DataArray(arr, coords=coords, dims=dims, **kwargs)
elif not isinstance(arr, DataArray):
supported_types = [
np.number,
str,
bool,
list,
pd.Series,
pd.DataFrame,
np.ndarray,
DataArray,
pl.Series,
]
supported_types_str = ", ".join([t.__name__ for t in supported_types])
raise TypeError(
f"Unsupported type of arr: {type(arr)}. Supported types are: {supported_types_str}"
)
arr = fill_missing_coords(arr)
return arr
def as_dataarray(
arr: Any,
coords: CoordsLike | None = None,
dims: DimsLike | None = None,
**kwargs: Any,
) -> DataArray:
"""
Convert ``arr`` to a DataArray and broadcast it against ``coords``.
When ``coords`` carries named dimensions, the result is aligned with
those coords:
- positional inputs (numpy, polars, unnamed pandas, scalar) are labeled
with the coord dim names by position;
- for every dim shared between ``arr`` and ``coords``, same-values-
different-order coordinates are reindexed to ``coords`` order;
- dims present in ``coords`` but not in ``arr`` are expanded to the
``coords`` shape;
- the result is transposed to ``coords`` order.
Dimensions present in ``arr`` but not in ``coords`` are preserved so
standard xarray broadcasting keeps working. Disagreeing coord values
on a shared dim (i.e. value sets that are not equal as sets) are
passed through unchanged: downstream xarray alignment decides how to
combine them. To enforce that ``arr.dims`` ⊆ ``coords.dims`` and that
shared coord values match, use ``validate_alignment`` (called
automatically for ``lower``, ``upper``, and ``mask`` in
:meth:`~linopy.model.Model.add_variables` and for ``mask`` in
:meth:`~linopy.model.Model.add_constraints`).
Parameters
----------
arr
Input scalar / list / numpy / polars / pandas / DataArray.
coords
Mapping of dim name → coord values, or a sequence of ``pd.Index``
/ unnamed sequences. ``None`` falls back to xarray's default
labeling (no broadcasting).
dims
Optional dim-names hint, used for positional inputs and to bias
pandas-axis interpretation.
**kwargs
Forwarded to the underlying DataArray construction.
Returns
-------
DataArray
Broadcast against ``coords`` (extra dims preserved).
"""
if coords is None:
return _as_dataarray_lax(arr, coords, dims, **kwargs)
if isinstance(coords, list | tuple) and any(isinstance(c, tuple) for c in coords):
# xarray reads bare `(a, b)` as `(dim_name, values)`; normalize so a
# coords entry passed as a tuple behaves identically to a list.
coords = [list(c) if isinstance(c, tuple) else c for c in coords]
expected = _coords_to_dict(coords, dims=dims)
if not expected:
return _as_dataarray_lax(arr, coords, dims, **kwargs)
if isinstance(arr, pd.Series | pd.DataFrame):
converted = _named_pandas_to_dataarray(arr)
if converted is not None:
arr = converted
if not isinstance(arr, DataArray):
# numpy/polars/unnamed-pandas inputs are positional — their only
# meaningful information is the values; any axis labels are
# auto-generated. Default dims to coords' keys so the lax conversion
# labels axes correctly (instead of dim_0/dim_1), then re-assign
# coords from expected so positional inputs align to coords by
# position. A shape mismatch surfaces here as a clear xarray
# "conflicting sizes" error rather than a confusing
# "coordinates do not match" further down.
if dims is None:
dims = list(expected)
arr = _as_dataarray_lax(arr, coords, dims=dims, **kwargs)
# Skip MultiIndex dims — re-assigning a PandasMultiIndex coord emits
# a FutureWarning and isn't needed (the lax pass already used it).
arr = arr.assign_coords(
{
d: expected[d]
for d in arr.dims
if d in expected and not isinstance(arr.indexes.get(d), pd.MultiIndex)
}
)
for dim, coord_values in expected.items():
if dim not in arr.dims:
continue
if isinstance(arr.indexes.get(dim), pd.MultiIndex):
continue
expected_idx = (
coord_values
if isinstance(coord_values, pd.Index)
else pd.Index(coord_values)
)
actual_idx = arr.coords[dim].to_index()
if actual_idx.equals(expected_idx):
continue
# Same values, different order → reindex to match expected order.
# Different value sets are left alone: downstream xarray alignment
# (e.g. xr.align in arithmetic) handles them. Callers needing strict
# value matching (add_variables / add_constraints) should use
# ``validate_alignment`` after this call.
if len(actual_idx) == len(expected_idx) and set(actual_idx) == set(
expected_idx
):
arr = arr.reindex({dim: expected_idx})
# expand_dims prepends new dimensions and their coordinate variables;
# the subsequent transpose restores coords order. Both are no-ops when
# the array already matches. Reconstruct so the DataArray's coords
# iteration order also follows coords (a Dataset built from this picks
# up its dim order from coord insertion).
expand = {k: v for k, v in expected.items() if k not in arr.dims}
if expand:
arr = arr.expand_dims(expand)
target_dims = tuple(d for d in expected if d in arr.dims) + tuple(
d for d in arr.dims if d not in expected
)
arr = arr.transpose(*target_dims)
coord_order = [c for c in target_dims if c in arr.coords] + [
c for c in arr.coords if c not in target_dims
]
if list(arr.coords) != coord_order:
arr = DataArray(
arr.variable,
coords={c: arr.coords[c] for c in coord_order},
name=arr.name,
)
return arr
def validate_alignment(
arr: DataArray,
coords: CoordsLike | None,
dims: DimsLike | None = None,
*,
label: str | None = None,
) -> None:
"""
Raise ``ValueError`` if ``arr`` is incompatible with ``coords``.
``arr`` is compatible with ``coords`` when both of the following hold:
- every dim in ``arr.dims`` is also a dim in ``coords`` (no extras);
- for every dim shared between ``arr`` and ``coords``, the coord
values are equal.
``dims`` mirrors the ``dims`` argument of ``as_dataarray``: it names
unnamed entries in a sequence-form ``coords`` by position, so
``coords=[[1, 2, 3]], dims=["x"]`` is enforced the same way as
``coords={"x": [1, 2, 3]}``.
``label`` names the argument in error messages (e.g. ``"lower bound"``).
No-op when ``coords`` is ``None`` or carries no named dimensions.
"""
if coords is None:
return
expected = _coords_to_dict(coords, dims=dims)
if not expected:
return
subject = label or "Value"
expected_dims = set(expected)
extra = set(arr.dims) - expected_dims
if extra:
raise ValueError(
f"{subject} has dimension(s) {sorted(extra, key=str)} not declared in coords "
f"({sorted(expected_dims, key=str)}). Add them to coords or remove them from "
f"{subject.lower()}."
)
for dim, coord_values in expected.items():
if dim not in arr.dims:
continue
expected_is_mi = isinstance(coord_values, pd.MultiIndex)
actual_is_mi = isinstance(arr.indexes.get(dim), pd.MultiIndex)
if expected_is_mi or actual_is_mi:
if expected_is_mi and actual_is_mi:
if not arr.indexes[dim].equals(coord_values):
raise ValueError(
f"{subject}: MultiIndex for dimension {dim!r} does not "
f"match coords."
)
continue
expected_idx = (
coord_values
if isinstance(coord_values, pd.Index)
else pd.Index(coord_values)
)
actual_idx = arr.coords[dim].to_index()
if not actual_idx.equals(expected_idx):
raise ValueError(
f"{subject}: coordinate values for dimension {dim!r} do not match "
f"coords — expected {expected_idx.tolist()}, got "
f"{actual_idx.tolist()}."
)
def align_to_coords(
value: Any,
coords: CoordsLike | None,
*,
label: str,
**kwargs: Any,
) -> DataArray:
"""
Convert ``value`` with :func:`as_dataarray` and enforce the coords contract.
Used by :meth:`~linopy.model.Model.add_variables` for ``lower``, ``upper``,
and ``mask``, and by :meth:`~linopy.model.Model.add_constraints` for
``mask``. Raises :class:`ValueError` with a message that names ``label``
when ``value`` cannot be aligned to ``coords``. Coords-parsing errors
propagate unchanged.
"""
if coords is not None:
_coords_to_dict(coords, dims=kwargs.get("dims"))
try:
da = as_dataarray(value, coords, **kwargs)
except TypeError as err:
raise TypeError(f"{label} could not be aligned to coords: {err}") from err
except (ValueError, CoordinateValidationError) as err:
raise ValueError(f"{label} could not be aligned to coords: {err}") from err
validate_alignment(da, coords, dims=kwargs.get("dims"), label=label)
return da
def _coords_to_dict(
coords: Sequence[Sequence | pd.Index] | Mapping,
dims: DimsLike | None = None,
) -> dict[Hashable, Any]:
"""
Normalize coords to a dict mapping dim names to coordinate values.
Container forms:
- ``xarray.Coordinates`` → kept dim entries only (MultiIndex level
coords dropped).
- ``Mapping`` → returned as a shallow ``dict`` copy.
- sequence-of-entries → each entry handled per the rules below.
Sequence-entry rules (``i`` is the position in ``coords``, ``dims[i]``
is the matching entry in ``dims`` when one exists). An entry is
*unlabeled* if it's an unnamed ``pd.Index`` or a bare ``list`` /
``tuple`` / ``range`` / ``ndarray``.
+---------------------------------+-----------------------+-----------+
| Entry | Naming source | Outcome |
+=================================+=======================+===========+
| ``pd.Index`` with ``.name`` | ``.name`` | accepted |
+---------------------------------+-----------------------+-----------+
| unlabeled entry | ``dims[i]`` | accepted |
+---------------------------------+-----------------------+-----------+
| unlabeled entry | — (no ``dims[i]``) | skipped |
| | | — xarray |
| | | assigns |
| | | ``dim_0`` |
| | | etc. |
+---------------------------------+-----------------------+-----------+
| ``pd.MultiIndex`` with ``.name``| ``.name`` | accepted |
+---------------------------------+-----------------------+-----------+
| ``pd.MultiIndex`` w/o ``.name`` | ``dims[i]`` | accepted |
| | | (named on |
| | | a copy) |
+---------------------------------+-----------------------+-----------+
| ``pd.MultiIndex`` w/o ``.name`` | — (no ``dims[i]``) | TypeError |
+---------------------------------+-----------------------+-----------+
| anything else (e.g. DataArray) | — | TypeError |
+---------------------------------+-----------------------+-----------+
"""
if isinstance(coords, Coordinates):
# Coordinates iterates over every coord variable, including
# MultiIndex level coords. Keep only the entries that are dims.
return {d: coords[d] for d in coords.dims if d in coords}
if isinstance(coords, Mapping):
return dict(coords)
dim_names: list[Any] | None = None
if dims is not None:
dim_names = list(dims) if isinstance(dims, list | tuple) else [dims]
result: dict[Hashable, Any] = {}
for i, c in enumerate(coords):
if isinstance(c, pd.MultiIndex):
name = c.name or (
dim_names[i] if dim_names and i < len(dim_names) else None
)
if name is None:
raise TypeError(
"MultiIndex coords entries must have .name set so "
"xarray can use it as the dimension name. Set it via "
"`idx.name = 'my_dim'`, or pass `dims=[...]` to name "
"entries by position."
)
if c.name is None:
c = c.copy()
c.name = name
result[name] = c
elif isinstance(c, pd.Index):
name = (
c.name
if c.name
else (dim_names[i] if dim_names and i < len(dim_names) else None)
)
if name is not None:
result[name] = c
elif isinstance(c, list | tuple | range | np.ndarray):
if dim_names and i < len(dim_names):
result[dim_names[i]] = pd.Index(c, name=dim_names[i])
else:
raise TypeError(
f"coords entries must be pd.Index or an unnamed sequence "
f"(list / tuple / range / numpy.ndarray); got "
f"{type(c).__name__}. For an xarray DataArray coord, pass "
f"`variable.indexes[<dim>]` (a pd.Index) instead."
)
return result
def _named_pandas_to_dataarray(arr: pd.Series | pd.DataFrame) -> DataArray | None:
"""
Convert a pandas Series or DataFrame with fully named axes to a DataArray.
Returns ``None`` if any axis (or MultiIndex level) is unnamed or
non-string, so the caller can fall back to ``as_dataarray``.
"""
names = list(arr.index.names)
if isinstance(arr, pd.DataFrame):
names += list(arr.columns.names)
if any(not isinstance(n, str) for n in names):
return None
if isinstance(arr, pd.DataFrame):
if isinstance(arr.index, pd.MultiIndex) or isinstance(
arr.columns, pd.MultiIndex
):
arr = arr.stack(list(range(arr.columns.nlevels)), future_stack=True)
return arr.to_xarray()
return DataArray(arr)
return arr.to_xarray()
# TODO: rename to to_pandas_dataframe
def to_dataframe(
ds: Dataset,
mask_func: Callable[[dict[Hashable, np.ndarray]], pd.Series] | None = None,
) -> pd.DataFrame:
"""
Convert an xarray Dataset to a pandas DataFrame.
This is an memory efficient alternative implementation to the built-in `to_dataframe` method, which
does not create a multi-indexed DataFrame.
Parameters
----------
ds : xarray.Dataset
Dataset to convert to a DataFrame.
"""
data = broadcast(ds)[0]
datadict = {k: v.values.reshape(-1) for k, v in data.items()}
if mask_func is not None:
mask = mask_func(datadict)
for k, v in datadict.items():
datadict[k] = v[mask]
return pd.DataFrame(datadict, copy=False)
def check_has_nulls(df: pd.DataFrame, name: str) -> None:
any_nan = df.isna().any()
if any_nan.any():
fields = ", ".join(df.columns[any_nan].to_list())
raise ValueError(f"Fields {name} contains nan's in field(s) {fields}")
def infer_schema_polars(ds: Dataset) -> dict[str, DataTypeClass]:
"""
Infer the polars data schema from a xarray dataset.
Args:
----
ds (polars.DataFrame): The Polars DataFrame for which to infer the schema.
Returns:
-------
dict: A dictionary mapping column names to their corresponding Polars data types.
"""
schema: dict[str, DataTypeClass] = {}
np_major_version = int(np.__version__.split(".")[0])
use_int32 = os.name == "nt" and np_major_version < 2
for name, array in ds.items():
name = str(name)
if np.issubdtype(array.dtype, np.integer):
schema[name] = pl.Int32 if use_int32 else pl.Int64
elif np.issubdtype(array.dtype, np.floating):
schema[name] = pl.Float64
elif np.issubdtype(array.dtype, np.bool_):
schema[name] = pl.Boolean
elif np.issubdtype(array.dtype, np.object_):
schema[name] = pl.Object
else:
schema[name] = pl.Utf8
return schema
def to_polars(ds: Dataset, **kwargs: Any) -> pl.DataFrame:
"""
Convert an xarray Dataset to a polars DataFrame.
This is an memory efficient alternative implementation
of `to_dataframe`.
Parameters
----------
ds : xarray.Dataset
Dataset to convert to a DataFrame.
kwargs : dict
Additional keyword arguments to be passed to the
DataFrame constructor.
"""
data = broadcast(ds)[0]
return pl.DataFrame({k: v.values.reshape(-1) for k, v in data.items()}, **kwargs)
def check_has_nulls_polars(df: pl.DataFrame, name: str = "") -> None:
"""
Checks if the given DataFrame contains any null or NaN values and raises a ValueError if it does.
Args:
----
df (pl.DataFrame): The DataFrame to check for null or NaN values.
name (str): The name of the data container being checked.
Raises:
------
ValueError: If the DataFrame contains null or NaN values,
a ValueError is raised with a message indicating the name of the constraint and the fields containing null/NaN values.
"""
# Check for null values in all columns
has_nulls = df.select(pl.col("*").is_null().any())
null_columns = [col for col in has_nulls.columns if has_nulls[col][0]]
# Check for NaN values only in numeric columns (avoid enum/categorical columns)
numeric_cols = [
col for col, dtype in zip(df.columns, df.dtypes) if dtype.is_numeric()
]
nan_columns = []
if numeric_cols:
has_nans = df.select(pl.col(numeric_cols).is_nan().any())
nan_columns = [col for col in has_nans.columns if has_nans[col][0]]
invalid_columns = list(set(null_columns + nan_columns))
if invalid_columns:
raise ValueError(f"{name} contains nan's in field(s) {invalid_columns}")
def filter_nulls_polars(df: pl.DataFrame) -> pl.DataFrame:
"""
Filter out rows containing "empty" values from a polars DataFrame.
Args:
----
df (pl.DataFrame): The DataFrame to filter.
Returns:
-------
pl.DataFrame: The filtered DataFrame.
"""
cond = []
varcols = [c for c in df.columns if c.startswith("vars")]
if varcols:
cond.append(reduce(operator.or_, [pl.col(c).ne(-1) for c in varcols]))
if "coeffs" in df.columns:
cond.append(pl.col("coeffs").ne(0))
if "labels" in df.columns:
cond.append(pl.col("labels").ne(-1))
cond = reduce(operator.and_, cond) # type: ignore[arg-type]
return df.filter(cond)
def group_terms_polars(df: pl.DataFrame) -> pl.DataFrame:
"""
Groups terms in a polars DataFrame.
Args:
----
df (pl.DataFrame): The input DataFrame containing the terms.
Returns:
-------
pl.DataFrame: The DataFrame with grouped terms.
"""
varcols = [c for c in df.columns if c.startswith("vars")]
agg_list = [pl.col("coeffs").sum().alias("coeffs")]
for col in set(df.columns) - set(["coeffs", "labels", *varcols]):
agg_list.append(pl.col(col).first().alias(col))
by = [c for c in ["labels"] + varcols if c in df.columns]
df = df.group_by(by, maintain_order=True).agg(agg_list)
return df
def maybe_group_terms_polars(df: pl.DataFrame) -> pl.DataFrame:
"""
Group terms only if there are duplicate (labels, vars) pairs.
This avoids the expensive group_by operation when terms already
reference distinct variables (e.g. ``x - y`` has ``_term=2`` but
no duplicates). When skipping, columns are reordered to match the
output of ``group_terms_polars``.
"""
varcols = [c for c in df.columns if c.startswith("vars")]
keys = [c for c in ["labels"] + varcols if c in df.columns]
key_count = df.select(pl.struct(keys).n_unique()).item()
if key_count < df.height:
return group_terms_polars(df)
# Match column order of group_terms (group-by keys, coeffs, rest)
rest = [c for c in df.columns if c not in keys and c != "coeffs"]
return df.select(keys + ["coeffs"] + rest)
def save_join(*dataarrays: DataArray, integer_dtype: bool = False) -> Dataset:
"""
Join multiple xarray Dataarray's to a Dataset and warn if coordinates are not equal.
"""
try:
arrs = xr_align(*dataarrays, join="exact")
except ValueError:
warn(
"Coordinates across variables not equal. Perform outer join.",
UserWarning,
)
arrs = xr_align(*dataarrays, join="outer")
if integer_dtype:
arrs = tuple([ds.fillna(-1).astype(int) for ds in arrs])
return Dataset({ds.name: ds for ds in arrs})
def assign_multiindex_safe(ds: Dataset, **fields: Any) -> Dataset:
"""
Assign a field to a xarray Dataset while being safe against warnings about multiindex corruption.
See https://github.com/PyPSA/linopy/issues/303 for more information
Parameters
----------
ds : Dataset
Dataset to assign the field to
keys : Union[str, List[str]]
Keys of the fields
to_assign : Union[List[DataArray], DataArray, Dataset]
New values added to the dataset
Returns
-------
Dataset
Merged dataset with the new field added
"""
remainders = list(set(ds) - set(fields))
return Dataset({**ds[remainders], **fields}, attrs=ds.attrs)
@overload
def fill_missing_coords(ds: DataArray, fill_helper_dims: bool = False) -> DataArray: ...
@overload
def fill_missing_coords(ds: Dataset, fill_helper_dims: bool = False) -> Dataset: ...
def fill_missing_coords(
ds: DataArray | Dataset, fill_helper_dims: bool = False
) -> Dataset | DataArray:
"""
Fill coordinates of a xarray Dataset or DataArray with integer coordinates.
This function fills in the integer coordinates for all dimensions of a
Dataset or DataArray that have no coordinates assigned yet.
Parameters
----------
ds : xarray.DataArray or xarray.Dataset
fill_helper_dims : bool, optional
Whether to fill in integer coordinates for helper dimensions, by default False.
"""
ds = ds.copy()
if not isinstance(ds, Dataset | DataArray):
raise TypeError(f"Expected xarray.DataArray or xarray.Dataset, got {type(ds)}.")
skip_dims = [] if fill_helper_dims else HELPER_DIMS
# Fill in missing integer coordinates
for dim in ds.dims:
if dim not in ds.coords and dim not in skip_dims:
ds.coords[dim] = arange(ds.sizes[dim])
return ds
T = TypeVar("T", Dataset, "Variable", "LinearExpression", "ConstraintBase")
@overload
def iterate_slices(
ds: Dataset,
slice_size: int | None = 10_000,
slice_dims: list | None = None,
) -> Generator[Dataset, None, None]: ...
@overload
def iterate_slices(
ds: Variable,
slice_size: int | None = 10_000,
slice_dims: list | None = None,
) -> Generator[Variable, None, None]: ...
@overload
def iterate_slices(
ds: LinearExpression,
slice_size: int | None = 10_000,
slice_dims: list | None = None,
) -> Generator[LinearExpression, None, None]: ...
@overload
def iterate_slices(
ds: ConstraintBase,
slice_size: int | None = 10_000,
slice_dims: list | None = None,
) -> Generator[ConstraintBase, None, None]: ...
def iterate_slices(
ds: T,
slice_size: int | None = 10_000,
slice_dims: list | None = None,
) -> Generator[T, None, None]:
"""
Generate slices of an xarray Dataset or DataArray with a specified soft maximum size.
The slicing is performed on the largest dimension of the input object.
If the maximum size is larger than the total size of the object, the function yields
the original object.
Parameters
----------
ds : xarray.Dataset or xarray.DataArray
The input xarray Dataset or DataArray to be sliced.
slice_size : int
The maximum number of elements in each slice. If the maximum size is too small to accommodate any slice,
the function splits the largest dimension.
slice_dims : list, optional
The dimensions to slice along. If None, all dimensions in `coord_dims` are used if
`coord_dims` is an attribute of the input object. Otherwise, all dimensions are used.
Yields
------
xarray.Dataset or xarray.DataArray
A slice of the input Dataset or DataArray.
"""
if slice_dims is None:
slice_dims = list(getattr(ds, "coord_dims", ds.dims))
if not set(slice_dims).issubset(ds.dims):
raise ValueError(
"Invalid slice dimensions. Must be a subset of the dataset dimensions."
)
# Calculate the total number of elements in the dataset
size = np.prod([ds.sizes[dim] for dim in ds.dims], dtype=int)
if slice_size is None or size <= slice_size:
yield ds
return
# number of slices
n_slices = max((size + slice_size - 1) // slice_size, 1)
# leading dimension (the dimension with the largest size)
sizes = {dim: ds.sizes[dim] for dim in slice_dims}
if not sizes:
yield ds
return
leading_dim = max(sizes, key=sizes.get) # type: ignore
size_of_leading_dim = ds.sizes[leading_dim]
if size_of_leading_dim < n_slices:
n_slices = size_of_leading_dim
chunk_size = (ds.sizes[leading_dim] + n_slices - 1) // n_slices
# Iterate over the Cartesian product of slice indices
for i in range(n_slices):
start = i * chunk_size
end = min(start + chunk_size, size_of_leading_dim)
slice_dict = {leading_dim: slice(start, end)}
yield ds.isel(slice_dict) # type: ignore[attr-defined]
def _remap(array: np.ndarray, mapping: np.ndarray) -> np.ndarray:
return mapping[array.ravel()].reshape(array.shape)
def count_initial_letters(word: str) -> int:
"""
Count the number of initial letters in a word.
"""
count = 0
for char in word:
if char.isalpha():
count += 1
else:
break
return count
def replace_by_map(ds: DataArray, mapping: np.ndarray) -> DataArray:
"""
Replace values in a DataArray by a one-dimensional mapping.