예제 #1
0
def ampToProb(N, psiN, marked):
    prob = zeros((N, 1))
    probMarked = zeros((N, 1))
    for x in range(N):
        prob[x] += (absolute(psiN[x])**2)
        probMarked[x] += (absolute(psiN[marked])**2)
    return prob, probMarked
예제 #2
0
def default_fill_value(obj):
    "Function to calculate default fill value for an object."
    if isinstance(obj, types.FloatType):
        return default_real_fill_value
    elif isinstance(obj, types.IntType) or isinstance(obj, types.LongType):
        return default_integer_fill_value
    elif isinstance(obj, types.StringType):
        return default_character_fill_value
    elif isinstance(obj, types.ComplexType):
        return default_complex_fill_value
    elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray):
        x = obj.dtype.char
        if x in typecodes["Float"]:
            return default_real_fill_value
        if x in typecodes["Integer"]:
            return default_integer_fill_value
        if x in typecodes["Complex"]:
            return default_complex_fill_value
        if x in typecodes["Character"]:
            return default_character_fill_value
        if x in typecodes["UnsignedInteger"]:
            return umath.absolute(default_integer_fill_value)
        return default_object_fill_value
    else:
        return default_object_fill_value
예제 #3
0
    def test_abs_blocked(self):
        "simd tests on abs"
        for dt in [np.float32, np.float64]:
            for out, inp, msg in _gen_alignment_data(dtype=dt,
                                                     type='unary',
                                                     max_size=17):
                tgt = [ncu.absolute(i) for i in inp]
                np.absolute(inp, out=out)
                assert_equal(out, tgt, err_msg=msg)
                self.assertTrue((out >= 0).all())

                # will throw invalid flag depending on compiler optimizations
                with np.errstate(invalid='ignore'):
                    for v in [np.nan, -np.inf, np.inf]:
                        for i in range(inp.size):
                            d = np.arange(inp.size, dtype=dt)
                            inp[:] = -d
                            inp[i] = v
                            d[i] = -v if v == -np.inf else v
                            assert_array_equal(np.abs(inp), d, err_msg=msg)
                            np.abs(inp, out=out)
                            assert_array_equal(out, d, err_msg=msg)

                            assert_array_equal(-inp, -1 * inp, err_msg=msg)
                            np.negative(inp, out=out)
                            assert_array_equal(out, -1 * inp, err_msg=msg)
예제 #4
0
 def denoise(self, data, wavelet):
     noiseSigma = median(absolute(data - median(data))) / 0.6745
     levels = int(floor(log(len(data))))
     WC = pywt.wavedec(data, wavelet, level=levels)
     threshold = noiseSigma * sqrt(2 * log(len(data)))
     NWC = map(lambda x: pywt.thresholding.hard(x, threshold), WC)
     return pywt.waverec(NWC, wavelet)
예제 #5
0
def approx (a, b, fill_value=1, rtol=1.e-5, atol=1.e-8):
    """Returns true if all components of a and b are equal subject to given tolerances.
    If fill_value is 1, masked values considered equal.
    If fill_value is 0, masked values considered unequal.
    The relative error rtol should be positive and << 1.0
    The absolute error atol comes into play for those elements of b that are 
    very small or zero; it says how small a must be also.
    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return N.equal(d1,d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = N.less_equal(umath.absolute(x-y), atol + rtol * umath.absolute(y))
    return d.ravel()
예제 #6
0
def valueOfGamma(N, H, gamma):
    x = []
    y = []
    plotName = ""
    for h, gamma in zip(hamList2, gammaList2):
        eigValues = (linalg.eig(h))
        maxEig = max((absolute(eigValues[0])))
        sndMaxEig = second_largest(absolute(eigValues[0]))
        x.append(gamma * N[0])
        y.append(maxEig - sndMaxEig)
    plot(x, y)
    xlabel("γN")
    ylabel("ΔE")
    plotName = N[0]
    savefig(
        r'/home/jaime/Programming/Jaime-Santos-Dissertation/Results/Simulations/ContQuantumWalk/Search/gamma'
        + str(plotName))
    clf()
예제 #7
0
def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
    """Returns true if all components of a and b are equal subject to given tolerances.

If fill_value is True, masked values considered equal. Otherwise, masked values
are considered unequal.
The relative error rtol should be positive and << 1.0
The absolute error atol comes into play for those elements of b that are very
small or zero; it says how small a must be also.
    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.less_equal(umath.absolute(x - y), atol + rtol * umath.absolute(y))
    return d.ravel()
예제 #8
0
def _get_pov_index(point, line, povs):
    angles = []

    for pov in povs:
        to_gevel = vector(pov, (point[X], point[Y]))
        dot = line[X] * to_gevel[X] + line[Y] * to_gevel[Y]  # dot product
        det = line[X] * to_gevel[Y] - line[Y] * to_gevel[X]  # determinant
        angle = absolute(arctan2(det, dot) - 0.5 * pi)
        angles.append(angle)

    return argmin(array(angles), axis=0)
def staggeredSearchList(N, tSpace, marked, oracleList, completeTessList,
                        thetas, configVec):
    prob = []
    probT = []
    for n, oracle, tess, steps, theta in zip(N, oracleList, completeTessList,
                                             tSpace, thetas):
        evol = evo(theta, tess, oracle)
        psiN = init(n)
        prob += [absolute(psiN[marked][0])**2]
        for step in range(1, steps + 1):
            psiN = evol.dot(psiN)
            prob += [(absolute(psiN[marked][0])**2)]
            # print(prob)
        # pairs.append(((absolute(psiN[marked][0])**2),step))
        # stepsAux.append(step)
        probT.append(prob)
        #stepsAuxT.append(stepsAux)
        #print("Experimental steps:%s\tTheoretical Steps:%s\n"%(max(pairs),(pi/4)*sqrt(n)))
        #    pairs = []
        #    stepsAux = []
        prob = []
    return probT
예제 #10
0
def runSearch(N, marked, tSpace, configVec, hamList):
    prob = []
    probT = []
    for (n, T, ham) in zip(N, tSpace, hamList):
        for t in T:
            evol = evo(ham, t)
            psiN = fin(n, evol)
            prob += [(absolute(psiN[marked][0])**2)]
            #print(prob)
        # print("Sqrt(N):%s\tprob:%s\n"%(1/n,prob[0]))
        probT.append(prob)
        prob = []
    return probT
예제 #11
0
    def test_abs_blocked(self):
        "simd tests on abs"
        for dt in [np.float32, np.float64]:
            for out, inp, msg in _gen_alignment_data(dtype=dt, type="unary", max_size=17):
                tgt = [ncu.absolute(i) for i in inp]
                np.absolute(inp, out=out)
                assert_equal(out, tgt, err_msg=msg)
                self.assertTrue((out >= 0).all())

                # will throw invalid flag depending on compiler optimizations
                with np.errstate(invalid="ignore"):
                    for v in [np.nan, -np.inf, np.inf]:
                        for i in range(inp.size):
                            d = np.arange(inp.size, dtype=dt)
                            inp[:] = -d
                            inp[i] = v
                            d[i] = -v if v == -np.inf else v
                            assert_array_equal(np.abs(inp), d, err_msg=msg)
                            np.abs(inp, out=out)
                            assert_array_equal(out, d, err_msg=msg)
예제 #12
0
def format_float(x, parens=False):
    if not np.issubdtype(type(x), np.floating):
        return str(x)

    opts = np.get_printoptions()

    if np.isnan(x):
        return opts['nanstr']
    elif np.isinf(x):
        return opts['infstr']

    exp_format = False
    if x != 0:
        a = absolute(x)
        if a >= 1.e8 or a < 10**min(0, -(opts['precision'] - 1) // 2):
            exp_format = True

    trim, unique = '0', True
    if opts['floatmode'] == 'fixed':
        trim, unique = 'k', False

    if exp_format:
        s = dragon4_scientific(x,
                               precision=opts['precision'],
                               unique=unique,
                               trim=trim,
                               sign=opts['sign'] == '+')
        if parens:
            s = '(' + s + ')'
    else:
        s = dragon4_positional(x,
                               precision=opts['precision'],
                               fractional=True,
                               unique=unique,
                               trim=trim,
                               sign=opts['sign'] == '+')
    return s
예제 #13
0
 def _add_independent_index(self):
     affine_approximation = self._current_affine_combination
     independent_index = argmax(
         absolute(affine_approximation - self._current_candidate))
     self.independence_indices.append(independent_index)
예제 #14
0
    def get_format_func(self, elem, **options):
        missing_opt = self.check_options(**options)
        if missing_opt:
            raise Exception("Missing options: {}".format(missing_opt))

        floatmode = options['floatmode']
        precision = None if floatmode == 'unique' else options['precision']
        suppress_small = options['suppress_small']
        sign = options['sign']
        infstr = options['infstr']
        nanstr = options['nanstr']
        exp_format = False
        pad_left, pad_right = 0, 0

        # only the finite values are used to compute the number of digits
        finite = umath.isfinite(elem)
        finite_vals = elem[finite]
        nonfinite_vals = elem[~finite]

        # choose exponential mode based on the non-zero finite values:
        abs_non_zero = umath.absolute(finite_vals[finite_vals != 0])
        if len(abs_non_zero) != 0:
            max_val = np.max(abs_non_zero)
            min_val = np.min(abs_non_zero)
            with np.errstate(over='ignore'):  # division can overflow
                if max_val >= 1.e8 or (not suppress_small and
                                       (min_val < 0.0001
                                        or max_val / min_val > 1000.)):
                    exp_format = True

        # do a first pass of printing all the numbers, to determine sizes
        if len(finite_vals) == 0:
            trim, exp_size, unique = '.', -1, True
        elif exp_format:
            trim, unique = '.', True
            if floatmode == 'fixed':
                trim, unique = 'k', False
            strs = (format_float_scientific(x,
                                            precision=precision,
                                            unique=unique,
                                            trim=trim,
                                            sign=sign == '+')
                    for x in finite_vals)
            frac_strs, _, exp_strs = zip(*(s.partition('e') for s in strs))
            int_part, frac_part = zip(*(s.split('.') for s in frac_strs))
            exp_size = max(len(s) for s in exp_strs) - 1

            trim = 'k'
            precision = max(len(s) for s in frac_part)

            # this should be only 1 or 2. Can be calculated from sign.
            pad_left = max(len(s) for s in int_part)
            # pad_right is only needed for nan length calculation
            pad_right = exp_size + 2 + precision

            unique = False
        else:
            trim, unique = '.', True
            if floatmode == 'fixed':
                trim, unique = 'k', False
            strs = (format_float_positional(x,
                                            precision=precision,
                                            fractional=True,
                                            unique=unique,
                                            trim=trim,
                                            sign=sign == '+')
                    for x in finite_vals)
            int_part, frac_part = zip(*(s.split('.') for s in strs))
            pad_left = max(len(s) for s in int_part)
            pad_right = max(len(s) for s in frac_part)
            exp_size = -1

            if floatmode in ['fixed', 'maxprec_equal']:
                precision = pad_right
                unique = False
                trim = 'k'
            else:
                unique = True
                trim = '.'

        # account for sign = ' ' by adding one to pad_left
        if sign == ' ' and not any(np.signbit(finite_vals)):
            pad_left += 1

        # account for nan and inf in pad_left
        if len(nonfinite_vals) != 0:
            nanlen, inflen = 0, 0
            if np.any(umath.isinf(nonfinite_vals)):
                neginf = sign != '-' or np.any(np.isneginf(nonfinite_vals))
                inflen = len(infstr) + neginf
            if np.any(umath.isnan(elem)):
                nanlen = len(nanstr)
            offset = pad_right + 1  # +1 for decimal pt
            pad_left = max(nanlen - offset, inflen - offset, pad_left)

        def print_nonfinite(x):
            with errstate(invalid='ignore'):
                if umath.isnan(x):
                    ret = ('+' if sign == '+' else '') + nanstr
                else:  # isinf
                    infsgn = '-' if x < 0 else '+' if sign == '+' else ''
                    ret = infsgn + infstr
                return ' ' * (pad_left + pad_right + 1 - len(ret)) + ret

        if exp_format:

            def print_finite(x):
                return format_float_scientific(x,
                                               precision=precision,
                                               unique=unique,
                                               trim=trim,
                                               sign=sign == '+',
                                               pad_left=pad_left,
                                               exp_digits=exp_size)
        else:

            def print_finite(x):
                return format_float_positional(x,
                                               precision=precision,
                                               unique=unique,
                                               fractional=True,
                                               trim=trim,
                                               sign=sign == '+',
                                               pad_left=pad_left,
                                               pad_right=pad_right)

        def fmt(x):
            if umath.isfinite(x):
                return print_finite(x)
            else:
                return print_nonfinite(x)

        return fmt
예제 #15
0
 def __call__(self, x):
     "Execute the call behavior."
     return umath.less(umath.absolute(umath.cos(x)), self.eps)
예제 #16
0
 def __call__(self, a, b):
     return umath.absolute(a) * self.tolerance >= umath.absolute(b)
예제 #17
0
def ampToProb(N, psiN):
    prob = zeros((N, 1))
    for x in range(N):
        for c in range(N):
            prob[x] += (absolute(psiN[ket2pos([x, c], [N, N])]))**2
    return prob