Example #1
0
    def test_array1(self):
        """
        Tests functions with single numpy 1d array output
        """

        def f1(x):
            # single scalar input
            return np.array([i*x**i for i in range(5)])

        df = jacobian(f1)(3.0)
        for i, d in enumerate(df):
            self.assertAlmostEqual(i**2 * 3.0 ** (i - 1), d)

        def f2(params):
            # one list, one numpy array input
            x,y = params[0]
            A = params[1]
            return np.linalg.dot(np.sin(A), np.array([x,y**2]))

        A = np.array([[1.0, 2.0],[3.0, 4.0]])
        x,y = 2.0, np.pi
        params = [[x, y], A]
        df = jacobian(f2)(params)
        # df0_dx
        self.assertAlmostEqual(df[0][0][0],  np.sin(A)[0][0])
        # df1_dx
        self.assertAlmostEqual(df[1][0][0],  np.sin(A)[1][0])
        # df0_dy
        self.assertAlmostEqual(df[0][0][1],  2*np.sin(A)[0][1]*y)
        # df1_dy
        self.assertAlmostEqual(df[1][0][1],  2*np.sin(A)[1][1]*y)
        # df_dA
        assert np.linalg.norm(df[0][1][0] - (np.cos(A)*np.array([x,y**2]))[0]) < 1e-10
        assert np.linalg.norm(df[1][1][1] - (np.cos(A)*np.array([x,y**2]))[1]) < 1e-10
Example #2
0
 def fun(input_dict):
     A = 0.
     B = 0.
     for i, (k, v) in enumerate(sorted(input_dict.items(), key=op.itemgetter(0))):
         A = A + np.sum(np.sin(v)) * (i + 1.0)
         B = B + np.sum(np.cos(v))
     for v in input_dict.values():
         A = A + np.sum(np.sin(v))
     for k in sorted(input_dict.keys()):
         A = A + np.sum(np.cos(input_dict[k]))
     return A + B
Example #3
0
def make_pinwheel_data(radial_std, tangential_std, num_classes, num_per_class, rate):
    rads = np.linspace(0, 2*np.pi, num_classes, endpoint=False)

    features = npr.randn(num_classes*num_per_class, 2) \
        * np.array([radial_std, tangential_std])
    features[:,0] += 1.
    labels = np.repeat(np.arange(num_classes), num_per_class)

    angles = rads[labels] + rate * np.exp(features[:,0])
    rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin(angles), np.cos(angles)])
    rotations = np.reshape(rotations.T, (-1, 2, 2))

    return 10*npr.permutation(np.einsum('ti,tij->tj', features, rotations))
Example #4
0
def make_pinwheel(radial_std, tangential_std, num_classes, num_per_class, rate,
                  rs=npr.RandomState(0)):
    """Based on code by Ryan P. Adams."""
    rads = np.linspace(0, 2*np.pi, num_classes, endpoint=False)

    features = rs.randn(num_classes*num_per_class, 2) \
        * np.array([radial_std, tangential_std])
    features[:, 0] += 1
    labels = np.repeat(np.arange(num_classes), num_per_class)

    angles = rads[labels] + rate * np.exp(features[:,0])
    rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin(angles), np.cos(angles)])
    rotations = np.reshape(rotations.T, (-1, 2, 2))

    return np.einsum('ti,tij->tj', features, rotations)
def ackley(x):
    a, b, c = 20.0, -0.2, 2.0*np.pi
    len_recip = 1.0/len(x)
    sum_sqrs = sum(x*x)
    sum_cos = sum(np.cos(c*x))
    return (-a * np.exp(b*np.sqrt(len_recip*sum_sqrs)) -
            np.exp(len_recip*sum_cos) + a + np.e)
Example #6
0
 def fun(input_dict):
     A = 0.
     B = 0.
     for i, k in enumerate(sorted(input_dict)):
         A = A + np.sum(np.sin(input_dict[k])) * (i + 1.0)
         B = B + np.sum(np.cos(input_dict[k]))
     return A + B
Example #7
0
 def plot_gmm(params, ax, num_points=100):
     angles = np.expand_dims(np.linspace(0, 2*np.pi, num_points), 1)
     xs, ys = np.cos(angles), np.sin(angles)
     circle_pts = np.concatenate([xs, ys], axis=1) * 2.0
     for log_proportion, mean, chol in zip(*unpack_params(params)):
         cur_pts = mean + np.dot(circle_pts, chol)
         ax.plot(cur_pts[:, 0], cur_pts[:, 1], '-')
Example #8
0
def build_toy_dataset(D=1, n_data=20, noise_std=0.1):
    rs = npr.RandomState(0)
    inputs  = np.concatenate([np.linspace(0, 3, num=n_data/2),
                              np.linspace(6, 8, num=n_data/2)])
    targets = (np.cos(inputs) + rs.randn(n_data) * noise_std) / 2.0
    inputs = (inputs - 4.0) / 2.0
    inputs  = inputs.reshape((len(inputs), D))
    return inputs, targets
Example #9
0
def make_pinwheel_data(num_spokes=5, points_per_spoke=40, rate=1.0, noise_std=0.005):
    """Make synthetic data in the shape of a pinwheel."""
    spoke_angles = np.linspace(0, 2 * np.pi, num_spokes + 1)[:-1]
    rs = npr.RandomState(0)
    x = np.linspace(0.1, 1, points_per_spoke)
    xs = np.concatenate([x * np.cos(angle + x * rate) + noise_std * rs.randn(len(x)) for angle in spoke_angles])
    ys = np.concatenate([x * np.sin(angle + x * rate) + noise_std * rs.randn(len(x)) for angle in spoke_angles])
    return np.concatenate([np.expand_dims(xs, 1), np.expand_dims(ys, 1)], axis=1)
Example #10
0
 def equa2pixel(self, s_equa):
     if self.use_wcs:
         print "using wcs in equa2pixel"
         return self.wcs.wcs_world2pix(np.atleast_2d(s_equa), 0).squeeze()
     phi1rad = self.phi_n[1] / 180. * np.pi
     s_iwc = np.array([ (s_equa[0] - self.phi_n[0]) * np.cos(phi1rad),
                                (s_equa[1] - self.phi_n[1]) ])
     s_pix = np.dot(self.Ups_n_inv, s_iwc) + self.rho_n
     return s_pix
def devec_ackley(x):
    a, b, c = 20.0, -0.2, 2.0*np.pi
    len_recip = 1.0/len(x)
    sum_sqrs, sum_cos = 0.0, 0.0
    for i in x:
        sum_cos += np.cos(c*i)
        sum_sqrs += i*i
    return (-a * np.exp(b*np.sqrt(len_recip*sum_sqrs)) -
            np.exp(len_recip*sum_cos) + a + np.e)
Example #12
0
def test_jacobian_higher_order():
    fun = lambda x: np.sin(np.outer(x, x)) + np.cos(np.dot(x, x))

    jacobian(fun)(npr.randn(3)).shape == (3, 3, 3)
    jacobian(jacobian(fun))(npr.randn(3)).shape == (3, 3, 3, 3)
    jacobian(jacobian(jacobian(fun)))(npr.randn(3)).shape == (3, 3, 3, 3, 3)

    check_grads(lambda x: np.sum(jacobian(fun)(x)), npr.randn(3))
    check_grads(lambda x: np.sum(jacobian(jacobian(fun))(x)), npr.randn(3))
Example #13
0
def build_toy_dataset(n_data=80, noise_std=0.1):
    rs = npr.RandomState(0)
    inputs  = np.concatenate([np.linspace(0, 3, num=n_data/2),
                              np.linspace(6, 8, num=n_data/2)])
    targets = np.cos(inputs) + rs.randn(n_data) * noise_std
    inputs = (inputs - 4.0) / 2.0
    inputs  = inputs[:, np.newaxis]
    targets = targets[:, np.newaxis] / 2.0
    return inputs, targets
Example #14
0
File: gmm.py Project: mattjj/svae
 def plot_ellipse(ax, alpha, mean, cov, line=None):
     t = np.linspace(0, 2*np.pi, 100) % (2*np.pi)
     circle = np.vstack((np.sin(t), np.cos(t)))
     ellipse = 2.*np.dot(np.linalg.cholesky(cov), circle) + mean[:,None]
     if line:
         line.set_data(ellipse)
         line.set_alpha(alpha)
     else:
         ax.plot(ellipse[0], ellipse[1], alpha=alpha, linestyle='-', linewidth=2)
Example #15
0
def exp(r):
    """ matrix exponential under the special orthogonal group SO(3) ->
    converts Rodrigues 3-vector r into 3x3 rotation matrix R"""
    theta = np.linalg.norm(r)
    if (theta == 0):
        return np.eye(3)
    K = hat(r / theta)
    # Compute w/ Rodrigues' formula
    return np.eye(3) + np.sin(theta) * K + \
        (1 - np.cos(theta)) * np.dot(K, K)
Example #16
0
def make_pinwheel_data(num_classes, num_per_class, rate=2.0, noise_std=0.001):
    spoke_angles = np.linspace(0, 2*np.pi, num_classes+1)[:-1]

    rs = npr.RandomState(0)
    x = np.linspace(0.1, 1, num_per_class)
    xs = np.concatenate([rate *x * np.cos(angle + x * rate) + noise_std * rs.randn(num_per_class)
                         for angle in spoke_angles])
    ys = np.concatenate([rate *x * np.sin(angle + x * rate) + noise_std * rs.randn(num_per_class)
                         for angle in spoke_angles])
    return np.concatenate([np.expand_dims(xs, 1), np.expand_dims(ys,1)], axis=1)
Example #17
0
def build_train_dataset(n_data=20, noise_std=0.1):
    D = 1
    rs = npr.RandomState(0)
    inputs  = np.concatenate([np.linspace(0, 3, num=n_data/2),
                              np.linspace(6, 8, num=n_data/2)])
    targets = np.cos(inputs) + rs.randn(n_data) * noise_std
    inputs = (inputs - 4.0) / 4.0
    inputs  = inputs.reshape((len(inputs), D))
    targets = targets.reshape((len(targets), D))
    return inputs, targets
def build_toy_dataset(n_data=40, noise_std=0.1):
    D = 1
    rs = npr.RandomState(0)
    inputs  = np.concatenate([np.linspace(0, 2, num=n_data/2),
                              np.linspace(6, 8, num=n_data/2)])
    targets = np.cos(inputs) + rs.randn(n_data) * noise_std
    inputs = (inputs - 5.0) / 4.0
    inputs  = inputs.reshape((len(inputs), D))
    targets = targets.reshape((len(targets), D))
    return inputs, targets
Example #19
0
        def dynamics(z):
            x, u = z[0:n], z[n:n + m]
            wheel_angle = x[2] + u[1]
            s, c = np.sin(wheel_angle), np.cos(wheel_angle)
            forward_velocity = nominal_velocity + u[0]

            return np.array([
                -forward_velocity * s, forward_velocity * c - nominal_velocity,
                (forward_velocity / body_length) * np.sin(u[1])
            ])
Example #20
0
def tensorexp(r):
    """ returns a stack of rotation matrices as a tensor """
    """ r should be (3,n), n column vectors """
    theta = np.sqrt(np.sum(r*r, axis=0))  # shape = (n,)
    # note: the case where theta == 0 is not handled; we assume there is enough
    # noise and bias that this won't happen
    K = tensorhat(r / theta)  # shape = (3,3,n)
    KK = np.einsum('ijl,jkl->ikl', K, K)
    # Compute w/ Rodrigues' formula
    return np.eye(3)[:, :, np.newaxis] + np.sin(theta) * K + \
        (1 - np.cos(theta)) * KK
Example #21
0
    def log_likelihoods(self, data, input, mask, tag):
        from autograd.scipy.special import i0
        # Compute the log likelihood of the data under each of the K classes
        # Return a TxK array of probability of data[t] under class k
        mus, kappas = self.mus, np.exp(self.log_kappas)
        mask = np.ones_like(data, dtype=bool) if mask is None else mask

        return np.sum(
            (kappas * (np.cos(data[:, None, :] - mus)) - np.log(2 * np.pi) -
             np.log(i0(kappas))) * mask[:, None, :],
            axis=2)
Example #22
0
  def dderiv(self, x, xdot, u):
    x = State(x)
    xdot = State(xdot)
    u = Control(u)

    accel = u.f / self.m
    xddd = (-accel * np.cos(x.theta)) * x.theta_vel
    zddd = (-accel * np.sin(x.theta)) * x.theta_vel
    tddd = 0 # Really, this should be I inv * Tau_dot

    return np.array((xdot.x_vel, xdot.z_vel, xdot.theta_vel, xddd, zddd, tddd))
Example #23
0
    def test_involutory_variance(self, tol):
        """Tests qubit observable that are involutory"""
        dev = qml.device('default.qubit', wires=1)

        @qml.qnode(dev)
        def circuit(a):
            qml.RX(a, wires=0)
            return qml.var(qml.PauliZ(0))

        a = 0.54
        var = circuit(a)
        expected = 1 - np.cos(a)**2
        assert np.allclose(var, expected, atol=tol, rtol=0)

        # circuit jacobians
        gradA = circuit.jacobian([a], method='A')
        gradF = circuit.jacobian([a], method='F')
        expected = 2 * np.sin(a) * np.cos(a)
        assert np.allclose(gradF, expected, atol=tol, rtol=0)
        assert np.allclose(gradA, expected, atol=tol, rtol=0)
Example #24
0
            def opt_f(x):
                u, theta = x

                x_t = np.array(
                    (p_des[0], p_des[1], theta, v_des[0], v_des[1], 0))
                u_t = np.array((u, 0))
                fm = self.learner.predict(x_t, u_t, t)

                return u * np.array(
                    (-np.sin(theta), np.cos(theta))) - np.array(
                        (0, self.model.g)) + fm - a_des
Example #25
0
def get_ceq(x):
    n = (x.shape[0] - 1) // 4

    tk, xk, yk, thetak = split_state(x)
    xk = np.concatenate(([start_x], xk, [goal_x]))
    yk = np.concatenate(([start_y], yk, [goal_y]))
    thetak = np.concatenate(([start_theta], thetak, [goal_theta]))

    dx = xk[1:] - xk[0:-1]
    dy = yk[1:] - yk[0:-1]
    dk = np.array([dx, dy, np.zeros(n + 1)]).T

    # constant curvature (trapezoidal collocation, see teb paper)
    ceq = np.array([
        np.cos(thetak[0:-1]) + np.cos(thetak[1:]),
        np.sin(thetak[0:-1]) + np.sin(thetak[1:]),
        np.zeros(n + 1)
    ]).T
    ceq = np.fabs(np.cross(ceq, dk, axisa=1, axisb=1)[:, 2])
    return ceq
    def _M(self, pos):
        """
        Inertial Mass matrix
        """
        x, th = pos
        I = self.inertial
        d0 = self.total_mass
        d1 = self.polemass_length * anp.cos(th)

        mass_matrix = anp.array([[d0, d1], [d1, I]])
        return mass_matrix
Example #27
0
def dataset(num_data=20, noise=0.5):
    num_dims = 1
    inputs = np.concatenate([
        np.linspace(0, 2, num=num_data / 2),
        np.linspace(6, 8, num=num_data / 2)
    ])
    targets = np.cos(inputs) + np.random.randn(num_data) * noise
    inputs = (inputs - 4.0) / 4.0
    inputs = inputs.reshape((len(inputs), num_dims))
    targets = targets.reshape((len(targets), num_dims))
    return inputs, targets
Example #28
0
def square_generator(t, **kwargs):
    '''
    Makes a random frequency square wave frequency input 
    '''
    square_freq = 0.2
    if 'square_freq' in kwargs:
        square_freq = kwargs['square_freq']

    # produce square wave based on cosine
    f = np.sign(np.maximum(0, np.cos(np.pi * square_freq * t))) + 1
    return f
Example #29
0
def ensemble_transfer_matrix_pi_half(NAtoms, g1d, gprime, gm, Delta1, Deltap,
                                     Omega):
    """
    NAtoms: The number of atoms
    g1d:    \Gamma_{1D}, the decay rate into the guided mode
    gprime: \Gamma', the decay rate into all the other modes
    gm:     \Gamma_m, the decay rate from the meta-stable state
    Delta1: The detuning of the carrier frequency \omega_L of the
            quantum field from the atomic transition frequency \omega_{ab}.
            Delta1 = \omega_L - \omega_{ab}
    Deltap: The detuning of the classical drive frequency \omega_p from
            the transition bc. Deltap = \omega_p - \omega_{bc}
    """
    kd = 0.5 * np.pi

    Mf = np.mat([[np.exp(1j * kd), 0], [0, np.exp(-1j * kd)]])

    beta3 = Lambda_type_minus_r_over_t(g1d, gprime, gm, Delta1, Deltap, Omega)
    M3 = np.mat([[1 - beta3, -beta3], [beta3, 1 + beta3]])

    beta2 = two_level_minus_r_over_t(g1d, gprime, Delta1)
    M2 = np.mat([[1 - beta2, -beta2], [beta2, 1 + beta2]])

    Mcell = Mf * M2 * Mf * M3
    NCells = NAtoms / 2

    #diag, V = np.linalg.eig(Mcell)
    #DN = np.diag(diag**(NCells))
    #V_inv = np.linalg.inv(V)

    #return V*DN*V_inv

    theta = np.arccos(0.5 * np.trace(Mcell))
    Id = np.mat([[1, 0], [0, 1]])

    Mensemble\
            = np.mat([[np.cos(NCells*theta)+1j*1j*np.sin(NCells*theta)/np.sin(theta)*(Mcell[1,1]-Mcell[0,0])/2,
                 -1j*1j*np.sin(NCells*theta)/np.sin(theta)*Mcell[0,1]],
                [-1j*1j*np.sin(NCells*theta)/np.sin(theta)*Mcell[1,0],
                 np.cos(NCells*theta)-1j*1j*np.sin(NCells*theta)/np.sin(theta)*(Mcell[1,1]-Mcell[0,0])/2]])
    return Mensemble
Example #30
0
def unit_lobatto_nodes(order, tol=1e-15, output=True):
	roots=[]

	print("Finding roots of the derivative of the Legendre polynomial of order ", order)

	# The polynomials are alternately even and odd functions
	# so evaluate only half the number of roots

	# order - 1, lobatto polynomial is derivative of legendre polynomial of order n-1
	order = order-1

	for i in range(1,int(order/2) +1):

		# initial guess, x0, for ith root 
		# the approximate values of the abscissas.
		# these are good initial guesses
		#x0=np.cos(np.pi*(i-0.25)/(order+0.5)) 
		x0=np.cos(np.pi*(i+0.1)/(order+0.5))  # not sure why this inital guess is better

		# call newton to find the roots of the lobatto polynomial
		#Ffun, Jfun = dL(order-1), ddL(order-1) 
		Ffun, Jfun = dL(order), ddL(order) 
		ri, _ = newton( Ffun, Jfun, x0 )

		roots.append(ri)

	# remove roots close to zero
	cleaned_roots = []
	tol = 1e-08
	for r in roots:
		if abs(r) >= tol:
			cleaned_roots += [r]
	roots = cleaned_roots

	# use symetric properties to find remmaining roots
	# the nodal abscissas are computed by finding the 
	# nonnegative zeros of the Legendre polynomial pm(x) 
	# with Newton’s method (the negative zeros are obtained from symmetry).
	roots = np.array(roots)
	
	# add -1 and 1 to tail ends
	# check parity of order + 1

	# even. no center 
	#if order % 2==0:
	if (order + 1) % 2==0:
		roots = np.concatenate( ([-1.0], -1.0*roots, roots[::-1], [1.0]) )

	# odd. center root is 0.0
	else:
		roots = np.concatenate( ([-1.0], -1.0*roots, [0.0], roots[::-1], [1.0] ) )

	return roots
Example #31
0
def SingleExcitation(phi):
    r"""Single excitation rotation.

    Args:
        phi (float): rotation angle

    Returns:
        array[float]: Single excitation rotation matrix
    """
    c = np.cos(phi / 2)
    s = np.sin(phi / 2)
    return np.array([[1, 0, 0, 0], [0, c, -s, 0], [0, s, c, 0], [0, 0, 0, 1]])
Example #32
0
def get_ad_t(t):

    if param.get('case_xd') == 0:
        return np.zeros((2, 1))
    elif param.get('case_xd') == 1:
        return np.zeros((2, 1))
    elif param.get('case_xd') == 2:
        return np.power(2 * np.pi / param.get('tf'), 2.) * np.array([
            -np.cos(2 * np.pi / param.get('tf') * t),
            -np.sin(2 * np.pi / param.get('tf') * t)
        ])
    return
Example #33
0
    def test_fanout(self, tol):
        """Tests qubit observable with repeated parameters"""
        dev = qml.device('default.qubit', wires=1)

        @qml.qnode(dev)
        def circuit(a):
            qml.RX(a, wires=0)
            qml.RY(a, wires=0)
            return qml.var(qml.PauliZ(0))

        a = 0.54
        var = circuit(a)
        expected = 0.5 * np.sin(a)**2 * (np.cos(2 * a) + 3)
        assert np.allclose(var, expected, atol=tol, rtol=0)

        # circuit jacobians
        gradA = circuit.jacobian([a], method='A')
        gradF = circuit.jacobian([a], method='F')
        expected = 4 * np.sin(a) * np.cos(a)**3
        assert np.allclose(gradA, expected, atol=tol, rtol=0)
        assert np.allclose(gradF, expected, atol=tol, rtol=0)
Example #34
0
def gaussian_sin(m, v, i, e=None):
    d = len(m)
    L = len(i)
    e = np.ones((1, L)) if e is None else np.atleast_2d(e)

    mi = np.atleast_2d(m[i])
    vi = v[np.ix_(i, i)]
    vii = np.atleast_2d(np.diag(vi))
    M = e * exp(-vii / 2) * sin(mi)
    M = M.flatten()

    lq = -(vii.T + vii) / 2
    q = exp(lq)
    V = ((exp(lq + vi) - q) * cos(mi.T - mi) -
         (exp(lq - vi) - q) * cos(mi.T + mi))
    V = np.dot(e.T, e) * V / 2

    C = np.diag((e * exp(-vii / 2) * cos(mi)).flatten())
    C = fill_mat(C, np.zeros((d, L)), i, None)

    return M, V, C
Example #35
0
 def dynamics(self, x, action):
     dt = 0.1
     action = np.clip(action, -1., 1.)
     noise = self.noise
     px, py, angle, vel, ang_vel = x
     vel = 0.*vel + action[0] * dt + random.randn(1)*noise[0]
     ang_vel = 0.*ang_vel + action[1] * dt + random.randn(1)*noise[1]
     angle += ang_vel * dt + random.randn(1)*noise[2]
     angle %= 2*pi
     px += vel * np.cos(angle) * dt + random.randn(1)*noise[3]
     py += vel * np.sin(angle) * dt + random.randn(1)*noise[4]
     return np.array((px, py, angle, vel, ang_vel)).reshape(-1)
Example #36
0
def get_vd_t(t):

    if param.get('case_xd') == 0:
        return np.zeros((2, 1))
    elif param.get('case_xd') == 1:
        return np.ones((2, 1))
    elif param.get('case_xd') == 2:
        return (2 * np.pi / param.get('tf')) * np.array([
            -np.sin(2 * np.pi / param.get('tf') * t),
            np.cos(2 * np.pi / param.get('tf') * t)
        ])
    return
Example #37
0
def getA1_matrix(wb, M, N, p):

    Mmatrix = Marray(M, p)
    Nmatrix = Narray(N, p)
    a = np.arange(p + 1)
    onevec = np.ones(p + 1)

    A = np.vstack([onevec, (-1)**a, np.cos(wb * a), Mmatrix, Nmatrix])

    print(f'A.shape: {A.shape}')

    return A
Example #38
0
def draw_ellipse(mu, cov, num_sd=1):
    # as I understand it -
    # diagonalise the cov matrix
    # use eigenvalues for radii
    # use eigenvector rotation from x axis for rotation
    x = mu[0]  #x-position of the center
    y = mu[1]  #y-position of the center
    cov = cov * num_sd  # show within num_sd standard deviations
    lam, V = np.linalg.eig(cov)  # eigenvalues and vectors
    t_rot = np.arctan(V[1, 0] / V[0, 0])
    a, b = lam[0], lam[1]
    t = np.linspace(0, 2 * np.pi, 100)
    Ell = np.array([a * np.cos(t), b * np.sin(t)])
    #u,v removed to keep the same center location
    R_rot = np.array([[cos(t_rot), -sin(t_rot)], [sin(t_rot), cos(t_rot)]])
    #2-D rotation matrix

    Ell_rot = np.zeros((2, Ell.shape[1]))
    for i in range(Ell.shape[1]):
        Ell_rot[:, i] = np.dot(R_rot, Ell[:, i])
    return x + Ell_rot[0, :], y + Ell_rot[1, :]
Example #39
0
    def visit_Function(self, node):
        f = node.value

        if f == EXP:
            return np.exp(self.visit(node.expr))

        if (f == LOG) or (f == LN):
            return np.log(self.visit(node.expr))

        if f == LOG10:
            return np.log10(self.visit(node.expr))

        if f == SQRT:
            return np.sqrt(self.visit(node.expr))

        if f == ABS:
            return np.abs(self.visit(node.expr))

        if f == SIGN:
            return np.sign(self.visit(node.expr))

        if f == SIN:
            return np.sin(self.visit(node.expr))

        if f == COS:
            return np.cos(self.visit(node.expr))

        if f == TAN:
            return np.tan(self.visit(node.expr))

        if f == ASIN:
            return np.arcsin(self.visit(node.expr))

        if f == ACOS:
            return np.arccos(self.visit(node.expr))

        if f == ATAN:
            return np.arctan(self.visit(node.expr))

        if f == MAX:
            raise NotImplementedError(MAX)

        if f == MIN:
            raise NotImplementedError(MIN)

        if f == NORMCDF:
            raise NotImplementedError(NORMCDF)

        if f == NORMPDF:
            raise NotImplementedError(NORMPDF)

        if f == ERF:
            return erf(self.visit(node.expr))
Example #40
0
def CRX(theta):
    r"""Two-qubit controlled rotation about the x axis.

    Args:
        theta (float): rotation angle

    Returns:
        array[complex]: unitary 4x4 rotation matrix
        :math:`|0\rangle\langle 0|\otimes \mathbb{I}+|1\rangle\langle 1|\otimes R_x(\theta)`
    """
    return (np.cos(theta / 4)**2 * II - 1j * np.sin(theta / 2) / 2 * IX +
            np.sin(theta / 4)**2 * ZI + 1j * np.sin(theta / 2) / 2 * ZX)
Example #41
0
    def calc_constraint(self, theta, a, b, c, d, e, f1, f2):

        # Equations in readable format
        exp1 = (f2 - e) * anp.cos(theta) - f1 * anp.sin(theta)

        exp2 = (f2 - e) * anp.sin(theta) + f1 * anp.cos(theta)
        exp2 = b * anp.pi * (exp2 ** c)
        exp2 = anp.abs(anp.sin(exp2))
        exp2 = a * (exp2 ** d)

        # as in the paper
        # val = - (exp1 - exp2)

        # as in the C code of NSGA2
        val = 1 - exp1 / exp2

        # ONE EQUATION
        # _val = - (anp.cos(theta) * (f2 - e) - anp.sin(theta) * f1 -
        #           a * anp.abs(anp.sin(b * anp.pi * (anp.sin(theta) * (f2 - e) + anp.cos(theta) * f1) ** c)) ** d)

        return val
Example #42
0
def GradAckleyProblem(xs):
    """del H/del xi = -20 * -0.2 * (xi * 1/n) / sqrt(1/n sum_j xj^2) * a + 2 pi sin(2 pi xi)/n * b"""
    out_shape = xs.shape
    a = np.exp(-0.2 *
               np.sqrt(1. / len(xs) * np.square(np.linalg.norm(xs, axis=0))))
    b = -np.exp(1. / len(xs) * np.sum(np.cos(2 * np.pi * xs), axis=0))
    a_p = -0.2 * (xs * 1. / len(xs)) / np.sqrt(
        1. / len(xs) * np.square(np.linalg.norm(xs, axis=0)))
    b_p = -2 * np.pi * np.sin(2 * np.pi * xs) / len(xs)
    return np.nan_to_num(-20 * a_p * a + b_p * b).reshape(
        out_shape
    )  # only when norm(x) == 0 do we have nan and we know the grad is zero there
Example #43
0
    def bDotT(self, x):
        """
        B dot T
        """
        vInfMag = x[0]
        vInfRA = x[1]
        vInfDec = x[2]
        bScalar = x[3]
        bTheta = x[4]
        TA = x[5]

        BT = bScalar * np.cos(bTheta)
        return BT
Example #44
0
 def eVector(self, x, mu):
     """
     eccentricity vector
     """
     eMag = self.eMag(x, mu)
     TAinf = self.TAinf(x, mu)
     s = self.sVector(x)
     bUnit = self.bVector(x)
     bUnit = bUnit / np.linalg.norm(bUnit)
     e = np.cos(np.pi - TAinf) * s - np.sin(np.pi - TAinf) * bUnit
     e = e / np.linalg.norm(e)
     e = eMag * e
     return e
Example #45
0
    def obj_func(self, X_, g, alpha=1):
        f = []

        for i in range(0, self.n_obj):
            _f = (1 + g)
            _f *= anp.prod(anp.cos(anp.power(X_[:, :X_.shape[1] - i], alpha) * anp.pi / 2.0), axis=1)
            if i > 0:
                _f *= anp.sin(anp.power(X_[:, X_.shape[1] - i], alpha) * anp.pi / 2.0)

            f.append(_f)

        f = anp.column_stack(f)
        return f
Example #46
0
    def eval(self, params, X, X2=None):

        w, mu, sigma = self.unpack_params(params)
        X2 = X if X2 is None else X2
        delta = np.expand_dims(X, 1) - \
                np.expand_dims(X2, 0)
        tau_sq = np.sum(delta**2, axis=2)
        tau = np.sqrt(tau_sq)
        out = np.zeros((X.shape[0], X2.shape[0]))
        for a in range(self.a):
            out += w[a] * np.exp(-2 * np.pi * tau_sq * sigma[0]) * \
                    np.cos(2 * np.pi * tau * mu[a])
        return out
Example #47
0
def make_pinwheel(radial_std,
                  tangential_std,
                  num_classes,
                  num_per_class,
                  rate,
                  rs=npr.RandomState(0)):
    """Based on code by Ryan P. Adams."""
    rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False)

    features = rs.randn(num_classes*num_per_class, 2) \
        * np.array([radial_std, tangential_std])
    features[:, 0] += 1
    labels = np.repeat(np.arange(num_classes), num_per_class)

    angles = rads[labels] + rate * np.exp(features[:, 0])
    rotations = np.stack(
        [np.cos(angles), -np.sin(angles),
         np.sin(angles),
         np.cos(angles)])
    rotations = np.reshape(rotations.T, (-1, 2, 2))

    return np.einsum('ti,tij->tj', features, rotations)
Example #48
0
def rodrigues_rotate_point(rot,X):
    sqtheta = np.sum(np.square(rot))
    if sqtheta != 0.:
        theta = np.sqrt(sqtheta)
        costheta = np.cos(theta)
        sintheta = np.sin(theta)  
        theta_inverse = 1. / theta

        w = theta_inverse * rot
        w_cross_X = cross(w,X)
        tmp = np.dot(w,X) * (1. - costheta)

        return X*costheta + w_cross_X * sintheta + w * tmp
    else:
        return X + cross(rot,X)
Example #49
0
    def cd_at_pixel(self, x, y):
        """ translation of dustin's wcs function:
        (x,y) to numpy array (2,2) -- the CD matrix at pixel x,y:

        [ [ dRA/dx * cos(Dec), dRA/dy * cos(Dec) ],
          [ dDec/dx          , dDec/dy           ] ]

        in FITS these are called:
        [ [ CD11             , CD12              ],
          [ CD21             , CD22              ] ]

          Note: these statements have not been verified by the FDA. :( :( :)
        """
        # TODO can this be analytically written out???
        ra0, dec0 = self.pixel2equa(np.array([x, y]))
        step = 10. # pixels
        rax, decx = self.pixel2equa(np.array([x+step, y]))
        ray, decy = self.pixel2equa(np.array([x, y+step]))
        cosd      = np.cos(dec0 * (np.pi / 180.))
        return np.array([ [(rax - ra0)/step * cosd, (ray-ra0)/step * cosd ],
                          [(decx - dec0)/step     , (decy-dec0)/step ] ])
Example #50
0
def test_cos():
    fun = lambda x : 3.0 * np.cos(x)
    d_fun = grad(fun)
    check_grads(fun, npr.randn())
    check_grads(d_fun, npr.randn())
Example #51
0
 def py_fun(node_params):
     messages, lognorm = natural_filter_forward_general(
         init_params, pair_params, node_params)
     return np.cos(lognorm) + messages_to_scalar(messages)
Example #52
0
 def cy_fun(node_params):
     dense_messages, lognorm = _natural_filter_forward_general(
         init_params, pair_params, node_params)
     messages = unpack_dense_messages(dense_messages)
     return np.cos(lognorm) + messages_to_scalar(messages)
	n_train = 10 # Number of training points
	noise_var = 0.025 # Process noise of observing the true function
	rs = npr.RandomState(0)

	length_scale = 1.0
	x_domain = (-5,5)
	n_pts = 100
	n_samples = 3
	num_params = 1

	full_x = np.linspace(x_domain[0],x_domain[1],n_pts).reshape((-1,1))

	seed = 222

	true_func = lambda xx: xx**2 * np.cos(xx)/xx
	# true_func = lambda xx: np.sqrt(np.abs(xx)) * np.sin(xx)**2
	# true_func = lambda xx: np.exp(-np.sin(xx)/xx)

	# Generate training points
	x_train = np.random.uniform(low=-5.,high=5.,size=n_train).reshape((-1,1))
	x_train.sort(0)
	y_train = true_func(x_train) + np.random.normal(loc=0.0,scale=noise_var,size=(n_train,1))

	##################################
	##  DETERMINISTIC PRIOR BASE GP ##
	##################################

	# Train Gaussian Process (only considering examples where noise is present)
	K = calcSigma(x_train,x_train,length_scale) # Get training covariance
	ks = calcSigma(x_train,full_x,length_scale) # Get covariance between train and test points
Example #54
0
 def f2(params):
     # one list, one numpy array input
     x,y = params[0]
     A = params[1]
     return np.sum(A**2) + np.cos(x) + np.exp(0.5*y)
Example #55
0
 def f2(params):
     return np.exp(params[0]) + params[1][0]**2 + np.cos(params[1][1])
Example #56
0
 def fun(input_tuple):
     A = np.sum(np.sin(input_tuple[0]))
     B = np.sum(np.cos(input_tuple[1]))
     return A + B
Example #57
0
 def fun(input_list):
     A = np.sum(np.sin(input_list[0]))
     B = np.sum(np.cos(input_list[1]))
     return A + B
Example #58
0
 def fun(input_dict):
     A = np.sum(np.sin(input_dict['item_1']))
     B = np.sum(np.cos(input_dict['item_2']))
     return A + B
Example #59
0
 def complicated_fun(a,b,c,d,e,f=1.1, g=9.0):
     return a + np.sin(b) + np.cosh(c) + np.cos(d) + np.tan(e) + f + g