def poly(seq_of_zeros): """ Find the coefficients of a polynomial with the given sequence of roots. Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros (multiple roots must be included in the sequence as many times as their multiplicity; see Examples). A square matrix (or array, which will be treated as a matrix) can also be given, in which case the coefficients of the characteristic polynomial of the matrix are returned. Parameters ---------- seq_of_zeros : array_like, shape (N,) or (N, N) A sequence of polynomial roots, or a square array or matrix object. Returns ------- c : ndarray 1D array of polynomial coefficients from highest to lowest degree: ``c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N]`` where c[0] always equals 1. Raises ------ ValueError If input is the wrong shape (the input must be a 1-D or square 2-D array). See Also -------- polyval : Compute polynomial values. roots : Return the roots of a polynomial. polyfit : Least squares polynomial fit. poly1d : A one-dimensional polynomial class. Notes ----- Specifying the roots of a polynomial still leaves one degree of freedom, typically represented by an undetermined leading coefficient. [1]_ In the case of this function, that coefficient - the first one in the returned array - is always taken as one. (If for some reason you have one other point, the only automatic way presently to leverage that information is to use ``polyfit``.) The characteristic polynomial, :math:`p_a(t)`, of an `n`-by-`n` matrix **A** is given by :math:`p_a(t) = \\mathrm{det}(t\\, \\mathbf{I} - \\mathbf{A})`, where **I** is the `n`-by-`n` identity matrix. [2]_ References ---------- .. [1] M. Sullivan and M. Sullivan, III, "Algebra and Trignometry, Enhanced With Graphing Utilities," Prentice-Hall, pg. 318, 1996. .. [2] G. Strang, "Linear Algebra and Its Applications, 2nd Edition," Academic Press, pg. 182, 1980. Examples -------- Given a sequence of a polynomial's zeros: >>> np.poly((0, 0, 0)) # Multiple root example array([1, 0, 0, 0]) The line above represents z**3 + 0*z**2 + 0*z + 0. >>> np.poly((-1./2, 0, 1./2)) array([ 1. , 0. , -0.25, 0. ]) The line above represents z**3 - z/4 >>> np.poly((np.random.random(1.)[0], 0, np.random.random(1.)[0])) array([ 1. , -0.77086955, 0.08618131, 0. ]) #random Given a square array object: >>> P = np.array([[0, 1./3], [-1./2, 0]]) >>> np.poly(P) array([ 1. , 0. , 0.16666667]) Or a square matrix object: >>> np.poly(np.matrix(P)) array([ 1. , 0. , 0.16666667]) Note how in all cases the leading coefficient is always 1. """ seq_of_zeros = atleast_1d(seq_of_zeros) sh = seq_of_zeros.shape if len(sh) == 2 and sh[0] == sh[1] and sh[0] != 0: seq_of_zeros = eigvals(seq_of_zeros) elif len(sh) == 1: dt = seq_of_zeros.dtype # Let object arrays slip through, e.g. for arbitrary precision if dt != object: seq_of_zeros = seq_of_zeros.astype(mintypecode(dt.char)) else: raise ValueError("input must be 1d or non-empty square 2d array.") if len(seq_of_zeros) == 0: return 1.0 dt = seq_of_zeros.dtype a = ones((1,), dtype=dt) for k in range(len(seq_of_zeros)): a = NX.convolve(a, array([1, -seq_of_zeros[k]], dtype=dt), mode='full') if issubclass(a.dtype.type, NX.complexfloating): # if complex roots are all complex conjugates, the roots are real. roots = NX.asarray(seq_of_zeros, complex) pos_roots = sort_complex(NX.compress(roots.imag > 0, roots)) neg_roots = NX.conjugate(sort_complex( NX.compress(roots.imag < 0, roots))) if (len(pos_roots) == len(neg_roots) and NX.alltrue(neg_roots == pos_roots)): a = a.real.copy() return a
def poly(seq_of_zeros): """ Find the coefficients of a polynomial with the given sequence of roots. Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros (multiple roots must be included in the sequence as many times as their multiplicity; see Examples). A square matrix (or array, which will be treated as a matrix) can also be given, in which case the coefficients of the characteristic polynomial of the matrix are returned. Parameters ---------- seq_of_zeros : array_like, shape (N,) or (N, N) A sequence of polynomial roots, or a square array or matrix object. Returns ------- c : ndarray 1D array of polynomial coefficients from highest to lowest degree: ``c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N]`` where c[0] always equals 1. Raises ------ ValueError If input is the wrong shape (the input must be a 1-D or square 2-D array). See Also -------- polyval : Evaluate a polynomial at a point. roots : Return the roots of a polynomial. polyfit : Least squares polynomial fit. poly1d : A one-dimensional polynomial class. Notes ----- Specifying the roots of a polynomial still leaves one degree of freedom, typically represented by an undetermined leading coefficient. [1]_ In the case of this function, that coefficient - the first one in the returned array - is always taken as one. (If for some reason you have one other point, the only automatic way presently to leverage that information is to use ``polyfit``.) The characteristic polynomial, :math:`p_a(t)`, of an `n`-by-`n` matrix **A** is given by :math:`p_a(t) = \\mathrm{det}(t\\, \\mathbf{I} - \\mathbf{A})`, where **I** is the `n`-by-`n` identity matrix. [2]_ References ---------- .. [1] M. Sullivan and M. Sullivan, III, "Algebra and Trignometry, Enhanced With Graphing Utilities," Prentice-Hall, pg. 318, 1996. .. [2] G. Strang, "Linear Algebra and Its Applications, 2nd Edition," Academic Press, pg. 182, 1980. Examples -------- Given a sequence of a polynomial's zeros: >>> np.poly((0, 0, 0)) # Multiple root example array([1, 0, 0, 0]) The line above represents z**3 + 0*z**2 + 0*z + 0. >>> np.poly((-1./2, 0, 1./2)) array([ 1. , 0. , -0.25, 0. ]) The line above represents z**3 - z/4 >>> np.poly((np.random.random(1.)[0], 0, np.random.random(1.)[0])) array([ 1. , -0.77086955, 0.08618131, 0. ]) #random Given a square array object: >>> P = np.array([[0, 1./3], [-1./2, 0]]) >>> np.poly(P) array([ 1. , 0. , 0.16666667]) Or a square matrix object: >>> np.poly(np.matrix(P)) array([ 1. , 0. , 0.16666667]) Note how in all cases the leading coefficient is always 1. """ seq_of_zeros = atleast_1d(seq_of_zeros) sh = seq_of_zeros.shape if len(sh) == 2 and sh[0] == sh[1] and sh[0] != 0: seq_of_zeros = eigvals(seq_of_zeros) elif len(sh) == 1: dt = seq_of_zeros.dtype # Let object arrays slip through, e.g. for arbitrary precision if dt != object: seq_of_zeros = seq_of_zeros.astype(mintypecode(dt.char)) else: raise ValueError("input must be 1d or non-empty square 2d array.") if len(seq_of_zeros) == 0: return 1.0 dt = seq_of_zeros.dtype a = ones((1, ), dtype=dt) for k in range(len(seq_of_zeros)): a = NX.convolve(a, array([1, -seq_of_zeros[k]], dtype=dt), mode='full') if issubclass(a.dtype.type, NX.complexfloating): # if complex roots are all complex conjugates, the roots are real. roots = NX.asarray(seq_of_zeros, complex) pos_roots = sort_complex(NX.compress(roots.imag > 0, roots)) neg_roots = NX.conjugate( sort_complex(NX.compress(roots.imag < 0, roots))) if (len(pos_roots) == len(neg_roots) and NX.alltrue(neg_roots == pos_roots)): a = a.real.copy() return a
def test_matscalar(self): b1 = matrix(ones((3,3),dtype=complex)) assert_equal(b1*1.0, b1)
def test_matscalar(self): b1 = matrix(ones((3, 3), dtype=complex)) assert_equal(b1 * 1.0, b1)
def coarseMolSurface(molFrag,XYZd,isovalue=5.0,resolution=-0.4,padding=0.0, name='CoarseMolSurface',geom=None): """ Function adapted from the Vision network which compute a coarse molecular surface in PMV @type molFrag: MolKit.AtomSet @param molFrag: the atoms selection @type XYZd: array @param XYZd: shape of the volume @type isovalue: float @param isovalue: isovalue for the isosurface computation @type resolution: float @param resolution: resolution of the final mesh @type padding: float @param padding: the padding @type name: string @param name: the name of the resultante geometry @type geom: DejaVu.Geom @param geom: update geom instead of creating a new one @rtype: DejaVu.Geom @return: the created or updated DejaVu.Geom """ import pdb from MolKit.molecule import Atom atoms = molFrag.findType(Atom) coords = atoms.coords radii = atoms.vdwRadius from UTpackages.UTblur import blur import numpy.core as Numeric volarr, origin, span = blur.generateBlurmap(coords, radii, XYZd,resolution, padding = 0.0) volarr.shape = (XYZd[0],XYZd[1],XYZd[2]) volarr = Numeric.ascontiguousarray(Numeric.transpose(volarr), 'f') weights = Numeric.ones(len(radii), 'f') h = {} from Volume.Grid3D import Grid3DF maskGrid = Grid3DF( volarr, origin, span , h) h['amin'], h['amax'],h['amean'],h['arms']= maskGrid.stats() from UTpackages.UTisocontour import isocontour isocontour.setVerboseLevel(0) data = maskGrid.data origin = Numeric.array(maskGrid.origin).astype('f') stepsize = Numeric.array(maskGrid.stepSize).astype('f') if data.dtype.char!=Numeric.float32: data = data.astype('f')#Numeric.Float32) newgrid3D = Numeric.ascontiguousarray(Numeric.reshape( Numeric.transpose(data), (1, 1)+tuple(data.shape) ), data.dtype.char) ndata = isocontour.newDatasetRegFloat3D(newgrid3D, origin, stepsize) isoc = isocontour.getContour3d(ndata, 0, 0, isovalue, isocontour.NO_COLOR_VARIABLE) vert = Numeric.zeros((isoc.nvert,3)).astype('f') norm = Numeric.zeros((isoc.nvert,3)).astype('f') col = Numeric.zeros((isoc.nvert)).astype('f') tri = Numeric.zeros((isoc.ntri,3)).astype('i') isocontour.getContour3dData(isoc, vert, norm, col, tri, 0) if maskGrid.crystal: vert = maskGrid.crystal.toCartesian(vert) return (vert, tri)
# array() # linspace() # logspace() # arange() # zeros() # ones() """ from numpy import * arr = array( [1, 2, 3, 4, 5.0] ) #implict conversion : means in the array one element is float so it will convert the entire array into float print(arr.dtype) print("\n example linspace()") als = linspace( 0, 15, 25 ) #linspace(start,stop,range)=> means in given range it will create mention range number of parts print(als) print("\n example of logspace()") ls = logspace(1, 40, 5) print(ls) print("\n example of zeros()") zs = zeros(5) print(zs) print("\n example of ones()") os = ones(22) print(os)
def coarseMolSurface(molFrag, XYZd, isovalue=5.0, resolution=-0.4, padding=0.0, name='CoarseMolSurface', geom=None): """ Function adapted from the Vision network which compute a coarse molecular surface in PMV @type molFrag: MolKit.AtomSet @param molFrag: the atoms selection @type XYZd: array @param XYZd: shape of the volume @type isovalue: float @param isovalue: isovalue for the isosurface computation @type resolution: float @param resolution: resolution of the final mesh @type padding: float @param padding: the padding @type name: string @param name: the name of the resultante geometry @type geom: DejaVu.Geom @param geom: update geom instead of creating a new one @rtype: DejaVu.Geom @return: the created or updated DejaVu.Geom """ import pdb from MolKit.molecule import Atom atoms = molFrag.findType(Atom) coords = atoms.coords radii = atoms.vdwRadius from UTpackages.UTblur import blur import numpy.core as Numeric volarr, origin, span = blur.generateBlurmap(coords, radii, XYZd, resolution, padding=0.0) volarr.shape = (XYZd[0], XYZd[1], XYZd[2]) volarr = Numeric.ascontiguousarray(Numeric.transpose(volarr), 'f') weights = Numeric.ones(len(radii), 'f') h = {} from Volume.Grid3D import Grid3DF maskGrid = Grid3DF(volarr, origin, span, h) h['amin'], h['amax'], h['amean'], h['arms'] = maskGrid.stats() from UTpackages.UTisocontour import isocontour isocontour.setVerboseLevel(0) data = maskGrid.data origin = Numeric.array(maskGrid.origin).astype('f') stepsize = Numeric.array(maskGrid.stepSize).astype('f') if data.dtype.char != Numeric.float32: data = data.astype('f') #Numeric.Float32) newgrid3D = Numeric.ascontiguousarray( Numeric.reshape(Numeric.transpose(data), (1, 1) + tuple(data.shape)), data.dtype.char) ndata = isocontour.newDatasetRegFloat3D(newgrid3D, origin, stepsize) isoc = isocontour.getContour3d(ndata, 0, 0, isovalue, isocontour.NO_COLOR_VARIABLE) vert = Numeric.zeros((isoc.nvert, 3)).astype('f') norm = Numeric.zeros((isoc.nvert, 3)).astype('f') col = Numeric.zeros((isoc.nvert)).astype('f') tri = Numeric.zeros((isoc.ntri, 3)).astype('i') isocontour.getContour3dData(isoc, vert, norm, col, tri, 0) if maskGrid.crystal: vert = maskGrid.crystal.toCartesian(vert) return (vert, tri)