Esempio n. 1
0
    def _contract(self, ket_1, ket_2, gate, direction):
        # Contract the tensor
        tens = np.tensordot(np.tensordot(ket1, gate, axes=[0, 2]),
                            ket2,
                            axes=([1, 4], [1, 0]))
        tens = tens.reshape((tens.shape[0] * tens.shape[1], -1))

        # Perform the SVD
        u, s, v = np.linalg.svd(tens, full_matrices=False)

        # Restrict to the pre-determined bond dimension ``self.bond_dim``
        u = u[:, :self.bond_dim]
        s = s[:self.bond_dim]
        v = v[:self.bond_dim, :]

        # Combine ``s`` with either ``u`` or ``v`` depending on whether direction is left or right, respectively
        if direction == "right":
            v = np.dot(np.diag(s), v)
        elif direction == "left":
            u = np.dot(u, np.diag(s))
        else:
            raise ValueError(
                "Direction must be one of ['right', 'left'], but has value {}".
                format(direction))

        # Keep coefficient of unity
        u = u / np.amax(u)
        v = v / np.amax(v)

        ket_1 = np.tranpose(u.reshape((-1, d, u.shape[1])), (1, 0, 2))
        ket_2 = np.tranpose(v.reshape((v.shape[1], d, -1)), (1, 0, 2))

        return ket_1, ket_2
Esempio n. 2
0
def corrnoise(mn=None, R=_default_R, n=100):
    if mn is None:
        mn = np.zeros(np.shape(R[0])[0])
    nvect = np.random.randn(np.shape(R)[0], n)
    R = 0.5 * (R + np.tranpose(R))
    v, d = np.linalg.eig(R)

    if np.any(np.diag <= 0):
        print('R must be positive definite')

    w = v * np.sqrt(d)
    nc = w * nvect
    Rout = (nc * np.tranpose(nc)) / n
    return nc, Rout
 def compute_accels_vectors(self, vels_vectors, time_checkpoints):
     x_vels, y_vels, z_vels = np.tranpose(vels_vectors)
     x_accels = self.compute_derivative(time_checkpoints, vels_vectors)
     y_accels = self.compute_derivative(time_checkpoints, vels_vectors)
     z_accels = self.compute_derivative(time_checkpoints, vels_vectors)
     accels_vectors = np.transpose([x_accels, y_accels, z_accels])
     return accels_vectors
Esempio n. 4
0
def feature_sign(A, y, g):
    y = np.array(y)
    dim = np.shape(A)
    x = np.zeros([dim(1), 1])
    theta = np.sign(x)
    act_set = []
    for i in range(100):
        D = 0
        index = 0
        for j in range(dim(1)):
            ai = np.tranpose(A)[j]
            ai = np.reshape(ai, [np.shape(ai)[0], 1])
            d = np.matmul(ai, y)
            d = d - (np.matmul(ai, np.matmul(A, y)))
            d = abs(d)
            if D < d:
                index = j
                D = d
        act_set.append(index)
        if D > g:
            theta[index] = -1
        else:
            theta[index] = 1
        act_set.append(i)
    return x
Esempio n. 5
0
def collectDaymet(tmpdir, bounds, start, end, vars=None, force=False):
    """Calls the DayMet Rest API to get data and save raw data."""
    if vars is None:
        vars = VALID_VARIABLES

    dat = dict()
    d_inited = False

    for year in range(start.year, end.year + 1):
        for var in vars:
            fname = downloadFile(tmpdir, bounds, year, var, force)
            x, y, v = loadFile(fname, var)
            if not d_inited:
                initData(dat, vars, numDays(start, end), len(x), len(y))
                d_inited = True

            # stuff v in the right spot
            if year == start.year and year == end.year:
                dat[var][:, :, :] = np.transpose(
                    v[start.doy:end.doy + 1, :, :], (0, 2, 1))
            elif year == start.year:
                dat[var][0:365 - start.doy + 1, :, :] = np.transpose(
                    v[start.doy - 1:, :, :], (0, 2, 1))
            elif year == end.year:
                dat[var][-end.doy:, :, :] = np.transpose(
                    v[-end.doy:, :, :], (0, 2, 1))
            else:
                my_start = 365 * (year - start.year) - start.doy + 1
                dat[var][my_start:my_start + 365, :, :] = np.tranpose(
                    v, (0, 2, 1))

    return dat
Esempio n. 6
0
def DiffOper(N):
    D = sp.diags([-np.ones(N, 1), np.ones(N, 1)], [0, 1], N, N + 1)
    D[:, 1] = []
    D[(1, 1)] = 0
    B = [[np.kron(sp.eye(N), D)], [np.kron(D, sp.eye(N))]]
    Bt = np.tranpose(B)
    BtB = Bt * B
    return (B, Bt, BtB)
def definit_R_informal(Uo, param, trans_tmp_cout_generalise, income, amenity):

    R_mat = 1 / param["size_shack"] * (
        income - trans_tmp.cout_generalise -
        (repmat(np.tranpose(Uo), 1, np.size(income, 2)) /
         (amenity *
          (param["size_shack"] - param["q0"])**param["coeff_beta"]))**
        (1 / param["coeff_alpha"]))
    return R_mat
Esempio n. 8
0
def omeFromMRP(mrp, mrpRates):
    sqNor = np.linalg.norm(mrp)**2
    matMRP = np.array([[
        1 - sqNor + 2 * mrp[0]**2, 2 * (mrp[0] * mrp[1] - mrp[2]),
        2 * (mrp[0] * mrp[2] - mrp[1])
    ],
                       [
                           2 * (mrp[0] * mrp[1] + mrp[2]),
                           1 - sqNor + 2 * mrp[1]**2,
                           2 * (mrp[2] * mrp[1] - mrp[0])
                       ],
                       [
                           2 * (mrp[0] * mrp[2] + mrp[1]),
                           2 * (mrp[2] * mrp[1] + mrp[0]),
                           1 - sqNor + 2 * mrp[2]**2
                       ]])
    return np.dot(np.tranpose(matMRP), mrpRates) * 4 / (1 + sqNor)**2
Esempio n. 9
0
def attack(args):
    outputs = construct_model_and_data(args)
    data_model = outputs['data_model']
    x_test = outputs['x_test']
    y_test = outputs['y_test']
    model = outputs['model']
    clip_max = outputs['clip_max']
    clip_min = outputs['clip_min']
    if args.attack_type == 'targeted':
        target_labels = outputs['target_labels']
        target_images = outputs['target_images']

    for i, sample in enumerate(x_test[:args.num_samples]):
        label = y_test[i]  #np.argmax(y_test[i])

        if args.attack_type == 'targeted':
            target_label = target_labels[i]
            target_image = target_images[i]
        else:
            target_label = None
            target_image = outputs['target_images'][i]

        print('attacking the {}th sample...'.format(i))

        perturbed = hsja(model,
                         sample,
                         clip_max=1,
                         clip_min=0,
                         constraint=args.constraint,
                         num_iterations=args.num_iterations,
                         gamma=1.0,
                         target_label=target_label,
                         target_image=target_image,
                         stepsize_search=args.stepsize_search,
                         max_num_evals=1e4,
                         init_num_evals=100)

        if np.argmin(sample.shape) == 0:
            sample = np.transpose(sample, (1, 2, 0))
        if np.argmin(perturbed.shape) == 0:
            perturbed = np.tranpose(perturbed, (1, 2, 0))
        image = np.concatenate(
            [sample, np.zeros((32, 8, 3)), perturbed], axis=1)
        imageio.imsave(
            '{}/figs/{}-{}-{}.jpg'.format(data_model, args.attack_type,
                                          args.constraint, i), image)
Esempio n. 10
0
def reshape_binned(x, bin_counts, reflect=False):
    """Reshape an array of `(n_samples, prod(n_bins_dim))` into `(n_samples, n_bins_dim0, n_bins_dim1, ...)`
    """
    x = x.reshape(-1, *bin_counts)
    ndims = len(bin_counts)
    if reflect:
        if ndims == 1:  # Flip x
            x = np.flip(x, axis=1)
        if ndims == 2:  # Swap x and y
            x = np.transpose(x, (0, 2, 1))
        else:
            if isinstance(reflect, tuple) and len(reflect == ndims + 1):
                x = np.tranpose(x, reflect)
            else:
                raise ValueError(
                    'For a n > 2 dimensional reflection, reflect must be a tuple for np.tranpose'
                )
    return x
Esempio n. 11
0
def sudoku_checker(board):
  # checking numbers in each row
  for row in board:
    dup_check = set(row)
    if len(dup_check) != len(row):
      return False
  # checking numbers in each column
  tranposed_board = numpy.tranpose(board)
  for col in tranposed_board:
    dup_check = set(col)
    if len(dup_check) != len(col):
      return False
  # checking in 3x3 quadrant
  for row in (0, 3, 6):
    for col in (0, 3, 6):
      quadrant = [board[x][y] for x in range(row, row + 3) for y in range(col, col + 3)]
      dup_check = set(quadrant)
      if len(dup_check) != len(quadrant):
        return False
  return True
Esempio n. 12
0
def read(ifile, **kwds):
    # ifile is a list, generate Feature object by iterating through list
    # Pixelsize must be function input (not kwd) by the time we call 'Feature'.
    arr = np.array([dicom.read_file(frame).pixel_array for frame in ifile])
    arr = np.tranpose(arr, axes=(1, 2, 0))

    if 'pixelsize' in kwds:
        px_size = float(kwds['pixelsize'])
    else:
        # Ensure that all frames share similar pixel sizes
        sizes = np.array([dicom.read_file(f).PixelSpacing for f in ifile],
                         dtype=float)
        sizes = np.ravel(sizes)
        if not np.allclose(sizes, sizes[0]):
            msg = 'Voxel dimensions are not the same.'
            raise NotImplementedError(msg)
        px_size = 1000 * sizes[0]
    warn('Pixelsize for sample {} has been set to: {}'.format(
        ifile[0], px_size))
    return Feature(arr, pixelsize=px_size)
Esempio n. 13
0
def J(xi, w_bar, N, Q_C, t):

    # create error vector
        # fill up error vector with all training data
    e = np.empty([N,1])

    for i in range(N):
        e.append(error_i(xi[i], xi[i+1],w_bar[i],w_bar[i+1]))

    # create Q matrix and invert it
    
    # create a vector of all Q_i entries
    Q_vect = np.empty([N,1])

    for i in range(N):
        Q_vect.append(Q_i(Q_C(6),t[i],t[i-1]))
    
    Q = np.diag(Q_vect)

    Q_inv = np.linalg.inv(Q)

    return (1/2)*np.matmul(np.matmul(np.tranpose(e),Q_inv),e)
Esempio n. 14
0
def computeLayer(X, W, b):
    S = np.dot(np.tranpose(W),X) + b
    return S
Esempio n. 15
0
def transpose(a, axes=None):
    try:
        return a.transpose(axes)
    except AttributeError:
        return numpy.tranpose(a, axes)
Esempio n. 16
0
	def setPoints(self, points):
		self.points = points
		del self.area
		x, y = np.tranpose(points)
		self.setData(x=x, y=y, symbolSize=2, symbol='o', symbolPen=(0, 0, 255), pen=None)
		self.setBorderVisibility(True)