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 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 #3
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 #4
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 #5
0
def ISRSfitfunction(x, y_acf, sensdict, simparams, 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)
    datablock = sp.zeros((nspecs, 2), dtype=x.dtype)
    datablock[:, 0] = x[sp.arange(0, nspecs * 2, 2)]
    datablock[:, 1] = x[sp.arange(1, nspecs * 2, 2)]
    v_i = x[-1]

    # 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()

    # penalties for densities not being equal
    nis = datablock[:-1, 0]
    ne = datablock[-1, 0]
    nisum = nis.sum()
    pentsum[-1] = sp.exp(-sp.absolute(ne - nisum))

    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 * 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 #6
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)
Example #7
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))