def test(): ''' author: twg ''' from joblib import Parallel, delayed, dump, load from tqdm import tqdm nmodes = 30 eigenval = [] eigenfn = gen_modes(nmodes, 1) beta = 0.04258226873188785 for itr in range(nmodes): eigenval.append(calc_eigenval(1, beta, itr)) eigenval = np.asarray(eigenval) eigenfn = np.asarray(eigenfn) np.savetxt(outdir + "eigenfn.csv", eigenfn, delimiter = ",") np.savetxt(outdir + "eigenval.csv", eigenval, delimiter = ",") outdir = r"/nfs/data/users/twg/gsmModes/" beamline = sxri_bl() beamline.setup_OE() #beamline.setup_beamline() #beamline.setup_metrology_beamline(beamline.bl) Parallel(n_jobs = 5,backend= "threading")(delayed(beamline.generate_mode)(mode_no, eigenfn, outdir) for mode_no in tqdm(range(nmodes)))
def solid_syms_Fourier(self, solid, apply_translation = True): # x = 0.5 + x, 0.5 - y, -z u1 = afnumpy.arrayfire.data.flip(solid.d_array, dim=1) u1 = afnumpy.arrayfire.data.flip(u1, dim=0) u1 = afnumpy.arrayfire.data.shift(u1, 1, d1=1) # x = -x, 0.5 + y, 0.5 - z u2 = afnumpy.arrayfire.data.flip(solid.d_array, dim=2) u2 = afnumpy.arrayfire.data.flip(u2, dim=0) u2 = afnumpy.arrayfire.data.shift(u2, 1, d2=1) # x = 0.5 - x, -y, 0.5 + z u3 = afnumpy.arrayfire.data.flip(solid.d_array, dim=2) u3 = afnumpy.arrayfire.data.flip(u3, dim=1) u3 = afnumpy.arrayfire.data.shift(u3, 0, d1=1, d2=1) U = afnumpy.arrayfire.data.join(3, solid.d_array, u1, u2, u3) U = afnumpy.arrayfire.data.moddims(U, self.syms.shape[3],self.syms.shape[2],self.syms.shape[1],self.syms.shape[0]) self.syms = afnumpy.asarray(U) if apply_translation : if self.translations is None : self.make_Ts() self.syms *= self.translations return self.syms
def unflip_modes_Fourier(self, U, apply_translation = True): # x = 0.5 + x, 0.5 - y, -z u1 = afnumpy.arrayfire.data.flip(U[1].d_array, dim=1) u1 = afnumpy.arrayfire.data.flip(u1, dim=0) u1 = afnumpy.arrayfire.data.shift(u1, 1, d1=1) # x = -x, 0.5 + y, 0.5 - z u2 = afnumpy.arrayfire.data.flip(U[2].d_array, dim=2) u2 = afnumpy.arrayfire.data.flip(u2, dim=0) u2 = afnumpy.arrayfire.data.shift(u2, 1, d2=1) # x = 0.5 - x, -y, 0.5 + z u3 = afnumpy.arrayfire.data.flip(U[3].d_array, dim=2) u3 = afnumpy.arrayfire.data.flip(u3, dim=1) u3 = afnumpy.arrayfire.data.shift(u3, 0, d1=1, d2=1) U_inv = afnumpy.arrayfire.data.join(3, U[0].d_array, u1, u2, u3) U_inv = afnumpy.arrayfire.data.moddims(U_inv, self.syms.shape[3],self.syms.shape[2],self.syms.shape[1],self.syms.shape[0]) U_inv = afnumpy.asarray(U_inv) if apply_translation : if self.translations is None : self.make_Ts() U_inv *= self.translations.conj() return U_inv
def arrayfire_4Dflip(a): c1 = afnumpy.arrayfire.data.flip(a.d_array, dim=1) c1 = afnumpy.arrayfire.data.shift(c1, 0, d1=1) b = afnumpy.arrayfire.data.join(3, a.d_array, c1) b = afnumpy.arrayfire.data.moddims(b, a.shape[2], a.shape[1], a.shape[0], 2) b = afnumpy.asarray(b) return b
def __init__(self, arg1, shape=None, dtype=None, copy=False): spmatrix.__init__(self) if isspmatrix(arg1): raise ValueError("Copying another sparse matrix not yet implemented") elif isinstance(arg1, tuple): if isshape(arg1): raise ValueError("Empty sparse matrices not implemented") # It's a tuple of matrix dimensions (M, N) # create empty matrix # self._shape = check_shape(arg1) else: if len(arg1) == 2: try: obj, (row, col) = arg1 except (TypeError, ValueError): raise TypeError('invalid input format') if shape is None: raise ValueError("shape parameter must not be None") obj = afnp.asarray(obj) # Arrayfire only supports floating point values if obj.dtype.kind != 'c' and obj.dtype.kind != 'f': obj = obj.astype(afnp.float32) self.dtype = obj.dtype self.d_array = arrayfire.sparse.create_sparse(afnp.asarray(obj).d_array, afnp.asarray(row).astype(afnp.int32).d_array, afnp.asarray(col).astype(afnp.int32).d_array, shape[0], shape[1], storage = arrayfire.STORAGE.COO) self.d_array = arrayfire.convert_sparse(self.d_array, arrayfire.STORAGE.CSR) self._shape = shape elif len(arg1) == 3: raise ValueError("(data, indices, indptr) format not implemented") else: raise ValueError("unrecognized %s_matrix constructor usage" % self.format) else: # must be dense try: arg1 = afnp.asarray(arg1) except: raise ValueError("unrecognized %s_matrix constructor usage" % self.format) d_array = arrayfire.sparse.create_sparse_from_dense(arg1)
def ifftshift(x, axes=None): tmp = afnumpy.asarray(x) ndim = len(tmp.shape) if axes is None: axes = list(range(ndim)) elif isinstance(axes, numbers.Integral): axes = [axes] shift = [0]*ndim for k in axes: n = tmp.shape[k] shift[k] = (n+1)//2 s = arrayfire.data.shift(tmp.d_array, *pu.c2f(shift)) return ndarray(pu.af_shape(s), dtype=pu.typemap(s.dtype()), af_array=s)
def ifftshift(x, axes=None): tmp = afnumpy.asarray(x) ndim = len(tmp.shape) if axes is None: axes = list(range(ndim)) elif isinstance(axes, numbers.Integral): axes = (axes,) y = tmp for k in axes: n = tmp.shape[k] p2 = n-(n+1)//2 mylist = afnumpy.concatenate((afnumpy.arange(p2, n), afnumpy.arange(p2))) y = afnumpy.take(y, mylist, k) return y
def angle(z, deg=0): """ Return the angle of the complex argument. Parameters ---------- z : array_like A complex number or sequence of complex numbers. deg : bool, optional Return angle in degrees if True, radians if False (default). Returns ------- angle : {ndarray, scalar} The counterclockwise angle from the positive real axis on the complex plane, with dtype as numpy.float64. See Also -------- arctan2 absolute Examples -------- >>> np.angle([1.0, 1.0j, 1+1j]) # in radians array([ 0. , 1.57079633, 0.78539816]) >>> np.angle(1+1j, deg=True) # in degrees 45.0 """ if deg: fact = 180 / pi else: fact = 1.0 z = afnumpy.asarray(z) if numpy.issubdtype(z.dtype, numpy.complexfloating): zimag = z.imag zreal = z.real else: zimag = 0 zreal = z return afnumpy.arctan2(zimag, zreal) * fact
def angle(z, deg=0): """ Return the angle of the complex argument. Parameters ---------- z : array_like A complex number or sequence of complex numbers. deg : bool, optional Return angle in degrees if True, radians if False (default). Returns ------- angle : {ndarray, scalar} The counterclockwise angle from the positive real axis on the complex plane, with dtype as numpy.float64. See Also -------- arctan2 absolute Examples -------- >>> np.angle([1.0, 1.0j, 1+1j]) # in radians array([ 0. , 1.57079633, 0.78539816]) >>> np.angle(1+1j, deg=True) # in degrees 45.0 """ if deg: fact = 180/pi else: fact = 1.0 z = afnumpy.asarray(z) if numpy.issubdtype(z.dtype, numpy.complexfloating): zimag = z.imag zreal = z.real else: zimag = 0 zreal = z return afnumpy.arctan2(zimag, zreal) * fact
def repeat(a, repeats, axis=None): """ Repeat elements of an array. Parameters ---------- a : array_like Input array. repeats : int or array of ints The number of repetitions for each element. `repeats` is broadcasted to fit the shape of the given axis. axis : int, optional The axis along which to repeat values. By default, use the flattened input array, and return a flat output array. Returns ------- repeated_array : ndarray Output array which has the same shape as `a`, except along the given axis. See Also -------- tile : Tile an array. Examples -------- >>> np.repeat(3, 4) array([3, 3, 3, 3]) >>> x = np.array([[1,2],[3,4]]) >>> np.repeat(x, 2) array([1, 1, 2, 2, 3, 3, 4, 4]) >>> np.repeat(x, 3, axis=1) array([[1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4]]) >>> np.repeat(x, [1, 2], axis=0) array([[1, 2], [3, 4], [3, 4]]) """ return afnumpy.asarray(a).repeat(repeats, axis=axis)
def solid_syms_real(self, solid): """ This uses pixel shifts (not phase ramps) for translation. Therefore sub-pixel shifts are ignored. """ translations = [] translations.append([self.unitcell_size[0]/2, self.unitcell_size[1]/2, 0]) translations.append([0, self.unitcell_size[1]/2, self.unitcell_size[2]/2]) translations.append([self.unitcell_size[0]/2, 0, self.unitcell_size[2]/2]) # x = 0.5 + x, 0.5 - y, -z u1 = afnumpy.arrayfire.data.flip(solid.d_array, dim=1) u1 = afnumpy.arrayfire.data.flip(u1, dim=0) u1 = afnumpy.arrayfire.data.shift(u1, 1, d1=1) t = translations[0] u1 = afnumpy.arrayfire.data.shift(u1, t[-1], d1=t[-2], d2=t[-3]) # x = -x, 0.5 + y, 0.5 - z u2 = afnumpy.arrayfire.data.flip(solid.d_array, dim=2) u2 = afnumpy.arrayfire.data.flip(u2, dim=0) u2 = afnumpy.arrayfire.data.shift(u2, 1, d2=1) t = translations[1] u2 = afnumpy.arrayfire.data.shift(u2, t[-1], d1=t[-2], d2=t[-3]) # x = 0.5 - x, -y, 0.5 + z u3 = afnumpy.arrayfire.data.flip(solid.d_array, dim=2) u3 = afnumpy.arrayfire.data.flip(u3, dim=1) u3 = afnumpy.arrayfire.data.shift(u3, 0, d1=1, d2=1) t = translations[2] u3 = afnumpy.arrayfire.data.shift(u3, t[-1], d1=t[-2], d2=t[-3]) U = afnumpy.arrayfire.data.join(3, solid.d_array, u1, u2, u3) U = afnumpy.arrayfire.data.moddims(U, self.syms.shape[3],self.syms.shape[2],self.syms.shape[1],self.syms.shape[0]) U = afnumpy.asarray(U) return U
def asfarray(a, dtype=_nx.float_): dtype = _nx.obj2sctype(dtype) if not issubclass(dtype, _nx.inexact): dtype = _nx.float_ return afnumpy.asarray(a, dtype=dtype)
def ravel(a, order='C'): """ Return a flattened array. A 1-D array, containing the elements of the input, is returned. A copy is made only if needed. Parameters ---------- a : array_like Input array. The elements in `a` are read in the order specified by `order`, and packed as a 1-D array. order : {'C','F', 'A', 'K'}, optional The elements of `a` are read using this index order. 'C' means to index the elements in C-like order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to index the elements in Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. 'A' means to read the elements in Fortran-like index order if `a` is Fortran *contiguous* in memory, C-like order otherwise. 'K' means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, 'C' index order is used. Returns ------- 1d_array : ndarray Output of the same dtype as `a`, and of shape ``(a.size,)``. See Also -------- ndarray.flat : 1-D iterator over an array. ndarray.flatten : 1-D array copy of the elements of an array in row-major order. Notes ----- In C-like (row-major) order, in two dimensions, the row index varies the slowest, and the column index the quickest. This can be generalized to multiple dimensions, where row-major order implies that the index along the first axis varies slowest, and the index along the last quickest. The opposite holds for Fortran-like, or column-major, index ordering. Examples -------- It is equivalent to ``reshape(-1, order=order)``. >>> x = np.array([[1, 2, 3], [4, 5, 6]]) >>> print np.ravel(x) [1 2 3 4 5 6] >>> print x.reshape(-1) [1 2 3 4 5 6] >>> print np.ravel(x, order='F') [1 4 2 5 3 6] When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering: >>> print np.ravel(x.T) [1 4 2 5 3 6] >>> print np.ravel(x.T, order='A') [1 2 3 4 5 6] When ``order`` is 'K', it will preserve orderings that are neither 'C' nor 'F', but won't reverse axes: >>> a = np.arange(3)[::-1]; a array([2, 1, 0]) >>> a.ravel(order='C') array([2, 1, 0]) >>> a.ravel(order='K') array([2, 1, 0]) >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a array([[[ 0, 2, 4], [ 1, 3, 5]], [[ 6, 8, 10], [ 7, 9, 11]]]) >>> a.ravel(order='C') array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11]) >>> a.ravel(order='K') array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) """ return afnumpy.asarray(a).ravel(order)
def __mul__(self, other): other = afnp.asarray(other).astype(self.dtype) s = arrayfire.matmul(self.d_array, other.d_array) a = afnp.ndarray(pu.af_shape(s), dtype=pu.typemap(s.dtype()), af_array=s) a._eval() return a
def norm(x, ord=None, axis=None, keepdims=False): x = asarray(x) # Check the default case first and handle it immediately. if ord is None and axis is None: ndim = x.ndim x = x.ravel(order='K') if isComplexType(x.dtype.type): sqnorm = dot(x.real, x.real) + dot(x.imag, x.imag) else: sqnorm = dot(x, x) ret = sqrt(sqnorm) if keepdims: ret = ret.reshape(ndim * [1]) return ret # Normalize the `axis` argument to a tuple. nd = x.ndim if axis is None: axis = tuple(range(nd)) elif not isinstance(axis, tuple): try: axis = int(axis) except: raise TypeError( "'axis' must be None, an integer or a tuple of integers") axis = (axis, ) if len(axis) == 1: if ord == Inf: return abs(x).max(axis=axis, keepdims=keepdims) elif ord == -Inf: return abs(x).min(axis=axis, keepdims=keepdims) elif ord == 0: # Zero norm return (x != 0).sum(axis=axis, keepdims=keepdims) elif ord == 1: # special case for speedup return afnumpy.sum(abs(x), axis=axis, keepdims=keepdims) elif ord is None or ord == 2: # special case for speedup s = (x.conj() * x).real return sqrt(afnumpy.sum(s, axis=axis, keepdims=keepdims)) else: try: ord + 1 except TypeError: raise ValueError("Invalid norm order for vectors.") if x.dtype.type is longdouble: # Convert to a float type, so integer arrays give # float results. Don't apply asfarray to longdouble arrays, # because it will downcast to float64. absx = abs(x) else: absx = x if isComplexType(x.dtype.type) else asfarray(x) if absx.dtype is x.dtype: absx = abs(absx) else: # if the type changed, we can safely overwrite absx abs(absx, out=absx) absx **= ord return afnumpy.sum(absx, axis=axis, keepdims=keepdims)**(1.0 / ord) elif len(axis) == 2: row_axis, col_axis = axis if not (-nd <= row_axis < nd and -nd <= col_axis < nd): raise ValueError('Invalid axis %r for an array with shape %r' % (axis, x.shape)) if row_axis % nd == col_axis % nd: raise ValueError('Duplicate axes given.') if ord == 2: ret = _multi_svd_norm(x, row_axis, col_axis, amax) elif ord == -2: ret = _multi_svd_norm(x, row_axis, col_axis, amin) elif ord == 1: if col_axis > row_axis: col_axis -= 1 ret = afnumpy.sum(abs(x), axis=row_axis).max(axis=col_axis) elif ord == Inf: if row_axis > col_axis: row_axis -= 1 ret = afnumpy.sum(abs(x), axis=col_axis).max(axis=row_axis) elif ord == -1: if col_axis > row_axis: col_axis -= 1 ret = afnumpy.sum(abs(x), axis=row_axis).min(axis=col_axis) elif ord == -Inf: if row_axis > col_axis: row_axis -= 1 ret = afnumpy.sum(abs(x), axis=col_axis).min(axis=row_axis) elif ord in [None, 'fro', 'f']: ret = sqrt(afnumpy.sum((x.conj() * x).real, axis=axis)) else: raise ValueError("Invalid norm order for matrices.") if keepdims: ret_shape = list(x.shape) ret_shape[axis[0]] = 1 ret_shape[axis[1]] = 1 ret = ret.reshape(ret_shape) return ret else: raise ValueError("Improper number of dimensions to norm.")
def norm(x, ord=None, axis=None, keepdims=False): x = asarray(x) # Check the default case first and handle it immediately. if ord is None and axis is None: ndim = x.ndim x = x.ravel(order='K') if isComplexType(x.dtype.type): sqnorm = dot(x.real, x.real) + dot(x.imag, x.imag) else: sqnorm = dot(x, x) ret = sqrt(sqnorm) if keepdims: ret = ret.reshape(ndim*[1]) return ret # Normalize the `axis` argument to a tuple. nd = x.ndim if axis is None: axis = tuple(range(nd)) elif not isinstance(axis, tuple): try: axis = int(axis) except: raise TypeError("'axis' must be None, an integer or a tuple of integers") axis = (axis,) if len(axis) == 1: if ord == Inf: return abs(x).max(axis=axis, keepdims=keepdims) elif ord == -Inf: return abs(x).min(axis=axis, keepdims=keepdims) elif ord == 0: # Zero norm return (x != 0).sum(axis=axis, keepdims=keepdims) elif ord == 1: # special case for speedup return afnumpy.sum(abs(x), axis=axis, keepdims=keepdims) elif ord is None or ord == 2: # special case for speedup s = (x.conj() * x).real return sqrt(afnumpy.sum(s, axis=axis, keepdims=keepdims)) else: try: ord + 1 except TypeError: raise ValueError("Invalid norm order for vectors.") if x.dtype.type is longdouble: # Convert to a float type, so integer arrays give # float results. Don't apply asfarray to longdouble arrays, # because it will downcast to float64. absx = abs(x) else: absx = x if isComplexType(x.dtype.type) else asfarray(x) if absx.dtype is x.dtype: absx = abs(absx) else: # if the type changed, we can safely overwrite absx abs(absx, out=absx) absx **= ord return afnumpy.sum(absx, axis=axis, keepdims=keepdims) ** (1.0 / ord) elif len(axis) == 2: row_axis, col_axis = axis if not (-nd <= row_axis < nd and -nd <= col_axis < nd): raise ValueError('Invalid axis %r for an array with shape %r' % (axis, x.shape)) if row_axis % nd == col_axis % nd: raise ValueError('Duplicate axes given.') if ord == 2: ret = _multi_svd_norm(x, row_axis, col_axis, amax) elif ord == -2: ret = _multi_svd_norm(x, row_axis, col_axis, amin) elif ord == 1: if col_axis > row_axis: col_axis -= 1 ret = afnumpy.sum(abs(x), axis=row_axis).max(axis=col_axis) elif ord == Inf: if row_axis > col_axis: row_axis -= 1 ret = afnumpy.sum(abs(x), axis=col_axis).max(axis=row_axis) elif ord == -1: if col_axis > row_axis: col_axis -= 1 ret = afnumpy.sum(abs(x), axis=row_axis).min(axis=col_axis) elif ord == -Inf: if row_axis > col_axis: row_axis -= 1 ret = afnumpy.sum(abs(x), axis=col_axis).min(axis=row_axis) elif ord in [None, 'fro', 'f']: ret = sqrt(afnumpy.sum((x.conj() * x).real, axis=axis)) else: raise ValueError("Invalid norm order for matrices.") if keepdims: ret_shape = list(x.shape) ret_shape[axis[0]] = 1 ret_shape[axis[1]] = 1 ret = ret.reshape(ret_shape) return ret else: raise ValueError("Improper number of dimensions to norm.")