Example #1
0
def norm2(x):
    """compute |x|^2 = x*conjugate(x)"""
    if iscomplexobj(x):
#        t1=time.time()
#        mat1=x.real**2 + x.imag**2
#        t2=time.time()
        mat2=multiply(x.real,x.real) + multiply(x.imag,x.imag)
#        t3=time.time()
#        print('---------------------------')
#        print('pow time='+str(t2-t1))
#        print('multiply time='+str(t3-t2))
#        print('pow time/multiply time='+str((t2-t1)/(t3-t2)))
#        print('shape(x)='+str(shape(x)))
#        print('x.typecode='+str(x.typecode()))
#        print('mat1.typecode='+str(mat1.typecode()))
#        print('mat2.typecode='+str(mat2.typecode()))
#        if len(shape(x))==1:
#            print('type(x[0])='+str(type(x[0])))
#            print('type(mat1[0])='+str(type(mat1[0])))
#            print('type(mat2[0])='+str(type(mat2[0])))
#        else:
#            print('type(x[0,0])='+str(type(x[0,0])))
#            print('type(mat1[0,0])='+str(type(mat1[0,0])))
#            print('type(mat2[0,0])='+str(type(mat2[0,0])))
        return mat2
    else:
        return multiply(x,x)
Example #2
0
def awgn(sig,snrdb,sigpower=0):
    """Additive white gaussian noise.  Assumes signal power is 0 dBW"""
    if sp.iscomplexobj(sig):
        noise = (sp.randn(*sig.shape) + 1j*sp.randn(*sig.shape))/math.sqrt(2)
    else:
        noise = sp.randn(*sig.shape)
    noisev = 10**((sigpower - snrdb)/20)
    return sig + noise*noisev
Example #3
0
    def numpyAssertAlmostEqualElements(self, a, prec=1.0000000000000001e-005):
        """Test for equality of all elements of array a."""

        if iscomplexobj(a):
            assert allclose(a.real.min(), a.real.max(), prec)
            assert allclose(a.imag.min(), a.imag.max(), prec)
        else:
            assert allclose(a.min(), a.max(), prec)
Example #4
0
    def numpyAssertEqualElements(self, a):
        """Test for equality of all elements of array a."""

        if iscomplexobj(a):
            self.assertEqual(a.real.min(), a.real.max())
            self.assertEqual(a.imag.min(), a.imag.max())
        else:
            self.assertEqual(a.min(), a.max())
Example #5
0
    def numpyAssertAlmostEqualElements(self, a, prec=1.0000000000000001e-005):
        """Test for equality of all elements of array a."""

        if iscomplexobj(a):
            assert allclose(a.real.min(), a.real.max(), prec)
            assert allclose(a.imag.min(), a.imag.max(), prec)
        else:
            assert allclose(a.min(), a.max(), prec)
Example #6
0
    def numpyAssertEqualElements(self, a):
        """Test for equality of all elements of array a."""

        if iscomplexobj(a):
            self.assertEqual(a.real.min(), a.real.max())
            self.assertEqual(a.imag.min(), a.imag.max())
        else:
            self.assertEqual(a.min(), a.max())
Example #7
0
def awgn(sig, snrdb, sigpower=0):
    """Additive white gaussian noise.  Assumes signal power is 0 dBW"""
    if sp.iscomplexobj(sig):
        noise = (sp.randn(*sig.shape) +
                 1j * sp.randn(*sig.shape)) / math.sqrt(2)
    else:
        noise = sp.randn(*sig.shape)
    noisev = 10**((sigpower - snrdb) / 20)
    return sig + noise * noisev
Example #8
0
    def numpyAssertAlmostEqual(self, a1, a2, prec=1.0000000000000001e-005):
        """Test for approximately equality of array fields a1 and a2."""

        self.assertEqual(type(a1), type(a2))
        self.assertEqual(a1.shape, a2.shape)
        self.assertEqual(a1.dtype, a2.dtype)

        if iscomplexobj(a1):
            ar1, ar2 = a1.real.ravel(), a2.real.ravel()
            assert allclose(ar1, ar2, prec)

            ar1, ar2 = a1.imag.ravel(), a2.imag.ravel()
            assert allclose(ar1, ar2, prec)
        else:
            assert allclose(a1, a2, prec)
Example #9
0
    def numpyAssertAlmostEqual(self, a1, a2, prec=1.0000000000000001e-005):
        """Test for approximately equality of array fields a1 and a2."""

        self.assertEqual(type(a1), type(a2))
        self.assertEqual(a1.shape, a2.shape)
        self.assertEqual(a1.dtype, a2.dtype)

        if iscomplexobj(a1):
            ar1, ar2 = a1.real.ravel(), a2.real.ravel()
            assert allclose(ar1, ar2, prec)

            ar1, ar2 = a1.imag.ravel(), a2.imag.ravel()
            assert allclose(ar1, ar2, prec)
        else:
            assert allclose(a1, a2, prec)
Example #10
0
    def __call__(self, field, skip=1, stat=False):

        self.fig = pl.gcf()
        self.axis = pl.gca()
        self.axis.set_title(field.name)

        if self.map is None: self.map = mappers.mapper(field.grid)
        if self.method is None:
            self.method = self.map.contourf
            self.copts.update(extend='both')

        self.map.draw()

        args = []
        X, Y = self.map(field.grid['lon'], field.grid['lat'])
        args.append(X[::skip, ::skip])
        args.append(Y[::skip, ::skip])
        z = field.data[0, 0, ::skip, ::skip]
        args.append(sp.real(z))
        if sp.any(sp.iscomplexobj(z.view(sp.ndarray))): args.append(sp.imag(z))

        cs = self.method(*args, **self.copts)

        if isinstance(cs, mlib.contour.ContourSet):
            if cs.filled:
                if self.cbar_opts is not None:
                    cb = pl.colorbar(**self.cbar_opts)
                    units = getattr(field, 'units', "")
                    cb.set_label(units)
            else:
                cs.clabel(**self.clab_opts)

        if stat:
            mean, std = field.aave(ret_std=True)
            ss = 'mean: %1.2f\nstd: %1.2f' % (mean.data.squeeze(),
                                              std.data.squeeze())
            self.draw_stat(ss)

        return cs
Example #11
0
 def is_complex(self):
     """Return whether the random numbers drawn from this probability
     distribution are complex."""
     # 2012-08-01
     return scipy.iscomplexobj(self(count_copies=False))
Example #12
0
File: dist.py Project: proggy/tb
 def is_complex(self):
     """Return whether the random numbers drawn from this probability
     distribution are complex."""
     # 2012-08-01
     return scipy.iscomplexobj(self(count_copies=False))
Example #13
0
def ISRSfitfunction(x,y_acf,sensdict,simparams,Niratios,y_err = None):
    """
    This is the fit fucntion that is used with scipy.optimize.leastsquares. It will
    take a set parameter values construct a spectrum/acf based on those values, apply
    the ambiguity function and take the difference between the two. Since the ACFs are
    complex the arrays split up and the size doubled as it is output.
    Inputs
    x - A Np array of parameter values used
    y_acf - This is the esitmated ACF/spectrum represented as a complex numpy array
    sensdict - This is a dictionary that holds many of the sensor parameters.
    simparams - This is a dictionary that holds info on the simulation parameters.
    y_err -  default None - A numpy array of size Nd that holds the standard deviations of the data.
    Output
    y_diff - A Nd or 2Nd array if input data is complex that is the difference
    between the data and the fitted model"""
    npts = simparams['numpoints']
    specs = simparams['species']
    amb_dict = simparams['amb_dict']
    numtype = simparams['dtype']
    if 'FitType' in simparams.keys():
        fitspec = simparams['FitType']
    else:
        fitspec ='Spectrum'
    nspecs = len(specs)

    (Ti,Ne,Te,v_i) = x
    datablock = sp.zeros((nspecs,2),dtype=x.dtype)
    datablock[:-1,0] = Ne*Niratios
    datablock[:-1,1] = Ti
    datablock[-1,0] = Ne
    datablock[-1,1] = Te

    # determine if you've gone beyond the bounds
    # penalty for being less then zero
    grt0 = sp.exp(-datablock)
    pentsum = sp.zeros(grt0.size+1)
    pentsum[:-1] = grt0.flatten()


    specobj = ISRSpectrum(centerFrequency =sensdict['fc'],nspec = npts,sampfreq=sensdict['fs'])
    (omeg,cur_spec,rcs) = specobj.getspecsep(datablock,specs,v_i,rcsflag=True)
    cur_spec.astype(numtype)
    # Create spectrum guess
    (tau,acf) = spect2acf(omeg,cur_spec)

    if amb_dict['WttMatrix'].shape[-1]!=acf.shape[0]:
        pdb.set_trace()
    guess_acf = sp.dot(amb_dict['WttMatrix'],acf)
    # apply ambiguity function

    guess_acf = guess_acf*rcs/guess_acf[0].real
    if fitspec.lower()=='spectrum':
        # fit to spectrums
        spec_interm = scfft.fft(guess_acf,n=len(cur_spec))
        spec_final = spec_interm.real
        y_interm = scfft.fft(y_acf,n=len(spec_final))
        y = y_interm.real
        yout = (y-spec_final)
    elif fitspec.lower() =='acf':
        yout = y_acf-guess_acf

    if y_err is not None:
        yout = yout*1./y_err
    # Cannot make the output a complex array! To avoid this problem simply double
    # the size of the array and place the real and imaginary parts in alternating spots.
    if sp.iscomplexobj(yout):
        youttmp=yout.copy()
        yout=sp.zeros(2*len(youttmp)).astype(youttmp.real.dtype)
        yout[::2]=youttmp.real
        yout[1::2] = youttmp.imag

    penadd = sp.sqrt(sp.power(sp.absolute(yout),2).sum())*pentsum.sum()
    return yout+penadd
Example #14
0
def ISRSfitfunction(x,y_acf,sensdict,simparams,Niratios,y_err = None):
    """
    This is the fit fucntion that is used with scipy.optimize.leastsquares. It will
    take a set parameter values construct a spectrum/acf based on those values, apply
    the ambiguity function and take the difference between the two. Since the ACFs are
    complex the arrays split up and the size doubled as it is output.
    Inputs
    x - A Np array of parameter values used
    y_acf - This is the esitmated ACF/spectrum represented as a complex numpy array
    sensdict - This is a dictionary that holds many of the sensor parameters.
    simparams - This is a dictionary that holds info on the simulation parameters.
    y_err -  default None - A numpy array of size Nd that holds the standard deviations of the data.
    Output
    y_diff - A Nd or 2Nd array if input data is complex that is the difference
    between the data and the fitted model"""
    npts = simparams['numpoints']
    specs = simparams['species']
    amb_dict = simparams['amb_dict']
    numtype = simparams['dtype']
    if 'FitType' in simparams.keys():
        fitspec = simparams['FitType']
    else:
        fitspec ='Spectrum'
    nspecs = len(specs)

    (Ti,Ne,Te,v_i) = x
    datablock = sp.zeros((nspecs,2),dtype=x.dtype)
    datablock[:-1,0] = Ne*Niratios
    datablock[:-1,1] = Ti
    datablock[-1,0] = Ne
    datablock[-1,1] = Te

    # determine if you've gone beyond the bounds
    # penalty for being less then zero
    grt0 = sp.exp(-datablock)
    pentsum = sp.zeros(grt0.size+1)
    pentsum[:-1] = grt0.flatten()


    specobj = ISRSpectrum(centerFrequency =sensdict['fc'],nspec = npts,sampfreq=sensdict['fs'])
    (omeg,cur_spec,rcs) = specobj.getspecsep(datablock,specs,v_i,rcsflag=True)
    cur_spec.astype(numtype)
    # Create spectrum guess
    (tau,acf) = spect2acf(omeg,cur_spec)

    if amb_dict['WttMatrix'].shape[-1]!=acf.shape[0]:
        pdb.set_trace()
    guess_acf = sp.dot(amb_dict['WttMatrix'],acf)
    # apply ambiguity function

    guess_acf = guess_acf*rcs/guess_acf[0].real
    if fitspec.lower()=='spectrum':
        # fit to spectrums
        spec_interm = scfft.fft(guess_acf,n=len(cur_spec))
        spec_final = spec_interm.real
        y_interm = scfft.fft(y_acf,n=len(spec_final))
        y = y_interm.real
        yout = (y-spec_final)
    elif fitspec.lower() =='acf':
        yout = y_acf-guess_acf

    if y_err is not None:
        yout = yout*1./y_err
    # Cannot make the output a complex array! To avoid this problem simply double
    # the size of the array and place the real and imaginary parts in alternating spots.
    if sp.iscomplexobj(yout):
        youttmp=yout.copy()
        yout=sp.zeros(2*len(youttmp)).astype(youttmp.real.dtype)
        yout[::2]=youttmp.real
        yout[1::2] = youttmp.imag

    penadd = sp.sqrt(sp.power(sp.absolute(yout),2).sum())*pentsum.sum()
    return yout+penadd
Example #15
0
2 * A  # scalar multiplication of matrix A
A.T  # matrix A transpose
A * A  # matrix multiplication
A ** 2  # Matrix 2 to the power of 2 (same as A*A)
B = 5 * sp.diag([1.0, 3, 5])
sp.mat(B)  # converts B to matrix type
sp.mat(B).I  # computes matrix inverse of sp.mat(B)

# isnan, isfinite, isinf are newly added functions to NumPy
C = B  # copy matrix B into C
C[0, 1] = sp.nan  # insert NaN value into 1st row, 2nd column element
sp.isnan(C)  # yields all 'False' elements except one element as True

# looking at complex numbers
a4 = sp.array([1 + 1j, 2, 5j])  # create complex array
sp.iscomplexobj(a4)  # determine whether a4 is complex (TRUE)
sp.isreal(a4)  # determines element by element which are REAL or COMPLEX
sp.iscomplex(a4)  # determination of COMPLEX elements
type(a4)  # outputs type and functional dependencies

# concatenating matrices and arrays:
a5 = sp.array([1, 2, 3])
a6 = sp.array([4, 5, 6])
sp.vstack((a5, a6))  # vertical array concatenation
sp.hstack((a5, a6))  # horizontal array concat
dstack((a5, a6))  # vertical array concat, transposed

# view all variables that have been created thus far:
sp.who()  # python command, similar to MATLAB

# importing and using matplotlib (plotting library from MATLAB)