コード例 #1
0
ファイル: kepler.py プロジェクト: dfm/theano_ops
def sky_position(period, t0, e, omega, incl, t, **kwargs):
    # Shorthands
    n = 2.0 * np.pi / period
    cos_omega = tt.cos(omega)
    sin_omega = tt.sin(omega)

    # Find the reference time that puts the center of transit at t0
    E0 = 2.0 * tt.atan2(
        tt.sqrt(1.0 - e) * cos_omega,
        tt.sqrt(1.0 + e) * (1.0 + sin_omega))
    tref = t0 - (E0 - e * tt.sin(E0)) / n

    # Solve Kepler's equation for the true anomaly
    M = (t - tref) * n
    kepler = KeplerOp(**kwargs)
    E = kepler(M, e + tt.zeros_like(M))
    f = 2.0 * tt.atan2(
        tt.sqrt(1.0 + e) * tt.tan(0.5 * E),
        tt.sqrt(1.0 - e) + tt.zeros_like(E))

    # Rotate into sky coordinates
    cf = tt.cos(f)
    sf = tt.sin(f)
    swpf = sin_omega * cf + cos_omega * sf
    cwpf = cos_omega * cf - sin_omega * sf

    # Star / planet distance
    r = (1.0 - e**2) / (1 + e * cf)

    return tt.stack(
        [-r * cwpf, -r * swpf * tt.cos(incl), r * swpf * tt.sin(incl)])
コード例 #2
0
ファイル: terms.py プロジェクト: stephaneudry/exoplanet
    def get_celerite_matrices(self, x, diag):
        x = tt.as_tensor_variable(x)
        diag = tt.as_tensor_variable(diag)
        ar, cr, ac, bc, cc, dc = self.coefficients
        a = diag + tt.sum(ar) + tt.sum(ac)
        U = tt.concatenate((
            ar[None, :] + tt.zeros_like(x)[:, None],
            ac[None, :] * tt.cos(dc[None, :] * x[:, None]) +
            bc[None, :] * tt.sin(dc[None, :] * x[:, None]),
            ac[None, :] * tt.sin(dc[None, :] * x[:, None]) -
            bc[None, :] * tt.cos(dc[None, :] * x[:, None]),
        ),
                           axis=1)

        V = tt.concatenate((
            tt.zeros_like(ar)[None, :] + tt.ones_like(x)[:, None],
            tt.cos(dc[None, :] * x[:, None]),
            tt.sin(dc[None, :] * x[:, None]),
        ),
                           axis=1)

        dx = x[1:] - x[:-1]
        P = tt.concatenate((
            tt.exp(-cr[None, :] * dx[:, None]),
            tt.exp(-cc[None, :] * dx[:, None]),
            tt.exp(-cc[None, :] * dx[:, None]),
        ),
                           axis=1)

        return a, U, V, P
コード例 #3
0
ファイル: trajectory.py プロジェクト: malayandi/DemPrefCode
 def f(t, x, u):
     d = (self.x[t][0] - x[0], self.x[t][1] - x[1])
     theta = self.x[t][2]
     dh = tt.cos(theta) * d[0] + tt.sin(theta) * d[1]
     dw = -tt.sin(theta) * d[0] + tt.cos(theta) * d[1]
     return tt.exp(-0.5 * (dh * dh / (height * height) + dw * dw /
                           (width * width)))
コード例 #4
0
    def get_radial_velocity(self, t, K=None, output_units=None):
        """Get the radial velocity of the star

        Args:
            t: The times where the radial velocity should be evaluated.
            K (Optional): The semi-amplitudes of the orbits. If provided, the
                ``m_planet`` and ``incl`` parameters will be ignored and this
                amplitude will be used instead.
            output_units (Optional): An AstroPy velocity unit. If not given,
                the output will be evaluated in ``m/s``. This is ignored if a
                value is given for ``K``.

        Returns:
            The reflex radial velocity evaluated at ``t`` in units of
            ``output_units``. For multiple planets, this will have one row for
            each planet.

        """

        # Special case for K given: m_planet, incl, etc. is ignored
        if K is not None:
            f = self._get_true_anomaly(t)
            if self.ecc is None:
                return tt.squeeze(K * tt.cos(f))
            # cos(w + f) + e * cos(w) from Lovis & Fischer
            return tt.squeeze(
                K * (self.cos_omega * tt.cos(f) - self.sin_omega * tt.sin(f) +
                     self.ecc * self.cos_omega))

        # Compute the velocity using the full orbit solution
        if output_units is None:
            output_units = u.m / u.s
        conv = (1 * u.R_sun / u.day).to(output_units).value
        v = self.get_star_velocity(t)
        return conv * v[2]
コード例 #5
0
ファイル: layers.py プロジェクト: yancz1989/text_warper
  def get_output_for(self, inputs, **kwargs):
    # see eq. (1) and sec 3.1 in [1]
    input, para = inputs
    num_batch, channels, height, width = input.shape
    _w = T.cast(width, dtype = self.dtype)
    _h = T.cast(height, dtype = self.dtype)
    mat = T.zeros((num_batch, 3, 3), dtype = self.dtype)
    mat = T.set_subtensor(mat[:, 0, 0], const(1.0))
    mat = T.set_subtensor(mat[:, 1, 1], const(1.0))
    mat = T.set_subtensor(mat[:, 2, 2], const(1.0))

    if self.method == 'perspective':
      mat = T.set_subtensor(mat[:, 2, 0], (para[:, 0] / 1e4 - 1e-3) * _w)
      mat = T.set_subtensor(mat[:, 2, 1], (para[:, 1] / 1e4 - 1e-3) * _h)
    elif self.method == 'angle':
      angle = T.cast(T.argmax(para, axis = 1), dtype = self.dtype) * np.pi / 90 - np.pi / 3.0
      # ss = np.sqrt(2.0)
      mat = T.set_subtensor(mat[:, :, :], T.stacklists([
        [T.cos(angle), T.sin(angle), -(T.cos(angle) * _w + T.sin(angle) * _h - _w) / (2.0 * _w)],
        [-T.sin(angle), T.cos(angle), -(-T.sin(angle) * _w + T.cos(angle) * _h - _h) / (2.0 * _h)],
        [constv(0, num_batch, self.dtype), constv(0, num_batch, self.dtype), constv(1, num_batch, self.dtype)]]).dimshuffle(2, 0, 1))
      # return [mat, _w, _h]
    elif self.method == 'all':
      mat = T.reshape(para, [-1, 3, 3])
      mat = T.set_subtensor(mat[:, 0, 2], mat[:, 0, 2] / T.cast(width, dtype))
      mat = T.set_subtensor(mat[:, 1, 2], mat[:, 1, 2] / T.cast(height, dtype))
      mat = T.set_subtensor(mat[:, 2, 0], mat[:, 2, 0] * T.cast(width, dtype))
      mat = T.set_subtensor(mat[:, 2, 1], mat[:, 2, 1] * T.cast(height, dtype))
    else:
      raise Exception('method not understood.')
    return transform_affine(mat, input, self.method, scale_factor = self.scale_factor)
コード例 #6
0
 def get_blender_proj(self, camera):
     deg2rad = lambda angle: (angle / 180.) * np.pi
     sa = tensor.sin(deg2rad(-camera[0]))
     ca = tensor.cos(deg2rad(-camera[0]))
     se = tensor.sin(deg2rad(-camera[1]))
     ce = tensor.cos(deg2rad(-camera[1]))
     R_world2obj = tensor.eye(3)
     R_world2obj = tensor.set_subtensor(R_world2obj[0, 0], ca * ce)
     R_world2obj = tensor.set_subtensor(R_world2obj[0, 1], sa * ce)
     R_world2obj = tensor.set_subtensor(R_world2obj[0, 2], -se)
     R_world2obj = tensor.set_subtensor(R_world2obj[1, 0], -sa)
     R_world2obj = tensor.set_subtensor(R_world2obj[1, 1], ca)
     R_world2obj = tensor.set_subtensor(R_world2obj[2, 0], ca * se)
     R_world2obj = tensor.set_subtensor(R_world2obj[2, 1], sa * se)
     R_world2obj = tensor.set_subtensor(R_world2obj[2, 2], ce)
     R_obj2cam = np.array(
         ((1.910685676922942e-15, 4.371138828673793e-08, 1.0),
          (1.0, -4.371138828673793e-08, -0.0), (4.371138828673793e-08, 1.0,
                                                -4.371138828673793e-08))).T
     R_world2cam = tensor.dot(R_obj2cam, R_world2obj)
     cam_location = tensor.zeros((3, 1))
     cam_location = tensor.set_subtensor(cam_location[0, 0],
                                         camera[2] * 1.75)
     T_world2cam = -1 * tensor.dot(R_obj2cam, cam_location)
     R_camfix = np.array(((1, 0, 0), (0, -1, 0), (0, 0, -1)))
     R_world2cam = tensor.dot(R_camfix, R_world2cam)
     T_world2cam = tensor.dot(R_camfix, T_world2cam)
     RT = tensor.concatenate([R_world2cam, T_world2cam], axis=1)
     return RT
コード例 #7
0
def theano_rot(rx, ry, rz, rescale=True):
    '''Return a theano tensor representing a rotation 
    matrix using specified rotation angles rx,ry, rz
    If rescale is True, treat the input angles as degrees.
    '''

    if rescale:
        rx = np.pi / 180. * (rx)
        ry = np.pi / 180. * (ry)
        rz = np.pi / 180. * (rz)

    sx = tt.sin(rx)
    sy = tt.sin(ry)
    sz = tt.sin(rz)
    cx = tt.cos(rx)
    cy = tt.cos(ry)
    cz = tt.cos(rz)
    Rx = [[1, 0, 0], [0, cx, -sx], [0, sx, cx]]
    Ry = [[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]]
    Rz = [[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]]

    Rxt = tt.stacklists(Rx)
    Ryt = tt.stacklists(Ry)
    Rzt = tt.stacklists(Rz)
    full_rotation = tt.dot(Rzt, tt.dot(Ryt, Rxt))
    return full_rotation
コード例 #8
0
def MMDEstimator(rng, x, y, n_in, n_batch, D):
    '''
    This layer is presenting the gaussian sampling process of Stochastic Gradient Variational Bayes(SVGB)
    :type x,y: theano.tensor.dmatrix
    :param x,y: a symbolic tensor of shape (n_batch, n_in)       
    
    '''    
    gamma = 1
    
    W_values = np.asarray(
        rng.standard_normal(
            size=(n_in, D)
        ),
        dtype=theano.config.floatX
    )

    W = theano.shared(value=W_values, name='MMDEstimator_W', borrow=True)

    b_values = np.asarray(
        rng.uniform(
            low = 0,
            high = 2 * np.pi,
            size=(D,)
        ),
        dtype=theano.config.floatX
    )
    b = theano.shared(value=b_values, name='MMDEstimator_b', borrow=True)

    psi_x = np.sqrt(2.0/D) * T.cos( np.sqrt(2/gamma) * T.dot(x, W) + b)
    psi_y = np.sqrt(2.0/D) * T.cos( np.sqrt(2/gamma) * T.dot(y, W) + b)
    MMD = T.sum(psi_x, axis=0) / n_batch[0] - T.sum(psi_y, axis=0) / n_batch[1]
        
    return MMD.norm(2)
コード例 #9
0
ファイル: theano_kriging.py プロジェクト: zaknbur/gempy
    def b_vector(self):
        """
        Creation of the independent vector b to solve the kriging system

        Args:
            verbose: -deprecated-

        Returns:
            theano.tensor.vector: independent vector
        """

        length_of_C = self.matrices_shapes()[-1]
        # =====================
        # Creation of the gradients G vector
        # Calculation of the cartesian components of the dips assuming the unit module
        G_x = T.sin(T.deg2rad(self.dip_angles)) * T.sin(T.deg2rad(
            self.azimuth)) * self.polarity
        G_y = T.sin(T.deg2rad(self.dip_angles)) * T.cos(T.deg2rad(
            self.azimuth)) * self.polarity
        G_z = T.cos(T.deg2rad(self.dip_angles)) * self.polarity

        G = T.concatenate((G_x, G_y, G_z))

        # Creation of the Dual Kriging vector
        b = T.zeros((length_of_C, ))
        b = T.set_subtensor(b[0:G.shape[0]], G)

        if str(sys._getframe().f_code.co_name) in self.verbose:
            b = theano.printing.Print('b vector')(b)

        # Add name to the theano node
        b.name = 'b vector'
        return b
コード例 #10
0
ファイル: base.py プロジェクト: mattsqerror/seya
    def _get_rotation(self):
        A = T.eye(self.dim)
        for i, (x, y) in enumerate(combinations(range(self.dim), 2)):
            B = T.eye(self.dim)

            if x == 0:
                b0 = []
                v3 = []
            else:
                b0 = T.zeros((x, ))
                v3 = T.zeros((x, self.dim))
            if self.dim - x - y - 1 == 0:
                b1 = []
            else:
                b1 = T.zeros((self.dim - x - y - 1, ))
            if self.dim - y + x + 1 == 0:
                v4 = []
            else:
                v4 = T.zeros((self.dim - y + x + 1, self.dim))
            if y - 1 == 0:
                b2 = []
            else:
                b2 = T.zeros((y - 1, ))

            v1 = T.concatenate(
                [b0, T.cos(self.W[i]), b2, -T.sin(self.W[i]), b1])
            v2 = T.concatenate(
                [b0, T.sin(self.W[i]), b2,
                 T.cos(self.W[i]), b1])

            B = T.concatenate([v1, v2, v3, v4], axis=0) + T.eye(self.dim)
            A = T.dot(A, B)
        return A
コード例 #11
0
 def _get_velocity(self, m, t):
     """Get the velocity vector of a body in the observer frame"""
     f = self._get_true_anomaly(t)
     K = self.K0 * m
     if self.ecc is None:
         return self._rotate_vector(-K * tt.sin(f), K * tt.cos(f))
     return self._rotate_vector(-K * tt.sin(f), K * (tt.cos(f) + self.ecc))
コード例 #12
0
    def __init__(self,
                 input,
                 input_shape,
                 id,
                 angle=None,
                 borrow=True,
                 verbose=2):
        super(rotate_layer, self).__init__(id=id,
                                           type='rotate',
                                           verbose=verbose)
        if verbose >= 3:
            print("... Creating rotate layer")

        if len(input_shape) == 4:
            if verbose >= 3:
                print("... Creating the rotate layer")

            if angle is None:
                angle = nprnd.uniform(size=(input_shape[0], 1), low=0, high=1)

            theta = T.stack([
                T.cos(angle[:, 0] * 90).reshape([angle.shape[0], 1]),
                -T.sin(angle[:, 0] * 90).reshape([angle.shape[0], 1]),
                T.zeros((input_shape[0], 1), dtype='float32'),
                T.sin(angle[:, 0] * 90).reshape([angle.shape[0], 1]),
                T.cos(angle[:, 0] * 90).reshape([angle.shape[0], 1]),
                T.zeros((input_shape[0], 1), dtype='float32')
            ],
                            axis=1)
            theta = theta.reshape((-1, 6))

            self.output = self._transform_affine(theta, input)
            self.output_shape = input_shape
            self.angle = angle
            self.inference = self.output
コード例 #13
0
def normalTriad(phi, theta):
	"""
	Calculate the so-called normal triad [p, q, r] which is associated with a spherical coordinate system .
	The three vectors are:
	p - The unit tangent vector in the direction of increasing longitudinal angle phi.
	q - The unit tangent vector in the direction of increasing latitudinal angle theta.
	r - The unit vector toward the point (phi, theta).
	Parameters
	----------
	phi   - longitude-like angle (e.g., right ascension, ecliptic longitude) in radians
	theta - latitide-like angle (e.g., declination, ecliptic latitude) in radians

	Returns
	-------
	The normal triad as the vectors p, q, r
	"""
	zeros  = tt.zeros_like(phi)
	sphi   = tt.sin(phi)
	stheta = tt.sin(theta)
	cphi   = tt.cos(phi)
	ctheta = tt.cos(theta)

	
	q = tt.stack([-stheta*cphi, -stheta*sphi, ctheta],axis=1)
	r = tt.stack([ctheta*cphi, ctheta*sphi, stheta],axis=1)
	p = tt.stack([-sphi, cphi, zeros],axis=1)

	return p, q, r
コード例 #14
0
ファイル: solver.py プロジェクト: dfm/exoplanet
    def grad(self, inputs, gradients):
        M, e = inputs
        E, f = self(M, e)

        bM = tt.zeros_like(M)
        be = tt.zeros_like(M)
        ecosE = e * tt.cos(E)

        if not isinstance(gradients[0].type, theano.gradient.DisconnectedType):
            # Backpropagate E_bar
            bM = gradients[0] / (1 - ecosE)
            be = tt.sin(E) * bM

        if not isinstance(gradients[1].type, theano.gradient.DisconnectedType):
            # Backpropagate f_bar
            sinf2 = tt.sin(0.5*f)
            cosf2 = tt.cos(0.5*f)
            tanf2 = sinf2 / cosf2
            e2 = e**2
            ome2 = 1 - e2
            ome = 1 - e
            ope = 1 + e
            cosf22 = cosf2**2
            twoecosf22 = 2 * e * cosf22
            factor = tt.sqrt(ope/ome)
            inner = (twoecosf22+ome) * tt.as_tensor_variable(gradients[1])

            bM += factor*(ome*tanf2**2+ope)*inner*cosf22/(ope*ome2)
            be += -2*cosf22*tanf2/ome2**2*inner*(ecosE-2+e2)

        return [bM, be]
コード例 #15
0
ファイル: terms.py プロジェクト: dfm/exoplanet
    def get_celerite_matrices(self, x, diag):
        x = tt.as_tensor_variable(x)
        diag = tt.as_tensor_variable(diag)
        ar, cr, ac, bc, cc, dc = self.coefficients
        a = diag + tt.sum(ar) + tt.sum(ac)
        U = tt.concatenate((
            ar[None, :] + tt.zeros_like(x)[:, None],
            ac[None, :] * tt.cos(dc[None, :] * x[:, None])
            + bc[None, :] * tt.sin(dc[None, :] * x[:, None]),
            ac[None, :] * tt.sin(dc[None, :] * x[:, None])
            - bc[None, :] * tt.cos(dc[None, :] * x[:, None]),
        ), axis=1)

        V = tt.concatenate((
            tt.zeros_like(ar)[None, :] + tt.ones_like(x)[:, None],
            tt.cos(dc[None, :] * x[:, None]),
            tt.sin(dc[None, :] * x[:, None]),
        ), axis=1)

        dx = x[1:] - x[:-1]
        P = tt.concatenate((
            tt.exp(-cr[None, :] * dx[:, None]),
            tt.exp(-cc[None, :] * dx[:, None]),
            tt.exp(-cc[None, :] * dx[:, None]),
        ), axis=1)

        return a, U, V, P
コード例 #16
0
ファイル: BaseModels.py プロジェクト: ZidCode/ibsen_eval
 def _forward_scat(self):
     alpha_border = 1.2  # Greg & Carder
     cos_theta = T.switch(T.gt(self.symbols['alpha'], alpha_border), 0.65, -0.1417 * self.symbols['alpha'] + 0.82)
     B3 = T.log(1 - cos_theta)
     B2 = B3 * (0.0783 + B3 * (-0.3824 - 0.5874 * B3))
     B1 = B3 * (1.459 + B3 * (0.1595 + 0.4129 * B3))
     return 1 - 0.5 * T.exp((B1 + B2 * T.cos(self.zenith_rad)) * T.cos(self.zenith_rad))
コード例 #17
0
def arc_distance_theano_broadcast_prepare(dtype='float64'):
    """
    Calculates the pairwise arc distance between all points in vector a and b.
    """
    a = tensor.matrix(dtype=str(dtype))
    b = tensor.matrix(dtype=str(dtype))

    theta_1 = a[:, 0][None, :]
    theta_2 = b[:, 0][None, :]
    phi_1 = a[:, 1][:, None]
    phi_2 = b[:, 1][None, :]

    temp = (tensor.sin((theta_2 - theta_1) / 2)**2
            +
            tensor.cos(theta_1) * tensor.cos(theta_2)
            * tensor.sin((phi_2 - phi_1) / 2)**2)
    distance_matrix = 2 * (tensor.arctan2(tensor.sqrt(temp),
                                          tensor.sqrt(1 - temp)))
    name = "arc_distance_theano_broadcast"
    rval = theano.function([a, b],
                           distance_matrix,
                           name=name)
    rval.__name__ = name

    return rval
コード例 #18
0
def arc_distance_theano_alloc_prepare(dtype='float64'):
    """
    Calculates the pairwise arc distance between all points in vector a and b.
    """
    a = tensor.matrix(dtype=str(dtype))
    b = tensor.matrix(dtype=str(dtype))
    # Theano don't implement all case of tile, so we do the equivalent with alloc.
    #theta_1 = tensor.tile(a[:, 0], (b.shape[0], 1)).T
    theta_1 = tensor.alloc(a[:, 0], b.shape[0], b.shape[0]).T
    phi_1 = tensor.alloc(a[:, 1], b.shape[0], b.shape[0]).T

    theta_2 = tensor.alloc(b[:, 0], a.shape[0], a.shape[0])
    phi_2 = tensor.alloc(b[:, 1], a.shape[0], a.shape[0])

    temp = (tensor.sin((theta_2 - theta_1) / 2)**2
            +
            tensor.cos(theta_1) * tensor.cos(theta_2)
            * tensor.sin((phi_2 - phi_1) / 2)**2)
    distance_matrix = 2 * (tensor.arctan2(tensor.sqrt(temp),
                                          tensor.sqrt(1 - temp)))
    name = "arc_distance_theano_alloc"
    rval = theano.function([a, b],
                           distance_matrix,
                           name=name)
    rval.__name__ = name

    return rval
コード例 #19
0
def theano_rot(rx,ry,rz, rescale=180./np.pi):
    '''Return a theano tensor representing a rotation 
    matrix using specified rotation angles rx,ry, rz
    Rescale can be used to change the angular units to i.e. degrees.
    '''

    rx = (rx)/rescale
    ry = (ry)/rescale
    rz = (rz)/rescale

    sx = tt.sin(rx)
    sy = tt.sin(ry)
    sz = tt.sin(rz)
    cx = tt.cos(rx)
    cy = tt.cos(ry)
    cz = tt.cos(rz)
    Rx = [[1.,0.,0.],[0.,cx,-sx],[0.,sx,cx]]
    Ry = [[cy,0.,sy],[0.,1.,0.],[-sy,0.,cy]]
    Rz = [[cz,-sz,0.],[sz,cz,0.],[0.,0.,1.]]


    Rxt = tt.stacklists(Rx)
    Ryt = tt.stacklists(Ry)
    Rzt = tt.stacklists(Rz)
    full_rotation=tt.dot(Rzt,tt.dot(Ryt, Rxt))
    return full_rotation
コード例 #20
0
    def grad(self, inputs, gradients):
        M, e = inputs
        E, f = self(M, e)

        bM = tt.zeros_like(M)
        be = tt.zeros_like(M)
        ecosE = e * tt.cos(E)

        if not isinstance(gradients[0].type, theano.gradient.DisconnectedType):
            # Backpropagate E_bar
            bM = gradients[0] / (1 - ecosE)
            be = tt.sin(E) * bM

        if not isinstance(gradients[1].type, theano.gradient.DisconnectedType):
            # Backpropagate f_bar
            sinf2 = tt.sin(0.5 * f)
            cosf2 = tt.cos(0.5 * f)
            tanf2 = sinf2 / cosf2
            e2 = e**2
            ome2 = 1 - e2
            ome = 1 - e
            ope = 1 + e
            cosf22 = cosf2**2
            twoecosf22 = 2 * e * cosf22
            factor = tt.sqrt(ope / ome)
            inner = (twoecosf22 + ome) * tt.as_tensor_variable(gradients[1])

            bM += factor * (ome * tanf2**2 + ope) * inner * cosf22 / (ope *
                                                                      ome2)
            be += -2 * cosf22 * tanf2 / ome2**2 * inner * (ecosE - 2 + e2)

        return [bM, be]
コード例 #21
0
        def f(x, u, i, terminal):
            # Original Gym does not impose a control cost, but does clip it
            # to [-1, 1]. This non-linear dynamics is hard for iLQG to handle,
            # so add a quadratic control penalty instead.
            if terminal:
                ctrl_cost = T.zeros_like(x[..., 0])
            else:
                ctrl_cost = T.square(u).sum(axis=-1)

            # x: (batch_size, 6), concatenation of qpos & qvel

            # Distance cost
            # The tricky part is finding Cartesian coords of pole tip.
            base_x = x[..., 0]  # qpos[0]: x axis of the slider
            hinge1_ang = x[..., 1]  # qpos[1]: angle of the first hinge
            hinge2_ang = x[..., 2]  # qpos[2]: angle of the second hinge
            hinge2_cum_ang = hinge1_ang + hinge2_ang
            # 0 degrees is y=1, x=0; rotates clockwise.
            hinge1_x, hinge1_y = T.sin(hinge1_ang), T.cos(hinge1_ang)
            hinge2_x, hinge2_y = T.sin(hinge2_cum_ang), T.cos(hinge2_cum_ang)
            tip_x = base_x + hinge1_x + hinge2_x
            tip_y = hinge1_y + hinge2_y
            dist_cost = 0.01 * T.square(tip_x) + T.square(tip_y - 2)

            # Velocity cost
            v1 = x[..., 4]  # qvel[1]
            v2 = x[..., 5]  # qvel[2]
            vel_cost = 1e-3 * T.square(v1) + 5e-3 * T.square(v2)

            # TODO: termination penalty? (shouldn't change optimal policy?)
            dist_below = T.max([T.zeros_like(tip_y), 1.1 - tip_y], axis=0)
            termination_cost = T.square(dist_below)

            cost = 5 * termination_cost + dist_cost + vel_cost + ctrl_coef * ctrl_cost
            return cost
コード例 #22
0
ファイル: balib.py プロジェクト: pavelgrib/pySLAM
def poseDiff2D(startingPose, endingPose):
    x1, y1, theta1 = endingPose[0], endingPose[1], endingPose[2]
    x2, y2, theta2 = startingPose[0], startingPose[1], startingPose[2]
    dx = (x1 - x2) * T.cos(theta2) + (y1 - y2) * T.sin(theta2)
    dy = -(x1 - x2) * T.sin(theta2) + (y1 - y2) * T.cos(theta2)
    dtheta = normalizeAngle(theta1 - theta2)
    return dx, dy, dtheta
コード例 #23
0
    def get_value(self, tau0):
        dt = self.delta
        ar, cr, a, b, c, d = self.term.coefficients

        # Format the lags correctly
        tau0 = tt.abs_(tau0)
        tau = tau0[..., None]

        # Precompute some factors
        dpt = dt + tau
        dmt = dt - tau

        # Real parts:
        # tau > Delta
        crd = cr * dt
        cosh = tt.cosh(crd)
        norm = 2 * ar / crd ** 2
        K_large = tt.sum(norm * (cosh - 1) * tt.exp(-cr * tau), axis=-1)

        # tau < Delta
        crdmt = cr * dmt
        K_small = K_large + tt.sum(norm * (crdmt - tt.sinh(crdmt)), axis=-1)

        # Complex part
        cd = c * dt
        dd = d * dt
        c2 = c ** 2
        d2 = d ** 2
        c2pd2 = c2 + d2
        C1 = a * (c2 - d2) + 2 * b * c * d
        C2 = b * (c2 - d2) - 2 * a * c * d
        norm = 1.0 / (dt * c2pd2) ** 2
        k0 = tt.exp(-c * tau)
        cdt = tt.cos(d * tau)
        sdt = tt.sin(d * tau)

        # For tau > Delta
        cos_term = 2 * (tt.cosh(cd) * tt.cos(dd) - 1)
        sin_term = 2 * (tt.sinh(cd) * tt.sin(dd))
        factor = k0 * norm
        K_large += tt.sum(
            (C1 * cos_term - C2 * sin_term) * factor * cdt, axis=-1
        )
        K_large += tt.sum(
            (C2 * cos_term + C1 * sin_term) * factor * sdt, axis=-1
        )

        # tau < Delta
        edmt = tt.exp(-c * dmt)
        edpt = tt.exp(-c * dpt)
        cos_term = (
            edmt * tt.cos(d * dmt) + edpt * tt.cos(d * dpt) - 2 * k0 * cdt
        )
        sin_term = (
            edmt * tt.sin(d * dmt) + edpt * tt.sin(d * dpt) - 2 * k0 * sdt
        )
        K_small += tt.sum(2 * (a * c + b * d) * c2pd2 * dmt * norm, axis=-1)
        K_small += tt.sum((C1 * cos_term + C2 * sin_term) * norm, axis=-1)

        return tt.switch(tt.le(tau0, dt), K_small, K_large)
コード例 #24
0
ファイル: balib.py プロジェクト: pavelgrib/pySLAM
def poseDiff2D(startingPose, endingPose):
    x1, y1, theta1 = endingPose[0], endingPose[1], endingPose[2]
    x2, y2, theta2 = startingPose[0], startingPose[1], startingPose[2]
    dx = (x1 - x2)*T.cos(theta2) + (y1 - y2)*T.sin(theta2)
    dy = -(x1 - x2)*T.sin(theta2) + (y1 - y2)*T.cos(theta2)
    dtheta = normalizeAngle(theta1 - theta2)
    return dx, dy, dtheta
コード例 #25
0
ファイル: utils.py プロジェクト: harpone/DerpRNN
def get_uhs_operator(uhs, depth, n_hidden, rhos):
    """

    :param uhs:
    :param depth:
    :param n_hidden:
    :param rhos: can be shared variable or constant of shape (depth, )!!
    :return:
    """
    # Will use a Fourier matrix (will be O(n^2)...)
    # Doesn't seem to slow things down much though!
    exp_phases = [T.cos(uhs), T.sin(uhs)]
    neg_exp_phases = [T.cos(uhs[:, ::-1]), -T.sin(uhs[:, ::-1])]
    ones_ = [T.ones((depth, 1), dtype=theano.config.floatX), T.zeros((depth, 1), dtype=theano.config.floatX)]

    rhos_reshaped = T.reshape(rhos, (depth, 1), ndim=2)
    rhos_reshaped = T.addbroadcast(rhos_reshaped, 1)

    eigvals_re = rhos_reshaped * T.concatenate((ones_[0], exp_phases[0], -ones_[0], neg_exp_phases[0]), axis=1)
    eigvals_im = rhos_reshaped * T.concatenate((ones_[1], exp_phases[1], -ones_[1], neg_exp_phases[1]), axis=1)
    phase_array = -2 * np.pi * np.outer(np.arange(n_hidden), np.arange(n_hidden)) / n_hidden
    f_array_re_val = np.cos(phase_array) / n_hidden
    f_array_im_val = np.sin(phase_array) / n_hidden
    f_array_re = theano.shared(f_array_re_val.astype(theano.config.floatX), name="f_arr_re")
    f_array_im = theano.shared(f_array_im_val.astype(theano.config.floatX), name="f_arr_im")

    a_k = T.dot(eigvals_re, f_array_re) + T.dot(eigvals_im, f_array_im)
    uhs_op = rep_vec(a_k, n_hidden, n_hidden)  # shape (depth, 2 * n_hidden - 1)

    return uhs_op
コード例 #26
0
 def EPhiTPhi_loop_i0(loop, EPhiTPhi, non_rec, D, order, MU, SIGMA_trf,
                      inv_SIGMA_trf, inv_SIGMA_trf_MU, inv_B, b_bold,
                      inv_B_b_bold, B, MU_S_hat_minus, MU_S_hat_plus,
                      big_sum_minus, big_sum_plus,
                      norm_EEPhiTPhi_U_temp):
     loop = loop + 1
     D_n = (inv_B +
            inv_SIGMA_trf[loop, :][None, None, :])**-1  # M x M x D[i]
     if non_rec == 0:
         d_n = D_n[:, :, D - order:D] * (
             inv_B_b_bold[:, :, D - order:D] +
             inv_SIGMA_trf_MU[loop, :][None, None, D - order:D]
         )  # M x M x N x order
         d_n = T.concatenate(
             (MU[loop, :][0:D - order][None, None, :] +
              T.zeros_like(inv_B[:, :, 0:D - order]), d_n),
             axis=2)  # M x M x N x D[i]
     else:
         d_n = MU[loop, :][None, None, :] + T.zeros_like(
             inv_B)  # M x M x N x D[i]
     W = B + SIGMA_trf[loop, :][None, None, :]  # M x M x D[i]
     norm_EEPhiTPhi_U_W = (norm_EEPhiTPhi_U_temp / W**0.5).prod(
         2
     )  # M x M  % here we put det(U), det(W), because of numeric issues (prod(2) is huge for huge input-dimensions)
     Z_n_W = T.exp(
         -0.5 *
         ((b_bold - MU[loop, :][None, None, :])**2 / W).sum(2))  # M x M
     EPhiTPhi = EPhiTPhi + Z_n_W * norm_EEPhiTPhi_U_W * (
         T.exp(-0.5 * (MU_S_hat_minus**2 * D_n).sum(2)) * T.cos(
             (MU_S_hat_minus * d_n).sum(2) + big_sum_minus) +
         T.exp(-0.5 * (MU_S_hat_plus**2 * D_n).sum(2)) * T.cos(
             (MU_S_hat_plus * d_n).sum(2) + big_sum_plus))  # M x M
     return loop, EPhiTPhi
コード例 #27
0
ファイル: terms.py プロジェクト: stephaneudry/exoplanet
    def value(self, tau0):
        dt = self.delta
        ar, cr, a, b, c, d = self.term.coefficients

        # Format the lags correctly
        tau0 = tt.abs_(tau0)
        tau = tt.reshape(tau0,
                         tt.concatenate([tau0.shape, [1]]),
                         ndim=tau0.ndim + 1)

        # Precompute some factors
        dpt = dt + tau
        dmt = dt - tau

        # Real parts:
        # tau > Delta
        crd = cr * dt
        norm = 1.0 / (crd)**2
        factor = (tt.exp(crd) + tt.exp(-crd) - 2) * norm,
        K_large = tt.sum(ar * tt.exp(-cr * tau) * factor, axis=-1)

        # tau < Delta
        K_small = tt.sum((2 * cr * (dmt) + tt.exp(-cr * dmt) +
                          tt.exp(-cr * dpt) - 2 * tt.exp(-cr * tau)) * norm,
                         axis=-1)

        # Complex part
        cd = c * dt
        dd = d * dt
        c2 = c**2
        d2 = d**2
        c2pd2 = c2 + d2
        C1 = a * (c2 - d2) + 2 * b * c * d
        C2 = b * (c2 - d2) - 2 * a * c * d
        norm = 1.0 / (dt * c2pd2)**2
        k0 = tt.exp(-c * tau)
        cdt = tt.cos(d * tau)
        sdt = tt.sin(d * tau)

        # For tau > Delta
        cos_term = 2 * (tt.cosh(cd) * tt.cos(dd) - 1)
        sin_term = 2 * (tt.sinh(cd) * tt.sin(dd))
        factor = k0 * norm
        K_large += tt.sum((C1 * cos_term - C2 * sin_term) * factor * cdt,
                          axis=-1)
        K_large += tt.sum((C2 * cos_term + C1 * sin_term) * factor * sdt,
                          axis=-1)

        # Real part
        edmt = tt.exp(-c * dmt)
        edpt = tt.exp(-c * dpt)
        cos_term = edmt * tt.cos(d * dmt) + edpt * tt.cos(
            d * dpt) - 2 * k0 * cdt
        sin_term = edmt * tt.sin(d * dmt) + edpt * tt.sin(
            d * dpt) - 2 * k0 * sdt
        K_small += tt.sum(2 * (a * c + b * d) * c2pd2 * dmt * norm, axis=-1)
        K_small += tt.sum((C1 * cos_term + C2 * sin_term) * norm, axis=-1)

        return tt.switch(tt.le(tau0, dt), K_small, K_large)
コード例 #28
0
ファイル: lfvbaeAlphaStable.py プロジェクト: onenoc/lfvbae
 def alpha_perfect(self, w, u):
     alpha = sharedX(1.5)
     beta = sharedX(0.5)
     S_var = self.S(alpha, beta)
     B_var = self.B(alpha, beta)
     first = T.sin(alpha * (u + B_var) / (T.cos(u)**(1 / alpha)))
     second = T.cos(u - alpha * (u + B_var)) / w
     return S_var * first * (second**((1 - alpha) / alpha))
コード例 #29
0
ファイル: lfvbaeAlphaStable.py プロジェクト: onenoc/lfvbae
 def alpha_perfect(self, w, u):
     alpha = sharedX(1.5)
     beta = sharedX(0.5)
     S_var = self.S(alpha,beta)
     B_var = self.B(alpha,beta)
     first = T.sin(alpha*(u+B_var)/(T.cos(u)**(1/alpha)))
     second = T.cos(u-alpha*(u+B_var))/w
     return S_var*first*(second**((1-alpha)/alpha))
コード例 #30
0
 def _getrz(self,d):
     r=theano.shared(np.zeros((3,3),dtype='float32'))
     r=T.set_subtensor(r[2,2],1.0)
     r=T.set_subtensor(r[0,0],T.cos(d))
     r=T.set_subtensor(r[0,1],-T.sin(d))
     r=T.set_subtensor(r[1,0],T.sin(d))
     r=T.set_subtensor(r[1,1],T.cos(d))        
     return r
コード例 #31
0
 def forward(self, inputtensor):
     inputimage = inputtensor[0]
     if inputimage.ndim == 4:
         return (T.cos(self.a.dimshuffle('x', 0, 'x', 'x') * inputimage), )
     if inputimage.ndim == 2:
         return (T.cos(self.a * inputimage), )
     else:
         raise NotImplementedError
コード例 #32
0
 def _getrz(self, d):
     r = theano.shared(np.zeros((3, 3), dtype='float32'))
     r = T.set_subtensor(r[2, 2], 1.0)
     r = T.set_subtensor(r[0, 0], T.cos(d))
     r = T.set_subtensor(r[0, 1], -T.sin(d))
     r = T.set_subtensor(r[1, 0], T.sin(d))
     r = T.set_subtensor(r[1, 1], T.cos(d))
     return r
コード例 #33
0
ファイル: SCFGP.py プロジェクト: MaxInGaussian/SCFGP
 def build_theano_models(self, algo, algo_params):
     epsilon = 1e-6
     kl = lambda mu, sig: sig+mu**2-TT.log(sig)
     X, y = TT.dmatrices('X', 'y')
     params = TT.dvector('params')
     a, b, c, l_F, F, l_FC, FC = self.unpack_params(params)
     sig2_n, sig_f = TT.exp(2*a), TT.exp(b)
     l_FF = TT.dot(X, l_F)+l_FC
     FF = TT.concatenate((l_FF, TT.dot(X, F)+FC), 1)
     Phi = TT.concatenate((TT.cos(FF), TT.sin(FF)), 1)
     Phi = sig_f*TT.sqrt(2./self.M)*Phi
     noise = TT.log(1+TT.exp(c))
     PhiTPhi = TT.dot(Phi.T, Phi)
     A = PhiTPhi+(sig2_n+epsilon)*TT.identity_like(PhiTPhi)
     L = Tlin.cholesky(A)
     Li = Tlin.matrix_inverse(L)
     PhiTy = Phi.T.dot(y)
     beta = TT.dot(Li, PhiTy)
     alpha = TT.dot(Li.T, beta)
     mu_f = TT.dot(Phi, alpha)
     var_f = (TT.dot(Phi, Li.T)**2).sum(1)[:, None]
     dsp = noise*(var_f+1)
     mu_l = TT.sum(TT.mean(l_F, axis=1))
     sig_l = TT.sum(TT.std(l_F, axis=1))
     mu_w = TT.sum(TT.mean(F, axis=1))
     sig_w = TT.sum(TT.std(F, axis=1))
     hermgauss = np.polynomial.hermite.hermgauss(30)
     herm_x = Ts(hermgauss[0])[None, None, :]
     herm_w = Ts(hermgauss[1]/np.sqrt(np.pi))[None, None, :]
     herm_f = TT.sqrt(2*var_f[:, :, None])*herm_x+mu_f[:, :, None]
     nlk = (0.5*herm_f**2.-y[:, :, None]*herm_f)/dsp[:, :, None]+0.5*(
         TT.log(2*np.pi*dsp[:, :, None])+y[:, :, None]**2/dsp[:, :, None])
     enll = herm_w*nlk
     nlml = 2*TT.log(TT.diagonal(L)).sum()+2*enll.sum()+1./sig2_n*(
         (y**2).sum()-(beta**2).sum())+2*(X.shape[0]-self.M)*a
     penelty = (kl(mu_w, sig_w)*self.M+kl(mu_l, sig_l)*self.S)/(self.S+self.M)
     cost = (nlml+penelty)/X.shape[0]
     grads = TT.grad(cost, params)
     updates = getattr(OPT, algo)(self.params, grads, **algo_params)
     updates = getattr(OPT, 'apply_nesterov_momentum')(updates, momentum=0.9)
     train_inputs = [X, y]
     train_outputs = [cost, alpha, Li]
     self.train_func = Tf(train_inputs, train_outputs,
         givens=[(params, self.params)])
     self.train_iter_func = Tf(train_inputs, train_outputs,
         givens=[(params, self.params)], updates=updates)
     Xs, Li, alpha = TT.dmatrices('Xs', 'Li', 'alpha')
     l_FFs = TT.dot(Xs, l_F)+l_FC
     FFs = TT.concatenate((l_FFs, TT.dot(Xs, F)+FC), 1)
     Phis = TT.concatenate((TT.cos(FFs), TT.sin(FFs)), 1)
     Phis = sig_f*TT.sqrt(2./self.M)*Phis
     mu_pred = TT.dot(Phis, alpha)
     std_pred = (noise*(1+(TT.dot(Phis, Li.T)**2).sum(1)))**0.5
     pred_inputs = [Xs, alpha, Li]
     pred_outputs = [mu_pred, std_pred]
     self.pred_func = Tf(pred_inputs, pred_outputs,
         givens=[(params, self.params)])
コード例 #34
0
 def generator(self, u):
     if u.ndim == 1:
         u = u[None, :]
     z, n = u[:, :self.z_dim], u[:, self.z_dim:self.z_dim + self.x_dim]
     loc, scale = self.x_gvn_z(z)
     alpha = 2 * scale / (1 + scale**2)
     phi = tt.arccos((tt.cos(2 * np.pi * n) + alpha) /
                     (1 + alpha * tt.cos(2 * np.pi * n))) + loc
     return tt.switch(n < 0.5, phi, 2 * np.pi - phi)
コード例 #35
0
 def theano_periodic_sinc(in_sig, bandwidth):
     eps = TT.constant(1e-10)
     denominator = TT.mul(TT.sin(TT.true_div(in_sig, bandwidth)), bandwidth)
     idx_modi = TT.lt(TT.abs_(denominator), eps)
     numerator = TT.switch(idx_modi, TT.cos(in_sig), TT.sin(in_sig))
     denominator = TT.switch(idx_modi,
                             TT.cos(TT.true_div(in_sig,
                                                bandwidth)), denominator)
     return TT.true_div(numerator, denominator)
コード例 #36
0
        def perturbation(nu=nu):
            phi = nu[:, 0]
            theta = 2.0 * nu[:, 1]

            return T.stack([
                T.sin(theta) * T.sin(phi),
                T.cos(theta) * T.sin(phi),
                T.cos(phi)
            ],
                           axis=1)
コード例 #37
0
def mmd_fourier(x1, x2, bandwidth=2., dim_r=500):
    """
    Approximate RBF kernel by random features
    """
    rW_n = T.sqrt(2. / bandwidth) * srng.normal((x1.shape[1], dim_r)).astype(
        theano.config.floatX) / T.sqrt(x1.shape[1])
    rb_u = 2 * np.pi * srng.uniform((dim_r, )).astype(theano.config.floatX)
    rf0 = T.sqrt(2. / rW_n.shape[1]) * T.cos(x1.dot(rW_n) + rb_u)
    rf1 = T.sqrt(2. / rW_n.shape[1]) * T.cos(x2.dot(rW_n) + rb_u)
    return ((rf0.mean(0) - rf1.mean(0))**2).sum()
コード例 #38
0
def xyz(R1, theta, R2, phi):
    theta_ = T.scalar('theta')
    phi_ = T.scalar('phi')

    x = R1 * T.cos(theta_) * R2 * T.cos(phi_)
    y = R2 * T.sin(theta_) * R2 * T.cos(phi_)
    z = R2 * T.sin(phi_)
    func = function([theta_, phi_], [x, y, z], allow_input_downcast=True)
    vals = func(theta, phi)
    return vals[0].flatten(), vals[1].flatten(), vals[2].flatten()
コード例 #39
0
ファイル: SLM_1.py プロジェクト: zyzju/slm-cg
    def __init__(self, NT, initial_phi=None, profile_s=None):
        
        self.n_pixels = int(NT/2) # target should be 512x512, but SLM pattern calculated should be 256x256.
        self.intensity_calc = None
        
        self.cost = None # placeholder for cost function.
        
        if profile_s is None:
            profile_s = np.ones((self.n_pixels, self.n_pixels)) # input amplitude set to flat ones if none given
        if initial_phi is None:
            initial_phi = np.random.uniform(low=0, high=2*np.pi, size=(self.n_pixels**2)) # input phase set to random if none given
        
        assert profile_s.shape == (self.n_pixels, self.n_pixels), 'profile_s is wrong shape, should be ({n},{n})'.format(n=self.n_pixels)
        self.profile_s_r = profile_s.real.astype('float64')
        self.profile_s_i = profile_s.imag.astype('float64')
        
        assert initial_phi.shape == (self.n_pixels**2,), "initial_phi must be a vector of phases of size N^2 (not (N,N)).  Shape is " + str(initial_phi.shape)

        # Linked to the fourier transform. Keeps the same quantity of light between the input and the output
        self.A0 = 1./NT
        
        # Set zeros matrix:
        self.zero_frame = np.zeros((2*self.n_pixels, 2*self.n_pixels), dtype='float64')
        self.zero_matrix = theano.shared(value=self.zero_frame,name='zero_matrix')
        
        # Phi and its momentum for use in gradient descent with momentum:
        self.phi = theano.shared(value=initial_phi.astype('float64'),name='phi')
        self.phi_rate = theano.shared(value=np.zeros_like(initial_phi).astype('float64'),name='phi_rate')
        self.phi_reshaped = self.phi.reshape((self.n_pixels, self.n_pixels))
        
        # E_in (n_pixels**2): Need to split real and imaginary parts as differentiating complex numbers is difficult
        self.S_r = theano.shared(value=self.profile_s_r,name='s_r')
        self.S_i = theano.shared(value=self.profile_s_i,name='s_i')
        self.E_in_r = self.A0 * (self.S_r*T.cos(self.phi_reshaped) - self.S_i*T.sin(self.phi_reshaped))
        self.E_in_i = self.A0 * (self.S_i*T.cos(self.phi_reshaped) + self.S_r*T.sin(self.phi_reshaped))
        
        # E_in padded (4n_pixels**2):
        idx_0, idx_1 = get_centre_range(self.n_pixels)
        self.E_in_r_pad = T.set_subtensor(self.zero_matrix[idx_0:idx_1,idx_0:idx_1], self.E_in_r)
        self.E_in_i_pad = T.set_subtensor(self.zero_matrix[idx_0:idx_1,idx_0:idx_1], self.E_in_i)
        self.phi_padded = T.set_subtensor(self.zero_matrix[idx_0:idx_1,idx_0:idx_1], self.phi_reshaped)

        ################################################################
        # E_out:
        self.E_out_r, self.E_out_i = (fft(self.E_in_r_pad, self.E_in_i_pad))        
        
        # Output intensity:
        self.E_out_2 = T.add(T.pow(self.E_out_r, 2), T.pow(self.E_out_i, 2))
        
        # E_out_phi:
        self.E_out_p = T.arctan2(self.E_out_i,self.E_out_r)
        self.E_out_p_nopad = self.E_out_p[idx_0:idx_1,idx_0:idx_1]
        
        # Output amplitude:
        self.E_out_amp = T.sqrt(self.E_out_2)
コード例 #40
0
 def f(x1, u1, x2, u2):
     #Ellipse centred on x2's position.
     del_x = x1[0] - x2[0]
     del_y = x1[1] - x2[1]
     #return -(1-tt.clip(((del_x/lat_radius)**2 + (del_y/long_radius)**2),0,1))
     #https://www.maa.org/external_archive/joma/Volume8/Kalman/General.html
     #Ellipse oriented according to x2's orientation. x1, the one incurring the cost, does not want to enter x2's ellipse
     return -(1 - tt.clip((
         ((del_x * tt.cos(x2[3]) + del_y * tt.sin(x2[3])) / lat_radius)**2 +
         ((del_x * tt.sin(x2[3]) - del_y * tt.cos(x2[3])) / long_radius)**
         2), 0, 1))
コード例 #41
0
def dist(y_pred, y):	
    y_pred_ra = T.deg2rad(y_pred)
    y_ra = T.deg2rad(y)
    lat1 = y_pred_ra[:, 0]
    lat2 = y_ra[:, 0]
    dlon = (y_pred_ra - y_ra)[:, 1]
    EARTH_R = 6372.8
    y = T.sqrt((T.cos(lat2) * T.sin(dlon)) ** 2+ (T.cos(lat1) * T.sin(lat2) - T.sin(lat1) * T.cos(lat2) * T.cos(dlon)) ** 2)
    x = T.sin(lat1) * T.sin(lat2) + T.cos(lat1) * T.cos(lat2) * T.cos(dlon)
    c = T.arctan2(y, x)
    return EARTH_R * c
コード例 #42
0
ファイル: gaborfitting.py プロジェクト: AgnezIO/agnez
 def get_output(self, train=False):
     rnorm = self.omega / np.sqrt(2*np.pi)*self.kappa
     val = - self.omega**2 / (8 * self.kappa**2)
     dir1 = 4 * (self._outter(self.x, tensor.cos(self.theta)) +
                 self._outter(self.y, tensor.sin(self.theta)))**2
     dir2 = (-self._outter(self.x, tensor.sin(self.theta)) +
             self._outter(self.y, tensor.cos(self.theta)))**2
     ex = 1j * (self.omega * self._outter(tensor.cos(self.theta), self.x) +
                self.omega * self._outter(tensor.sin(self.theta), self.y))
     output = rnorm * tensor.exp(val * (dir1 + dir2)) * (tensor.exp(ex)
                                                         - tensor.exp(-self.kappa**2 / 2))
     return output
コード例 #43
0
def xyz2(theta, a, b, m, n1, n2, n3, rho, a2, b2, m2, n4, n5, n6):
    theta_ = T.scalar('theta')
    rho_ = T.scalar('rho')
    R1 = R(theta, a, b, m, n1, n2, n3)
    R2 = R(rho, a2, b2, m2, n4, n5, n6)

    x = R1 * T.cos(theta_) * R2 * T.cos(rho_)
    y = R1 * T.sin(theta_) * R2 * T.cos(rho_)
    z = R2 * T.sin(rho_)
    func = function([theta_, rho_], [x, y, z], allow_input_downcast=True)
    vals = func(theta, rho)
    return vals[0].flatten(), vals[1].flatten(), vals[2].flatten()
コード例 #44
0
ファイル: slm.py プロジェクト: sjdenny/slm-theano
 def __init__(self, target, initial_phi, profile_s=None, A0=1.0):
     self.target = target
     self.n_pixels = int(target.shape[0] / 2)   # target should be 512x512, but SLM pattern calculated should be 256x256.
     self.intensity_calc = None
     
     self.cost = None   # placeholder for cost function.
     
     if profile_s is None:
         profile_s = np.ones((self.n_pixels, self.n_pixels))
         
     assert profile_s.shape == (self.n_pixels, self.n_pixels), 'profile_s is wrong shape, should be ({n},{n})'.format(n=self.n_pixels)
     self.profile_s_r = profile_s.real.astype('float64')
     self.profile_s_i = profile_s.imag.astype('float64')
     
     assert initial_phi.shape == (self.n_pixels**2,), "initial_phi must be a vector of phases of size N^2 (not (N,N)).  Shape is " + str(initial_phi.shape)
     
     self.A0 = A0
     
     # Set zeros matrix:
     self.zero_frame = np.zeros((2*self.n_pixels, 2*self.n_pixels), dtype='float64')
     
     # Phi and its momentum for use in gradient descent with momentum:
     self.phi    = theano.shared(value=initial_phi.astype('float64'),
                                 name='phi')
     self.phi_rate = theano.shared(value=np.zeros_like(initial_phi).astype('float64'),
                                   name='phi_rate')
     
     self.S_r = theano.shared(value=self.profile_s_r,
                              name='s_r')
     self.S_i = theano.shared(value=self.profile_s_i,
                              name='s_i')
     self.zero_matrix = theano.shared(value=self.zero_frame,
                                      name='zero_matrix')
     
     # E_in: (n_pixels**2)
     phi_reshaped = self.phi.reshape((self.n_pixels, self.n_pixels))
     self.E_in_r = self.A0 * (self.S_r*T.cos(phi_reshaped) - self.S_i*T.sin(phi_reshaped))
     self.E_in_i = self.A0 * (self.S_i*T.cos(phi_reshaped) + self.S_r*T.sin(phi_reshaped))
     
     # E_in padded: (4n_pixels**2)
     idx_0, idx_1 = get_centre_range(self.n_pixels)
     self.E_in_r_pad = T.set_subtensor(self.zero_matrix[idx_0:idx_1,idx_0:idx_1], self.E_in_r)
     self.E_in_i_pad = T.set_subtensor(self.zero_matrix[idx_0:idx_1,idx_0:idx_1], self.E_in_i)
     
     # E_out:
     self.E_out_r, self.E_out_i = fft(self.E_in_r_pad, self.E_in_i_pad)        
     
     # finally, the output intensity:
     self.E_out_2 = T.add(T.pow(self.E_out_r, 2), T.pow(self.E_out_i, 2))
コード例 #45
0
ファイル: error.py プロジェクト: DragonCircle/taxi
def hdist(a, b):
    lat1 = a[:, 0] * deg2rad
    lon1 = a[:, 1] * deg2rad
    lat2 = b[:, 0] * deg2rad
    lon2 = b[:, 1] * deg2rad

    dlat = abs(lat1-lat2)
    dlon = abs(lon1-lon2)

    al = tensor.sin(dlat/2)**2  + tensor.cos(lat1) * tensor.cos(lat2) * (tensor.sin(dlon/2)**2)
    d = tensor.arctan2(tensor.sqrt(al), tensor.sqrt(const(1)-al))

    hd = const(2) * rearth * d

    return tensor.switch(tensor.eq(hd, float('nan')), (a-b).norm(2, axis=1), hd)
コード例 #46
0
ファイル: cartpole.py プロジェクト: SFPD/rlreloaded
    def symbolic_call(self,x,u):

        u = TT.clip(u, -self.max_force, self.max_force) #pylint: disable=E1111

        dt = self.dt

        z = TT.take(x,0,axis=x.ndim-1)
        zdot = TT.take(x,1,axis=x.ndim-1)    
        th = TT.take(x,2,axis=x.ndim-1)
        thdot = TT.take(x,3,axis=x.ndim-1)
        u0 = TT.take(u,0,axis=u.ndim-1)

        th1 = np.pi - th

        g = 10.
        mc = 1. # mass of cart
        mp = .1 # mass of pole
        muc = .0005 # coeff friction of cart
        mup = .000002 # coeff friction of pole
        l = 1. # length of pole

        def sign(x):
            return TT.switch(x>0, 1, -1)

        thddot = -(-g*TT.sin(th1)
         + TT.cos(th1) * (-u0 - mp * l *thdot**2 * TT.sin(th1) + muc*sign(zdot))/(mc+mp)
          - mup*thdot / (mp*l))  \
        / (l*(4/3. - mp*TT.cos(th1)**2 / (mc + mp)))
        zddot = (u0 + mp*l*(thdot**2 * TT.sin(th1) - thddot * TT.cos(th1)) - muc*sign(zdot))  \
            / (mc+mp)

        newzdot = zdot + dt*zddot
        newz = z + dt*newzdot
        newthdot = thdot + dt*thddot
        newth = th + dt*newthdot

        done = (z > self.max_cart_pos) | (z < -self.max_cart_pos) | (th > self.max_pole_angle) | (th < -self.max_pole_angle) 

        ucost = 1e-5*(u**2).sum(axis=u.ndim-1)
        xcost = 1-TT.cos(th)
        # notdone = TT.neg(done) #pylint: disable=W0612,E1111
        notdone = 1-done
        costs = TT.stack((done-1)*10., notdone*xcost, notdone*ucost).T #pylint: disable=E1103


        newx = TT.stack(newz, newzdot, newth, newthdot).T #pylint: disable=E1103

        return [newx,newx,costs,done]
コード例 #47
0
 def get_output_for(self, input, **kwargs):
     cosT = T.cos(self.Degree * 3.1415926 / 180.0)
     sinT = T.sin(self.Degree * 3.1415926 / 180.0)
     zeros = T.zeros_like(cosT)
     # zeros = self.Translation
     finalResult = T.stack([cosT, sinT, zeros, -sinT, cosT, zeros], axis = 1)
     return finalResult
コード例 #48
0
 def get_output_for(self, input, **kwargs):
     cosT = T.cos(self.Degree * 3.1415926 / 180.0)
     sinT = T.sin(self.Degree * 3.1415926 / 180.0)
     zeros = T.zeros_like(cosT)
     # zeros = self.Translation
     theta = T.stack([cosT, sinT, zeros, -sinT, cosT, zeros], axis = 1)
     return transform_affine(theta, input)
コード例 #49
0
 def get_output_for(self, input, **kwargs):
     cosT = T.cos(self.Degree[:, 0] * 3.1415926 / 180.0)
     sinT = T.sin(self.Degree[:, 0] * 3.1415926 / 180.0)
     ones = self.scaling[:, 0]
     zeros = T.zeros_like(self.translation[:,0])
     theta = T.stack([ones * cosT, sinT, self.translation[:,0], -sinT, ones * cosT, self.translation[:,1]], axis = 1)
     return transform_affine(theta, input)
コード例 #50
0
    def get_output_for(self, input, **kwargs):
        #self.translation = T.zeros((n, 2))
        #ones = T.exp(self.scaling[:, 0])
        ones = T.ones((self.n,))
        zeros = T.zeros((self.n,))
        cosTx = T.cos(self.DegreeX * 3.1415926 / 180.0)
        sinTx = T.sin(self.DegreeX * 3.1415926 / 180.0)
        cosTy = T.cos(self.DegreeY * 3.1415926 / 180.0)
        sinTy = T.sin(self.DegreeY * 3.1415926 / 180.0)
        cosTz = T.cos(self.DegreeZ * 3.1415926 / 180.0)
        sinTz = T.sin(self.DegreeZ * 3.1415926 / 180.0)
        thetaX = T.stack([ones, zeros, zeros, zeros, zeros, cosTx, -sinTx, zeros, zeros, sinTx, cosTx, zeros, zeros, zeros, zeros, ones], axis = 1)
        thetaY = T.stack([cosTy, zeros, sinTy, zeros, zeros, ones, zeros, zeros, -sinTy, zeros, cosTy, zeros, zeros, zeros, zeros, ones], axis = 1)
        thetaZ = T.stack([cosTz, -sinTz, zeros, zeros, sinTz, cosTz, zeros, zeros, zeros, zeros, ones, zeros, zeros, zeros, zeros, ones], axis = 1)

        return transform_affine(thetaX, thetaY, thetaZ, input)
コード例 #51
0
def rotate(angle, axis):
    """Returns a transform to represent a rotation"""

    angle = T.as_tensor_variable(angle)
    axis = T.as_tensor_variable(axis)
    a = axis

    radians = angle*np.pi/180.0
    s = T.sin(radians)
    c = T.cos(radians)

    m = T.alloc(0., 4, 4)

    m = T.set_subtensor(m[0,0], a[0] * a[0] + (1. - a[0] * a[0]) * c)
    m = T.set_subtensor(m[0,1], a[0] * a[1] * (1. - c) - a[2] * s)
    m = T.set_subtensor(m[0,2], a[0] * a[2] * (1. - c) + a[1] * s)

    m = T.set_subtensor(m[1,0], a[0] * a[1] * (1. - c) + a[2] * s)
    m = T.set_subtensor(m[1,1], a[1] * a[1] + (1. - a[1] * a[1]) * c)
    m = T.set_subtensor(m[1,2], a[1] * a[2] * (1. - c) - a[0] * s)

    m = T.set_subtensor(m[2,0], a[0] * a[2] * (1. - c) - a[1] * s)
    m = T.set_subtensor(m[2,1], a[1] * a[2] * (1. - c) + a[0] * s)
    m = T.set_subtensor(m[2,2], a[2] * a[2] + (1. - a[2] * a[2]) * c)

    m = T.set_subtensor(m[3,3], 1)

    return Transform(m, m.T)
コード例 #52
0
 def For_MMD_Sub_class(self,target,data,omega,num_FF,Xlabel):
     
     Num=T.sum(Xlabel,0)
     D_num=Xlabel.shape[1]
     N=data.shape[0]
     
     F_times_Omega = T.dot(data, omega)#minibatch_size*n_rff
     Phi = (self.sf2**0.5 /num_FF**0.5 ) * T.concatenate([T.cos(F_times_Omega), T.sin(F_times_Omega)],1)
     
     #各RFFは2N_rffのたてベクトル
     Phi_total=T.sum(Phi.T,-1)/N
     
     #Domain_number*2N_rffの行列
     Phi_each_domain, updates = theano.scan(fn=lambda a,b: T.switch(T.neq(b,0), Phi.T*a/b, 0),
                           sequences=[Xlabel.T,Num])
     each_Phi=T.sum(Phi_each_domain,-1)
     #まず自分自身との内積 結果はD次元のベクトル
     each_domain_sum=T.sum(each_Phi*each_Phi,-1)
     
     #全体の内積
     tot_sum=T.dot(Phi_total,Phi_total)
     
     #全体とドメインのクロス内積
     tot_domain_sum, updates=theano.scan(fn=lambda a: a*Phi_total,
                           sequences=[each_Phi])
     
     #MMDの計算
     MMD_central=T.sum(each_domain_sum)+D_num*tot_sum-2*T.sum(tot_domain_sum)
     
     return MMD_central     
コード例 #53
0
ファイル: test_opt.py プロジェクト: Abioy/Theano
def test_opt_gpujoin_joinvectors_elemwise_then_minusone():
    # from a bug in gpu normal sampling
    _a = numpy.asarray([1, 2, 3, 4], dtype='float32')
    _b = numpy.asarray([5, 6, 7, 8], dtype='float32')
    a = cuda.shared_constructor(_a)
    b = cuda.shared_constructor(_b)

    a_prime = tensor.cos(a)
    b_prime = tensor.sin(b)

    c = tensor.join(0, a_prime, b_prime)

    d = c[:-1]

    f = theano.function([], d, mode=mode_with_gpu)

    graph_nodes = f.maker.fgraph.toposort()

    assert isinstance(graph_nodes[-1].op, cuda.HostFromGpu)
    assert isinstance(graph_nodes[-2].op, cuda.GpuSubtensor)
    assert isinstance(graph_nodes[-3].op, cuda.GpuJoin)

    concat = numpy.concatenate([numpy.cos(_a), numpy.sin(_b)], axis=0)
    concat = concat[:-1]

    assert numpy.allclose(numpy.asarray(f()), concat)
コード例 #54
0
ファイル: keplerian.py プロジェクト: dfm/exoplanet
 def _get_position(self, a, t):
     f = self._get_true_anomaly(t)
     cosf = tt.cos(f)
     if self.ecc is None:
         r = a
     else:
         r = a * (1.0 - self.ecc**2) / (1 + self.ecc * cosf)
     return self._rotate_vector(r * cosf, r * tt.sin(f))
コード例 #55
0
ファイル: error.py プロジェクト: DragonCircle/taxi
def erdist(a, b):
    lat1 = a[:, 0] * deg2rad
    lon1 = a[:, 1] * deg2rad
    lat2 = b[:, 0] * deg2rad
    lon2 = b[:, 1] * deg2rad
    x = (lon2-lon1) * tensor.cos((lat1+lat2)/2)
    y = (lat2-lat1)
    return tensor.sqrt(tensor.sqr(x) + tensor.sqr(y)) * rearth
コード例 #56
0
ファイル: lasagne_tools.py プロジェクト: cvlab-epfl/LIFT
    def xyzt_2_param(xyzt):
        # get individual xyz
        dx = xyzt[:, 0]  # x and y are already between -1 and 1
        dy = xyzt[:, 1]  # x and y are already between -1 and 1
        z = xyzt[:, 2]
        t = xyzt[:, 3]
        # compute the resize from the largest scale image
        dr = (np.cast[floatX](reduc_ratio) * np.cast[floatX]
              (2.0)**z / np.cast[floatX](max_scale))

        # dimshuffle before concatenate
        params = [dr * T.cos(t), -dr * T.sin(t), dx, dr * T.sin(t),
                  dr * T.cos(t), dy]
        params = [_p.flatten().dimshuffle(0, 'x') for _p in params]

        # concatenate to have (1 0 0 0 1 0) when identity transform
        return T.concatenate(params, axis=1)
コード例 #57
0
 def get_output_for(self, inputs, **kwargs):
     input, degree = inputs
     cosT = T.cos(degree)
     sinT = T.sin(degree)
     zeros = T.zeros_like(cosT)
     # zeros = self.Translation
     theta = T.stack([cosT, sinT, zeros, -sinT, cosT, zeros], axis = 1)
     return transform_affine(theta, input)
コード例 #58
0
ファイル: keplerian.py プロジェクト: dfm/exoplanet
 def _get_acceleration(self, a, m, t):
     f = self._get_true_anomaly(t)
     K = self.K0 * m
     cosf = tt.cos(f)
     if self.ecc is None:
         factor = -K**2 / a
     else:
         factor = K**2 * (self.ecc*cosf + 1)**2 / (a*(self.ecc**2 - 1))
     return self._rotate_vector(factor * cosf, factor * tt.sin(f))
コード例 #59
0
def true_gradient(param, g_k, axis=0):
    """
    Douglas et. al, On Gradient Adaptation With Unit-Norm Constraints.
    See section on "True Gradient Method".
    """
    h_k = g_k -  (g_k*param).sum(axis=0) * param
    theta_k = T.sqrt(1e-8+T.sqr(h_k).sum(axis=0))
    u_k = h_k / theta_k
    return T.cos(theta_k) * param + T.sin(theta_k) * u_k