示例#1
0
 def circuit(w):
     qml.RX(w[np.unravel_index(0, s)], 0)  # b[0]
     qml.RX(w[np.unravel_index(1, s)], 1)  # b[1]
     qml.RX(w[np.unravel_index(2, s)], 2)  # ...
     qml.RX(w[np.unravel_index(3, s)], 3)
     qml.RX(w[np.unravel_index(4, s)], 4)
     qml.RX(w[np.unravel_index(5, s)], 5)
     qml.RX(w[np.unravel_index(6, s)], 6)
     qml.RX(w[np.unravel_index(7, s)], 7)
     return tuple(qml.expval.PauliZ(idx) for idx in range(len(b)))
示例#2
0
 def circuit(w):
     qml.RX(w[np.unravel_index(0, s)], wires=0)  # b[0]
     qml.RX(w[np.unravel_index(1, s)], wires=1)  # b[1]
     qml.RX(w[np.unravel_index(2, s)], wires=2)  # ...
     qml.RX(w[np.unravel_index(3, s)], wires=3)
     qml.RX(w[np.unravel_index(4, s)], wires=4)
     qml.RX(w[np.unravel_index(5, s)], wires=5)
     qml.RX(w[np.unravel_index(6, s)], wires=6)
     qml.RX(w[np.unravel_index(7, s)], wires=7)
     return tuple(qml.expval(qml.PauliZ(idx)) for idx in range(len(b)))
示例#3
0
def _fit_pixel_center(morph, center, window=None):
    cy, cx = np.int(center[0]), np.int(center[1])

    if window is None:
        window = slice(cy - 2, cy + 3), slice(cx - 2, cx + 3)

    _morph = morph[window]
    yx0 = np.array([window[0].start, window[1].start])
    return tuple(np.unravel_index(np.argmax(_morph), _morph.shape) + yx0)
示例#4
0
def uncentered_operator(X, func, center=None, fill=None, **kwargs):
    """Only apply the operator on a centered patch

    In some cases, for example symmetry, an operator might not make
    sense outside of a centered box. This operator only updates
    the portion of `X` inside the centered region.

    Parameters
    ----------
    X: array
        The parameter to update.
    func: `function`
        The function (or operator) to apply to `X`.
    center: tuple
        The location of the center of the sub-region to
        apply `func` to `X`.
    `fill`: `float`
        The value to fill the region outside of centered
        `sub-region`, for example `0`. If `fill` is `None`
        then only the subregion is updated and the rest of
        `X` remains unchanged.
    """
    if center is None:
        py, px = np.unravel_index(np.argmax(X), X.shape)
    else:
        py, px = center
    cy, cx = np.array(X.shape) // 2

    if py == cy and px == cx:
        return func(X, **kwargs)

    dy = int(2 * (py - cy))
    dx = int(2 * (px - cx))
    if not X.shape[0] % 2:
        dy += 1
    if not X.shape[1] % 2:
        dx += 1
    if dx < 0:
        xslice = slice(None, dx)
    else:
        xslice = slice(dx, None)
    if dy < 0:
        yslice = slice(None, dy)
    else:
        yslice = slice(dy, None)

    if fill is not None:
        _X = np.ones(X.shape, X.dtype) * fill
        _X[yslice, xslice] = func(X[yslice, xslice], **kwargs)
        X[:] = _X
    else:
        X[yslice, xslice] = func(X[yslice, xslice], **kwargs)

    return X
示例#5
0
def flatten_nested_list_of_2d_arrays(this_list):
    current_el = this_list.copy()
    shp = tuple(())
    while isinstance(current_el, list):
        shp = shp + (len(current_el), )
        current_el = current_el[0]
    nflat = np.prod(shp)
    n0, n1 = current_el.shape
    to_return = np.zeros((n0, n1 * nflat))
    for iflat in range(nflat):
        imulti = np.unravel_index(iflat, shp)
        to_return[:, iflat * n1:(iflat + 1) * n1] = access_nested_list_element(
            this_list, imulti)
    return to_return
 def compute_tr_siginv2_sig1(stim_deriv,noise,pc_list):
         # pc_list a list of PCs of the covariance matrix, each a tuple of (sigma,normed vector)
     tot = 0
     this_ncelltypes = len(pc_list[0][0])
     for iel in range(stim_deriv.shape[1]):
         iS,iT,icelltype = np.unravel_index(iel,(nS,nT,this_ncelltypes))
         sigma2 = np.sum(stim_deriv[:,iel]**2)
         #print_labeled('sigma2',sigma2)
         if sigma2>0 and not pc_list[iS][iT][icelltype] is None:
             inner_prod = np.sum([pc[0]**2*np.sqrt(sigma2)*inner_product_(stim_deriv[:,iel],pc[1]) for pc in pc_list[iS][iT][icelltype]])
         else:
             inner_prod = 0 
         tot = tot - 1/noise/(noise + sigma2)*inner_prod #.sum()
     return tot
示例#7
0
    def __init__(self, vec, other_vec, whole, otherwhole, actInd, **kwargs):
        actInd = (int(actInd[0]), int(actInd[1]))
        DistanceMat = np.array([[distance(i, j) for j in otherwhole]
                                for i in whole])

        # print("Mindistance:", np.min(DistanceMat))
        # print("len(whole),len(otherwhole)",len(whole),len(otherwhole))

        insectPT = np.nonzero(
            DistanceMat < INTERSECTLIM)  # The index of the intersection point
        try:
            insectPT = (insectPT[0][0], insectPT[1][0])
        except IndexError:  # the case where is no pair of points fall in the threshold, find the least distance point instead
            insectPT = np.unravel_index(np.argmin(DistanceMat, axis=None),
                                        DistanceMat.shape)

        egopath = whole[actInd[0]:insectPT[0]]
        otherpath = otherwhole[actInd[1]:insectPT[1]]
        # path a None in is just to call the lambda function
        egoPTs = np.sum(
            (self._distance(self._diff(lambda x: egopath[:, 0]),
                            self._diff(lambda y: egopath[:, 1])))(None))
        otherPTs = np.sum(
            self._distance(self._diff(lambda x: otherpath[:, 0]),
                           self._diff(lambda y: otherpath[:, 1]))(None))
        otherDistance = self._cumsum(
            self._distance(
                self._diff(lambda x: otherwhole[actInd[1]:, 0]),
                self._diff(lambda y: otherwhole[actInd[1]:, 1])))(None)
        self.other_vec = other_vec
        self.whole = whole
        self.otherwhole = otherwhole
        self.actInd = actInd
        self.insectPT = insectPT
        self.egoPTs = egoPTs
        self.otherPTs = otherPTs
        self.otherDistance = otherDistance
        super().__init__(vec,
                         other_vec,
                         whole=whole,
                         otherwhole=otherwhole,
                         actInd=actInd,
                         intersectInd=insectPT,
                         intersectPTs=(self.egoPTs, self.otherPTs),
                         otherDist=otherDistance,
                         **kwargs)
示例#8
0
def getRadialMonotonicWeights(shape,
                              useNearest=True,
                              minGradient=1,
                              center=None):
    """Create the weights used for the Radial Monotonicity Operator
    This version of the radial monotonicity operator selects all of the pixels closer to the peak
    for each pixel and weights their flux based on their alignment with a vector from the pixel
    to the peak. In order to quickly create this using sparse matrices, its construction is a bit opaque.
    """
    if center is None:
        center = ((shape[0] - 1) // 2, (shape[1] - 1) // 2)
    name = "RadialMonotonicWeights"

    key = tuple(shape) + tuple(center) + (useNearest, minGradient)
    try:

        cosNorm = Cache.check(name, key)
    except KeyError:

        # Center on the center pixel
        py, px = int(center[0]), int(center[1])
        # Calculate the distance between each pixel and the peak
        x = np.arange(shape[1])
        y = np.arange(shape[0])
        X, Y = np.meshgrid(x, y)
        X = X - px
        Y = Y - py
        distance = np.sqrt(X**2 + Y**2)

        # Find each pixels neighbors further from the peak and mark them as invalid
        # (to be removed later)
        distArr, mask = diagonalizeArray(distance, dtype=np.float64)
        relativeDist = (distance.flatten()[:, None] - distArr.T).T
        invalidPix = relativeDist <= 0

        # Calculate the angle between each pixel and the x axis, relative to the peak position
        # (also avoid dividing by zero and set the tan(infinity) pixel values to pi/2 manually)
        inf = X == 0
        tX = X.copy()
        tX[inf] = 1
        angles = np.arctan2(-Y, -tX)
        angles[inf & (Y != 0)] = 0.5 * np.pi * np.sign(angles[inf & (Y != 0)])

        # Calcualte the angle between each pixel and it's neighbors
        xArr, m = diagonalizeArray(X)
        yArr, m = diagonalizeArray(Y)
        dx = (xArr.T - X.flatten()[:, None]).T
        dy = (yArr.T - Y.flatten()[:, None]).T
        # Avoid dividing by zero and set the tan(infinity) pixel values to pi/2 manually
        inf = dx == 0
        dx[inf] = 1
        relativeAngles = np.arctan2(dy, dx)
        relativeAngles[inf & (dy != 0)] = 0.5 * np.pi * np.sign(
            relativeAngles[inf & (dy != 0)])

        # Find the difference between each pixels angle with the peak
        # and the relative angles to its neighbors, and take the
        # cos to find its neighbors weight
        dAngles = (angles.flatten()[:, None] - relativeAngles.T).T
        cosWeight = np.cos(dAngles)
        # Mask edge pixels, array elements outside the operator (for offdiagonal bands with < N elements),
        # and neighbors further from the peak than the reference pixel
        cosWeight[invalidPix] = 0
        cosWeight[mask] = 0

        if useNearest:
            # Only use a single pixel most in line with peak
            cosNorm = np.zeros_like(cosWeight)
            columnIndices = np.arange(cosWeight.shape[1])
            maxIndices = np.argmax(cosWeight, axis=0)
            indices = maxIndices * cosNorm.shape[1] + columnIndices
            indices = np.unravel_index(indices, cosNorm.shape)
            cosNorm[indices] = minGradient
            # Remove the reference for the peak pixel
            cosNorm[:, px + py * shape[1]] = 0
        else:
            # Normalize the cos weights for each pixel
            normalize = np.sum(cosWeight, axis=0)
            normalize[normalize == 0] = 1
            cosNorm = (cosWeight.T / normalize[:, None]).T
            cosNorm[mask] = 0

        Cache.set(name, key, cosNorm)

    return cosNorm
'''
for n_point in n_points:
    print('n_points: ', n_point)
    for i in range(Z.shape[0]):
        print(i)
        for j in range(Z.shape[1]):
            Z[i,j] = swarm.MAP_loss([X[i,j], Y[i,j]], xSol[50, :], Cins[50],xSol[50:n_point+50,0])
    np.save('Z_diff_n_points_from_stationary/Z_' + str(n_point) + '.npy', Z)

sys.exit()
'''

Z = np.load('Z_small_domain.npy')
#Z = np.load('/Users/Neythen/Desktop/masters_project/parameter_estimation/global_optimsiation/Z_diff_n_points/Z_2.npy')
ind = Z.argmin()
ind = np.unravel_index(ind, (100, 100))
min = np.min(Z)
'''
print(Z)
print(min)
print(X[ind], Y[ind])
'''
fig = plt.figure(figsize=(12, 8))
im = plt.contour(X, Y, Z, 40, vmin=abs(Z).min(), vmax=abs(Z).max())

cb = fig.colorbar(im)

swarm.find_minimum_time_series(50)

print(swarm.global_best_positions)
print(swarm.global_best_values)
示例#10
0
    R_int_term_2 = k_grad[2]*\
    (
      ((input_vec[2] - input_vec[1])/(2*DELTA_H))**2 +
      ((input_vec[4] - input_vec[3])/(2*DELTA_H))**2
    )

    R_int_term_3 = input_vec[5]

    return R_int_term_1 + R_int_term_2 + R_int_term_3


compute_R_int_grad = grad(compute_R_int)

ravel = lambda i, j: np.ravel_multi_index(
    (i, j), [int(1 / DELTA_H) + 1, int(1 / DELTA_H) + 1])
unravel = lambda n: np.unravel_index(
    n, [int(1 / DELTA_H) + 1, int(1 / DELTA_H) + 1])
'''
  Functions for discrete k
'''


def compute_R_int_discrete_k(
    input_vec
):  # input_vec = [T_i,j    T_i-1,j    T_i+1,j    T_i,j-1    T_i,j+1    q    k_i,j    k_i-1,j    k_i+1,j    k_i,j-1    k_i,j+1]

    R_int_term_1 = input_vec[6]*\
      (
        (input_vec[2] - 2*input_vec[0] + input_vec[1])/(DELTA_H**2) +
        (input_vec[4] - 2*input_vec[0] + input_vec[3])/(DELTA_H**2)
      )