2from ..debugging
import debug
3from .imports
import dependsOnPackage, ensureImported
5from sympy
import Matrix, ImmutableMatrix, latex, sympify, pprint, eye, randMatrix, flatten, sqrt, zeros, Integer, Float
9def matrix(string, rows=None, cols=None, cp=False, np=False, immutable=False, verbose=False):
11 assert rows
is None or cols
is None
17 _caster =
lambda x: list(map(
lambda a: list(map(
lambda b: float(b), a)), x))
19 type_ = Matrix
if not immutable
else ImmutableMatrix
20 _caster = _caster =
lambda x: list(map(
lambda a: list(map(
lambda b: sympify(b), a)), x))
22 if string.startswith(
'c'):
25 elif string.startswith(
'r'):
28 elif rows
is None and cols
is None:
31 num = er.anyOf(er.optional(
'-')+er.matchMax(er.anyCharExcept(er.space))+er.space, er.optional(
'-')+er.optional(
r'\.')+er.anything).compile()
34 _cols = string.split(
';')
35 _cols = [num.findall(i)
for i
in _cols]
37 debug(_cols, active=verbose)
42 for c
in range(len(_cols[0])):
45 _rows[-1].append(i[c])
46 ans = type_(_caster(_rows))
48 _rows = string.split(
';')
49 debug(_rows, active=verbose)
50 ans = type_(_caster([num.findall(i)
for i
in _rows]))
53 from clipboard
import copy
59def combineMatricies(*mats):
64 rtn = rtn.col_insert(index, c)
71class Space(sp.matrices.matrices.MatrixSubspaces):
72 def __init__(self, *bases):
73 if len(bases) == 1
and isinstance(bases[0], (list, tuple)):
76 self.
bases = self.
basis = ensureIterable(bases)
78 def __contains__(self, mat):
80 return any(Matrix.hstack(*self.
bases).LUsolve(mat))
81 except (ValueError, ShapeError)
as err:
85 return prettyMats(self.
bases)
88 def orthogonal_basis(self):
89 return Matrix.orthogonalize(*self.
basis)
92 def orthonormal_basis(self):
93 return Matrix.orthogonalize(*self.
basis, normalize=
True)
95 def orthogonalized(self):
98 def orthonormalized(self):
101 def projectionMatrix(self):
107 return Space([M.col(pivot)
for pivot
in M.rref()[1]])
110 return {i[0]:
Space(i[2])
for i
in mat.eigenvects()}
112def convert2Equs(mat, vars):
113 """ Converts a matrix into the list of equations it represents """
115 assert mat.cols == len(vars), f
'Must have exactly 1 variable for each column ({mat.cols} columns, {len(vars)} variables)'
117 for i
in range(mat.rows):
119 for cnt, e
in enumerate(mat.row(i)):
125 debug(
'This is wrong', clr=-1)
126 first = args[0].eigenvals()
127 return all(i == first
for i
in args)
130def steadyState(stochastic, accuracy=10000000000000, verbose=False):
132 if isinstance(stochastic, np.ndarray):
133 stochastic = Matrix(stochastic)
138 assert stochastic.cols == stochastic.rows,
"Stochastic matricies must be square"
139 P = stochastic-eye(stochastic.cols)
149 P = Matrix(np.array((P*accuracy).tolist(), dtype=int))
156 w = [m / sum(flatten(m))
for m
in P.nullspace()]
162 return [(matrix2numpy(ans, dtype=float)
if numpy
else ans)
for ans
in w]
164@dependsOnPackage('sympy', ('randMatrix', 'flatten', 'Matrix'))
165def randMarkovState(rows, balanced=True, np=False):
166 cast = matrix2numpy
if np
else lambda a, **_: a
168 r = randMatrix(rows, 1)
169 return cast(r / sum(flatten(r.tolist())), dtype=float)
171 tmp = ([1] + ([0]*(rows-1)))
173 return cast(Matrix([tmp]).T, dtype=float)
175@dependsOnPackage('sympy', 'Matrix')
176def isOrthogonal(*vects, innerProduct=None):
177 if innerProduct
is None:
178 innerProduct = Matrix.dot
179 return not any([innerProduct(v1, v2)
for v2
in vects
for v1
in vects
if v1 != v2])
188@dependsOnPackage('sympy', 'sqrt')
191 return sqrt(sum([i**2
for i
in v]))
193def EuclideanDist(u, v):
194 return vectorLength(u-v)
197def manhattanDist(a, b):
198 assert len(a) == len(b)
199 return sum(abs(a[i] - b[i])
for i
in range(len(a)))
202def minkowskiDist(a, b, p):
203 assert len(a) == len(b)
204 return sum([abs(a[i] - b[i])**p
for i
in range(len(a))])**(1/p)
217def orthonormalize(orthogonalSet):
218 return [v / vectorLength(v)
for v
in orthogonalSet]
223def splitVector(y:
'Matrix', W:
'Space', innerProduct=
None) -> list:
224 """ Returns vectors in W which can be linearly combined to get y """
225 if innerProduct
is None:
226 innerProduct = Matrix.dot
227 return [(innerProduct(y, u) / innerProduct(u, u))*u
for u
in W.orthogonal_basis]
235def project(y:
'Matrix', W:
'Space', innerProduct=
None) ->
'(vector in W, vector in W⟂)':
236 """ W = a subspace of R^n we want to describe y with (to get proj_y)
238 proj_y = a vector
in W
239 z = a vector
in W⟂ (W perp)
"""
240 if innerProduct
is None:
241 innerProduct = Matrix.dot
242 proj_y = sum(splitVector(y, W, innerProduct), start=zeros(y.rows, 1))
260def normalizePercentage(p, error='Percentage is of the wrong type (int
or float expected)
'):
261 if isinstance(p, (int, Integer)):
263 elif isinstance(p, (float, Float)):
265 elif isinstance(p, bool):
271 if error
is not None:
272 raise TypeError(error)
def orthonormal_basis(self)
def orthogonal_basis(self)