-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathvariables.py
More file actions
1671 lines (1391 loc) · 50.5 KB
/
variables.py
File metadata and controls
1671 lines (1391 loc) · 50.5 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
"""
Linopy variables module.
This module contains variable related definitions of the package.
"""
from __future__ import annotations
import functools
import logging
from collections.abc import Callable, Hashable, ItemsView, Iterator, Mapping
from dataclasses import dataclass
from types import NotImplementedType
from typing import (
TYPE_CHECKING,
Any,
cast,
overload,
)
from warnings import warn
import numpy as np
import pandas as pd
import polars as pl
from numpy import floating, int64, issubdtype, ndarray, str_
from pandas.core.frame import DataFrame
from xarray import DataArray, Dataset, broadcast
from xarray.core.coordinates import DatasetCoordinates
from xarray.core.indexes import Indexes
from xarray.core.utils import Frozen
import linopy.expressions as expressions
from linopy.common import (
LabelPositionIndex,
LocIndexer,
as_dataarray,
assign_multiindex_safe,
catch_datetime_type_error_and_re_raise,
check_has_nulls,
check_has_nulls_polars,
filter_nulls_polars,
format_string_as_variable_name,
generate_indices_for_printout,
get_dims_with_index_levels,
get_label_position,
has_optimized_model,
iterate_slices,
print_coord,
print_single_variable,
require_constant,
save_join,
set_int_index,
to_dataframe,
to_polars,
)
from linopy.config import options
from linopy.constants import HELPER_DIMS, TERM_DIM
from linopy.solver_capabilities import SolverFeature, solver_supports
from linopy.types import (
ConstantLike,
DimsLike,
ExpressionLike,
SideLike,
VariableLike,
)
if TYPE_CHECKING:
from linopy.constraints import AnonymousScalarConstraint, Constraint
from linopy.expressions import (
GenericExpression,
LinearExpression,
LinearExpressionGroupby,
QuadraticExpression,
ScalarLinearExpression,
)
from linopy.model import Model
logger = logging.getLogger(__name__)
FILL_VALUE = {"labels": -1, "lower": np.nan, "upper": np.nan}
def varwrap(
method: Callable, *default_args: Any, **new_default_kwargs: Any
) -> Callable:
@functools.wraps(method)
def _varwrap(var: Variable, *args: Any, **kwargs: Any) -> Variable:
for k, v in new_default_kwargs.items():
kwargs.setdefault(k, v)
return var.__class__(
method(var.data, *default_args, *args, **kwargs), var.model, var.name
)
_varwrap.__doc__ = (
f"Wrapper for the xarray {method.__qualname__} function for linopy.Variable"
)
if new_default_kwargs:
_varwrap.__doc__ += f" with default arguments: {new_default_kwargs}"
return _varwrap
def _var_unwrap(var: Variable | Dataset) -> Dataset:
return var.data if isinstance(var, Variable) else var
class Variable:
"""
Variable container for storing variable labels.
The Variable class is a subclass of xr.DataArray hence most xarray functions
can be applied to it. However most arithmetic operations are overwritten.
Like this one can easily combine variables into a linear expression.
Examples
--------
>>> from linopy import Model
>>> import pandas as pd
>>> m = Model()
>>> x = m.add_variables(pd.Series([0, 0]), 1, name="x")
>>> y = m.add_variables(4, pd.Series([8, 10]), name="y")
Add variable together:
>>> x + y # doctest: +SKIP
Linear Expression with 2 term(s):
----------------------------------
<BLANKLINE>
Dimensions: (dim_0: 2, _term: 2)
Coordinates:
* dim_0 (dim_0) int64 0 1
Dimensions without coordinates: _term
Data:
coeffs (dim_0, _term) int64 1 1 1 1
vars (dim_0, _term) int64 0 2 1 3
Multiply them with a coefficient:
>>> 3 * x # doctest: +SKIP
Linear Expression with 1 term(s):
----------------------------------
<BLANKLINE>
Dimensions: (dim_0: 2, _term: 1)
Coordinates:
* dim_0 (dim_0) int64 0 1
Dimensions without coordinates: _term
Data:
coeffs (dim_0, _term) int64 3 3
vars (dim_0, _term) int64 0 1
Further operations like taking the negative and subtracting are supported.
"""
__slots__ = ("_data", "_model")
__array_ufunc__ = None
__array_priority__ = 10000
__pandas_priority__ = 10000
_fill_value = FILL_VALUE
def __init__(
self, data: Dataset, model: Model, name: str, skip_broadcast: bool = False
) -> None:
"""
Initialize the Variable.
Parameters
----------
labels : xarray.Dataset
data of the variable.
model : linopy.Model
Underlying model.
"""
from linopy.model import Model
if not isinstance(data, Dataset):
raise ValueError(f"data must be a Dataset, got {type(data)}")
if not isinstance(model, Model):
raise ValueError(f"model must be a Model, got {type(model)}")
# check that `labels`, `lower` and `upper`, `sign` and `mask` are in data
for attr in ("labels", "lower", "upper"):
if attr not in data:
raise ValueError(f"missing '{attr}' in data")
data = data.assign_attrs(name=name)
if not skip_broadcast:
(data,) = broadcast(data)
for attr in ("lower", "upper"):
# convert to float, important for operations like "shift"
if not issubdtype(data[attr].dtype, floating):
data[attr].values = data[attr].values.astype(float)
if "label_range" not in data.attrs:
data.assign_attrs(label_range=(data.labels.min(), data.labels.max()))
if "sos_type" in data.attrs or "sos_dim" in data.attrs:
if (sos_type := data.attrs.get("sos_type")) not in (1, 2):
raise ValueError(f"sos_type must be 1 or 2, got {sos_type}")
if (sos_dim := data.attrs.get("sos_dim")) not in data.dims:
raise ValueError(
f"sos_dim must name a variable dimension, got {sos_dim}"
)
self._data = data
self._model = model
def __getitem__(
self, selector: list[int] | int | slice | tuple[int64, str_]
) -> Variable | ScalarVariable:
# return selected Variable
data = Dataset({k: self.data[k][selector] for k in self.data}, attrs=self.attrs)
return self.__class__(data, self.model, self.name)
@property
def attrs(self) -> dict[str, Hashable]:
"""
Get the attributes of the variable.
"""
return self.data.attrs
@property
def coords(self) -> DatasetCoordinates:
"""
Get the coordinates of the variable.
"""
return self.data.coords
@property
def indexes(self) -> Indexes:
"""
Get the indexes of the variable.
"""
return self.data.indexes
@property
def sizes(self) -> Frozen:
"""
Get the sizes of the variable.
"""
return self.data.sizes
@property
def shape(self) -> tuple[int, ...]:
"""
Get the shape of the variable.
"""
return self.labels.shape
@property
def size(self) -> int:
"""
Get the size of the variable.
"""
return self.labels.size
@property
def dims(self) -> tuple[Hashable, ...]:
"""
Get the dimensions of the variable.
"""
return self.labels.dims
@property
def ndim(self) -> int:
"""
Get the number of dimensions of the variable.
"""
return self.labels.ndim
@property
def at(self) -> AtIndexer:
"""
Access a single value of the variable.
This method is a wrapper around the `__getitem__` method and allows
to access a single value of the variable.
Examples
--------
>>> from linopy import Model
>>> import pandas as pd
>>> m = Model()
>>> x = m.add_variables(pd.Series([0, 0]), 1, name="x")
>>> x.at[0]
ScalarVariable: x[0]
"""
return AtIndexer(self)
@property
def loc(self) -> LocIndexer:
return LocIndexer(self)
def to_pandas(self) -> pd.Series:
return self.labels.to_pandas()
@catch_datetime_type_error_and_re_raise
def to_linexpr(
self,
coefficient: ConstantLike = 1,
) -> expressions.LinearExpression:
"""
Create a linear expression from the variables.
Parameters
----------
coefficient : array-like, optional
Coefficient for the linear expression. This can be a numeric value, numpy array,
pandas series/dataframe or a DataArray. Default is 1.
Returns
-------
linopy.LinearExpression
Linear expression with the variables and coefficients.
"""
coefficient = as_dataarray(coefficient, coords=self.coords, dims=self.dims)
ds = Dataset({"coeffs": coefficient, "vars": self.labels}).expand_dims(
TERM_DIM, -1
)
return expressions.LinearExpression(ds, self.model)
def __repr__(self) -> str:
"""
Print the variable arrays.
"""
max_lines = options["display_max_rows"]
dims = list(self.sizes)
dim_names = self.coord_names
dim_sizes = list(self.sizes.values())
masked_entries = (~self.mask).sum().values
sos_type = self.attrs.get("sos_type")
sos_dim = self.attrs.get("sos_dim")
lines = []
if dims:
for indices in generate_indices_for_printout(dim_sizes, max_lines):
if indices is None:
lines.append("\t\t...")
else:
coord = [
self.data.indexes[dims[i]][ind] for i, ind in enumerate(indices)
]
label = self.labels.values[indices]
line = (
print_coord(coord)
+ ": "
+ print_single_variable(self.model, label)
)
lines.append(line)
# lines = align_lines_by_delimiter(lines, "∈")
shape_str = ", ".join(f"{d}: {s}" for d, s in zip(dim_names, dim_sizes))
mask_str = f" - {masked_entries} masked entries" if masked_entries else ""
sos_str = f" - sos{sos_type} on {sos_dim}" if sos_type and sos_dim else ""
lines.insert(
0,
f"Variable ({shape_str}){mask_str}{sos_str}\n"
f"{'-' * (len(shape_str) + len(mask_str) + len(sos_str) + 11)}",
)
else:
lines.append(
f"Variable\n{'-' * 8}\n{print_single_variable(self.model, self.labels.item())}"
)
return "\n".join(lines)
def print(self, display_max_rows: int = 20) -> None:
"""
Print the linear expression.
Parameters
----------
display_max_rows : int
Maximum number of rows to be displayed.
display_max_terms : int
Maximum number of terms to be displayed.
"""
with options as opts:
opts.set_value(display_max_rows=display_max_rows)
print(self)
def __neg__(self) -> LinearExpression:
"""
Calculate the negative of the variables (converts coefficients only).
"""
return self.to_linexpr(-1)
@overload
def __mul__(self, other: ConstantLike) -> LinearExpression: ...
@overload
def __mul__(self, other: ExpressionLike | VariableLike) -> QuadraticExpression: ...
def __mul__(self, other: SideLike) -> ExpressionLike:
"""
Multiply variables with a coefficient, variable, or expression.
"""
try:
if isinstance(other, Variable | ScalarVariable):
return self.to_linexpr() * other
return self.to_linexpr(other)
except TypeError:
return NotImplemented
def __rmul__(self, other: ConstantLike) -> LinearExpression:
"""
Right-multiply variables by a constant
"""
try:
return self * other
except TypeError:
return NotImplemented
def __pow__(self, other: int) -> QuadraticExpression:
"""
Power of the variables with a coefficient. The only coefficient allowed is 2.
"""
if not isinstance(other, int):
return NotImplemented
if other == 2:
expr = self.to_linexpr()
return cast(
"QuadraticExpression", expr._multiply_by_linear_expression(expr)
)
raise ValueError("Can only raise to the power of 2")
@overload
def __matmul__(self, other: ConstantLike) -> LinearExpression: ...
@overload
def __matmul__(
self, other: VariableLike | ExpressionLike
) -> QuadraticExpression: ...
def __matmul__(
self, other: ConstantLike | VariableLike | ExpressionLike
) -> LinearExpression | QuadraticExpression:
"""
Matrix multiplication of variables with a coefficient.
"""
return self.to_linexpr() @ other
def __div__(
self, other: float | int | LinearExpression | Variable
) -> LinearExpression:
"""
Divide variables with a coefficient.
"""
if isinstance(other, expressions.LinearExpression | Variable):
raise TypeError(
"unsupported operand type(s) for /: "
f"{type(self)} and {type(other)}. "
"Non-linear expressions are not yet supported."
)
return self.to_linexpr(1 / other)
def __truediv__(
self, coefficient: float | int | LinearExpression | Variable
) -> LinearExpression:
"""
True divide variables with a coefficient.
"""
try:
return self.__div__(coefficient)
except TypeError:
return NotImplemented
@overload
def __add__(
self, other: ConstantLike | Variable | ScalarLinearExpression
) -> LinearExpression: ...
@overload
def __add__(self, other: GenericExpression) -> GenericExpression: ...
def __add__(
self,
other: ConstantLike | Variable | ScalarLinearExpression | GenericExpression,
) -> LinearExpression | GenericExpression:
"""
Add variables to linear expressions or other variables.
"""
try:
return self.to_linexpr() + other
except TypeError:
return NotImplemented
def __radd__(self, other: ConstantLike) -> LinearExpression:
try:
return self + other
except TypeError:
return NotImplemented
@overload
def __sub__(
self, other: ConstantLike | Variable | ScalarLinearExpression
) -> LinearExpression: ...
@overload
def __sub__(self, other: GenericExpression) -> GenericExpression: ...
def __sub__(
self,
other: ConstantLike | Variable | ScalarLinearExpression | GenericExpression,
) -> LinearExpression | GenericExpression:
"""
Subtract linear expressions or other variables from the variables.
"""
try:
return self.to_linexpr() - other
except TypeError:
return NotImplemented
def __rsub__(self, other: ConstantLike) -> LinearExpression:
"""
Subtract linear expressions or other variables from the variables.
"""
try:
return self.to_linexpr(-1) + other
except TypeError:
return NotImplemented
def __le__(self, other: SideLike) -> Constraint:
return self.to_linexpr().__le__(other)
def __ge__(self, other: SideLike) -> Constraint:
return self.to_linexpr().__ge__(other)
def __eq__(self, other: SideLike) -> Constraint: # type: ignore
return self.to_linexpr().__eq__(other)
def __gt__(self, other: Any) -> NotImplementedType:
raise NotImplementedError(
"Inequalities only ever defined for >= rather than >."
)
def __lt__(self, other: Any) -> NotImplementedType:
raise NotImplementedError(
"Inequalities only ever defined for >= rather than >."
)
def __contains__(self, value: str) -> bool:
return self.data.__contains__(value)
def add(self, other: Variable) -> LinearExpression:
"""
Add variables to linear expressions or other variables.
"""
return self.__add__(other)
def sub(self, other: Variable) -> LinearExpression:
"""
Subtract linear expressions or other variables from the variables.
"""
return self.__sub__(other)
def mul(self, other: int) -> LinearExpression:
"""
Multiply variables with a coefficient.
"""
return self.__mul__(other)
def div(self, other: int) -> LinearExpression:
"""
Divide variables with a coefficient.
"""
return self.__div__(other)
def pow(self, other: int) -> QuadraticExpression:
"""
Power of the variables with a coefficient. The only coefficient allowed is 2.
"""
return self.__pow__(other)
def dot(self, other: ndarray | Variable) -> QuadraticExpression | LinearExpression:
"""
Generalized dot product for linopy and compatible objects. Like np.einsum if performs a
multiplaction of the two objects with a subsequent summation over common dimensions.
"""
return self.__matmul__(other)
def groupby(
self,
group: DataArray,
restore_coord_dims: bool | None = None,
) -> LinearExpressionGroupby:
"""
Returns a LinearExpressionGroupBy object for performing grouped
operations.
Docstring and arguments are borrowed from `xarray.Dataset.groupby`
Parameters
----------
group : str, DataArray or IndexVariable
Array whose unique values should be used to group this array. If a
string, must be the name of a variable contained in this dataset.
restore_coord_dims : bool, optional
If True, also restore the dimension order of multi-dimensional
coordinates.
Returns
-------
grouped
A `LinearExpressionGroupBy` containing the xarray groups and ensuring
the correct return type.
"""
return self.to_linexpr().groupby(
group=group, restore_coord_dims=restore_coord_dims
)
def rolling(
self,
dim: Mapping[Any, int] | None = None,
min_periods: int | None = None,
center: bool | Mapping[Any, bool] = False,
**window_kwargs: int,
) -> expressions.LinearExpressionRolling:
"""
Rolling window object.
Docstring and arguments are borrowed from `xarray.Dataset.rolling`
Parameters
----------
dim : dict, optional
Mapping from the dimension name to create the rolling iterator
along (e.g. `time`) to its moving window size.
min_periods : int, default: None
Minimum number of observations in window required to have a value
(otherwise result is NA). The default, None, is equivalent to
setting min_periods equal to the size of the window.
center : bool or mapping, default: False
Set the labels at the center of the window.
**window_kwargs : optional
The keyword arguments form of ``dim``.
One of dim or window_kwargs must be provided.
Returns
-------
linopy.expression.LinearExpressionRolling
"""
return self.to_linexpr().rolling(
dim=dim, min_periods=min_periods, center=center, **window_kwargs
)
def cumsum(
self,
dim: DimsLike | None = None,
*,
skipna: bool | None = None,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> expressions.LinearExpression:
"""
Cumulated sum along a given axis.
Docstring and arguments are borrowed from `xarray.Dataset.cumsum`
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``cumsum``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If "..." or None, will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``cumsum`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
linopy.expression.LinearExpression
"""
return self.to_linexpr().cumsum(
dim=dim, skipna=skipna, keep_attrs=keep_attrs, **kwargs
)
@property
def name(self) -> str:
"""
Return the name of the variable.
"""
return str(self.attrs["name"])
@property
def labels(self) -> DataArray:
"""
Return the labels of the variable.
"""
return self.data.labels
@property
def data(self) -> Dataset:
"""
Get the data of the variable.
"""
# Needed for compatibility with linopy.merge
return self._data
@property
def model(self) -> Model:
"""
Return the model of the variable.
"""
return self._model
@property
def type(self) -> str:
"""
Type of the variable.
Returns
-------
str
Type of the variable.
"""
if self.attrs["integer"]:
return "Integer Variable"
elif self.attrs["binary"]:
return "Binary Variable"
else:
return "Continuous Variable"
@property
def coord_dims(self) -> tuple[Hashable, ...]:
return tuple(k for k in self.dims if k not in HELPER_DIMS)
@property
def coord_sizes(self) -> dict[Hashable, int]:
return {k: v for k, v in self.sizes.items() if k not in HELPER_DIMS}
@property
def coord_names(self) -> list[str]:
"""
Get the names of the coordinates.
"""
return get_dims_with_index_levels(self.data, self.coord_dims)
@property
def range(self) -> tuple[int, int]:
"""
Return the range of the variable.
"""
return self.data.attrs["label_range"]
@property
def mask(self) -> DataArray:
"""
Get the mask of the variable.
The mask indicates on which coordinates the variable array is enabled
(True) and disabled (False).
Returns
-------
xr.DataArray
"""
return (self.labels != self._fill_value["labels"]).astype(bool)
@property
def upper(self) -> DataArray:
"""
Get the upper bounds of the variables.
The function raises an error in case no model is set as a
reference.
"""
return self.data.upper
@upper.setter
@require_constant
def upper(self, value: ConstantLike) -> None:
"""
Set the upper bounds of the variables.
The function raises an error in case no model is set as a
reference.
"""
value = DataArray(value).broadcast_like(self.upper)
if not set(value.dims).issubset(self.model.variables[self.name].dims):
raise ValueError("Cannot assign new dimensions to existing variable.")
self._data = assign_multiindex_safe(self.data, upper=value)
@property
def lower(self) -> DataArray:
"""
Get the lower bounds of the variables.
The function raises an error in case no model is set as a
reference.
"""
return self.data.lower
@lower.setter
@require_constant
def lower(self, value: ConstantLike) -> None:
"""
Set the lower bounds of the variables.
The function raises an error in case no model is set as a
reference.
"""
value = DataArray(value).broadcast_like(self.lower)
if not set(value.dims).issubset(self.model.variables[self.name].dims):
raise ValueError("Cannot assign new dimensions to existing variable.")
self._data = assign_multiindex_safe(self.data, lower=value)
@property
@has_optimized_model
def solution(self) -> DataArray:
"""
Get the optimal values of the variable.
The function raises an error in case no model is set as a
reference or the model is not optimized.
"""
return self.data["solution"]
@solution.setter
def solution(self, value: ConstantLike) -> None:
"""
Set the optimal values of the variable.
"""
value = DataArray(value).broadcast_like(self.labels)
self._data = assign_multiindex_safe(self.data, solution=value)
@property
@has_optimized_model
def sol(self) -> DataArray:
"""
Get the optimal values of the variable.
The function raises an error in case no model is set as a
reference or the model is not optimized.
"""
warn(
"`Variable.sol` is deprecated. Use `Variable.solution` instead.",
DeprecationWarning,
)
return self.solution
@has_optimized_model
def get_solver_attribute(self, attr: str) -> DataArray:
"""
Get an attribute from the solver model.
Parameters
----------
attr : str
Name of the attribute to get.
Returns
-------
xr.DataArray
"""
solver_model = self.model.solver_model
if not solver_supports(
self.model.solver_name, SolverFeature.SOLVER_ATTRIBUTE_ACCESS
):
raise NotImplementedError(
"Solver attribute getter only supports the Gurobi solver for now."
)
vals = pd.Series(
{v.VarName: getattr(v, attr) for v in solver_model.getVars()}, dtype=float
)
vals = set_int_index(vals)
idx = np.ravel(self.labels)
try:
values = vals[idx].to_numpy().reshape(self.labels.shape)
except KeyError:
values = vals.reindex(idx).to_numpy().reshape(self.labels.shape)
return DataArray(values, self.coords)
@property
def flat(self) -> DataFrame:
"""
Convert the variable to a pandas DataFrame.
The resulting DataFrame represents a long table format of the variable
with columns `labels`, `lower`, `upper` which are not masked.
Returns
-------
df : pandas.DataFrame
"""
ds = self.data
def mask_func(data: pd.DataFrame) -> pd.Series:
return data["labels"] != -1
df = to_dataframe(ds, mask_func=mask_func)
check_has_nulls(df, name=f"{self.type} {self.name}")
return df
def to_polars(self) -> pl.DataFrame:
"""
Convert all variables to a single polars DataFrame.
The resulting dataframe is a long format of the variables
with columns `labels`, `lower`, 'upper` and `mask`.
Returns
-------
pl.DataFrame
"""
df = to_polars(self.data)
df = filter_nulls_polars(df)
check_has_nulls_polars(df, name=f"{self.type} {self.name}")
return df
def sum(self, dim: str | None = None, **kwargs: Any) -> LinearExpression:
"""
Sum the variables over all or a subset of dimensions.
This stack all terms of the dimensions, that are summed over, together.
The function works exactly in the same way as ``LinearExpression.sum()``.
Parameters
----------
dim : str/list, optional
Dimension(s) to sum over. The default is None which results in all
dimensions.
dims : str/list, optional
Deprecated. Use ``dim`` instead.
Returns
-------
linopy.LinearExpression
Summed expression.
"""
if dim is None and "dims" in kwargs:
dim = kwargs.pop("dims")
warn(
"The `dims` argument is deprecated. Use `dim` instead.",
DeprecationWarning,
)
if kwargs:
raise ValueError(f"Unknown keyword argument(s): {kwargs}")
return self.to_linexpr().sum(dim)
def diff(self, dim: str, n: int = 1) -> LinearExpression:
"""
Calculate the n-th order discrete difference along the given dimension.
This function works exactly in the same way as ``LinearExpression.diff()``.
Parameters
----------
dim : str
Dimension over which to calculate the finite difference.
n : int, default: 1
The number of times values are differenced.
Returns
-------
linopy.LinearExpression
Finite difference expression.
"""
return self.to_linexpr().diff(dim, n)
def isnull(self) -> DataArray:
"""
Get a boolean mask with true values where there is missing values.
"""
return self.labels == -1
def where(
self,
cond: DataArray | list[bool],
other: ScalarVariable
| dict[str, str | float | int]
| Variable
| Dataset
| None = None,
**kwargs: Any,
) -> Variable:
"""
Filter variables based on a condition.
This operation call ``xarray.DataArray.where`` but sets the default
fill value to -1 and ensures preserving the linopy.Variable type.
Parameters