forked from XiongPengNUS/rsome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lp.py
2654 lines (1866 loc) · 79 KB
/
lp.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
from .subroutines import *
import numpy as np
import pandas as pd
import scipy.sparse as sp
import warnings
from numbers import Real
from scipy.sparse import csr_matrix
from scipy.sparse import coo_matrix
from collections import Iterable, Sized
from .lpg_solver import solve as def_sol
class Model:
"""
The Model class creates an LP model object
"""
def __init__(self, nobj=False, mtype='R', name=None):
self.mtype = mtype
self.nobj = nobj
self.name = name
self.vars = []
self.auxs = []
self.last = 0
self.lin_constr = []
self.pws_constr = []
self.bounds = []
self.aux_constr = []
self.aux_bounds = []
self.obj = None
self.sign = 1
self.primal = None
self.dual = None
self.solution = None
self.pupdate = True
self.dupdate = True
if not nobj:
self.dvar()
def dvar(self, shape=(1,), vtype='C', name=None, aux=False):
if not isinstance(shape, tuple):
shape = (shape, )
new_shape = ()
for item in shape:
if not isinstance(item, (int, np.int8, np.int16,
np.int32, np.int64)):
raise TypeError('Shape dimensions must be int type!')
new_shape += (item, )
new_var = Vars(self, self.last, new_shape, vtype, name)
if not aux:
self.vars.append(new_var)
else:
self.auxs.append(new_var)
self.last += np.prod(shape)
return new_var
def st(self, constr):
if isinstance(constr, Iterable):
for item in constr:
self.st(item)
else:
if constr.model is not self:
raise ValueError('Constraints are not defined for this model.')
if isinstance(constr, LinConstr):
self.lin_constr.append(constr)
elif isinstance(constr, CvxConstr):
if constr.xtype in 'AMI':
self.pws_constr.append(constr)
else:
raise TypeError('Incorrect constraint type.')
elif isinstance(constr, Bounds):
self.bounds.append(constr)
else:
raise TypeError('Unknown constraint type.')
self.pupdate = True
self.dupdate = True
def min(self, obj):
"""
Minimize the given objective function.
Parameters
----------
obj
An objective function
Notes
-----
The objective function given as an array must have the size
to be one.
"""
if obj.size > 1:
raise ValueError('Incorrect function dimension.')
self.obj = obj
self.sign = 1
self.pupdate = True
self.dupdate = True
def max(self, obj):
"""
Maximize the given objective function.
Parameters
----------
obj
An objective function
Notes
-----
The objective function given as an array must have the size
to be one.
"""
if obj.size > 1:
raise ValueError('Incorrect function dimension.')
self.obj = obj
self.sign = - 1
self.pupdate = True
self.dupdate = True
def do_math(self, primal=True, refresh=True, obj=False):
if primal:
if self.primal is not None and not self.pupdate:
return self.primal
if refresh:
self.auxs = []
self.aux_constr = []
self.aux_bounds = []
self.last = self.vars[-1].first + self.vars[-1].size
more_cvx = []
if self.obj:
obj_constr = (self.vars[0] >= self.sign * self.obj)
if isinstance(obj_constr, LinConstr):
self.aux_constr.append(obj_constr)
elif isinstance(obj_constr, CvxConstr):
more_cvx.append(obj_constr)
for constr in self.pws_constr + more_cvx:
if constr.xtype == 'A':
self.aux_constr.append(constr.affine_in +
constr.affine_out <= 0)
self.aux_constr.append(-constr.affine_in +
constr.affine_out <= 0)
elif constr.xtype == 'M':
aux = self.dvar(constr.affine_in.shape, aux=True)
self.aux_constr.append(constr.affine_in <= aux)
self.aux_constr.append(-constr.affine_in <= aux)
self.aux_constr.append(sum(aux) + constr.affine_out <= 0)
elif constr.xtype == 'I':
aux = self.dvar(1, aux=True)
self.aux_constr.append(constr.affine_in <= aux)
self.aux_constr.append(-constr.affine_in <= aux)
self.aux_constr.append(aux + constr.affine_out <= 0)
if obj:
obj = np.array(csr_matrix(([1.0], ([0], [0])),
(1, self.last)).todense())
else:
obj = np.ones((1, self.last))
data_list = []
indices_list = []
indptr = [0]
last = 0
data_list += [item.linear.data
for item in self.lin_constr + self.aux_constr]
indices_list += [item.linear.indices
for item in self.lin_constr + self.aux_constr]
if data_list:
data = np.concatenate(tuple(data_list))
indices = np.concatenate(tuple(indices_list))
for item in self.lin_constr + self.aux_constr:
indptr.extend(list(item.linear.indptr[1:] + last))
last += item.linear.indptr[-1]
linear = csr_matrix((data, indices, indptr),
(len(indptr) - 1, self.last))
const_list = [item.const for item in
self.lin_constr + self.aux_constr]
sense_list = [item.sense
if isinstance(item.sense, np.ndarray) else
np.array([item.sense])
for item in self.lin_constr
+ self.aux_constr]
const = np.concatenate(tuple(const_list))
sense = np.concatenate(tuple(sense_list))
else:
linear = csr_matrix(([], ([], [])), (1, self.last))
const = np.array([0])
sense = np.array([1])
vtype = np.concatenate([np.array([item.vtype] * item.size)
if len(item.vtype) == 1
else np.array(list(item.vtype))
for item in self.vars + self.auxs])
# ub = np.array([np.infty] * linear.shape[1])
# lb = np.array([-np.infty] * linear.shape[1])
ub = np.array([np.infty] * self.last)
lb = np.array([-np.infty] * self.last)
for b in self.bounds + self.aux_bounds:
if b.btype == 'U':
ub[b.indices] = np.minimum(b.values, ub[b.indices])
elif b.btype == 'L':
lb[b.indices] = np.maximum(b.values, lb[b.indices])
formula = LinProg(linear, const, sense,
vtype, ub, lb, obj)
self.primal = formula
self.pupdate = False
return formula
else:
if self.dual is not None and not self.dupdate:
return self.dual
primal = self.do_math(obj=obj)
if 'B' in primal.vtype or 'I' in primal.vtype:
string = '\nIntegers detected.'
string += '\nDual of the continuous relaxtion is returned'
warnings.warn(string)
primal_linear = primal.linear
primal_const = primal.const
primal_sense = primal.sense
indices_ub = np.where((primal.ub != 0) &
(primal.ub != np.infty))[0]
indices_lb = np.where((primal.lb != 0) &
(primal.lb != - np.infty))[0]
nub = len(indices_ub)
nlb = len(indices_lb)
nv = primal_linear.shape[1]
if nub > 0:
matrix_ub = csr_matrix((np.array([1] * nub), indices_ub,
np.arange(nub + 1)), (nub, nv))
primal_linear = sp.vstack((primal_linear, matrix_ub))
primal_const = np.concatenate((primal_const,
primal.ub[indices_ub]))
primal_sense = np.concatenate((primal_sense, np.zeros(nub)))
if nlb > 0:
matrix_lb = csr_matrix((np.array([-1] * nlb), indices_lb,
np.arange(nlb + 1)), (nlb, nv))
primal_linear = sp.vstack((primal_linear, matrix_lb))
primal_const = np.concatenate((primal_const,
-primal.lb[indices_lb]))
primal_sense = np.concatenate((primal_sense, np.zeros(nlb)))
indices_free = np.where((primal.lb != 0) &
(primal.ub != 0))[0]
indices_neg = np.where(primal.ub == 0)[0]
dual_linear = csr_matrix(primal_linear.T)
ndv = dual_linear.shape[1]
dual_obj = - primal_const
dual_const = primal.obj.reshape((nv, ))
dual_sense = np.zeros(dual_linear.shape[0])
dual_sense[indices_free] = 1
dual_ub = np.zeros(dual_linear.shape[1])
dual_lb = - np.ones(ndv) * np.infty
indices_eq = np.where(primal_sense == 1)[0]
if len(indices_eq):
dual_ub[indices_eq] = np.infty
if len(indices_neg) > 0:
dual_linear[indices_neg, :] = - dual_linear[indices_neg, :]
dual_const[indices_neg] = - dual_const[indices_neg]
formula = LinProg(dual_linear, dual_const, dual_sense,
np.array(['C']*ndv), dual_ub, dual_lb, dual_obj)
self.dual = formula
self.dupdate = False
return formula
def solve(self, solver=None, display=True, export=False, params={}):
"""
Solve the model with the selected solver interface.
Parameters
----------
solver : {None, lpg_solver, mip_solver,
clp_solver, grb_solver, msk_solver}
Solver interface used for model solution. Use default solver
if solver=None.
display : bool
Display option of the solver interface.
export : bool
Export option of the solver interface. A standard model file
is generated if the option is True.
params : dict
A dictionary that specifies parameters of the selected solver.
So far the argument only applies to Gurobi, CPLEX,and MOSEK.
"""
if solver is None:
solution = def_sol(self.do_math(obj=True), display, export, params)
else:
solution = solver.solve(self.do_math(obj=True),
display, export, params)
if instance(solution, Solution):
self.solution = solution
else:
if not solution:
warnings.warn('No feasible solutions can be found.')
else:
x = solution.x
self.solution = Solution(x[0], x, solution.status)
def get(self):
if self.solution is None:
raise SyntaxError('The model is unsolved or no feasible solution.')
return self.sign * self.solution.objval
class SparseVec:
__array_priority__ = 200
def __init__(self, index, value, nvar):
self.index = index
self.value = value
self.nvar = nvar
def __str__(self):
string = 'Indices: ' + str(self.index) + ' | '
string += 'Values: ' + str(self.value)
return string
def __repr__(self):
return self.__str__()
def __add__(self, other):
return SparseVec(self.index+other.index,
self.value+other.value, max(self.nvar, other.nvar))
def __radd__(self, other):
return self.__add__(other)
def __mul__(self, other):
values = [v*other for v in self.value]
return SparseVec(self.index, values, self.nvar)
def __rmul__(self, other):
return self.__mul__(other)
class Vars:
"""
The Var class creates a variable array.
"""
__array_priority__ = 100
def __init__(self, model, first, shape, vtype, name, sparray=None):
self.model = model
self.first = first
self.shape = shape
self.size = int(np.prod(shape))
self.last = first + self.size
self.ndim = len(shape)
self.vtype = vtype
self.name = name
self.sparray = sparray
def __str__(self):
vtype = self.vtype
if 'C' not in vtype and 'B' not in vtype and 'I' not in vtype:
raise ValueError('Unknown variable type.')
var_name = '' if self.name is None else self.name + ': '
"""
model_type = ('RSO model' if self.model.mtype == 'R' else
'Robust counterpart' if self.model.mtype == 'C' else
'Support' if self.model.mtype == 'S' else
'Expectation set' if self.model.mtype == 'E' else
'Probability set')
"""
var_type = ('continuous' if vtype == 'C' else
'binary' if vtype == 'B' else
'integer' if vtype == 'I' else
'Mixed-type')
suffix = 's' if np.prod(self.shape) > 1 else ''
string = var_name
string += 'x'.join([str(size) for size in self.shape]) + ' '
string += var_type + ' variable' + suffix
# string += ' ({0})'.format(model_type)
return string
def __repr__(self):
return self.__str__()
def sv_array(self, index=False):
shape = self.shape
shape = shape if isinstance(shape, tuple) else (int(shape), )
size = np.prod(shape).item()
if index:
elements = [SparseVec([i], [1], size) for i in range(size)]
else:
elements = [SparseVec([i], [1.0], size) for i in range(size)]
return np.array(elements).reshape(shape)
# noinspection PyPep8Naming
@property
def T(self):
return self.to_affine().T
def to_affine(self):
dim = self.size
data = np.ones(dim)
indices = self.first + np.arange(dim)
indptr = np.arange(dim+1)
linear = csr_matrix((data, indices, indptr),
shape=(dim, self.model.last))
const = np.zeros(self.shape)
return Affine(self.model, linear, const, self.sparray)
def get_ind(self):
return np.array(range(self.first, self.first + self.size))
def reshape(self, shape):
return self.to_affine().reshape(shape)
def norm(self, degree):
return self.to_affine().norm(degree)
def get(self):
if self.model.solution is None:
raise SyntaxError('The model is unsolved.')
indices = range(self.first, self.first + self.size)
var_sol = np.array(self.model.solution.x)[indices]
if isinstance(var_sol, np.ndarray):
var_sol = var_sol.reshape(self.shape)
return var_sol
def __getitem__(self, item):
item_array = index_array(self.shape)
indices = item_array[item]
if not isinstance(indices, np.ndarray):
indices = np.array([indices]).reshape((1, ) * self.ndim)
return VarSub(self, indices)
def __iter__(self):
shape = self.shape
for i in range(shape[0]):
yield self[i]
def __abs__(self):
return self.to_affine().__abs__()
def sum(self, axis=None):
return self.to_affine().sum(axis)
def __mul__(self, other):
return self.to_affine() * other
def __rmul__(self, other):
return other * self.to_affine()
def __matmul__(self, other):
return self.to_affine() @ other
def __rmatmul__(self, other):
return other @ self.to_affine()
def __add__(self, other):
return self.to_affine() + other
def __radd__(self, other):
return self.to_affine() + other
def __sub__(self, other):
return self.to_affine() - other
def __rsub__(self, other):
return (-self.to_affine()) + other
def __neg__(self):
return - self.to_affine()
def __le__(self, other):
if ((isinstance(other, (Real, np.ndarray)) or sp.issparse(other))
and self.model.mtype not in 'EP'):
upper = other + np.zeros(self.shape)
upper = upper.reshape((upper.size, ))
indices = np.arange(self.first, self.first + self.size,
dtype=np.int32)
return Bounds(self.model, indices, upper, 'U')
else:
return self.to_affine() <= other
def __ge__(self, other):
if ((isinstance(other, (Real, np.ndarray)) or sp.issparse(other))
and self.model.mtype not in 'EP'):
lower = other + np.zeros(self.shape)
lower = lower.reshape((lower.size, ))
indices = np.arange(self.first, self.first + self.size,
dtype=np.int32)
return Bounds(self.model, indices, lower, 'L')
else:
return self.to_affine() >= other
def __eq__(self, other):
return self.to_affine() == other
class VarSub(Vars):
"""
The VarSub class creates a variable array with subscript indices
"""
def __init__(self, var, indices):
super().__init__(var.model, var.first,
var.shape, var.vtype, var.name, var.sparray)
self.indices = indices
def __repr__(self):
var_name = '' if self.name is None else self.name + ': '
"""
model_type = ('RSO model' if self.model.mtype == 'R' else
'Robust counterpart' if self.model.mtype == 'C' else
'Support' if self.model.mtype == 'S' else
'Expectation set' if self.model.mtype == 'E' else
'Probability set')
"""
var_type = ('continuous' if self.vtype == 'C' else
'binary' if self.vtype == 'B' else 'integer')
suffix = 's' if np.prod(self.shape) > 1 else ''
string = var_name
string += 'x'.join([str(dim) for dim in self.indices.shape]) + ' '
string += 'slice of '
string += var_type + ' variable' + suffix
# string += ' ({0})'.format(model_type)
return string
@property
def T(self):
return self.to_affine().T
def get_ind(self):
indices_all = super().get_ind()
return indices_all[self.indices].flatten()
def __getitem__(self, item):
raise SyntaxError('Nested indexing of variables is forbidden.')
def sum(self, axis=None):
return self.to_affine().sum(axis)
def to_affine(self):
select = list(self.indices.reshape((self.indices.size,)))
dim = self.size
data = np.ones(dim)
indices = self.first + np.arange(dim)
indptr = np.arange(dim + 1)
linear = csr_matrix((data, indices, indptr),
shape=(dim, self.model.last))
const = np.zeros(self.indices.shape)
return Affine(self.model, linear[select, :], const)
def reshape(self, shape):
return self.to_affine().reshape(shape)
def __add__(self, other):
return self.to_affine() + other
def __radd__(self, other):
return self.to_affine() + other
def __le__(self, other):
upper = super().__le__(other)
if isinstance(upper, Bounds):
indices = self.indices.reshape((self.indices.size, ))
bound_indices = upper.indices.reshape((upper.indices.size, ))[indices]
bound_values = upper.values.reshape(upper.values.size)[indices]
return Bounds(upper.model, bound_indices, bound_values, 'U')
else:
return self.to_affine().__le__(other)
def __ge__(self, other):
lower = super().__ge__(other)
if isinstance(lower, Bounds):
indices = self.indices.reshape((self.indices.size, ))
bound_indices = lower.indices.reshape((lower.indices.size, ))[indices]
bound_values = lower.values.reshape((lower.indices.size, ))[indices]
return Bounds(lower.model, bound_indices, bound_values, 'L')
else:
return self.to_affine().__ge__(other)
class Affine:
"""
The Affine class creates an array of affine expressions
"""
__array_priority__ = 100
def __init__(self, model, linear, const, sparray=None):
self.model = model
self.linear = linear
self.const = const
self.shape = const.shape
self.size = np.prod(self.shape)
self.sparray = sparray
self.expect = False
def __repr__(self):
"""
model_type = ('RSO model' if self.model.mtype == 'R' else
'Robust counterpart' if self.model.mtype == 'C' else
'Support' if self.model.mtype == 'S' else
'Expectation set' if self.model.mtype == 'E' else
'Probability set')
"""
string = 'x'.join([str(dim) for dim in self.shape]) + ' '
string += 'affine expressions '
# string += '({0})'.format(model_type)
return string
def __getitem__(self, item):
if self.sparray is None:
# self.sparray = sparse_array(self.shape)
self.sparray = self.sv_array()
indices = self.sparray[item]
if not isinstance(indices, np.ndarray):
indices = np.array([indices]).reshape((1, ))
# linear = array_to_sparse(indices) @ self.linear
linear = sv_to_csr(indices) @ self.linear
const = self.const[item]
if not isinstance(const, np.ndarray):
const = np.array([const])
return Affine(self.model, linear, const)
def to_affine(self):
return self
def rand_to_roaffine(self, rc_model):
size = self.size
num_rand = self.model.vars[-1].last
reduced_linear = self.linear[:, :num_rand]
num_dec = rc_model.last
raffine = Affine(rc_model,
csr_matrix((size*num_rand, num_dec)),
reduced_linear.toarray())
affine = Affine(rc_model, csr_matrix((size, num_dec)),
self.const)
return RoAffine(raffine, affine, self.model)
def sv_array(self, index=False):
shape = self.shape
shape = shape if isinstance(shape, tuple) else (int(shape), )
size = np.prod(shape).item()
if index:
elements = [SparseVec([i], [1], size) for i in range(size)]
else:
elements = [SparseVec([i], [1.0], size) for i in range(size)]
return np.array(elements).reshape(shape)
def sv_zeros(self, nvar):
shape = (self.shape if isinstance(self.shape, tuple) else
(int(self.shape),))
size = np.prod(self.shape).item()
elements = [SparseVec([], [], nvar) for _ in range(size)]
return np.array(elements).reshape(shape)
# noinspection PyPep8Naming
@property
def T(self):
linear = sp_trans(self) @ self.linear
const = self.const.T
return Affine(self.model, linear, const)
def reshape(self, shape):
new_const = self.const.reshape(shape)
return Affine(self.model, self.linear, new_const)
def sum(self, axis=None):
if self.sparray is None:
# self.sparray = sparse_array(self.shape)
self.sparray = self.sv_array()
indices = self.sparray.sum(axis=axis)
if not isinstance(indices, np.ndarray):
indices = np.array([indices])
# linear = array_to_sparse(indices) @ self.linear
linear = sv_to_csr(indices) @ self.linear
const = self.const.sum(axis=axis)
if not isinstance(const, np.ndarray):
const = np.array([const])
return Affine(self.model, linear, const)
def __abs__(self):
return Convex(self, np.zeros(self.shape), 'A', 1)
def abs(self):
return self.__abs__()
def norm(self, degree):
shape = self.shape
if np.prod(shape) != max(shape):
raise ValueError('Funciton "norm" only applies to vectors.')
new_shape = (1,) * len(shape)
if degree == 1:
return Convex(self, np.zeros(new_shape), 'M', 1)
elif degree == np.infty or degree == 'inf':
return Convex(self, np.zeros(new_shape), 'I', 1)
elif degree == 2:
return Convex(self, np.zeros(new_shape), 'E', 1)
else:
raise ValueError('Incorrect degree for the norm function.')
def square(self):
size = self.size
shape = self.shape
return Convex(self.reshape((size,)), np.zeros(shape), 'S', 1)
def sumsqr(self):
shape = self.shape
if np.prod(shape) != max(shape):
raise ValueError('Funciton "sumsqr" only applies to vectors.')
new_shape = (1,) * len(shape)
return Convex(self, np.zeros(new_shape), 'Q', 1)
def __mul__(self, other):
if isinstance(other, (Vars, VarSub, Affine)):
if self.model.mtype in 'VR' and other.model.mtype in 'SM':
other = other.to_affine()
if self.shape != other.shape:
raffine = self * np.ones(other.to_affine().shape)
other = np.ones(self.shape) * other.to_affine()
else:
raffine = self
other = other.to_affine()
raffine = raffine.reshape((raffine.size, 1))
rvar_last = other.model.vars[-1].last
reduced_linear = other.linear[:, :rvar_last]
trans_sparray = np.array([line for line in reduced_linear])
raffine = raffine * array_to_sparse(trans_sparray)
affine = self * other.const
return RoAffine(raffine, affine, other.model)
else:
return other.__mul__(self)
else:
other = check_numeric(other)
if isinstance(other, Real):
other = np.array([other])
new_linear = sparse_mul(other, self.to_affine()) @ self.linear
new_const = self.const * other
return Affine(self.model, new_linear, new_const)
def __rmul__(self, other):
if isinstance(other, (Vars, VarSub, Affine)):
if self.model.mtype in 'VR' and other.model.mtype == 'S':
other = other.to_affine()
if self.shape != other.shape:
raffine = self * np.ones(other.to_affine().shape)
other = np.ones(self.shape) * other.to_affine()
else:
raffine = self
other = other.to_affine()
raffine = raffine.reshape((raffine.size, 1))
rvar_last = other.model.vars[-1].last
reduced_linear = other.linear[:, :rvar_last]
trans_sparray = np.array([line for line in reduced_linear])
raffine = raffine * array_to_sparse(trans_sparray)
affine = self * other.const
return RoAffine(raffine, affine, other.model)
else:
return other.__rmul__(self)
else:
other = check_numeric(other)
if isinstance(other, Real):
other = np.array([other])
new_linear = sparse_mul(other, self.to_affine()) @ self.linear
new_const = self.const * other
return Affine(self.model, new_linear, new_const)
def __matmul__(self, other):
if isinstance(other, (Vars, VarSub, Affine)):
if self.model.mtype in 'VR' and other.model.mtype in 'SM':
other = other.to_affine()
affine = self @ other.const
num_rand = other.model.vars[-1].last
ind_array = self.sv_array()
temp = ind_array @ np.arange(other.size).reshape(other.shape)
if isinstance(temp, np.ndarray):
all_items = list(temp.reshape((temp.size, )))
else:
all_items = [temp]
temp = np.array([temp])
col_ind = np.concatenate(tuple(item.index
for item in all_items))
row_ind = tuple(np.array(all_items[i].value) + i*other.size
for i in range(len(all_items)))
row_ind = np.concatenate(row_ind)
csr_temp = csr_matrix((np.ones(len(col_ind)),
(row_ind, col_ind)),
shape=(temp.size*other.size, self.size))
self_flat = self.reshape(self.size)
affine_temp = (csr_temp @ self_flat).reshape((temp.size,
other.size))
raffine = affine_temp @ other.linear[:, :num_rand]
return RoAffine(raffine, affine, other.model)
elif self.model.mtype in 'SM' and other.model.mtype in 'VR':
affine = self.const @ other
other = other.to_affine()
num_rand = self.model.vars[-1].last
ind_array = self.sv_array()
temp = ind_array @ np.arange(other.size).reshape(other.shape)
if isinstance(temp, np.ndarray):
all_items = list(temp.reshape((temp.size, )))
else:
all_items = [temp]
temp = np.array([temp])
col_ind = np.concatenate(tuple(item.value
for item in all_items))
row_ind = tuple(np.array(all_items[i].index) + i*self.size
for i in range(len(all_items)))
row_ind = np.concatenate(row_ind)
csr_temp = csr_matrix((np.ones(len(col_ind)),
(row_ind, col_ind)),
shape=(temp.size*self.size, other.size))
other_flat = other.reshape(other.size)
affine_temp = (csr_temp @ other_flat).reshape((temp.size,
self.size))
raffine = affine_temp @ self.linear[:, :num_rand]
roaffine = RoAffine(raffine, affine, self.model)
if isinstance(other, DecAffine):
return DecRoAffine(roaffine, other.event_adapt, 'R')
else:
return roaffine
else:
other = check_numeric(other)
new_const = self.const @ other
if not isinstance(new_const, np.ndarray):
new_const = np.array([new_const])
new_linear = sp_lmatmul(other, self, new_const.shape) @ self.linear
return Affine(self.model, new_linear, new_const)
def __rmatmul__(self, other):
other = check_numeric(other)
new_const = other @ self.const
if not isinstance(new_const, np.ndarray):
new_const = np.array([new_const])
new_linear = sp_matmul(other, self, new_const.shape) @ self.linear
return Affine(self.model, new_linear, new_const)
def __add__(self, other):
if isinstance(other, (Vars, VarSub, Affine)):