forked from CURENT/andes
-
Notifications
You must be signed in to change notification settings - Fork 2
/
scipy.py
97 lines (73 loc) 路 1.93 KB
/
scipy.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
"""
Scipy sparse linear solver with SuperLU backend.
"""
import numpy as np
from scipy.sparse import csc_matrix
from scipy.sparse.linalg import spsolve, splu
class SciPySolver:
"""
Base class for scipy family solvers.
"""
def __init__(self):
self.factorize = True
# when `new_A` is True, rebuild and factorize A
self.new_A = True
def to_csc(self, A):
"""
Convert A to scipy.sparse.csc_matrix.
Parameters
----------
A : kvxopt.spmatrix
Sparse N-by-N matrix
Returns
-------
scipy.sparse.csc_matrix
Converted csc_matrix
"""
ccs = A.CCS
size = A.size
data = np.array(ccs[2]).ravel()
indices = np.array(ccs[1]).ravel()
indptr = np.array(ccs[0]).ravel()
return csc_matrix((data, indices, indptr), shape=size)
def solve(self, A, b):
"""
Solve linear systems.
Parameters
----------
A : scipy.csc_matrix
Sparse N-by-N matrix
b : numpy.ndarray
Dense 1-dimensional array of size N
Returns
-------
np.ndarray
Solution x to `Ax = b`
"""
raise NotImplementedError
def linsolve(self, A, b):
"""
Exactly same functionality as `solve`.
"""
return self.solve(A, b)
def clear(self):
pass
class SpSolve(SciPySolver):
"""
scipy.sparse.linalg.spsolve Solver.
"""
def solve(self, A, b):
if self.factorize or self.new_A:
A_csc = self.to_csc(A)
self.lu = splu(A_csc)
self.factorize = False
self.new_A = False
x = self.lu.solve(np.ravel(b))
return x
def linsolve(self, A, b):
"""
Solve using `spsolve`.
"""
A_csc = self.to_csc(A)
b = np.ravel(b)
return spsolve(A_csc, b)