admmsolver 0.7.6__tar.gz → 0.8.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: admmsolver
3
- Version: 0.7.6
3
+ Version: 0.8.0
4
4
  Summary: Fast and general ADMM solver
5
5
  Home-page: https://github.com/SpM-lab/admmsolver
6
6
  Author: Hiroshi Shinaoka
@@ -14,12 +14,35 @@ Classifier: License :: OSI Approved :: MIT License
14
14
  Classifier: Programming Language :: Python :: 3
15
15
  Requires-Python: >=3.6
16
16
  Description-Content-Type: text/markdown
17
+ License-File: LICENSE.txt
18
+ Requires-Dist: numpy
19
+ Requires-Dist: scipy
17
20
  Provides-Extra: test
21
+ Requires-Dist: pytest; extra == "test"
22
+ Requires-Dist: mypy; extra == "test"
18
23
  Provides-Extra: dev
19
- License-File: LICENSE.txt
24
+ Requires-Dist: pytest; extra == "dev"
25
+ Requires-Dist: mypy; extra == "dev"
26
+ Dynamic: author
27
+ Dynamic: author-email
28
+ Dynamic: classifier
29
+ Dynamic: description
30
+ Dynamic: description-content-type
31
+ Dynamic: home-page
32
+ Dynamic: keywords
33
+ Dynamic: license-file
34
+ Dynamic: provides-extra
35
+ Dynamic: requires-dist
36
+ Dynamic: requires-python
37
+ Dynamic: summary
20
38
 
21
39
  A fast and general ADMM solver
22
40
  =======================================================================
41
+
42
+ > Part of the [SpM-lab](https://spm-lab.github.io/) tools for imaginary-time Green's functions and analytic continuation.
43
+ > Related: the [sparse-ir ecosystem](https://spm-lab.github.io/sparse-ir-doc/) (IR/DLR bases, sparse sampling) and the other
44
+ > [analytic continuation tools](https://spm-lab.github.io/#analytic-continuation).
45
+
23
46
  # Installation
24
47
 
25
48
  ```
@@ -1,5 +1,10 @@
1
1
  A fast and general ADMM solver
2
2
  =======================================================================
3
+
4
+ > Part of the [SpM-lab](https://spm-lab.github.io/) tools for imaginary-time Green's functions and analytic continuation.
5
+ > Related: the [sparse-ir ecosystem](https://spm-lab.github.io/sparse-ir-doc/) (IR/DLR bases, sparse sampling) and the other
6
+ > [analytic continuation tools](https://spm-lab.github.io/#analytic-continuation).
7
+
3
8
  # Installation
4
9
 
5
10
  ```
@@ -2,4 +2,4 @@
2
2
  # SPDX-License-Identifier: MIT
3
3
 
4
4
  __license__ = "MIT"
5
- __version__ = "0.7.6"
5
+ __version__ = "0.8.0"
@@ -5,77 +5,79 @@ import numpy as np
5
5
  from typing import Union, Tuple, Optional, cast
6
6
  from abc import abstractmethod
7
7
 
8
+
8
9
  class MatrixBase(object):
9
10
  def __init__(self) -> None:
10
11
  super().__init__()
11
12
 
12
- self.shape = (1,1)
13
+ self.shape = (1, 1)
13
14
  self.ndim = 2
14
15
 
15
16
  def is_diagonal(self) -> bool:
16
17
  return self.shape[0] == self.shape[1]
17
18
 
18
- def __neg__(self)->'MatrixBase':
19
+ def __neg__(self) -> 'MatrixBase':
19
20
  return -1.0 * self
20
21
 
21
22
  @abstractmethod
22
- def asmatrix(self)->np.ndarray:
23
+ def asmatrix(self) -> np.ndarray:
23
24
  pass
24
25
 
25
26
  @abstractmethod
26
- def __mul__(self, other: Union[float, complex, np.float64, np.complex128])->'MatrixBase':
27
+ def __mul__(self, other: Union[float, complex, np.float64, np.complex128]) -> 'MatrixBase':
27
28
  return NotImplemented
28
29
 
29
30
  __rmul__ = __mul__
30
31
 
31
32
  @abstractmethod
32
- def __matmul__(self, other: Union['MatrixBase', np.ndarray])->Union['MatrixBase',np.ndarray]:
33
+ def __matmul__(self, other: Union['MatrixBase', np.ndarray]) -> Union['MatrixBase', np.ndarray]:
33
34
  return NotImplemented
34
35
 
35
36
  @abstractmethod
36
- def __add__(self, other: 'MatrixBase')->'MatrixBase':
37
+ def __add__(self, other: 'MatrixBase') -> 'MatrixBase':
37
38
  return NotImplemented
38
39
 
39
40
  @abstractmethod
40
- def conjugate(self)->'MatrixBase':
41
+ def conjugate(self) -> 'MatrixBase':
41
42
  pass
42
43
 
43
44
  @property
44
45
  @abstractmethod
45
- def T(self)->'MatrixBase':
46
+ def T(self) -> 'MatrixBase':
46
47
  pass
47
48
 
48
49
  conj = conjugate
49
50
 
50
- def __sub__(self, other)->'MatrixBase':
51
+ def __sub__(self, other) -> 'MatrixBase':
51
52
  return self + (-other)
52
53
 
53
54
  @abstractmethod
54
- def inv(self)->'MatrixBase':
55
+ def inv(self) -> 'MatrixBase':
55
56
  pass
56
57
 
57
58
  @abstractmethod
58
- def hash(self)->int:
59
+ def hash(self) -> int:
59
60
  pass
60
61
 
62
+
61
63
  class DenseMatrix(MatrixBase):
62
64
  def __init__(self, matrix: np.ndarray) -> None:
63
65
  assert isinstance(matrix, np.ndarray)
64
66
  assert matrix.ndim == 2
65
67
  self.data = matrix
66
- self.shape = cast(Tuple[int,int], matrix.shape)
68
+ self.shape = cast(Tuple[int, int], matrix.shape)
67
69
  self.ndim = 2
68
70
 
69
- def hash(self)->int:
71
+ def hash(self) -> int:
70
72
  return matrix_hash(self.asmatrix())
71
73
 
72
- def asmatrix(self)->np.ndarray:
74
+ def asmatrix(self) -> np.ndarray:
73
75
  return self.data
74
76
 
75
- def inv(self)->'DenseMatrix':
77
+ def inv(self) -> 'DenseMatrix':
76
78
  return DenseMatrix(np.linalg.inv(self.asmatrix()))
77
79
 
78
- def __neg__(self)->'DenseMatrix':
80
+ def __neg__(self) -> 'DenseMatrix':
79
81
  return -1.0 * self
80
82
 
81
83
  @property
@@ -87,7 +89,7 @@ class DenseMatrix(MatrixBase):
87
89
 
88
90
  conj = conjugate
89
91
 
90
- def __mul__(self, other)->'DenseMatrix':
92
+ def __mul__(self, other) -> 'DenseMatrix':
91
93
  if np.isscalar(other):
92
94
  return DenseMatrix(self.data * other)
93
95
  else:
@@ -95,61 +97,62 @@ class DenseMatrix(MatrixBase):
95
97
 
96
98
  __rmul__ = __mul__
97
99
 
98
- def __matmul__(self, other)->Union['DenseMatrix', np.ndarray]:
100
+ def __matmul__(self, other) -> Union['DenseMatrix', np.ndarray]:
99
101
  assert self.shape[1] == other.shape[0]
100
- assert isinstance(other, MatrixBase) or (isinstance(other, np.ndarray) and other.ndim<=2)
102
+ assert isinstance(other, MatrixBase) or (
103
+ isinstance(other, np.ndarray) and other.ndim <= 2)
101
104
  if isinstance(other, np.ndarray):
102
105
  return self.asmatrix() @ other
103
106
  else:
104
107
  if isinstance(other, ScaledIdentityMatrix):
105
108
  return self @ other.to_diagonal_matrix()
106
109
  elif isinstance(other, DiagonalMatrix):
107
- res = np.zeros((self.shape[0], other.shape[1]), dtype=np.complex128) # make real if possible
110
+ # make real if possible
111
+ res = np.zeros(
112
+ (self.shape[0], other.shape[1]), dtype=np.complex128)
108
113
  min_size = min(*other.shape)
109
114
  res[:, 0:min_size] = \
110
- self.data[:, 0:min_size] * other.diagonals[None,:]
115
+ self.data[:, 0:min_size] * other.diagonals[None, :]
111
116
  return DenseMatrix(res)
112
117
  else:
113
118
  return DenseMatrix(self.data @ other.asmatrix())
114
119
 
115
- def __add__(self, other)->'DenseMatrix':
116
- assert isinstance(other, MatrixBase)
117
- assert self.shape == other.shape
118
-
119
- return DenseMatrix(self.asmatrix() + other.asmatrix())
120
-
120
+ def __add__(self, other):
121
+ return _add_matrices(self, other)
121
122
 
122
123
 
123
124
  class ScaledIdentityMatrix(MatrixBase):
124
125
  """
125
126
  Scaled Identity matrix with a rectangular shape
126
127
  """
128
+
127
129
  def __init__(
128
- self,
129
- shape: Union[int, Tuple[int,int]],
130
- coeff: Union[complex, float, np.float64, np.complex128]
131
- )->None:
132
- assert type(coeff) in [complex, float, np.float64, np.complex128], type(coeff)
133
- self.shape = (0,0) # type: Tuple[int, int]
130
+ self,
131
+ shape: Union[int, Tuple[int, int]],
132
+ coeff: Union[complex, float, np.float64, np.complex128]
133
+ ) -> None:
134
+ assert type(coeff) in [complex, float,
135
+ np.float64, np.complex128], type(coeff)
136
+ self.shape = (0, 0) # type: Tuple[int, int]
134
137
  if isinstance(shape, int):
135
138
  self.shape = (shape, shape)
136
139
  elif isinstance(shape, tuple):
137
140
  self.shape = shape
138
141
  else:
139
142
  raise ValueError("Invalid shape value!")
140
- self.coeff = coeff # type: Union[complex, float, np.float64, np.complex128]
141
- self.ndim = 2 # type: int
143
+ self.coeff = coeff
144
+ self.ndim = 2 # type: int
142
145
 
143
- def hash(self)->int:
146
+ def hash(self) -> int:
144
147
  return matrix_hash(self.coeff)
145
148
 
146
149
  def asmatrix(self) -> np.ndarray:
147
150
  return self.coeff * np.eye(N=self.shape[0], M=self.shape[1])
148
151
 
149
- def __neg__(self)->'ScaledIdentityMatrix':
152
+ def __neg__(self) -> 'ScaledIdentityMatrix':
150
153
  return -1.0 * self
151
154
 
152
- def inv(self)->'ScaledIdentityMatrix':
155
+ def inv(self) -> 'ScaledIdentityMatrix':
153
156
  if not self.is_diagonal():
154
157
  raise RuntimeError("A rectangular matrix is not invertible!")
155
158
  return ScaledIdentityMatrix(self.shape, 1/self.coeff)
@@ -159,17 +162,18 @@ class ScaledIdentityMatrix(MatrixBase):
159
162
  return ScaledIdentityMatrix((self.shape[1], self.shape[0]), self.coeff)
160
163
 
161
164
  @property
162
- def diagonals(self)->np.ndarray:
165
+ def diagonals(self) -> np.ndarray:
163
166
  if not self.is_diagonal():
164
- raise RuntimeError("Diagonals of a rectangular matrix is ill defined!")
167
+ raise RuntimeError(
168
+ "Diagonals of a rectangular matrix is ill defined!")
165
169
  return np.full(self.shape[0], self.coeff)
166
170
 
167
- def conjugate(self)->'ScaledIdentityMatrix':
171
+ def conjugate(self) -> 'ScaledIdentityMatrix':
168
172
  return ScaledIdentityMatrix(self.shape, np.conjugate(self.coeff))
169
173
 
170
174
  conj = conjugate
171
175
 
172
- def __mul__(self, other)->'ScaledIdentityMatrix':
176
+ def __mul__(self, other) -> 'ScaledIdentityMatrix':
173
177
  if type(other) in [complex, float, np.float64, np.complex128]:
174
178
  return ScaledIdentityMatrix(self.shape, self.coeff*other)
175
179
  else:
@@ -177,35 +181,25 @@ class ScaledIdentityMatrix(MatrixBase):
177
181
 
178
182
  __rmul__ = __mul__
179
183
 
180
- def __matmul__(self, other: Union[MatrixBase, np.ndarray])->Union[MatrixBase,np.ndarray]:
184
+ def __matmul__(self, other: Union[MatrixBase, np.ndarray]) -> Union[MatrixBase, np.ndarray]:
181
185
  assert self.shape[1] == other.shape[0], f"{self.shape} {other.shape}"
182
186
  assert isinstance(other, MatrixBase) or isinstance(other, np.ndarray)
183
187
  return self.to_diagonal_matrix() @ other
184
188
 
185
- def __add__(self, other: MatrixBase)->MatrixBase:
186
- assert isinstance(other, MatrixBase)
187
- assert self.shape == other.shape, f"{self.shape} {other.shape}"
188
-
189
- if isinstance(other, ScaledIdentityMatrix):
190
- return ScaledIdentityMatrix(self.shape, self.coeff + other.coeff)
191
- elif isinstance(other, DiagonalMatrix):
192
- return DiagonalMatrix(self.coeff*np.ones(self.shape[0]) + other.diagonals)
193
- elif isinstance(other, PartialDiagonalMatrix):
194
- return PartialDiagonalMatrix(
195
- ScaledIdentityMatrix(other.matrix.shape[0], self.coeff) + other.matrix,
196
- other.rest_dims)
197
- else:
198
- return DenseMatrix(self.asmatrix() + other.asmatrix())
189
+ def __add__(self, other: MatrixBase) -> MatrixBase:
190
+ return _add_matrices(self, other)
199
191
 
200
192
  def to_diagonal_matrix(self):
201
193
  """ Convert to a diagonal matrix """
202
194
  return DiagonalMatrix(self.coeff*np.ones(min(*self.shape)), self.shape)
203
195
 
196
+
204
197
  class DiagonalMatrix(MatrixBase):
205
198
  """
206
199
  Diagonal matrix
207
200
  """
208
- def __init__(self, diagonals, shape: Optional[Tuple[int,int]] = None)->None:
201
+
202
+ def __init__(self, diagonals, shape: Optional[Tuple[int, int]] = None) -> None:
209
203
  assert diagonals.ndim == 1
210
204
  self._diagonals = diagonals
211
205
  self.ndim = 2
@@ -213,7 +207,8 @@ class DiagonalMatrix(MatrixBase):
213
207
  self.shape = (diagonals.size, diagonals.size)
214
208
  else:
215
209
  self.shape = shape
216
- assert min(*self.shape) == diagonals.size, f"{self.shape} {diagonals.size}"
210
+ assert min(
211
+ *self.shape) == diagonals.size, f"{self.shape} {diagonals.size}"
217
212
 
218
213
  def hash(self) -> int:
219
214
  return matrix_hash(self.diagonals)
@@ -222,7 +217,7 @@ class DiagonalMatrix(MatrixBase):
222
217
  def diagonals(self) -> np.ndarray:
223
218
  return self._diagonals
224
219
 
225
- def __neg__(self)->'DiagonalMatrix':
220
+ def __neg__(self) -> 'DiagonalMatrix':
226
221
  return -1.0 * self
227
222
 
228
223
  def inv(self) -> 'DiagonalMatrix':
@@ -234,7 +229,7 @@ class DiagonalMatrix(MatrixBase):
234
229
  mat = np.zeros(self.shape, dtype=self.diagonals.dtype)
235
230
  min_size = min(*self.shape)
236
231
  for i in range(min_size):
237
- mat[i,i] = self.diagonals[i]
232
+ mat[i, i] = self.diagonals[i]
238
233
  return mat
239
234
 
240
235
  @property
@@ -255,20 +250,7 @@ class DiagonalMatrix(MatrixBase):
255
250
  __rmul__ = __mul__
256
251
 
257
252
  def __add__(self, other) -> MatrixBase:
258
- assert isinstance(other, MatrixBase)
259
- assert self.shape == other.shape
260
-
261
- if isinstance(other, DenseMatrix):
262
- return DenseMatrix(other.asmatrix() + np.diag(self.diagonals))
263
- elif isinstance(other, ScaledIdentityMatrix):
264
- return DiagonalMatrix(self.diagonals + np.full(self.diagonals.size, other.coeff))
265
- elif isinstance(other, DiagonalMatrix):
266
- return DiagonalMatrix(self.diagonals + other.diagonals)
267
- elif isinstance(other, PartialDiagonalMatrix):
268
- return DenseMatrix(self.asmatrix() + other.asmatrix())
269
- else:
270
- return NotImplemented
271
-
253
+ return _add_matrices(self, other)
272
254
 
273
255
  def __matmul__(self, other: Union[MatrixBase, np.ndarray]) -> Union[MatrixBase, np.ndarray]:
274
256
  """ self @ other """
@@ -287,10 +269,11 @@ class DiagonalMatrix(MatrixBase):
287
269
  res = np.zeros((self.shape[0],) + rest_dim, dtype=dtype)
288
270
  min_len = min(self._diagonals.size, other.size)
289
271
  res[0:min_len, ...] = \
290
- np.einsum('d,d...->d...', self._diagonals[0:min_len], other[0:min_len, ...], optimize=True)
272
+ np.einsum(
273
+ 'd,d...->d...', self._diagonals[0:min_len], other[0:min_len, ...], optimize=True)
291
274
  return res
292
275
  elif isinstance(other, DenseMatrix):
293
- return DenseMatrix(self._diagonals[:,None] * other.data)
276
+ return DenseMatrix(self._diagonals[:, None] * other.data)
294
277
  elif isinstance(other, DiagonalMatrix):
295
278
  min_size = min(self.shape[0], other.shape[1])
296
279
  return DiagonalMatrix(
@@ -298,7 +281,14 @@ class DiagonalMatrix(MatrixBase):
298
281
  (self.shape[0], other.shape[1])
299
282
  )
300
283
  elif isinstance(other, PartialDiagonalMatrix):
301
- return DenseMatrix(self._diagonals[:,None] * other.asmatrix())
284
+ diags = self.diagonals.reshape(other.matrix.shape[0], -1)
285
+ if np.allclose(diags, diags[:, 0:1]):
286
+ return PartialDiagonalMatrix(
287
+ diags[:, 0][:, None] * other.matrix.asmatrix(),
288
+ other.rest_dims
289
+ )
290
+ else:
291
+ return DenseMatrix(self._diagonals[:, None] * other.asmatrix())
302
292
  elif isinstance(other, ScaledIdentityMatrix):
303
293
  return self @ other.to_diagonal_matrix()
304
294
  else:
@@ -313,13 +303,15 @@ class PartialDiagonalMatrix(MatrixBase):
313
303
  Matrix that can be composed as
314
304
  A otimes I.
315
305
  """
306
+
316
307
  def __init__(self, matrix: Union[np.ndarray, MatrixBase], rest_dims: tuple) -> None:
317
308
  assert matrix.ndim == 2
318
309
  self.matrix = asmatrixtype(matrix)
319
310
  self._matrix_cg = matrix.T.conj()
320
311
  self.rest_dims = rest_dims
321
312
  self.ndim = 2
322
- self.shape = (matrix.shape[0]*np.prod(rest_dims), matrix.shape[1]*np.prod(rest_dims))
313
+ self.shape = (matrix.shape[0]*np.prod(rest_dims),
314
+ matrix.shape[1]*np.prod(rest_dims))
323
315
 
324
316
  def hash(self) -> int:
325
317
  return matrix_hash(self.matrix)
@@ -332,7 +324,7 @@ class PartialDiagonalMatrix(MatrixBase):
332
324
  optimize=True
333
325
  ).reshape(self.shape)
334
326
 
335
- def __neg__(self)->'PartialDiagonalMatrix':
327
+ def __neg__(self) -> 'PartialDiagonalMatrix':
336
328
  return -1.0 * self
337
329
 
338
330
  def inv(self) -> 'PartialDiagonalMatrix':
@@ -353,11 +345,13 @@ class PartialDiagonalMatrix(MatrixBase):
353
345
  assert isinstance(other, MatrixBase) or isinstance(other, np.ndarray)
354
346
  if isinstance(other, np.ndarray):
355
347
  return self.matvec(other)
356
- elif isinstance(other, PartialDiagonalMatrix) and self.rest_dims == other.rest_dims:
357
- return PartialDiagonalMatrix(self.matrix@other.matrix, self.rest_dims)
358
- else:
359
- return DenseMatrix(self.asmatrix() @ other.asmatrix())
360
348
 
349
+ if isinstance(other, PartialDiagonalMatrix) and self.rest_dims == other.rest_dims:
350
+ return PartialDiagonalMatrix(self.matrix@other.matrix, self.rest_dims)
351
+ if isinstance(other, ScaledIdentityMatrix) and other.is_diagonal():
352
+ return PartialDiagonalMatrix(other.coeff * self.matrix, self.rest_dims)
353
+
354
+ return DenseMatrix(self.asmatrix() @ other.asmatrix())
361
355
 
362
356
  def __mul__(self, other) -> 'PartialDiagonalMatrix':
363
357
  if type(other) in [float, complex, np.float64, np.complex128]:
@@ -368,17 +362,7 @@ class PartialDiagonalMatrix(MatrixBase):
368
362
  __rmul__ = __mul__
369
363
 
370
364
  def __add__(self, other) -> MatrixBase:
371
- assert isinstance(other, MatrixBase)
372
- assert self.shape == other.shape
373
-
374
- if isinstance(other, ScaledIdentityMatrix):
375
- return PartialDiagonalMatrix(
376
- self.matrix + ScaledIdentityMatrix(self.matrix.shape, other.coeff),
377
- self.rest_dims
378
- )
379
- else:
380
- return DenseMatrix(self.asmatrix() + other.asmatrix())
381
-
365
+ return _add_matrices(self, other)
382
366
 
383
367
  def matvec(self, v: np.ndarray) -> np.ndarray:
384
368
  r"""
@@ -390,13 +374,13 @@ class PartialDiagonalMatrix(MatrixBase):
390
374
 
391
375
 
392
376
  def _matvec_impl(
393
- matrix: Union[MatrixBase, np.ndarray],
394
- v: np.ndarray,
395
- rest_dims: tuple
396
- ) -> np.ndarray:
377
+ matrix: Union[MatrixBase, np.ndarray],
378
+ v: np.ndarray,
379
+ rest_dims: tuple
380
+ ) -> np.ndarray:
397
381
 
398
382
  res_leading_dim = matrix.shape[0] * np.prod(rest_dims)
399
- res_shape = (0,) # type: Tuple[int,...]
383
+ res_shape = (0,) # type: Tuple[int,...]
400
384
  if v.ndim == 1:
401
385
  res_shape = (res_leading_dim,)
402
386
  else:
@@ -409,13 +393,14 @@ def _matvec_impl(
409
393
  return np.tensordot(
410
394
  matrix.asmatrix(),
411
395
  v,
412
- axes=(-1,0)
396
+ axes=(-1, 0)
413
397
  ).reshape(res_shape)
414
398
  elif isinstance(matrix, ScaledIdentityMatrix):
415
399
  return (matrix.coeff * v.ravel()).reshape(res_shape)
416
400
  else:
417
401
  raise RuntimeError(f"Unsupported type{type(matrix)}!")
418
402
 
403
+
419
404
  def identity(n, dtype=np.float64) -> ScaledIdentityMatrix:
420
405
  """ Create an identity matrix """
421
406
  n = int(n)
@@ -426,14 +411,16 @@ def identity(n, dtype=np.float64) -> ScaledIdentityMatrix:
426
411
  def matrix_hash(a) -> int:
427
412
  """ Compute hash of a matrix a"""
428
413
  if isinstance(a, np.ndarray):
429
- return hash(a.data.tobytes()) # This makes a copy
414
+ return hash(a.data.tobytes()) # This makes a copy
430
415
  elif np.isscalar(a):
431
416
  return hash(a)
432
417
  else:
433
418
  return a.hash()
434
419
 
420
+
435
421
  def asmatrixtype(a) -> MatrixBase:
436
- assert isinstance(a, MatrixBase) or (isinstance(a, np.ndarray) and a.ndim==2)
422
+ assert isinstance(a, MatrixBase) or (
423
+ isinstance(a, np.ndarray) and a.ndim == 2)
437
424
  if isinstance(a, np.ndarray):
438
425
  return DenseMatrix(a)
439
426
  return a
@@ -451,10 +438,77 @@ def _vecprod(v1: np.ndarray, v2: np.ndarray, size=Optional[int]):
451
438
  res = v1[0:min_size] * v2[0:min_size]
452
439
  return _pad_by_zero(res, size)
453
440
 
441
+
454
442
  def _pad_by_zero(arr: np.ndarray, size: int):
455
443
  assert arr.size <= size
456
444
  if arr.size == size:
457
445
  return arr
458
446
  res = np.zeros(size, dtype=arr.dtype)
459
447
  res[0:arr.size] = arr
460
- return res
448
+ return res
449
+
450
+
451
+
452
+
453
+ def _add_DiagonalMatrix_DenseMatrix(a, b):
454
+ return DenseMatrix(b.asmatrix() + np.diag(a.diagonals))
455
+
456
+
457
+ def _add_DiagonalMatrix_DiagonalMatrix(a, b):
458
+ return DiagonalMatrix(a.diagonals + b.diagonals)
459
+
460
+
461
+ def _add_DiagonalMatrix_PartialDiagonalMatrix(a, b):
462
+ a_diag = a.diagonals.reshape(b.matrix.shape[0], -1)
463
+ if np.allclose(a_diag, a_diag[:, 0:1]):
464
+ return PartialDiagonalMatrix(
465
+ b.matrix + DiagonalMatrix(a_diag[:, 0]),
466
+ b.rest_dims
467
+ )
468
+ return DenseMatrix(a.asmatrix() + b.asmatrix())
469
+
470
+
471
+ def _add_PartialDiagonalMatrix_PartialDiagonalMatrix(a, b):
472
+ if a.rest_dims == b.rest_dims:
473
+ return PartialDiagonalMatrix(a.matrix + b.matrix, a.rest_dims)
474
+ return DenseMatrix(a.asmatrix() + b.asmatrix())
475
+
476
+
477
+ def _add_DenseMatrix_DenseMatrix(a, b):
478
+ return DenseMatrix(a.asmatrix() + b.asmatrix())
479
+
480
+
481
+ def _add_ScaledIdentityMatrix_ScaledIdentityMatrix(a, b):
482
+ return ScaledIdentityMatrix(a.shape, a.coeff + b.coeff)
483
+
484
+
485
+ def _add_ScaledIdentityMatrix_DiagonalMatrix(a, b):
486
+ return DiagonalMatrix(a.coeff*np.ones(a.shape[0]) + b.diagonals)
487
+
488
+
489
+ def _add_ScaledIdentityMatrix_PartialDiagonalMatrix(a, b):
490
+ return PartialDiagonalMatrix(
491
+ ScaledIdentityMatrix(
492
+ b.matrix.shape[0], a.coeff) + b.matrix,
493
+ b.rest_dims)
494
+
495
+
496
+ def _add_matrices(a, b):
497
+ assert isinstance(a, MatrixBase)
498
+ assert isinstance(b, MatrixBase)
499
+
500
+ assert a.shape == b.shape
501
+
502
+ func_name_1 = f"_add_{type(a).__name__}_{type(b).__name__}"
503
+
504
+ add_func1 = globals().get(func_name_1)
505
+ if add_func1 is not None:
506
+ return add_func1(a, b)
507
+
508
+ func_name_2 = f"_add_{type(b).__name__}_{type(a).__name__}"
509
+ add_func2 = globals().get(func_name_2)
510
+ if add_func2 is not None:
511
+ return add_func2(b, a)
512
+
513
+ return DenseMatrix(a.asmatrix() + b.asmatrix())
514
+