Python theano.tensor.sin() Examples

The following are 30 code examples of theano.tensor.sin(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module theano.tensor , or try the search function .
Example #1
Source File: pendulum.py    From ilqr with GNU General Public License v3.0 6 votes vote down vote up
def reduce_state(cls, state):
        """Reduces a non-angular state into an angular state by replacing
        sin(theta) and cos(theta) with theta.

        In this case, it converts:

            [sin(theta), cos(theta), theta'] -> [theta, theta']

        Args:
            state: Augmented state vector [state_size].

        Returns:
            Reduced state size [reducted_state_size].
        """
        if state.ndim == 1:
            sin_theta, cos_theta, theta_dot = state
        else:
            sin_theta = state[..., 0].reshape(-1, 1)
            cos_theta = state[..., 1].reshape(-1, 1)
            theta_dot = state[..., 2].reshape(-1, 1)

        theta = np.arctan2(sin_theta, cos_theta)
        return np.hstack([theta, theta_dot]) 
Example #2
Source File: utils_.py    From kusanagi with MIT License 6 votes vote down vote up
def gTrig_np(x, angi):
    '''
        Replaces angle dimensions with their complex representation
    '''
    if isinstance(x, list):
        x = np.array(x)
    if x.ndim == 1:
        x = x[None, :]
    D = x.shape[1]
    Da = 2*len(angi)
    n = x.shape[0]
    xang = np.zeros((n, Da))
    xi = x[:, angi]
    xang[:, ::2] = np.sin(xi)
    xang[:, 1::2] = np.cos(xi)

    na_dims = list(set(range(D)).difference(angi))
    xnang = x[:, na_dims]
    m = np.concatenate([xnang, xang], axis=1)

    return m 
Example #3
Source File: test_vm.py    From attention-lvcsr with MIT License 6 votes vote down vote up
def test_no_leak_many_graphs():
        # Verify no memory leaks when creating and deleting a lot of functions

        # This isn't really a unit test, you have to run it and look at top to
        # see if there's a leak
        for i in xrange(10000):
            x = tensor.vector()
            z = x
            for d in range(10):
                z = tensor.sin(-z + 1)

            f = function([x], z, mode=Mode(optimizer=None, linker='cvm'))
            if not i % 100:
                print(gc.collect())
            sys.stdout.flush()

            gc.collect()
            if 1:
                f([2.0])
                f([3.0])
                f([4.0])
                f([5.0]) 
Example #4
Source File: core.py    From starry with MIT License 6 votes vote down vote up
def compute_ortho_grid_inc_obl(self, res, inc, obl):
        """Compute the polynomial basis on the plane of the sky, accounting
        for the map inclination and obliquity."""
        # See NOTE on tt.mgrid bug in `compute_ortho_grid`
        dx = 2.0 / (res - 0.01)
        y, x = tt.mgrid[-1:1:dx, -1:1:dx]
        z = tt.sqrt(1 - x ** 2 - y ** 2)
        y = tt.set_subtensor(y[tt.isnan(z)], np.nan)
        x = tt.reshape(x, [1, -1])
        y = tt.reshape(y, [1, -1])
        z = tt.reshape(z, [1, -1])
        Robl = self.RAxisAngle(tt.as_tensor_variable([0.0, 0.0, 1.0]), -obl)
        Rinc = self.RAxisAngle(
            tt.as_tensor_variable([tt.cos(obl), tt.sin(obl), 0.0]),
            -(0.5 * np.pi - inc),
        )
        R = tt.dot(Robl, Rinc)
        xyz = tt.dot(R, tt.concatenate((x, y, z)))
        x = tt.reshape(xyz[0], [1, -1])
        y = tt.reshape(xyz[1], [1, -1])
        z = tt.reshape(xyz[2], [1, -1])
        lat = tt.reshape(0.5 * np.pi - tt.arccos(y), [1, -1])
        lon = tt.reshape(tt.arctan2(x, z), [1, -1])
        return tt.concatenate((lat, lon)), tt.concatenate((x, y, z)) 
Example #5
Source File: cartpole.py    From ilqr with GNU General Public License v3.0 6 votes vote down vote up
def reduce_state(cls, state):
        """Reduces a non-angular state into an angular state by replacing
        sin(theta) and cos(theta) with theta.

        In this case, it converts:

            [x, x', sin(theta), cos(theta), theta'] -> [x, x', theta, theta']

        Args:
            state: Augmented state vector [state_size].

        Returns:
            Reduced state size [reducted_state_size].
        """
        if state.ndim == 1:
            x, x_dot, sin_theta, cos_theta, theta_dot = state
        else:
            x = state[..., 0].reshape(-1, 1)
            x_dot = state[..., 1].reshape(-1, 1)
            sin_theta = state[..., 2].reshape(-1, 1)
            cos_theta = state[..., 3].reshape(-1, 1)
            theta_dot = state[..., 4].reshape(-1, 1)

        theta = np.arctan2(sin_theta, cos_theta)
        return np.hstack([x, x_dot, theta, theta_dot]) 
Example #6
Source File: cartpole.py    From ilqr with GNU General Public License v3.0 6 votes vote down vote up
def augment_state(cls, state):
        """Augments angular state into a non-angular state by replacing theta
        with sin(theta) and cos(theta).

        In this case, it converts:

            [x, x', theta, theta'] -> [x, x', sin(theta), cos(theta), theta']

        Args:
            state: State vector [reducted_state_size].

        Returns:
            Augmented state size [state_size].
        """
        if state.ndim == 1:
            x, x_dot, theta, theta_dot = state
        else:
            x = state[..., 0].reshape(-1, 1)
            x_dot = state[..., 1].reshape(-1, 1)
            theta = state[..., 2].reshape(-1, 1)
            theta_dot = state[..., 3].reshape(-1, 1)

        return np.hstack([x, x_dot, np.sin(theta), np.cos(theta), theta_dot]) 
Example #7
Source File: pendulum.py    From ilqr with GNU General Public License v3.0 6 votes vote down vote up
def augment_state(cls, state):
        """Augments angular state into a non-angular state by replacing theta
        with sin(theta) and cos(theta).

        In this case, it converts:

            [theta, theta'] -> [sin(theta), cos(theta), theta']

        Args:
            state: State vector [reducted_state_size].

        Returns:
            Augmented state size [state_size].
        """
        if state.ndim == 1:
            theta, theta_dot = state
        else:
            theta = state[..., 0].reshape(-1, 1)
            theta_dot = state[..., 1].reshape(-1, 1)

        return np.hstack([np.sin(theta), np.cos(theta), theta_dot]) 
Example #8
Source File: core.py    From starry with MIT License 6 votes vote down vote up
def compute_rect_grid(self, res):
        """Compute the polynomial basis on a rectangular lat/lon grid."""
        # See NOTE on tt.mgrid bug in `compute_ortho_grid`
        dx = np.pi / (res - 0.01)
        lat, lon = tt.mgrid[
            -np.pi / 2 : np.pi / 2 : dx, -3 * np.pi / 2 : np.pi / 2 : 2 * dx
        ]
        x = tt.reshape(tt.cos(lat) * tt.cos(lon), [1, -1])
        y = tt.reshape(tt.cos(lat) * tt.sin(lon), [1, -1])
        z = tt.reshape(tt.sin(lat), [1, -1])
        R = self.RAxisAngle(tt.as_tensor_variable([1.0, 0.0, 0.0]), -np.pi / 2)
        return (
            tt.concatenate(
                (
                    tt.reshape(lat, [1, -1]),
                    tt.reshape(lon + 0.5 * np.pi, [1, -1]),
                )
            ),
            tt.dot(R, tt.concatenate((x, y, z))),
        ) 
Example #9
Source File: test_vm.py    From D-VAE with MIT License 6 votes vote down vote up
def test_no_leak_many_graphs():
        # Verify no memory leaks when creating and deleting a lot of functions

        # This isn't really a unit test, you have to run it and look at top to
        # see if there's a leak
        for i in xrange(10000):
            x = tensor.vector()
            z = x
            for d in range(10):
                z = tensor.sin(-z + 1)

            f = function([x], z, mode=Mode(optimizer=None, linker='cvm'))
            if not i % 100:
                print(gc.collect())
            sys.stdout.flush()

            gc.collect()
            if 1:
                f([2.0])
                f([3.0])
                f([4.0])
                f([5.0]) 
Example #10
Source File: mujoco_costs.py    From adversarial-policies with MIT License 6 votes vote down vote up
def __init__(self):
        def f(x, u, i, terminal):
            if terminal:
                ctrl_cost = T.zeros_like(x[..., 0])
            else:
                ctrl_cost = T.square(u).sum(axis=-1)

            # x: (batch_size, 8)
            # x[..., 0:4]: qpos
            # x[..., 4:8]: qvel, time derivatives of qpos, not used in the cost.
            theta = x[..., 0]  # qpos[0]: angle of joint 0
            phi = x[..., 1]  # qpos[1]: angle of joint 1
            target_xpos = x[..., 2:4]  # qpos[2:4], target x & y coordinate
            body1_xpos = 0.1 * T.stack([T.cos(theta), T.sin(theta)], axis=1)
            tip_xpos_incr = 0.11 * T.stack([T.cos(phi), T.sin(phi)], axis=1)
            tip_xpos = body1_xpos + tip_xpos_incr
            delta = tip_xpos - target_xpos

            state_cost = T.sqrt(T.sum(delta * delta, axis=-1))
            cost = state_cost + ctrl_cost

            return cost

        super().__init__(f, state_size=8, action_size=2) 
Example #11
Source File: rotconv.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rot_filters(self, theta):
        fsize = self.filter_size[0];
        ind = T.as_tensor_variable(np.indices((fsize, fsize)) - (fsize - 1.0) / 2.0);
        rotate = T.stack(T.cos(theta), -T.sin(theta), T.sin(theta), T.cos(theta)).reshape((2, 2));
        ind_rot = T.tensordot(rotate, ind, axes=((0, 0))) + (fsize - 1.0) / 2.0;
        transy = T.clip(ind_rot[0], 0, fsize - 1 - .00001);
        transx = T.clip(ind_rot[1], 0, fsize - 1 - .00001);
        vert = T.iround(transy);
        horz = T.iround(transx);
        return self.W[:, :, vert, horz]; 
Example #12
Source File: rotconv.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rot_filters(self, theta):
        fsize = self.filter_size[0];
        ind = T.as_tensor_variable(np.indices((fsize, fsize)) - (fsize - 1.0) / 2.0);
        rotate = T.stack(T.cos(theta), -T.sin(theta), T.sin(theta), T.cos(theta)).reshape((2, 2));
        ind_rot = T.tensordot(rotate, ind, axes=((0, 0))) + (fsize - 1.0) / 2.0;
        transy = T.clip(ind_rot[0], 0, fsize - 1 - .00001);
        transx = T.clip(ind_rot[1], 0, fsize - 1 - .00001);
        vert = T.iround(transy);
        horz = T.iround(transx);
        return self.W[:, :, vert, horz]; 
Example #13
Source File: rotconv.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rot_filters(self, theta):
        fsize = self.filter_size[0];
        ind = T.as_tensor_variable(np.indices((fsize, fsize)) - (fsize - 1.0) / 2.0);
        rotate = T.stack(T.cos(theta), -T.sin(theta), T.sin(theta), T.cos(theta)).reshape((2, 2));
        ind_rot = T.tensordot(rotate, ind, axes=((0, 0))) + (fsize - 1.0) / 2.0;
        transy = T.clip(ind_rot[0], 0, fsize - 1 - .00001);
        transx = T.clip(ind_rot[1], 0, fsize - 1 - .00001);
        vert = T.iround(transy);
        horz = T.iround(transx);
        return self.W[:, :, vert, horz]; 
Example #14
Source File: rotconv.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rot_filters(self, theta):
        fsize = self.filter_size[0];
        ind = T.as_tensor_variable(np.indices((fsize, fsize)) - (fsize - 1.0) / 2.0);
        rotate = T.stack(T.cos(theta), -T.sin(theta), T.sin(theta), T.cos(theta)).reshape((2, 2));
        ind_rot = T.tensordot(rotate, ind, axes=((0, 0))) + (fsize - 1.0) / 2.0;
        transy = T.clip(ind_rot[0], 0, fsize - 1 - .00001);
        transx = T.clip(ind_rot[1], 0, fsize - 1 - .00001);
        vert = T.iround(transy);
        horz = T.iround(transx);
        return self.W[:, :, vert, horz]; 
Example #15
Source File: rotconv.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rot_filters(self, theta):
        fsize = self.filter_size[0];
        ind = T.as_tensor_variable(np.indices((fsize, fsize)) - (fsize - 1.0) / 2.0);
        rotate = T.stack(T.cos(theta), -T.sin(theta), T.sin(theta), T.cos(theta)).reshape((2, 2));
        ind_rot = T.tensordot(rotate, ind, axes=((0, 0))) + (fsize - 1.0) / 2.0;
        transy = T.clip(ind_rot[0], 0, fsize - 1 - .00001);
        transx = T.clip(ind_rot[1], 0, fsize - 1 - .00001);
        vert = T.iround(transy);
        horz = T.iround(transx);
        return self.W[:, :, vert, horz]; 
Example #16
Source File: rotconv.py    From u24_lymphocyte with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rot_filters(self, theta):
        fsize = self.filter_size[0];
        ind = T.as_tensor_variable(np.indices((fsize, fsize)) - (fsize - 1.0) / 2.0);
        rotate = T.stack(T.cos(theta), -T.sin(theta), T.sin(theta), T.cos(theta)).reshape((2, 2));
        ind_rot = T.tensordot(rotate, ind, axes=((0, 0))) + (fsize - 1.0) / 2.0;
        transy = T.clip(ind_rot[0], 0, fsize - 1 - .00001);
        transx = T.clip(ind_rot[1], 0, fsize - 1 - .00001);
        vert = T.iround(transy);
        horz = T.iround(transx);
        return self.W[:, :, vert, horz]; 
Example #17
Source File: distributions_T.py    From MJHMC with GNU General Public License v2.0 5 votes vote down vote up
def dEdX_val(self, X):
        sinX = T.sin(X*2*np.pi/self.scale2)
        dEdX = X/self.scale1**2 + -sinX*2*np.pi/self.scale2
        return dEdX 
Example #18
Source File: s3c.py    From TextDetector with GNU General Public License v3.0 5 votes vote down vote up
def rotate_towards(old_W, new_W, new_coeff):
    """
    .. todo::

        WRITEME properly

    For each column, rotates old_w toward new_w by new_coeff * theta,
    where theta is the angle between them

    Parameters
    ----------
    old_W : WRITEME
        every column is a unit vector
    new_W : WRITEME
    new_coeff : WRITEME
    """

    norms = theano_norms(new_W)

    # update, scaled back onto unit sphere
    scal_points = new_W / norms.dimshuffle('x',0)

    # dot product between scaled update and current W
    dot_update = (old_W * scal_points).sum(axis=0)

    theta = T.arccos(dot_update)

    rot_amt = new_coeff * theta

    new_basis_dir = scal_points - dot_update * old_W

    new_basis_norms = theano_norms(new_basis_dir)

    new_basis = new_basis_dir / new_basis_norms

    rval = T.cos(rot_amt) * old_W + T.sin(rot_amt) * new_basis

    return rval 
Example #19
Source File: theano_backend.py    From deepQuest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sin(x):
    return T.sin(x) 
Example #20
Source File: theano_backend.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def sin(x):
    return T.sin(x) 
Example #21
Source File: theano_backend.py    From KerasNeuralFingerprint with MIT License 5 votes vote down vote up
def sin(x):
    return T.sin(x) 
Example #22
Source File: images2D_carrier.py    From lddmm-ot with MIT License 5 votes vote down vote up
def _dirac_truncated_rfft(self, point) :
		"""
		Returns the truncated real FFT of a dirac at position 'point',
		as a (2+1)-d array of size "K.shape//2+1" + (4,),.
		See real_fft._irfft_2d to understand the format of the output.
		The code may seem quite circonvoluted but hey, it's not my fault
		if theano forces us to use real-valued FFT...
		"""
		su, di = self._phase_shifts(point)
		re_re = T.cos(di) + T.cos(su) # 2 cos(a)cos(b) = cos(a-b) + cos(a+b)
		re_im = T.sin(su) + T.sin(di) # 2 sin(a)cos(b) = sin(a+b) + sin(a-b)
		im_re = T.sin(su) - T.sin(di) # 2 cos(a)sin(b) = sin(a+b) - sin(a-b)
		im_im = T.cos(di) - T.cos(su) # 2 sin(a)sin(b) = cos(a-b) - cos(a+b)
		return .5 * T.stack([re_re, re_im, im_re, im_im], axis=2) # Don't forget the .5 ! 
Example #23
Source File: theano_graph_pro.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def b_vector(self, dip_angles=None, azimuth=None, polarity=None):
        """
        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]
        if dip_angles is None:
            dip_angles = self.dip_angles
        if azimuth is None:
            azimuth = self.azimuth
        if polarity is None:
            polarity = self.polarity

        # =====================
        # Creation of the gradients G vector
        # Calculation of the cartesian components of the dips assuming the unit module
        G_x = T.sin(T.deg2rad(dip_angles)) * T.sin(T.deg2rad(azimuth)) * polarity
        G_y = T.sin(T.deg2rad(dip_angles)) * T.cos(T.deg2rad(azimuth)) * polarity
        G_z = T.cos(T.deg2rad(dip_angles)) * 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 
Example #24
Source File: theano_kriging.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example #25
Source File: theano_graph.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example #26
Source File: core.py    From starry with MIT License 5 votes vote down vote up
def compute_moll_grid(self, res):
        """Compute the polynomial basis on a Mollweide grid."""
        # See NOTE on tt.mgrid bug in `compute_ortho_grid`
        dx = 2 * np.sqrt(2) / (res - 0.01)
        y, x = tt.mgrid[
            -np.sqrt(2) : np.sqrt(2) : dx,
            -2 * np.sqrt(2) : 2 * np.sqrt(2) : 2 * dx,
        ]

        # Make points off-grid nan
        a = np.sqrt(2)
        b = 2 * np.sqrt(2)
        y = tt.where((y / a) ** 2 + (x / b) ** 2 <= 1, y, np.nan)

        # https://en.wikipedia.org/wiki/Mollweide_projection
        theta = tt.arcsin(y / np.sqrt(2))
        lat = tt.arcsin((2 * theta + tt.sin(2 * theta)) / np.pi)
        lon0 = 3 * np.pi / 2
        lon = lon0 + np.pi * x / (2 * np.sqrt(2) * tt.cos(theta))

        # Back to Cartesian, this time on the *sky*
        x = tt.reshape(tt.cos(lat) * tt.cos(lon), [1, -1])
        y = tt.reshape(tt.cos(lat) * tt.sin(lon), [1, -1])
        z = tt.reshape(tt.sin(lat), [1, -1])
        R = self.RAxisAngle(tt.as_tensor_variable([1.0, 0.0, 0.0]), -np.pi / 2)
        return (
            tt.concatenate(
                (
                    tt.reshape(lat, (1, -1)),
                    tt.reshape(lon - 1.5 * np.pi, (1, -1)),
                )
            ),
            tt.dot(R, tt.concatenate((x, y, z))),
        ) 
Example #27
Source File: core.py    From starry with MIT License 5 votes vote down vote up
def RAxisAngle(self, axis=[0, 1, 0], theta=0):
        """Wigner axis-angle rotation matrix."""

        def compute(axis=[0, 1, 0], theta=0):
            axis = tt.as_tensor_variable(axis)
            axis /= axis.norm(2)
            cost = tt.cos(theta)
            sint = tt.sin(theta)

            return tt.reshape(
                tt.as_tensor_variable(
                    [
                        cost + axis[0] * axis[0] * (1 - cost),
                        axis[0] * axis[1] * (1 - cost) - axis[2] * sint,
                        axis[0] * axis[2] * (1 - cost) + axis[1] * sint,
                        axis[1] * axis[0] * (1 - cost) + axis[2] * sint,
                        cost + axis[1] * axis[1] * (1 - cost),
                        axis[1] * axis[2] * (1 - cost) - axis[0] * sint,
                        axis[2] * axis[0] * (1 - cost) - axis[1] * sint,
                        axis[2] * axis[1] * (1 - cost) + axis[0] * sint,
                        cost + axis[2] * axis[2] * (1 - cost),
                    ]
                ),
                [3, 3],
            )

        # If theta is a vector, this is a tensor!
        if hasattr(theta, "ndim") and theta.ndim > 0:
            fn = lambda theta, axis: compute(axis=axis, theta=theta)
            R, _ = theano.scan(fn=fn, sequences=[theta], non_sequences=[axis])
            return R
        else:
            return compute(axis=axis, theta=theta) 
Example #28
Source File: pymc3.py    From bilby with MIT License 5 votes vote down vote up
def _sine_prior(self, key):
        """
        Map the bilby Sine prior to a PyMC3 style function
        """

        # check prior is a Sine
        pymc3, STEP_METHODS, floatX = self._import_external_sampler()
        theano, tt, as_op = self._import_theano()
        if isinstance(self.priors[key], Sine):

            class Pymc3Sine(pymc3.Continuous):
                def __init__(self, lower=0., upper=np.pi):
                    if lower >= upper:
                        raise ValueError("Lower bound is above upper bound!")

                    # set the mode
                    self.lower = lower = tt.as_tensor_variable(floatX(lower))
                    self.upper = upper = tt.as_tensor_variable(floatX(upper))
                    self.norm = (tt.cos(lower) - tt.cos(upper))
                    self.mean = \
                        (tt.sin(upper) + lower * tt.cos(lower) -
                         tt.sin(lower) - upper * tt.cos(upper)) / self.norm

                    transform = pymc3.distributions.transforms.interval(lower,
                                                                        upper)

                    super(Pymc3Sine, self).__init__(transform=transform)

                def logp(self, value):
                    upper = self.upper
                    lower = self.lower
                    return pymc3.distributions.dist_math.bound(
                        tt.log(tt.sin(value) / self.norm),
                        lower <= value, value <= upper)

            return Pymc3Sine(key, lower=self.priors[key].minimum,
                             upper=self.priors[key].maximum)
        else:
            raise ValueError("Prior for '{}' is not a Sine".format(key)) 
Example #29
Source File: pymc3.py    From bilby with MIT License 5 votes vote down vote up
def _cosine_prior(self, key):
        """
        Map the bilby Cosine prior to a PyMC3 style function
        """

        # check prior is a Cosine
        pymc3, STEP_METHODS, floatX = self._import_external_sampler()
        theano, tt, as_op = self._import_theano()
        if isinstance(self.priors[key], Cosine):

            class Pymc3Cosine(pymc3.Continuous):
                def __init__(self, lower=-np.pi / 2., upper=np.pi / 2.):
                    if lower >= upper:
                        raise ValueError("Lower bound is above upper bound!")

                    self.lower = lower = tt.as_tensor_variable(floatX(lower))
                    self.upper = upper = tt.as_tensor_variable(floatX(upper))
                    self.norm = (tt.sin(upper) - tt.sin(lower))
                    self.mean = \
                        (upper * tt.sin(upper) + tt.cos(upper) -
                         lower * tt.sin(lower) - tt.cos(lower)) / self.norm

                    transform = pymc3.distributions.transforms.interval(lower,
                                                                        upper)

                    super(Pymc3Cosine, self).__init__(transform=transform)

                def logp(self, value):
                    upper = self.upper
                    lower = self.lower
                    return pymc3.distributions.dist_math.bound(
                        tt.log(tt.cos(value) / self.norm),
                        lower <= value, value <= upper)

            return Pymc3Cosine(key, lower=self.priors[key].minimum,
                               upper=self.priors[key].maximum)
        else:
            raise ValueError("Prior for '{}' is not a Cosine".format(key)) 
Example #30
Source File: theano_backend.py    From keras-lambda with MIT License 5 votes vote down vote up
def sin(x):
    return T.sin(x)