linalg_numpy.py (1845B)
1 ############################################################################ 2 # 3 # This file is a part of siple. 4 # 5 # Copyright 2010 David Maxwell 6 # 7 # siple is free software: you can redistribute it and/or modify 8 # it under the terms of the GNU General Public License as published by 9 # the Free Software Foundation, either version 2 of the License, or 10 # (at your option) any later version. 11 # 12 ############################################################################ 13 14 from .linalg_abstract import AbstractVector 15 import numpy as np 16 17 class NumpyVector(AbstractVector): 18 """Implements the siple.linalg.AbstractVector interface for a numpy array.""" 19 def __init__(self,u): 20 if isinstance(u,tuple): 21 u = np.ndarray(u) 22 elif not isinstance(u,np.ndarray): 23 raise ValueError("An NumpyVector can only be constructed from a numpy array or a size specification: found %s" % u) 24 25 self._core = u 26 27 def _set_from_abstract(self,rhs): 28 self._core[:] = rhs._core[:] 29 30 def _set_from_array(self,rhs): 31 self._core[:] = rhs[:] 32 33 def acc(self,rhs): 34 self._core += rhs._core 35 36 def scale(self,t): 37 self._core *= t 38 39 def axpy(self,t,v): 40 self._core += t*v._core 41 42 def copy(self): 43 return NumpyVector(self._core.copy()) 44 45 def vector_like(self): 46 return NumpyVector(np.ndarray(self._core.shape)) 47 48 def zero_like(self): 49 z = np.zeros(self._core.shape) 50 return NumpyVector(z) 51 52 def dim(self): 53 return self._core.shape[0] 54 55 def core(self): 56 return self._core 57 58 def norm(self,name): 59 if name == 'l2': 60 return np.linalg.norm(self._core,2) 61 if name == 'l1': 62 return np.linalg.norm(self._core,1) 63 if name == 'linf': 64 return np.linalg.norm(self._core,np.inf) 65 66 def __repr__(self): 67 return self._core.__repr__() 68 def __str__(self): 69 return self._core.__str__()