예제 #1
0
    def test_deepcopy_trust_input(self):
        a = tt.dscalar()  # the a is for 'anonymous' (un-named).
        x, s = tt.dscalars("xs")

        f = function(
            [
                x,
                In(a, value=1.0, name="a"),
                In(s, value=0.0, update=s + a * x, mutable=True),
            ],
            s + a * x,
        )
        f.trust_input = True
        try:
            g = copy.deepcopy(f)
        except NotImplementedError as e:
            if e[0].startswith("DebugMode is not picklable"):
                return
            else:
                raise
        assert f.trust_input is g.trust_input
        f(np.asarray(2.0))
        with pytest.raises(
            (ValueError, AttributeError, theano.compile.debugmode.InvalidValueError)
        ):
            f(2.0)
        g(np.asarray(2.0))
        with pytest.raises(
            (ValueError, AttributeError, theano.compile.debugmode.InvalidValueError)
        ):
            g(2.0)
예제 #2
0
    def test_scalars(self):

        try:
            import theano.tensor as T
            from theano import function
        except:
            return

        # Set up variables and function
        vals = [1, 2, 3, 4, 5]
        f = lambda a, b, c, d, e: a + (b * c) - d**e

        # Set up our objects
        Cs = [ch.Ch(v) for v in vals]
        C_result = f(*Cs)

        # Set up Theano's equivalents
        Ts = T.dscalars('T1', 'T2', 'T3', 'T4', 'T5')
        TF = f(*Ts)
        T_result = function(Ts, TF)

        # Make sure values and derivatives are equal
        self.assertEqual(C_result.r, T_result(*vals))
        for k in range(len(vals)):
            theano_derivative = function(Ts, T.grad(TF, Ts[k]))(*vals)
            #print(C_result.dr_wrt(Cs[k]))
            our_derivative = C_result.dr_wrt(Cs[k])[0, 0]
            #print(theano_derivative, our_derivative)
            self.assertEqual(theano_derivative, our_derivative)
예제 #3
0
def sample_gradient():
    print "微分"
    x, y = T.dscalars("x", "y")
    z = (x+2*y)**2
    # dz/dx
    gx = T.grad(z, x)
    fgx = theano.function([x,y], gx)
    print fgx(1.0, 1.0)
    # dz/dy
    gy = T.grad(z, y)
    fgy = theano.function([x,y], gy)
    print fgy(1.0, 1.0)
    # d{sigmoid(x)}/dx
    x = T.dscalar("x")
    sig = sigmoid(x)
    dsig = T.grad(sig, x)
    f = theano.function([x], dsig)
    print f(0.0)
    print f(1.0)
    # d{sigmoid(<x,w>)}/dx
    w = T.dscalar("w")
    sig = sigmoid(T.dot(x,w))
    dsig = T.grad(sig, x)
    f = theano.function([x, w], dsig)
    print f(1.0, 2.0)
    print f(3.0, 4.0)
    print
예제 #4
0
파일: test_ch.py 프로젝트: MPI-IS/chumpy
    def test_scalars(self):
        
        try:
            import theano.tensor as T
            from theano import function            
        except:
            return
        
        # Set up variables and function
        vals = [1, 2, 3, 4, 5]
        f = lambda a, b, c, d, e : a + (b * c) - d ** e

        # Set up our objects
        Cs = [ch.Ch(v) for v in vals]
        C_result = f(*Cs)

        # Set up Theano's equivalents
        Ts = T.dscalars('T1', 'T2', 'T3', 'T4', 'T5')
        TF = f(*Ts)        
        T_result = function(Ts, TF)        

        # Make sure values and derivatives are equal
        self.assertEqual(C_result.r, T_result(*vals))
        for k in range(len(vals)):
            theano_derivative = function(Ts, T.grad(TF, Ts[k]))(*vals)
            #print C_result.dr_wrt(Cs[k])
            our_derivative = C_result.dr_wrt(Cs[k])[0,0]
            #print theano_derivative, our_derivative
            self.assertEqual(theano_derivative, our_derivative)
예제 #5
0
    def test_examples_6(self):

        from theano import Param
        x, y = T.dscalars('x', 'y')
        z = x + y
        f = function([x, Param(y, default=1)], z)
        assert f(33) == array(34.0)
        assert f(33, 2) == array(35.0)
예제 #6
0
    def test_examples_6(self):

        from theano import Param
        x, y = T.dscalars('x', 'y')
        z = x + y
        f = function([x, Param(y, default=1)], z)
        assert f(33)    == array(34.0)
        assert f(33, 2) == array(35.0)
예제 #7
0
 def test_examples_7(self):
     from theano import Param
     x, y, w = T.dscalars('x', 'y', 'w')
     z = (x + y) * w
     f = function([x, Param(y, default=1), Param(w, default=2, name='w_by_name')], z)
     assert f(33)                   == array(68.0)
     assert f(33, 2)                == array(70.0)
     assert f(33, 0, 1)             == array(33.0)
     assert f(33, w_by_name=1)      == array(34.0)
     assert f(33, w_by_name=1, y=0) == array(33.0)
예제 #8
0
파일: theanoL.py 프로젝트: thbeucher/DQN
def defaultValue(*arg):
    x, y, w = T.dscalars('x', 'y', 'w')
    z = x + y + w
    f = th.function([x, th.In(y, value=1), th.In(w, value=2, name='wName')], z)
    if len(arg) == 3:
        print(f(arg[0], wName = arg[1], y = arg[2]))
    elif len(arg) == 2:
        print(f(arg[0], arg[1]))
    else:
        print(f(arg[0]))
예제 #9
0
 def test_examples_7(self):
     from theano import Param
     x, y, w = T.dscalars('x', 'y', 'w')
     z = (x + y) * w
     f = function([x, Param(y, default=1), Param(w, default=2, name='w_by_name')], z)
     assert f(33)                   == array(68.0)
     assert f(33, 2)                == array(70.0)
     assert f(33, 0, 1)             == array(33.0)
     assert f(33, w_by_name=1)      == array(34.0)
     assert f(33, w_by_name=1, y=0) == array(33.0)
def main():
    x = T.dmatrix('x')

    # T.exp
    s = 1 / (1 + T.exp(-x))
    logistic = function([x], s)

    # 0 is 0.5, negative < 0.5...
    print(logistic([[0, 1], [-1, -2]]))
    # logistic function can be expressed with hyperbolic tan term
    s2 = (1 + T.tanh(x / 2)) / 2
    logistic2 = function([x], s2)
    print(
        np.allclose(logistic([[0, 1], [-1, -2]]), logistic2([[0, 1], [-1,
                                                                      -2]])))

    # do more things at a time
    a, b = T.dmatrices('a', 'b')
    diff = a - b
    abs_diff = abs(diff)
    diff_squared = diff**2
    f = function([a, b], [diff, abs_diff, diff_squared])
    print(f([[1, 1], [1, 1]], [[0, 1], [2, 3]]))

    # default value
    x, y = T.dscalars('x', 'y')
    z = x + y
    f = function([x, In(y, value=1)], z)
    print(f(33))
    print(f(33, 2))

    # Inputs with default values must follow inputs without default
    # values (like Python’s functions). There can be multiple inputs
    # with default values. These parameters can be set positionally
    # or by name, as in standard Python
    x, y, w = T.dscalars('x', 'y', 'w')
    z = (x + y) * w
    f = function([x, In(y, value=1), In(w, value=2, name='w_by_name')], z)
    print(f(33))
    print(f(33, 2))
    print(f(33, 0, 1))
    print(f(33, w_by_name=1))
    print(f(33, w_by_name=1, y=0))
예제 #11
0
 def test_default_values(self):
     # Check that default values are restored
     # when an exception occurs in interactive mode.
     a, b = T.dscalars('a', 'b')
     c = a + b
     func = theano.function([theano.In(a, name='first'), theano.In(b, value=1, name='second')], c)
     x = func(first=1)
     try:
         func(second=2)
     except TypeError:
         assert(func(first=1) == x)
예제 #12
0
 def test_default_values(self):
     # Check that default values are restored
     # when an exception occurs in interactive mode.
     a, b = T.dscalars('a', 'b')
     c = a + b
     func = theano.function([theano.In(a, name='first'), theano.In(b, value=1, name='second')], c)
     x = func(first=1)
     try:
         func(second=2)
     except TypeError:
         assert(func(first=1) == x)
예제 #13
0
    def test_default_values(self):
        # Check that default values are restored
        # when an exception occurs in interactive mode.

        a, b = tt.dscalars("a", "b")
        c = a + b
        func = theano.function(
            [theano.In(a, name="first"), theano.In(b, value=1, name="second")], c
        )
        x = func(first=1)
        try:
            func(second=2)
        except TypeError:
            assert func(first=1) == x
예제 #14
0
    def __init__(self, Q, D, layers, order, D_cum_sum, N, M, non_rec):
        try:
            print('Trying to load model...')
            with open('model_SV1.save', 'rb') as file_handle:
                self.f, self.g = pickle.load(file_handle)
                print('Loaded!')
            return
        except:
            print('Failed. Creating a new model...')

        print('Setting up variables...')
        hyp, SIGMA_S, U, b, MU_S = T.dmatrices('hyp', 'SIGMA_S', 'U', 'b','MU_S')
        y, MEAN_MAP, sn, sf = T.dvectors('y','MEAN_MAP','sn','sf')
        w = T.dscalars('w')
        if Q > 1:
            X = T.dmatrix('X')
        else:
            X = T.dvector('X')     
        if layers > 1:
            MU, SIGMA = T.dmatrices('MU', 'SIGMA')
        else:
            MU, SIGMA = T.dvectors('MU', 'SIGMA')        
        
        SIGMA_trf, SIGMA_S_trf = T.log(1+T.exp(SIGMA))**2, T.log(1+T.exp(SIGMA_S))**2       
        sf_trf, sn_trf, lengthscale_trf, lengthscale_p_trf  =  T.log(1 + T.exp(sf))**2, T.log(1 + T.exp(sn))**2, T.log(1 + T.exp(hyp[:,0])), T.log(1 + T.exp(hyp[:,1]))
        
        print('Setting up model...')
        LL, KL = self.get_model(w, lengthscale_trf, lengthscale_p_trf, sn_trf, sf_trf, MU_S, SIGMA_S_trf, MU, SIGMA_trf, U, b, X, y, MEAN_MAP, Q, D, D_cum_sum, layers, order, non_rec, N, M)

        print('Compiling model...')
        
        inputs = {'X': X, 'MU': MU, 'SIGMA': SIGMA, 'MU_S': MU_S, 'SIGMA_S': SIGMA_S, 'U':  U, 'b':  b, 'hyp': hyp, 'y': y, 'MEAN_MAP': MEAN_MAP, 'sn': sn, 'sf': sf, 'w': w}
        z = 0.0 * sum([T.sum(v) for v in inputs.values()]) # solve a bug with derivative wrt inputs not in the graph
        f = {'LL': LL, 'KL': KL}
        self.f = {fn: theano.function(list(inputs.values()), fv+z, name=fn, on_unused_input='ignore') for fn,fv in f.items()}  
                  
        g = {'LL': LL, 'KL': KL}
        wrt = {'MU': MU, 'SIGMA': SIGMA, 'MU_S': MU_S, 'SIGMA_S': SIGMA_S, 'U':  U, 'b':  b, 'hyp': hyp, 'MEAN_MAP': MEAN_MAP,  'sn': sn, 'sf': sf, 'w': w}
        self.g = {vn: {gn: theano.function(list(inputs.values()), T.grad(gv+z, vv), name='d'+gn+'_d'+vn, on_unused_input='ignore') for gn,gv in g.items()} for vn, vv in wrt.items()}


        with open('model_SV1.save', 'wb') as file_handle:
            print('Saving model...')
            sys.setrecursionlimit(100000)
            pickle.dump([self.f, self.g], file_handle, protocol=pickle.HIGHEST_PROTOCOL)
예제 #15
0
    def operation_bilinear(self):
        # Declare variables
        te_1, te_2, ne_1, ne_2, emis_11, emis_12, emis_21, emis_22, x_in, y_in = tt.dscalars(
            10)

        # Output function
        out_bInterp = (emis_11 * (te_2 - x_in) * (ne_2 - y_in) + emis_21 *
                       (x_in - te_1) * (ne_2 - y_in) + emis_12 *
                       (te_2 - x_in) * (y_in - ne_1) + emis_22 *
                       (x_in - te_1) * (y_in - ne_1)) / ((te_2 - te_1) *
                                                         (ne_2 - ne_1))

        # Compile function
        self.tt_interp_array = function(inputs=[
            te_1, te_2, ne_1, ne_2, emis_11, emis_12, emis_21, emis_22, x_in,
            y_in
        ],
                                        outputs=out_bInterp)
예제 #16
0
    def test_deepcopy_trust_input(self):
        a = T.dscalar()  # the a is for 'anonymous' (un-named).
        x, s = T.dscalars('xs')

        f = function([x, In(a, value=1.0, name='a'),
                      In(s, value=0.0, update=s + a * x, mutable=True)],
                     s + a * x)
        f.trust_input = True
        try:
            g = copy.deepcopy(f)
        except NotImplementedError as e:
            if e[0].startswith('DebugMode is not picklable'):
                return
            else:
                raise
        self.assertTrue(f.trust_input is g.trust_input)
        f(np.asarray(2.))
        self.assertRaises((ValueError, AttributeError), f, 2.)
        g(np.asarray(2.))
        self.assertRaises((ValueError, AttributeError), g, 2.)
예제 #17
0
    def test_deepcopy_trust_input(self):
        a = T.dscalar()  # the a is for 'anonymous' (un-named).
        x, s = T.dscalars('xs')

        f = function([x, In(a, value=1.0, name='a'),
                      In(s, value=0.0, update=s + a * x, mutable=True)],
                     s + a * x)
        f.trust_input = True
        try:
            g = copy.deepcopy(f)
        except NotImplementedError as e:
            if e[0].startswith('DebugMode is not picklable'):
                return
            else:
                raise
        self.assertTrue(f.trust_input is g.trust_input)
        f(np.asarray(2.))
        self.assertRaises((ValueError, AttributeError), f, 2.)
        g(np.asarray(2.))
        self.assertRaises((ValueError, AttributeError), g, 2.)
    def __init__(self, label_list, ion_list):

        # Inherit Emission flux model
        print('\n- Compiling theano flux equations')
        EmissionFluxModel.__init__(self, label_list, ion_list)

        # Loop through all the observed lines and assign a flux equation
        self.declare_emission_flux_functions(label_list, ion_list)

        # Compile the theano functions for all the input emission lines
        for label, func in self.emFluxEqDict.items():
            func_params = tt.dscalars(self.emFluxParamDict[label])
            self.emFluxEqDict[label] = function(inputs=func_params,
                                                outputs=func(*func_params),
                                                on_unused_input='ignore')

        # Assign function dictionary with flexible arguments
        self.assign_flux_eqtt()
        print('-- done\n')

        return
예제 #19
0
def test():
    # multiple inputs, multiple outputs
    a, b = T.dmatrices('a', 'b')
    diff = a - b
    abs_diff = T.abs_(diff)
    sqr_diff = diff ** 2
    f = function([a, b], [diff, abs_diff, sqr_diff])
    h, i, j = f([[0, 1], [2, 3]], [[4, 5], [6, 7]])

    # default value for function arguments
    a, b = T.dscalars('a', 'b')
    z = a + b
    f = function([a, Param(b, default=1)], z)
    print f(1, b=2)
    print f(1)
    print f(1, 2)

    # shared variable
    state = shared(0)
    inc = T.lscalar('inc') # state is int64 by default
    accumulator = function([inc], state, updates=[(state, state + inc)])
    print accumulator(300)
    print state.get_value()
def brachistochrone_functional():
    # define all symbols
    lx, ly = T.dscalars('lx', 'ly')
    fseq = T.dvector('fseq')
    N = fseq.size + 1
    delta_x = lx / N
    iseq = T.arange(N-1)

    # functional term
    functional_ithterm = lambda i: T.switch(T.eq(i, 0),
                                            T.sqrt(0.5*(delta_x**2+(fseq[0]-ly)**2)/(ly-0.5*(fseq[0]+ly))),
                                            T.sqrt(0.5*(delta_x**2+(fseq[i]-fseq[i-1])**2)/(ly-0.5*(fseq[i]+fseq[i-1])))
                                            )

    # defining the functions
    functional_parts, _ = theano.map(fn=lambda k: functional_ithterm(k), sequences=[iseq])
    functional = functional_parts.sum() + T.sqrt(0.5*(delta_x**2+(0-fseq[N-2])**2)/(ly-0.5*(0+fseq[N-2])))
    gfunc = T.grad(functional, fseq)

    # compile the functions
    time_fcn = theano.function(inputs=[fseq, lx, ly], outputs=functional)
    grad_time_fcn = theano.function(inputs=[fseq, lx, ly], outputs=gfunc)

    return time_fcn, grad_time_fcn
from time import clock
from numpy import ones

from theano import Mode
from theano import function

from theano.tensor import dscalars
from theano.tensor import dmatrices

from theano.tensor import lt
from theano.tensor import mean

from theano.tensor import switch
from theano.ifelse import ifelse

a_dscalar, b_dscalar = dscalars('a', 'b')
x_dmatrix, y_dmatrix = dmatrices('x', 'y')

z_switch_dmatrix = switch(lt(a_dscalar, b_dscalar), mean(x_dmatrix), mean(y_dmatrix))
z_ifelse_dmatrix = ifelse(lt(a_dscalar, b_dscalar), mean(x_dmatrix), mean(y_dmatrix))

# Both ops build a condition over symbolic variables. IfElse takes a boolean condition and two variables as inputs.
# Switch evaluates both output variables, ifelse is lazy and only evaluates one variable with respect to the condition.
# Unless linker='vm' or linker='cvm' are used, ifelse will compute both variables and take the same computation time as switch.
f_switch = function([a_dscalar, b_dscalar, x_dmatrix, y_dmatrix], z_switch_dmatrix, mode=Mode(linker='vm'))
f_ifelse = function([a_dscalar, b_dscalar, x_dmatrix, y_dmatrix], z_ifelse_dmatrix, mode=Mode(linker='vm'))

var1 = 0.
var2 = 1.
big_mat1 = ones((10000, 1000))
big_mat2 = ones((10000, 1000))
def get_compiled_Hkep_Hpert_full():
        # resonance j and k
        j,k = T.lscalars('jk')
        s = (j-k) / k

        # Planet masses: m1,m2
        m1,m2 = T.dscalars(2)
        Mstar = 1
        eta0 = Mstar
        eta1 = eta0+m1
        eta2 =eta1+m2
        mtilde1 = m1 * (eta0/eta1)
        Mtilde1 = Mstar * (eta1/eta0)
        mtilde2 = m2 * (eta1/eta2)
        Mtilde2 = Mstar * (eta2/eta1)
        eps = m1 * m2 / (mtilde1 + mtilde2) / Mstar
        beta1 = mtilde1 / (mtilde1 + mtilde2)
        beta2 = mtilde2 / (mtilde1 + mtilde2)
        gamma = mtilde2/mtilde1
        

        # Dynamical variables:
        dyvars = T.vector()
        Q,sigma1, sigma2, I1, I2, amd = [dyvars[i] for i in range(6)]

        # Set lambda2=0
        l2 = T.constant(0.)
        l1 = -1 * k * Q 
        w1 = (1+s) * l2 - s * l1 - sigma1
        w2 = (1+s) * l2 - s * l1 - sigma2
        
        Gamma1 = I1
        Gamma2 = I2
        
        # Resonant semi-major axis ratio
        alpha_res = ((j-k)/j)**(2/3) * ((Mstar + m1) / (Mstar+m2))**(1/3)
        P0 = k * ( beta2 - beta1 * T.sqrt(alpha_res) ) / 2
        P = P0 - k * (s+1/2) * amd
        
        Ltot = beta1 * T.sqrt(alpha_res) + beta2 - amd
        L1 = Ltot/2 - P / k - s * (I1 + I2)
        L2 = Ltot/2 + P / k + (1 + s) * (I1 + I2)
        
        a1 = (L1 / beta1 )**2 * eta0 / eta1
        e1 = T.sqrt(1-(1-(Gamma1 / L1))**2)
        
        a2 = (L2 / beta2 )**2 * eta1 / eta2
        e2 = T.sqrt(1-(1-(Gamma2 / L2))**2)
        
        Hkep = - eta1 * beta1 / (2 * a1) / eta0  - eta2 * beta2 / (2 * a2) / eta1
        
        alpha = a1 / a2
        
        ko = KeplerOp()
        
        M1 = l1 - w1
        M2 = l2 - w2
        
        sinf1,cosf1 =  ko( M1, e1 + T.zeros_like(M1) )
        sinf2,cosf2 =  ko( M2, e2 + T.zeros_like(M2) )
        
        R = calc_DisturbingFunction_with_sinf_cosf(alpha,e1,e2,w1,w2,sinf1,cosf1,sinf2,cosf2)
        
        Hpert = -eps * R / a2
        
        omega_syn = T.sqrt(eta2/eta1)/a2**1.5 - T.sqrt(eta1/eta0) / a1**1.5
        gradHpert = T.grad(Hpert,wrt=dyvars)
        gradHkep = T.grad(Hkep,wrt=dyvars)
        grad_omega_syn = T.grad(omega_syn,wrt=dyvars)

        extra_ins = [m1,m2,j,k]
        ins = [dyvars] + extra_ins

        # Scalars
        omega_syn_fn = theano.function(
            inputs=ins,
            outputs=omega_syn,
            givens=None,
            on_unused_input='ignore'
        )
        Hpert_fn = theano.function(
            inputs=ins,
            outputs=Hpert,
            givens=None,
            on_unused_input='ignore'
        )
        Hkep_fn = theano.function(
            inputs=ins,
            outputs=Hkep,
            givens=None,
            on_unused_input='ignore'
        )
        # gradients
        grad_omega_syn_fn = theano.function(
            inputs=ins,
            outputs=grad_omega_syn,
            givens=None,
            on_unused_input='ignore'
        )
        gradHpert_fn = theano.function(
            inputs=ins,
            outputs=gradHpert,
            givens=None,
            on_unused_input='ignore'
        )
        gradHkep_fn = theano.function(
            inputs=ins,
            outputs=gradHkep,
            givens=None,
            on_unused_input='ignore'
        )
        return omega_syn_fn,Hkep_fn,Hpert_fn,grad_omega_syn_fn,gradHkep_fn,gradHpert_fn
'''
Executing multiple functions
'''
a,b = T.dmatrices('a','b')
diff = a-b
abs_diff = abs(a-b)
diff_sq = diff**2
mult = function([a,b],[diff,abs_diff,diff_sq])
print mult([[0,1],[1,2]],[[-1,2],[5,7]])
#print pp(diff)
#print pp(abs_diff)

'''
Setting a default value for an argument
So, if arg not give, take default value; else take the given value
'''
x, y = T.dscalars("x","y")
z = x+y
add = function([x,Param(y,default=1)],z)
print add(33.0)
print add(2,6)

'''
Setting names to parameters
'''
x,y,w = T.dscalars("x","y","w")
z = (x+y)*w
add_par = function([x,Param(y,default=1),Param(w,default=2,name="debalu")],z)
print add_par(33)
print add_par(33,6,debalu=5)
예제 #24
0
def _get_compiled_theano_functions(N_QUAD_PTS):
    # Planet masses: m1,m2
    m1, m2 = T.dscalars(2)
    mstar = 1
    mu1 = m1 * mstar / (mstar + m1)
    mu2 = m2 * mstar / (mstar + m2)
    Mstar1 = mstar + m1
    Mstar2 = mstar + m2
    beta1 = mu1 * T.sqrt(Mstar1 / mstar) / (mu1 + mu2)
    beta2 = mu2 * T.sqrt(Mstar2 / mstar) / (mu1 + mu2)
    j, k = T.lscalars('jk')
    s = (j - k) / k

    # Angle variable for averaging over
    psi = T.dvector()

    # Quadrature weights
    quad_weights = T.dvector('w')

    # Dynamical variables:
    Ndof = 3
    Nconst = 1
    dyvars = T.vector()
    y1, y2, y_inc, x1, x2, x_inc, amd = [
        dyvars[i] for i in range(2 * Ndof + Nconst)
    ]

    a20 = T.constant(1.)
    a10 = ((j - k) / j)**(2 / 3) * (Mstar1 / Mstar2)**(1 / 3)
    L10 = beta1 * T.sqrt(a10)
    L20 = beta2 * T.sqrt(a20)
    Ltot = L10 + L20
    f = L10 / L20
    L2res = (Ltot + amd) / (1 + f)
    Psi = -k * (s * L2res + (1 + s) * f * L2res)
    ###
    # actions
    ###
    I1 = 0.5 * (x1 * x1 + y1 * y1)
    I2 = 0.5 * (x2 * x2 + y2 * y2)
    Phi = 0.5 * (x_inc * x_inc + y_inc * y_inc)
    L1 = -s * Ltot - Psi / k - s * (I1 + I2 + Phi)
    L2 = (1 + s) * Ltot + Psi / k + (1 + s) * (I1 + I2 + Phi)

    # Set lambda2=0
    l2 = T.constant(0.)
    l1 = -1 * k * psi
    theta_res = (1 + s) * l2 - s * l1
    cos_theta_res = T.cos(theta_res)
    sin_theta_res = T.sin(theta_res)

    kappa1 = x1 * cos_theta_res + y1 * sin_theta_res
    eta1 = y1 * cos_theta_res - x1 * sin_theta_res

    kappa2 = x2 * cos_theta_res + y2 * sin_theta_res
    eta2 = y2 * cos_theta_res - x2 * sin_theta_res

    sigma = x_inc * cos_theta_res + y_inc * sin_theta_res
    rho = y_inc * cos_theta_res - x_inc * sin_theta_res
    # y = (sigma-i*rho)/sqrt(2)
    #   = sqrt(Phi) * exp[i (Omega1+Omega2) / 2]
    # Malige+ 2002,  Eqs 20 and 21
    r2byr1 = (L2 - L1 - I2 + I1) / Ltot
    sigma1 = rho * T.sqrt(1 + r2byr1) / T.sqrt(2)
    sigma2 = -rho * T.sqrt(1 - r2byr1) / T.sqrt(2)
    rho1 = -sigma * T.sqrt(1 + r2byr1) / T.sqrt(2)
    rho2 = sigma * T.sqrt(1 - r2byr1) / T.sqrt(2)

    Xre1 = kappa1 / T.sqrt(L1)
    Xim1 = -eta1 / T.sqrt(L1)
    Yre1 = 0.5 * sigma1 / T.sqrt(L1)
    Yim1 = -0.5 * rho1 / T.sqrt(L1)

    Xre2 = kappa2 / T.sqrt(L2)
    Xim2 = -eta2 / T.sqrt(L2)
    Yre2 = 0.5 * sigma2 / T.sqrt(L2)
    Yim2 = -0.5 * rho2 / T.sqrt(L2)

    absX1_sq = 2 * I1 / L1
    absX2_sq = 2 * I2 / L2
    X_to_z1 = T.sqrt(1 - absX1_sq / 4)
    X_to_z2 = T.sqrt(1 - absX2_sq / 4)
    Y_to_zeta1 = 1 / T.sqrt(1 - absX1_sq / 2)
    Y_to_zeta2 = 1 / T.sqrt(1 - absX2_sq / 2)

    a1 = (L1 / beta1)**2
    k1 = Xre1 * X_to_z1
    h1 = Xim1 * X_to_z1
    q1 = Yre1 * Y_to_zeta1
    p1 = Yim1 * Y_to_zeta1
    e1 = T.sqrt(absX1_sq) * X_to_z1
    inc1 = 2 * T.arcsin(T.sqrt(p1 * p1 + q1 * q1))

    a2 = (L2 / beta2)**2
    k2 = Xre2 * X_to_z2
    h2 = Xim2 * X_to_z2
    q2 = Yre2 * Y_to_zeta2
    p2 = Yim2 * Y_to_zeta2
    e2 = T.sqrt(absX2_sq) * X_to_z2
    inc2 = 2 * T.arcsin(T.sqrt(p2 * p2 + q2 * q2))

    beta1p = T.sqrt(Mstar1) * beta1
    beta2p = T.sqrt(Mstar2) * beta2
    Hkep = -0.5 * beta1p / a1 - 0.5 * beta2p / a2

    Hdir, Hind = calc_Hint_components_spatial(a1, a2, l1, l2, h1, k1, h2, k2,
                                              p1, q1, p2, q2, Mstar1, Mstar2)
    eps = m1 * m2 / (mu1 + mu2) / T.sqrt(mstar)
    Hpert = (Hdir + Hind / mstar)
    Hpert_av = Hpert.dot(quad_weights)
    Htot = Hkep + eps * Hpert_av

    #####################################################
    # Set parameters for compiling functions with Theano
    #####################################################

    # Get numerical quadrature nodes and weights
    nodes, weights = np.polynomial.legendre.leggauss(N_QUAD_PTS)

    # Rescale for integration interval from [-1,1] to [-pi,pi]
    nodes = nodes * np.pi
    weights = weights * 0.5

    # 'givens' will fix some parameters of Theano functions compiled below
    givens = [(psi, nodes), (quad_weights, weights)]

    # 'ins' will set the inputs of Theano functions compiled below
    #   Note: 'extra_ins' will be passed as values of object attributes
    #   of the 'ResonanceEquations' class 'defined below
    extra_ins = [m1, m2, j, k]
    ins = [dyvars] + extra_ins

    Stilde = Phi * (L2 - I2 - L1 + I1) / (Ltot)
    Q1 = 0.5 * (Phi + Stilde)
    Q2 = 0.5 * (Phi - Stilde)
    inc1 = T.arccos(1 - Q1 / (L1 - I1))
    inc2 = T.arccos(1 - Q2 / (L2 - I2))

    orbels = [
        a1, e1, inc1, k * T.arctan2(y1, x1), a2, e2, inc2,
        k * T.arctan2(y2, x2),
        T.arctan2(y_inc, x_inc)
    ]
    orbels_dict = dict(
        zip([
            'a1', 'e1', 'inc1', 'theta1', 'a2', 'e2', 'inc2', 'theta2', 'phi'
        ], orbels))

    actions = [L1, L2, I1, I2, Q1, Q2]
    actions_dict = dict(
        zip(['L1', 'L2', 'Gamma1', 'Gamma2', 'Q1', 'Q2'], actions))

    #  Conservative flow
    gradHtot = T.grad(Htot, wrt=dyvars)
    gradHpert = T.grad(Hpert_av, wrt=dyvars)
    gradHkep = T.grad(Hkep, wrt=dyvars)

    hessHtot = theano.gradient.hessian(Htot, wrt=dyvars)
    hessHpert = theano.gradient.hessian(Hpert_av, wrt=dyvars)
    hessHkep = theano.gradient.hessian(Hkep, wrt=dyvars)

    Jtens = T.as_tensor(np.pad(getOmegaMatrix(Ndof), (0, Nconst), 'constant'))
    H_flow_vec = Jtens.dot(gradHtot)
    Hpert_flow_vec = Jtens.dot(gradHpert)
    Hkep_flow_vec = Jtens.dot(gradHkep)

    H_flow_jac = Jtens.dot(hessHtot)
    Hpert_flow_jac = Jtens.dot(hessHpert)
    Hkep_flow_jac = Jtens.dot(hessHkep)

    ##########################
    # Compile Theano functions
    ##########################
    func_dict = {
        # Hamiltonians
        'H': Htot,
        #'Hpert':Hpert_av,
        #'Hkep':Hkep,
        ## Hamiltonian flows
        'H_flow': H_flow_vec,
        #'Hpert_flow':Hpert_flow_vec,
        #'Hkep_flow':Hkep_flow_vec,
        ## Hamiltonian flow Jacobians
        'H_flow_jac': H_flow_jac,
        #'Hpert_flow_jac':Hpert_flow_jac,
        #'Hkep_flow_jac':Hkep_flow_jac,
        ## Extras
        'orbital_elements': orbels_dict,
        'actions': actions_dict
    }
    compiled_func_dict = dict()
    with tqdm(func_dict.items()) as t:
        for key, val in t:
            t.set_description("Compiling '{}'".format(key))
            if key is 'timescales':
                inputs = extra_ins
            else:
                inputs = ins
            cf = theano.function(inputs=inputs,
                                 outputs=val,
                                 givens=givens,
                                 on_unused_input='ignore')
            compiled_func_dict[key] = cf
    return compiled_func_dict
    def __init__(self):

        # ------------------- #
        # ---  variables  --- #
        # ------------------- #

        # focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p

        focus = T.dscalar('focus')  # focus length od camera

        # variables of device state
        xt, yt, zt = T.dscalars('xt', 'yt', 'zt')  # position
        ox, oy, oz = T.dscalars('ox', 'oy', 'oz')  # orientation

        # variables of landmark state
        xi, yi, zi = T.dscalars('xi', 'yi',
                                'zi')  # Device position at first observation
        theta, phi = T.dscalars(
            'theta', 'phi'
        )  # theta, phi (Azimuth & elevation of the ray at first observation)
        p = T.dscalar(
            'p'
        )  # d_inv (Inverse depth at first observation. 0.1 means depth is 10 meter.)

        # ------------------- #
        # --- observation --- #
        # ------------------- #
        # T.sin(ox)
        # T.cos(ox)
        # T.sin(oy)
        # T.cos(oy)
        # T.sin(oz)
        # T.cos(oz)
        # T.sin(theta)
        # T.cos(theta)
        # T.sin(phi)
        # T.cos(phi)

        # --- # h_ = [hx, hy, hz].T in the global coordinates --- #
        h_x = p * (xi - xt) + T.cos(phi) * T.sin(theta)
        h_y = p * (yi - yt) - T.sin(phi)
        h_z = p * (zi - zt) + T.cos(phi) * T.cos(theta)

        # ---- hx, hy, hz ---- #
        hx = (T.cos(oy) * T.cos(oz)) * h_x + (T.cos(oy) * T.sin(oz)) * h_y + (
            -T.sin(oy)) * h_z
        hy = (-T.cos(ox) * T.sin(oz) + T.sin(ox) * T.sin(oy) * T.cos(oz)
              ) * h_x + (T.cos(ox) * T.cos(oz) + T.sin(ox) * T.sin(oy) *
                         T.sin(oz)) * h_y + (T.sin(ox) * T.cos(oy)) * h_z
        hz = (T.sin(ox) * T.sin(oz) + T.cos(ox) * T.sin(oy) * T.cos(oz)
              ) * h_x + (-T.sin(ox) * T.cos(oz) + T.cos(ox) * T.sin(oy) *
                         T.sin(oz)) * h_y + (T.cos(ox) * T.cos(oy)) * h_z

        # --- h1, h2 --- #
        h1 = -(focus * hx / hz)
        h2 = focus * hy / hz

        self.fh1 = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=h1)
        self.fh2 = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=h2)

        # partial derivative
        dh1xt = T.grad(cost=h1, wrt=xt)
        dh1yt = T.grad(cost=h1, wrt=yt)
        dh1zt = T.grad(cost=h1, wrt=zt)
        dh1ox = T.grad(cost=h1, wrt=ox)
        dh1oy = T.grad(cost=h1, wrt=oy)
        dh1oz = T.grad(cost=h1, wrt=oz)
        dh1xi = T.grad(cost=h1, wrt=xi)
        dh1yi = T.grad(cost=h1, wrt=yi)
        dh1zi = T.grad(cost=h1, wrt=zi)
        dh1theta = T.grad(cost=h1, wrt=theta)
        dh1phi = T.grad(cost=h1, wrt=phi)
        dh1p = T.grad(cost=h1, wrt=p)

        dh2xt = T.grad(cost=h2, wrt=xt)
        dh2yt = T.grad(cost=h2, wrt=yt)
        dh2zt = T.grad(cost=h2, wrt=zt)
        dh2ox = T.grad(cost=h2, wrt=ox)
        dh2oy = T.grad(cost=h2, wrt=oy)
        dh2oz = T.grad(cost=h2, wrt=oz)
        dh2xi = T.grad(cost=h2, wrt=xi)
        dh2yi = T.grad(cost=h2, wrt=yi)
        dh2zi = T.grad(cost=h2, wrt=zi)
        dh2theta = T.grad(cost=h2, wrt=theta)
        dh2phi = T.grad(cost=h2, wrt=phi)
        dh2p = T.grad(cost=h2, wrt=p)

        # function of partial derivative
        self.fdh1xt = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1xt)
        self.fdh1yt = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1yt)
        self.fdh1zt = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1zt)
        self.fdh1ox = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1ox)
        self.fdh1oy = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1oy)
        self.fdh1oz = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1oz)
        self.fdh1xi = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1xi)
        self.fdh1yi = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1yi)
        self.fdh1zi = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1zi)
        self.fdh1theta = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1theta)
        self.fdh1phi = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1phi)
        self.fdh1p = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh1p)

        self.fdh2xt = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2xt)
        self.fdh2yt = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2yt)
        self.fdh2zt = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2zt)
        self.fdh2ox = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2ox)
        self.fdh2oy = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2oy)
        self.fdh2oz = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2oz)
        self.fdh2xi = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2xi)
        self.fdh2yi = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2yi)
        self.fdh2zi = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2zi)
        self.fdh2theta = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2theta)
        self.fdh2phi = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2phi)
        self.fdh2p = theano.function(
            inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p],
            outputs=dh2p)
예제 #26
0
def test_1_examples_param_default():
    x, y = T.dscalars('x', 'y')
    f = theano.function([x, theano.Param(y, default=1)], x + y)
    assert f(1, 2) == 3
    assert f(1) == 2
ion_list = ['O3', 'S3', 'H1r', 'He1r']

emtt = sr.EmissionTensors(label_list, ion_list)

emis_ratio, cHbeta, flambda, abund, ftau = 0.352, 0.12, 0.2, 7.8, 0.0
params = dict(emis_ratio=emis_ratio,
              cHbeta=cHbeta,
              flambda=flambda,
              abund=abund,
              ftau=ftau)
flux_i = emtt.emFluxEqDict['O3_5007A'](emis_ratio, cHbeta, flambda, abund,
                                       ftau, {})
print('Flux_i', flux_i)

print('\nFlux computation using theano graphs')
emis_ratio_t, cHbeta_t, flambda_t, abund_t, ftau_t = T.dscalars(
    'emis_ratio_t', 'cHbeta_t', 'flambda_t', 'abund_t', 'ftau_t')
emGraph = sr.EmissionFluxModel(label_list, ion_list)
params = {
    emis_ratio_t: 0.352,
    cHbeta_t: 0.12,
    flambda_t: 0.2,
    abund_t: 7.8,
    ftau_t: 0.0
}
flux_j = emGraph.emFluxEqDict['O3_5007A'](emis_ratio_t, cHbeta_t, flambda_t,
                                          abund_t, ftau_t, {})
print('flux_j = ', flux_j.eval(params))

print('\nEmissivity interpolation')
예제 #28
0
def defaultValue():
    x, y, z = T.dscalars('x', 'y', 'z')
    return function([x, In(y, value=1), In(z, value=2, name='namedZ')], (x + y) * z)
예제 #29
0
파일: DL_1.py 프로젝트: maximus009/PyNN
def set_default_value():
    x, y = T.dscalars('x','y')
    z = x+y
    f = theano.function([x, theano.Param(y, default=1)], z)
    print f(33)
예제 #30
0
def get_compiled_theano_functions(N_QUAD_PTS):
        # Planet masses: m1,m2
        m1,m2 = T.dscalars(2)
        mstar = 1
        mu1  = m1 * mstar / (mstar  + m1) 
        mu2  = m2 * mstar / (mstar  + m2) 
        Mstar1 = mstar + m1
        Mstar2 = mstar + m2
        beta1 = mu1 * T.sqrt(Mstar1/mstar) / (mu1 + mu2)
        beta2 = mu2 * T.sqrt(Mstar2/mstar) / (mu1 + mu2)
        j,k = T.lscalars('jk')
        s = (j-k) / k
        
        # Angle variable for averaging over
        psi = T.dvector()

        # Dynamical variables:
        Ndof = 2
        Nconst = 1
        dyvars = T.vector()
        y1, y2, x1, x2, amd = [dyvars[i] for i in range(2*Ndof + Nconst)]

        # Quadrature weights
        quad_weights = T.dvector('w')
        
        # Set lambda2=0
        l2 = T.constant(0.)
        l1 = -1 * k * psi 
        theta_res = (1+s) * l2 - s * l1
        cos_theta_res = T.cos(theta_res)
        sin_theta_res = T.sin(theta_res)
        
        kappa1 = x1 * cos_theta_res + y1 * sin_theta_res
        eta1   = y1 * cos_theta_res - x1 * sin_theta_res
        kappa2 = x2 * cos_theta_res + y2 * sin_theta_res
        eta2   = y2 * cos_theta_res - x2 * sin_theta_res

        Gamma1 = (x1 * x1 + y1 * y1) / 2
        Gamma2 = (x2 * x2 + y2 * y2) / 2
        
        # Resonant semi-major axis ratio
        alpha_res = ((j-k)/j)**(2/3) * (Mstar1 / Mstar2)**(1/3)
        #P0 =  k * ( beta2 - beta1 * T.sqrt(alpha_res) ) / 2
        #P = P0 - k * (s+1/2) * amd
        #Ltot = beta1 * T.sqrt(alpha_res) + beta2 - amd
        a20 = 1
        a10 = alpha_res * a20
        Ltot = beta1 * T.sqrt(a10) + beta2 * np.sqrt(a20)
        L1byL2res = beta1 * T.sqrt(a10) / beta2 * np.sqrt(a20)
        L2res = (amd + Ltot) / (1 + L1byL2res)
        P = 0.5 * L2res * (1 - L1byL2res) - (s+1/2) * amd 

        L1 = Ltot/2 - P / k - s * (Gamma1 + Gamma2)
        L2 = Ltot/2 + P / k + (1 + s) * (Gamma1 + Gamma2)

        Xre1 = kappa1 / T.sqrt(L1)
        Xim1 = -eta1 / T.sqrt(L1)

        Xre2 = kappa2 / T.sqrt(L2)
        Xim2 = -eta2 / T.sqrt(L2)
        
        absX1_sq = 2 * Gamma1 / L1
        absX2_sq = 2 * Gamma2 / L2
        X_to_z1 = T.sqrt(1 - absX1_sq / 4 )
        X_to_z2 = T.sqrt(1 - absX2_sq / 4 )

        a1 = (L1 / beta1 )**2 
        k1 = Xre1 * X_to_z1
        h1 = Xim1 * X_to_z1
        e1 = T.sqrt( absX1_sq ) * X_to_z1
        
        a2 = (L2 / beta2 )**2 
        k2 = Xre2 * X_to_z2
        h2 = Xim2 * X_to_z2
        e2 = T.sqrt( absX2_sq ) * X_to_z2
        
        beta1p = T.sqrt(Mstar1) * beta1
        beta2p = T.sqrt(Mstar2) * beta2
        Hkep = -0.5 * beta1p / a1 - 0.5 * beta2p / a2
        
        Hdir,Hind = calc_Hint_components_planar(
                a1,a2,l1,l2,h1,k1,h2,k2,Mstar1/mstar,Mstar2/mstar
        )
        eps = m1*m2/ (mu1 + mu2) / T.sqrt(mstar)
        Hpert = (Hdir + Hind/mstar)
        Hpert_av = Hpert.dot(quad_weights)
        Htot = Hkep + eps * Hpert_av

        ######################
        # Dissipative dynamics
        ######################
        tau_alpha_0, K1, K2, p = T.dscalars(4)
        y1dot_dis,y2dot_dis,x1dot_dis,x2dot_dis,amddot_dis = T.dscalars(5)
        tau_m_inv = 1/tau_alpha_0
        # Define timescales
        tau_e1 = tau_alpha_0 / K1
        tau_e2 = tau_alpha_0 / K2
        tau_a1_0_inv = -beta2p * alpha_res * tau_m_inv / (beta1p + alpha_res * beta2p)
        tau_a2_0_inv = beta1p * tau_m_inv / (beta1p + alpha_res * beta2p)
        tau_a1 = 1 / (tau_a1_0_inv + 2 * p * e1*e1 / tau_e1 )
        tau_a2 = 1 / (tau_a2_0_inv + 2 * p * e2*e2 / tau_e2 )
        
        tau_L1 = 2 * tau_a1
        tau_L2 = 2 * tau_a2
        tau_Gamma1_inv = 1/tau_L1 + (Gamma1-2*L1) / (Gamma1-L1) / tau_e1 
        tau_Gamma2_inv = 1/tau_L2 + (Gamma2-2*L2) / (Gamma2-L2) / tau_e2 
        # Time derivatives of canonical variables
        x1dot_dis = -0.5 * x1 * tau_Gamma1_inv
        x2dot_dis = -0.5 * x2 * tau_Gamma2_inv
        y1dot_dis = -0.5 * y1 * tau_Gamma1_inv
        y2dot_dis = -0.5 * y2 * tau_Gamma2_inv
        Pdot_dis = -0.5 * k * ( L2 / tau_L2 - L1 / tau_L1) + k * (s + 1/2) * (Gamma1 * tau_Gamma1_inv + Gamma2 * tau_Gamma2_inv)
        amddot_dis = Pdot_dis / T.grad(P,amd)
        
        #####################################################
        # Set parameters for compiling functions with Theano
        #####################################################
        
        # Get numerical quadrature nodes and weight
        nodes,weights = np.polynomial.legendre.leggauss(N_QUAD_PTS)
        
        # Rescale for integration interval from [-1,1] to [-pi,pi]
        nodes = nodes * np.pi
        weights = weights * 0.5
        
        # 'givens' will fix some parameters of Theano functions compiled below
        givens = [(psi,nodes),(quad_weights,weights)]

        # 'ins' will set the inputs of Theano functions compiled below
        #   Note: 'extra_ins' will be passed as values of object attributes
        #   of the 'ResonanceEquations' class defined below
        extra_ins = [m1,m2,j,k,tau_alpha_0,K1,K2,p]
        ins = [dyvars] + extra_ins
        
        # Define flows and jacobians.

        #  Conservative flow
        gradHtot = T.grad(Htot,wrt=dyvars)
        gradHpert = T.grad(Hpert_av,wrt=dyvars)
        gradHkep = T.grad(Hkep,wrt=dyvars)

        hessHtot = theano.gradient.hessian(Htot,wrt=dyvars)
        hessHpert = theano.gradient.hessian(Hpert_av,wrt=dyvars)
        hessHkep = theano.gradient.hessian(Hkep,wrt=dyvars)

        Jtens = T.as_tensor(np.pad(getOmegaMatrix(Ndof),(0,Nconst),'constant'))
        H_flow_vec = Jtens.dot(gradHtot)
        Hpert_flow_vec = Jtens.dot(gradHpert)
        Hkep_flow_vec = Jtens.dot(gradHkep)

        H_flow_jac = Jtens.dot(hessHtot)
        Hpert_flow_jac = Jtens.dot(hessHpert)
        Hkep_flow_jac = Jtens.dot(hessHkep)
        
        # Dissipative flow
        dis_flow_vec = T.stack(y1dot_dis,y2dot_dis,x1dot_dis,x2dot_dis,amddot_dis)
        dis_flow_jac = theano.gradient.jacobian(dis_flow_vec,dyvars)

        # Extras
        sigma1 = T.arctan2(y1,x1)
        sigma2 = T.arctan2(y2,x2)
        orbels = [a1,e1,k*sigma1,a2,e2,k*sigma2]
        dis_timescales = [1/tau_a1_0_inv,1/tau_a2_0_inv,tau_e1,tau_e2]

        orbels_dict = dict(zip(
                ['a1','e1','theta1','a2','e2','theta2'],
                orbels
            )
        )

        actions = [L1,L2,Gamma1,Gamma2]
        actions_dict = dict(
            zip(
                ['L1','L2','Gamma1','Gamma2'],
                actions
                )
        )
        
        timescales_dict = dict(zip(
            ['tau_m1','tau_m2','tau_e1','tau_e2'],
            dis_timescales
            )
        )
        ##########################
        # Compile Theano functions
        ##########################
        func_dict={
         # Hamiltonians
         'H':Htot,
         'Hpert':Hpert_av,
         'Hkep':Hkep,
         # Hamiltonian flows
         'H_flow':H_flow_vec,
         'Hpert_flow':Hpert_flow_vec,
         'Hkep_flow':Hkep_flow_vec,
         # Hamiltonian flow Jacobians
         'H_flow_jac':H_flow_jac,
         'Hpert_flow_jac':Hpert_flow_jac,
         'Hkep_flow_jac':Hkep_flow_jac,
         # Dissipative flow and Jacobian
         'dissipative_flow':dis_flow_vec,
         'dissipative_flow_jac':dis_flow_jac,
         # Extras
         'orbital_elements':orbels_dict,
         'actions':actions_dict,
         'timescales':timescales_dict
        }
        compiled_func_dict=dict()
        for key,val in func_dict.items():
            if key is 'timescales':
                inputs = extra_ins
            else:
                inputs = ins 
            cf = theano.function(
                inputs=inputs,
                outputs=val,
                givens=givens,
                on_unused_input='ignore'
            )
            compiled_func_dict[key]=cf
        return compiled_func_dict
예제 #31
0
def create_spatialglimpse_function(img_h=480, img_w=640, fovH=64, fovW=64):
    fovHalfH = fovH / 2
    fovHalfW = fovW / 2
    glimpseInpImg = T.dtensor3('glimpseInpImg')
    glimpseInpLoc_y, glimpseInpLoc_x = T.dscalars('gilY', 'gilX') # each lies between -1 and 1
    glimpseLocOnImg_y = T.cast(((glimpseInpLoc_y + 1) / 2.0) * img_h, 'int32')
    glimpseLocOnImg_x = T.cast(((glimpseInpLoc_x + 1) / 2.0) * img_w, 'int32')

    y1 = T.max((glimpseLocOnImg_y - fovHalfH, 0))
    y2 = T.min((glimpseLocOnImg_y + fovHalfH, img_h))
    x1 = T.max((glimpseLocOnImg_x - fovHalfW, 0))
    x2 = T.min((glimpseLocOnImg_x + fovHalfW, img_w))

    y3 = T.max((glimpseLocOnImg_y - fovH, 0))
    y4 = T.min((glimpseLocOnImg_y + fovH, img_h))
    x3 = T.max((glimpseLocOnImg_x - fovW, 0))
    x4 = T.min((glimpseLocOnImg_x + fovW, img_w))

    y5 = T.max((glimpseLocOnImg_y - 2*fovH, 0))
    y6 = T.min((glimpseLocOnImg_y + 2*fovH, img_h))
    x5 = T.max((glimpseLocOnImg_x - 2*fovW, 0))
    x6 = T.min((glimpseLocOnImg_x + 2*fovW, img_w))

    glimpse1= glimpseInpImg[:, y1:y2, x1:x2]
    if T.lt(glimpse1.shape[1], fovH):
        pad = T.zeros((glimpse1.shape[0], fovH - glimpse1.shape[1], glimpse1.shape[2]))
        if T.eq(y1, 0):
            glimpse1 = T.concatenate((pad, glimpse1), 1)
        else:
            glimpse1 = T.concatenate((glimpse1, pad), 1)
    if T.lt(glimpse1.shape[2], fovW):
        pad = T.zeros((glimpse1.shape[0], glimpse1.shape[1], fovW - glimpse1.shape[2]))
        if T.eq(x1, 0):
            glimpse1 = T.concatenate((pad, glimpse1), 2)
        else:
            glimpse1 = T.concatenate((glimpse1, pad), 2)

    glimpse2 = glimpseInpImg[:, y3:y4, x3:x4]
    if T.lt(glimpse2.shape[1], 2*fovH):
        pad = T.zeros((glimpse2.shape[0], 2*fovH - glimpse2.shape[1], glimpse2.shape[2]))
        if T.eq(y3, 0):
            glimpse2 = T.concatenate((pad, glimpse2), 1)
        else:
            glimpse2 = T.concatenate((glimpse2, pad), 1)
    if T.lt(glimpse2.shape[2], 2*fovW):
        pad = T.zeros((glimpse2.shape[0], glimpse2.shape[1], 2*fovW - glimpse2.shape[2]))
        if T.eq(x3, 0):
            glimpse2 = T.concatenate((pad, glimpse2), 2)
        else:
            glimpse2 = T.concatenate((glimpse2, pad), 2)

    glimpse2 = T.signal.pool.pool_2d(glimpse2, (2, 2), ignore_border=True, mode='average_exc_pad')

    glimpse3 = glimpseInpImg[:, y5:y6, x5:x6]
    if T.lt(glimpse3.shape[1], 4*fovH):
        pad = T.zeros((glimpse3.shape[0], 4*fovH - glimpse3.shape[1], glimpse3.shape[2]))
        if T.eq(y5, 0):
            glimpse3 = T.concatenate((pad, glimpse3), 1)
        else:
            glimpse3 = T.concatenate((glimpse3, pad), 1)
    if T.lt(glimpse3.shape[2], 4*fovW):
        pad = T.zeros((glimpse3.shape[0], glimpse3.shape[1], 4*fovW - glimpse3.shape[2]))
        if T.eq(x5, 0):
            glimpse3 = T.concatenate((pad, glimpse3), 2)
        else:
            glimpse3 = T.concatenate((glimpse3, pad), 2)
    glimpse3 = pool.pool_2d(glimpse3, (4, 4), ignore_border=True, mode='average_exc_pad')

    glimpse1 = T.cast(glimpse1, 'uint8')
    glimpse2 = T.cast(glimpse2, 'uint8')
    glimpse3 = T.cast(glimpse3, 'uint8')

    fun = theano.function([glimpseInpImg, glimpseInpLoc_y, glimpseInpLoc_x], [glimpse1, glimpse2, glimpse3])
    return fun
예제 #32
0
'''
Created on Feb 24, 2016

@author: lqy
'''
import theano
import theano.tensor as T
from theano import In
from theano import function

x, y = T.dscalars("x", "y")

out = x + y

f = function([x, In(y, value=1)], out)

print f(2, 3)
예제 #33
0
def get_compiled_theano_functions(N_QUAD_PTS):
    # resonance j and k
    j, k = T.lscalars('jk')

    # Planet masses: m1,m2
    m1, m2 = T.dscalars(2)

    # resonance f and g coefficients
    f, g = T.dscalars(2)

    # Planet and star mass variables
    Mstar = 1
    mu1 = m1 / (Mstar + m1)
    mu2 = m2 / (Mstar + m2)
    eps = m1 * mu2 / (mu1 + mu2) / Mstar

    # Resonant semi-major axis ratio
    alpha = ((j - k) / j)**(2 / 3) * ((Mstar + m1) / (Mstar + m2))**(1 / 3)

    # Constants in Eq. (15)
    fTilde = T.sqrt((mu1 + mu2) / (mu1 * T.sqrt(alpha))) * f
    gTilde = T.sqrt((mu1 + mu2) / mu2) * g

    # Constant in Eq. (8)
    A = 1.5 * j * (mu1 + mu2) * (j / mu2 + (j - k) / mu1 / T.sqrt(alpha))

    # Dynamical variables:
    dyvars = T.vector()
    theta, theta_star, J, J_star = [dyvars[i] for i in range(4)]

    # Angle variable to average disturbing function over
    kappa = T.dvector()

    # Quadrature weights
    quad_weights = T.dvector('w')

    # Convert dynamical variables to eccentricities and angles:
    # Note:
    #   Q is set to zero since it does not
    #   enter disturbing function except in combinations
    #   with z and w.
    Q = T.as_tensor(0)
    z = Q / k - theta

    # See Eq. 20
    Zsq = J * (fTilde * fTilde + gTilde * gTilde) / (f * f + g * g)
    Z = T.sqrt(Zsq)

    # Set W to zero
    Wsinw, Wcosw = 0, 0
    Zsinz, Zcosz = Z * T.sin(z), Z * T.cos(z)

    # Convert Z and W to planet eccentricities
    atan_f_g = T.arctan2(g, f)
    c, s = T.cos(atan_f_g), T.sin(atan_f_g)

    e1cos = c * Zcosz - s * Wcosw
    e1sin = c * Zsinz - s * Wsinw

    e2cos = s * Zcosz + c * Wcosw
    e2sin = s * Zsinz + c * Wsinw

    w1 = T.arctan2(e1sin, e1cos)
    w2 = T.arctan2(e2sin, e2cos)

    e1 = T.sqrt(e1sin * e1sin + e1cos * e1cos)
    e2 = T.sqrt(e2sin * e2sin + e2cos * e2cos)

    # Planets' mean longitudes
    l1 = Q / k - j * kappa
    l2 = Q / k + (k - j) * kappa

    # Planets mean anomalies
    M1 = l1 - w1
    M2 = l2 - w2

    # Convert mean to true anomalies using
    # function 'exoplanet.theano_ops.kepler.KeplerOp'
    ko = KeplerOp()
    sinf1, cosf1 = ko(M1, e1 + T.zeros_like(M1))
    sinf2, cosf2 = ko(M2, e2 + T.zeros_like(M2))

    # Vector of distrubing function values with same dimension as kappa vector
    DFfull = calc_DisturbingFunction_with_sinf_cosf(alpha, e1, e2, w1, w2,
                                                    sinf1, cosf1, sinf2, cosf2)

    # Average distrubing function by weighting values with user-specified
    # quadrature weights.
    DFav = DFfull.dot(quad_weights)

    # Hamiltonian
    Hkep = -0.5 * A / k / k * (J - J_star) * (J - J_star)
    Hres = -2 * eps * DFav
    # ******************IMPORTANT NOTE*************************
    # I have *NOT* subtraced off the secular component of
    # the disturbing function. This means that the Hamiltonian
    # differs slightly from the one defined in the paper.
    # This is generally of little consequence to the resonant
    # dynamics but should be borne in mind when exploring
    # secular dynamics.
    # *********************************************************
    H = Hkep + Hres

    # Gradient and hessian of Hamiltonian w.r.t. phase space variables
    gradHtot = T.grad(H, wrt=dyvars)
    hessHtot = theano.gradient.hessian(H, wrt=dyvars)

    # Flow vector and Jacobian for equations of motion
    OmegaTens = T.as_tensor(getOmegaMatrix(2))
    H_flow_vec = OmegaTens.dot(gradHtot)
    H_flow_jac = OmegaTens.dot(hessHtot)

    #####################################################
    # Set parameters for compiling functions with Theano
    #####################################################

    # Get numerical quadrature nodes and weights
    nodes, weights = np.polynomial.legendre.leggauss(N_QUAD_PTS)

    # Rescale for integration interval from [-1,1] to [-pi,pi]
    nodes = nodes * np.pi
    weights = weights * 0.5

    # 'ins' will set the inputs of Theano functions compiled below
    extra_ins = [m1, m2, j, k, f, g]
    ins = [dyvars] + extra_ins

    # 'givens' will fix some parameters of Theano functions compiled below
    givens = [(kappa, nodes), (quad_weights, weights)]

    ##########################
    # Compile Theano functions
    ##########################

    if not DEBUG:
        # Note that compiling can take a while
        #  so I've put a debugging switch here
        #  to skip evaluating these functions when
        #  desired.
        H_fn = theano.function(inputs=ins, outputs=H, givens=givens)

        H_flow_vec_fn = theano.function(inputs=ins,
                                        outputs=H_flow_vec,
                                        givens=givens)

        H_flow_jac_fn = theano.function(inputs=ins,
                                        outputs=H_flow_jac,
                                        givens=givens)
    else:
        H_fn, H_flow_vec_fn, H_flow_jac_fn = [lambda x: x for _ in range(3)]

    # Some convenience functions...
    Zsq_to_J_Eq20 = (f * f + g * g) / (fTilde * fTilde + gTilde * gTilde)
    dJ_to_Delta_Eq21 = 1.5 * (mu1 + mu2) * (j * mu1 * T.sqrt(alpha) +
                                            (j - k) * mu2) / (
                                                k * T.sqrt(alpha) * mu1 * mu2)
    ecc_vars_fn = theano.function(inputs=ins,
                                  outputs=[e1, w1, e2, w2],
                                  on_unused_input='ignore')
    Zsq_to_J_Eq20_fn = theano.function(inputs=extra_ins,
                                       outputs=Zsq_to_J_Eq20,
                                       on_unused_input='ignore')
    dJ_to_Delta_Eq21_fn = theano.function(inputs=extra_ins,
                                          outputs=dJ_to_Delta_Eq21,
                                          on_unused_input='ignore')
    return (H_fn, H_flow_vec_fn, H_flow_jac_fn, Zsq_to_J_Eq20_fn,
            dJ_to_Delta_Eq21_fn, ecc_vars_fn)
예제 #34
0
#coding: utf-8
import theano
import theano.tensor as T

## まとめて宣言
x, y = T.dscalars("x", "y")

z = (x+2*y)**2

## zをxについて微分
gx = T.grad(z, x)

## zをyについて微分
gy = T.grad(z, y)

## まとめて

v1 = [x, y]
v2 = [x, y]

## 配列を足してもできる
v = v1+v2

# vの中の変数について順番に微分
grads = T.grad(z, v)

print grads

fgy = theano.function([x, y], grads[3])
fgx = theano.function([x, y], grads[2])
예제 #35
0
import theano, time
from theano import tensor as T
from theano import function
from theano.ifelse import ifelse

#tensor.gt (greater than), .ge (greater than or equal to)
#Similarly there are lt, le, eq, ne
#The evaluation of the above are all element-wise

#time.clock() can be used to get the time at any point in the operation.
# tic_1 = time.clock()
# Operation
#tic_2 = time.clock()
#tic_2 - tic_1 gives the time taken to run Operation.

a, b = T.dscalars(2)
x, y = T.dvectors(2)

z_switch = T.switch(T.le(a, b), T.mean(x), T.max(y))
z_ifelse = ifelse(T.gt(a, b), T.max(x), T.mean(y))

f_switch = function([a, b, x, y], z_switch, mode=theano.Mode(linker='vm'))
f_ifelse = function([a, b, x, y], z_ifelse, mode=theano.Mode(linker='vm'))

value1 = 2.3
value2 = 3.44

vector_1 = np.ones((4000, ))
vector_2 = [2.3, 4.5, 5.6, 7.8, 9, 10, 11, 12, 13, 14, 576, 456, 32467, 43598]

print f_switch(value1, value2, vector_1, vector_2)
예제 #36
0
'''
Executing multiple functions
'''
a, b = T.dmatrices('a', 'b')
diff = a - b
abs_diff = abs(a - b)
diff_sq = diff**2
mult = function([a, b], [diff, abs_diff, diff_sq])
print mult([[0, 1], [1, 2]], [[-1, 2], [5, 7]])
#print pp(diff)
#print pp(abs_diff)
'''
Setting a default value for an argument
So, if arg not give, take default value; else take the given value
'''
x, y = T.dscalars("x", "y")
z = x + y
add = function([x, Param(y, default=1)], z)
print add(33.0)
print add(2, 6)
'''
Setting names to parameters
'''
x, y, w = T.dscalars("x", "y", "w")
z = (x + y) * w
add_par = function(
    [x, Param(y, default=1),
     Param(w, default=2, name="debalu")], z)
print add_par(33)
print add_par(33, 6, debalu=5)
'''
Created on Jun 1, 2015

@author: xujian
'''

import theano
from theano import Param
import theano.tensor as T
from samba.dcerpc.atsvc import Third

a,b,c = T.dscalars('a','b','c')
z=(a+b)*c
f=theano.function([a,Param(b,default=0),Param(c,default=1,name="third_var")],z)
print f(1)
print f(1,2)
print f(1,third_var=2)
예제 #38
0
import numpy
import theano.tensor as T
from theano import function
from theano import In

x, y, w = T.dscalars('x', 'y', 'w')
z = (x + 2 * y) * w
f = function([In(x, value = 0), In(y, value = 0, name='y_name'), In(w, value = 1)], z)
print 'f(): ' + str(f())
print 'f(4): ' + str(f(4))
print 'f(y_name=3): ' + str(f(y_name=3))
print 'f(4, 3, 2): ' + str(f(4, 3, 2))
print 'f(4, 3): ' + str(f(4, 3))
print 'f(y_name=3, w = 4): ' + str(f(y_name=3, w = 4))
예제 #39
0
def tuto():
    
    print "\nLogistic Function 1"
    print "---------------------"
    x = T.dmatrix('x')
    s = 1 / (1 + T.exp(-x))
    logistic = theano.function([x], s)
    print logistic([[0, 1], [-1, -2]])

    print "\nLogistic Function 2"
    print "---------------------"
    s2 = (1 + T.tanh(x / 2)) / 2
    logistic2 = theano.function([x], s2)
    print logistic2([[0, 1], [-1, -2]])
    
    print "\nComputing More than one Thing at the Same Time"
    print "------------------------------------------------"
    a, b = T.dmatrices('a', 'b')
    diff = a - b
    abs_diff = abs(diff)
    diff_squared = diff**2
    f = theano.function([a, b], [diff, abs_diff, diff_squared])
    print f([[1, 1], [1, 1]], [[0, 1], [2, 3]]) 
    
    print "\nSetting a Default Value for an Argument"
    print "---------------------------------------"
    x, y = T.dscalars('x', 'y')
    z = x + y
    f = function([x, In(y, value=1)], z)
    print f(33)
    print f(33, 2)
    
    print "A Real Example: Logistic Regression"
    print "-----------------------------------"
    rng = numpy.random
    N = 400                                   # training sample size
    feats = 784                               # number of input variables
    
    # generate a dataset: D = (input_values, target_class)
    D = (rng.randn(N, feats), rng.randint(size=N, low=0, high=2))
    training_steps = 10000
    
    # Declare Theano symbolic variables
    x = T.dmatrix("x")
    y = T.dvector("y")
    
    # initialize the weight vector w randomly
    #
    # this and the following bias variable b
    # are shared so they keep their values
    # between training iterations (updates)
    w = theano.shared(rng.randn(feats), name="w")
    
    # initialize the bias term
    b = theano.shared(0., name="b")
    
    print("Initial model:")
    print(w.get_value())
    print(b.get_value())
    
    # Construct Theano expression graph
    p_1 = 1 / (1 + T.exp(-T.dot(x, w) - b))   # Probability that target = 1
    prediction = p_1 > 0.5                    # The prediction thresholded
    xent = -y * T.log(p_1) - (1-y) * T.log(1-p_1) # Cross-entropy loss function
    cost = xent.mean() + 0.01 * (w ** 2).sum()# The cost to minimize
    gw, gb = T.grad(cost, [w, b])             # Compute the gradient of the cost
                                              # w.r.t weight vector w and
                                              # bias term b
                                              # (we shall return to this in a
                                              # following section of this tutorial)
    
    # Compile
    train = theano.function(
              inputs=[x,y],
              outputs=[prediction, xent],
              updates=((w, w - 0.1 * gw), (b, b - 0.1 * gb)))
    predict = theano.function(inputs=[x], outputs=prediction)
    
    # Train
    for i in range(training_steps):
        pred, err = train(D[0], D[1])
    
    print("Final model:")
    print(w.get_value())
    print(b.get_value())
    print("target values for D:")
    print(D[1])
    print("prediction on D:")
    print(predict(D[0]))
예제 #40
0
import theano.tensor as T
from theano import *

# x and y are double precision scalars defined at once.
x, y = T.dscalars('x', 'y')

# define sum of those
z = x + y

# define default value for y with Param object.
f = function([x, Param(y, default=1)], z)

# works. should be 34
print f(33)

# override default value, should be 35
print f(33, 2)

# define three double precision scalars
x, y, w = T.dscalars('x', 'y', 'w')

# define an expression out of them
z = (x + y) * w

# attach default values and name for overriding keyword arg
f = function([x, Param(y, default=1),
              Param(w, default=2, name='w_by_name')], z)

print f(33)  # (33 + 1) * 2 = 68
print f(33, 2)  # (33 + 2) * 2 = 70
print f(33, 0, 1)  # (33 + 0) * 1 = 33
예제 #41
0
def plot_results(ens,params,mn,corr,lam_lst,figname,\
    figsize=(7,7/1.618034333)):
    ''' plot data '''
    dset = {'proton': 0, 'gA': 1, 'gV': 2}
    di = dset[corr]
    clrs = ['k', rgb(ens)]
    lbl = ['SS', 'PS']
    ylabel = {
        'proton': r'$m_{eff}(t)$',
        'gA': r'$g_A^{FH}(t)$',
        'gV': r'$g_V^{FH}(t)$'
    }
    y, y_bs = get_data(ens, params, alldata=True)
    nt = y[di].shape[0]

    fig = plt.figure(figname)
    ax = plt.axes([.15, .15, .8, .8])
    for i in range(y[di].shape[-1]):
        if corr == 'proton':
            eff = np.log(y[di][:, i] / np.roll(y[di][:, i], -1))
            eff_bs = np.log(y_bs[di][:, :, i] /
                            np.roll(y_bs[di][:, :, i], -1, axis=1))
        else:
            eff = y[di][:, i]
            eff_bs = y_bs[di][:, :, i]
        ax.errorbar(np.arange(nt),eff,yerr=eff_bs.std(axis=0),linestyle='None',\
            color=clrs[i],marker='s',mfc='None',mec=clrs[i],label=lbl[i])
    ax.axis(params[ens]['plt_range'][corr])
    ax.set_xlabel(r'$t$', fontsize=20)
    ax.set_ylabel(ylabel[corr], fontsize=20)
    ax.legend(numpoints=1, fontsize=16, loc=2)
    ''' add Theano functions to plot fits '''
    lam_all = mn.parameters
    p_all = {k: mn.values[k] for k in lam_all}
    l_ss, l_ps = lam_lst[0], lam_lst[1]
    i_ss = [i for i, l in enumerate(lam_all) if l not in l_ss]
    i_ps = [i for i, l in enumerate(lam_all) if l not in l_ps]
    cov_param = np.array(mn.matrix(correlation=False))

    cov_ss = np.delete(np.delete(cov_param, i_ss, axis=0), i_ss, axis=1)
    cov_ps = np.delete(np.delete(cov_param, i_ps, axis=0), i_ps, axis=1)

    t_p_i, t_p_f = params[ens]['t_min_max']['proton']
    t_gA_i, t_gA_f = params[ens]['t_min_max']['gA']
    t_gV_i, t_gV_f = params[ens]['t_min_max']['gV']
    dt = 0.1
    shift = int(params['tau'] / dt)
    if corr == 'proton':
        tp = np.arange(t_p_i, t_p_f + dt, dt)
    elif corr == 'gA':
        tp = np.arange(t_gA_i, t_gA_f + dt, dt)
    elif corr == 'gV':
        tp = np.arange(t_gV_i, t_gV_f + dt, dt)
    ''' define the theano scalars we need '''
    t, tau, e0, zs0, zp0, de10, zs1, zp1 = Tn.dscalars('t', 'tau', 'e0', 'zs0',
                                                       'zp0', 'de10', 'zs1',
                                                       'zp1')
    g00, g11, g10 = Tn.dscalars('g00', 'g11', 'g10')
    ds0, dp0, ds1, dp1 = Tn.dscalars('ds0', 'dp0', 'ds1', 'dp1')
    ''' now construct the theano functions '''
    parr_ss = dict()
    for p in l_ss:
        n = p.split('_')[-1]
        if 'zs' in p:
            parr_ss['src_' + n] = p_all[p]
            parr_ss['snk_' + n] = p_all[p]
        elif 'dA' in p or 'dV' in p:
            parr_ss['d_' + n] = p_all[p]
        elif 'gA' in p or 'gV' in p:
            parr_ss['g_' + n] = p_all[p]
        else:
            parr_ss[p] = p_all[p]
    parr_ps = dict()
    for p in l_ps:
        n = p.split('_')[-1]
        if 'zs' in p:
            parr_ps['src_' + n] = p_all[p]
        elif 'zp' in p:
            parr_ps['snk_' + n] = p_all[p]
        elif 'dA' in p or 'dV' in p:
            parr_ps['d_' + n] = p_all[p]
        elif 'gA' in p or 'gV' in p:
            parr_ps['g_' + n] = p_all[p]
        else:
            parr_ps[p] = p_all[p]
    ''' 2pt function '''
    th_ss = zs0**2 * Tn.exp(-t * e0) + zs1**2 * Tn.exp(-t * (e0 + de10))
    th_tau_ss = zs0**2 * Tn.exp(-(t + tau) * e0) + zs1**2 * Tn.exp(-(t + tau) *
                                                                   (e0 + de10))
    th_eff_ss = Tn.log(th_ss / th_tau_ss) / tau
    d_th_eff_ss = Tn.grad(th_eff_ss, [e0, de10, zs0, zs1])
    d_th_eff_ss_def = th.function([t, tau, e0, de10, zs0, zs1], d_th_eff_ss)
    d_th_eff_ss_fun = lambda t,tau:\
        d_th_eff_ss_def(t,tau,p_all['E_0'],p_all['dE_10'],\
            p_all['zs_0'],p_all['zs_1'])

    th_ps = zp0 * zs0 * Tn.exp(-t * e0) + zp1 * zs1 * Tn.exp(-t * (e0 + de10))
    th_tau_ps = zp0 * zs0 * Tn.exp(-(t + tau) * e0) + zp1 * zs1 * Tn.exp(
        -(t + tau) * (e0 + de10))
    th_eff_ps = Tn.log(th_ps / th_tau_ps) / tau
    d_th_eff_ps = Tn.grad(th_eff_ps, [e0, de10, zs0, zp0, zs1, zp1])
    d_th_eff_ps_def = th.function([t, tau, e0, de10, zs0, zp0, zs1, zp1],
                                  d_th_eff_ps)
    d_th_eff_ps_fun = lambda t,tau:\
        d_th_eff_ps_def(t,tau,p_all['E_0'],p_all['dE_10'],\
            p_all['zs_0'],p_all['zp_0'],p_all['zs_1'],p_all['zp_1'])
    ''' FH gA function '''
    g_00 = corr + '_00'
    g_11 = corr + '_11'
    g_10 = corr + '_10'
    d_ss_0 = corr.replace('g', 'd') + 'ss_0'
    d_ss_1 = corr.replace('g', 'd') + 'ss_1'
    d_ps_0 = corr.replace('g', 'd') + 'ps_0'
    d_ps_1 = corr.replace('g', 'd') + 'ps_1'

    th_num_ss = (t - 1) * zs0**2 * Tn.exp(-t * e0) * g00
    th_num_ss += (t - 1) * zs1**2 * Tn.exp(-t * (e0 + de10)) * g11
    th_num_ss += ds0 * Tn.exp(-t * e0)
    th_num_ss += ds1 * Tn.exp(-t * (e0 + de10))
    th_num_ss += zs0*zs1*g10*(Tn.exp(-t*e0)*Tn.exp(-de10/2) - Tn.exp(-t*(e0+de10))*Tn.exp(de10/2))\
        / (Tn.exp(de10 / 2) - Tn.exp(-de10 / 2))
    th_num_ss += zs1*zs0*g10*(Tn.exp(-t*(e0+de10))*Tn.exp(de10/2) - Tn.exp(-t*e0)*Tn.exp(-de10/2))\
        /(Tn.exp(-de10 / 2) - Tn.exp(de10 / 2))

    th_num_dt_ss = (t - 1 + tau) * zs0**2 * Tn.exp(-(t + tau) * e0) * g00
    th_num_dt_ss += (t - 1 + tau) * zs1**2 * Tn.exp(-(t + tau) *
                                                    (e0 + de10)) * g11
    th_num_dt_ss += ds0 * Tn.exp(-(t + tau) * e0)
    th_num_dt_ss += ds1 * Tn.exp(-(t + tau) * (e0 + de10))
    th_num_dt_ss += zs0*zs1*g10*\
        (Tn.exp(-(t+tau)*e0)*Tn.exp(-de10/2) - Tn.exp(-(t+tau)*(e0+de10))*Tn.exp(de10/2))\
        / (Tn.exp(de10 / 2) - Tn.exp(-de10 / 2))
    th_num_dt_ss += zs1*zs0*g10*\
        (Tn.exp(-(t+tau)*(e0+de10))*Tn.exp(de10/2) - Tn.exp(-(t+tau)*e0)*Tn.exp(-de10/2))\
        /(Tn.exp(-de10 / 2) - Tn.exp(de10 / 2))

    th_fh_ss = (th_num_dt_ss / th_tau_ss - th_num_ss / th_ss) / tau
    th_fh_grad_ss = Tn.grad(th_fh_ss,
                            [e0, de10, zs0, zs1, g00, g11, g10, ds0, ds1])
    th_grad_ss_def = th.function(
        [t, tau, e0, de10, zs0, zs1, g00, g11, g10, ds0, ds1], th_fh_grad_ss)
    th_grad_ss_fun = lambda t,tau: \
        th_grad_ss_def(t,tau,p_all['E_0'],p_all['dE_10'],p_all['zs_0'],p_all['zs_1'],\
            p_all[g_00],p_all[g_11],p_all[g_10],\
            p_all[d_ss_0],p_all[d_ss_1])
    ''' FH PS '''
    th_num_ps = (t - 1) * zp0 * zs0 * Tn.exp(-t * e0) * g00
    th_num_ps += (t - 1) * zp1 * zs1 * Tn.exp(-t * (e0 + de10)) * g11
    th_num_ps += dp0 * Tn.exp(-t * e0)
    th_num_ps += dp1 * Tn.exp(-t * (e0 + de10))
    th_num_ps += zp0*zs1*g10*(Tn.exp(-t*e0)*Tn.exp(-de10/2) - Tn.exp(-t*(e0+de10))*Tn.exp(de10/2))\
        / (Tn.exp(de10 / 2) - Tn.exp(-de10 / 2))
    th_num_ps += zp1*zs0*g10*(Tn.exp(-t*(e0+de10))*Tn.exp(de10/2) - Tn.exp(-t*e0)*Tn.exp(-de10/2))\
        /(Tn.exp(-de10 / 2) - Tn.exp(de10 / 2))

    th_num_dt_ps = (t - 1 + tau) * zp0 * zs0 * Tn.exp(-(t + tau) * e0) * g00
    th_num_dt_ps += (t - 1 + tau) * zp1 * zs1 * Tn.exp(-(t + tau) *
                                                       (e0 + de10)) * g11
    th_num_dt_ps += dp0 * Tn.exp(-(t + tau) * e0)
    th_num_dt_ps += dp1 * Tn.exp(-(t + tau) * (e0 + de10))
    th_num_dt_ps += zp0*zs1*g10*\
        (Tn.exp(-(t+tau)*e0)*Tn.exp(-de10/2) - Tn.exp(-(t+tau)*(e0+de10))*Tn.exp(de10/2))\
        / (Tn.exp(de10 / 2) - Tn.exp(-de10 / 2))
    th_num_dt_ps += zp1*zs0*g10*\
        (Tn.exp(-(t+tau)*(e0+de10))*Tn.exp(de10/2) - Tn.exp(-(t+tau)*e0)*Tn.exp(-de10/2))\
        /(Tn.exp(-de10 / 2) - Tn.exp(de10 / 2))

    th_fh_ps = (th_num_dt_ps / th_tau_ps - th_num_ps / th_ps) / tau
    th_fh_grad_ps = Tn.grad(
        th_fh_ps, [e0, de10, zs0, zp0, zs1, zp1, g00, g11, g10, dp0, dp1])
    th_grad_ps_def = th.function(
        [t, tau, e0, de10, zs0, zp0, zs1, zp1, g00, g11, g10, dp0, dp1],
        th_fh_grad_ps)
    th_grad_ps_fun = lambda t,tau: \
        th_grad_ps_def(t,tau,p_all['E_0'],p_all['dE_10'],\
            p_all['zs_0'],p_all['zp_0'],p_all['zs_1'],p_all['zp_1'],\
            p_all[g_00],p_all[g_11],p_all[g_10],\
            p_all[d_ps_0],p_all[d_ps_1])

    if corr == 'proton':
        fit_ss = fit_fh.c2pt(tp, **parr_ss)
        eff_ss = np.log(fit_ss / np.roll(fit_ss, -shift)) / (shift * dt)
        eff_ss[-shift:] = eff_ss[-(shift + 1)]
        fit_ps = fit_fh.c2pt(tp, **parr_ps)
        eff_ps = np.log(fit_ps / np.roll(fit_ps, -shift)) / (shift * dt)
        eff_ps[-shift:] = eff_ps[-(shift + 1)]

        err_ss = np.zeros_like(tp)
        err_ps = np.zeros_like(tp)
        for i, t in enumerate(tp):
            err_ss[i] = np.sqrt(np.dot(\
                d_th_eff_ss_fun(t,dt),np.dot(cov_ss,d_th_eff_ss_fun(t,dt))))
            err_ps[i] = np.sqrt(np.dot(\
                d_th_eff_ps_fun(t,dt),np.dot(cov_ps,d_th_eff_ps_fun(t,dt))))
    elif corr in ['gA', 'gV']:
        fit_ss = fit_fh.fh_derivative(tp, shift * dt, **parr_ss)
        eff_ss = fit_ss
        eff_ss[-shift:] = eff_ss[-(shift + 1)]
        fit_ps = fit_fh.fh_derivative(tp, shift * dt, **parr_ps)
        eff_ps = fit_ps
        eff_ps[-shift:] = eff_ps[-(shift + 1)]

        err_ss = np.zeros_like(tp)
        err_ps = np.zeros_like(tp)
        for i, t in enumerate(tp):
            err_ss[i] = np.sqrt(np.dot(\
                th_grad_ss_fun(t,dt),np.dot(cov_ss,th_grad_ss_fun(t,dt))))
            err_ps[i] = np.sqrt(np.dot(\
                th_grad_ps_fun(t,dt),np.dot(cov_ps,th_grad_ps_fun(t,dt))))

    ax.fill_between(tp,
                    eff_ss - err_ss,
                    eff_ss + err_ss,
                    color=clrs[0],
                    alpha=.3)
    ax.fill_between(tp,
                    eff_ps - err_ps,
                    eff_ps + err_ps,
                    color=clrs[1],
                    alpha=.3)
def get_compiled_theano_functions(N_QUAD_PTS):
        # resonance j and k
        j,k = T.lscalars('jk')
        s = (j-k) / k

        # Planet masses: m1,m2
        m1,m2 = T.dscalars(2)
        Mstar = 1
        eta0 = Mstar
        eta1 = eta0+m1
        eta2 =eta1+m2
        mtilde1 = m1 * (eta0/eta1)
        Mtilde1 = Mstar * (eta1/eta0)
        mtilde2 = m2 * (eta1/eta2)
        Mtilde2 = Mstar * (eta2/eta1)
        eps = m1 * m2 / (mtilde1 + mtilde2) / Mstar
        beta1 = mtilde1 / (mtilde1 + mtilde2)
        beta2 = mtilde2 / (mtilde1 + mtilde2)
        gamma = mtilde2/mtilde1
        
        # Angle variable for averaging over
        Q = T.dvector('Q')

        # Dynamical variables:
        dyvars = T.vector()
        sigma1, sigma2, I1, I2, amd = [dyvars[i] for i in range(5)]


        # Quadrature weights
        quad_weights = T.dvector('w')
        
        # Set lambda2=0
        l2 = T.constant(0.)
        
        l1 = -1 * k * Q 
        w1 = (1+s) * l2 - s * l1 - sigma1
        w2 = (1+s) * l2 - s * l1 - sigma2
        
        Gamma1 = I1
        Gamma2 = I2
        
        # Resonant semi-major axis ratio
        alpha_res = ((j-k)/j)**(2/3) * ((Mstar + m1) / (Mstar+m2))**(1/3)
        P0 =  k * ( beta2 - beta1 * T.sqrt(alpha_res) ) / 2
        P = P0 - k * (s+1/2) * amd
        Ltot = beta1 * T.sqrt(alpha_res) + beta2 - amd
        L1 = Ltot/2 - P / k - s * (I1 + I2)
        L2 = Ltot/2 + P / k + (1 + s) * (I1 + I2)
        
        
        a1 = (L1 / beta1 )**2 * eta0 / eta1
        e1 = T.sqrt(1-(1-(Gamma1 / L1))**2)
        
        a2 = (L2 / beta2 )**2 * eta1 / eta2
        e2 = T.sqrt(1-(1-(Gamma2 / L2))**2)
        
        Hkep = - eta1 * beta1 / (2 * a1) / eta0  - eta2 * beta2 / (2 * a2) / eta1
        
        alpha = a1 / a2
        
        ko = KeplerOp()
        
        M1 = l1 - w1
        M2 = l2 - w2
        
        sinf1,cosf1 =  ko( M1, e1 + T.zeros_like(M1) )
        sinf2,cosf2 =  ko( M2, e2 + T.zeros_like(M2) )
        
        R = calc_DisturbingFunction_with_sinf_cosf(alpha,e1,e2,w1,w2,sinf1,cosf1,sinf2,cosf2)
        Rav = R.dot(quad_weights)
        
        Hpert = -eps * Rav / a2
        Htot = Hkep + Hpert

        ######################
        # Dissipative dynamics
        ######################
        tau_alpha_0, K1, K2, p = T.dscalars(4)
        sigma1dot_dis,sigma2dot_dis,I1dot_dis,I2dot_dis,amddot_dis = T.dscalars(5)
        sigma1dot_dis,sigma2dot_dis = T.as_tensor(0.),T.as_tensor(0.)
        
        # Define timescales
        tau_e1 = tau_alpha_0 / K1
        tau_e2 = tau_alpha_0 / K2
        tau_a1_0 = -1 * tau_alpha_0 * (1+alpha_res * gamma)/ (alpha_res * gamma)
        tau_a2_0 = -1 * alpha_res * gamma * tau_a1_0
        tau_a1 = 1 / (1/tau_a1_0 + 2 * p * e1*e1 / tau_e1 )
        tau_a2 = 1 / (1/tau_a2_0 + 2 * p * e2*e2 / tau_e2 )

        # Time derivative of orbital elements
        e1dot_dis = -1*e1 / tau_e1
        e2dot_dis = -1*e2 / tau_e2
        a1dot_dis = -1*a1 / tau_a1
        a2dot_dis = -1*a2 / tau_a2

        # Time derivatives of canonical variables
        I1dot_dis = L1 * e1 * e1dot_dis / ( T.sqrt(1-e1*e1) ) - I1 / tau_a1 / 2
        I2dot_dis = L2 * e2 * e2dot_dis / ( T.sqrt(1-e2*e2) ) - I2 / tau_a2 / 2
        Pdot_dis = -1*k * ( L2 / tau_a2 - L1 / tau_a1) / 4 - k * (s + 1/2) * (I1dot_dis + I2dot_dis)
        amddot_dis = Pdot_dis / T.grad(P,amd)

        #####################################################
        # Set parameters for compiling functions with Theano
        #####################################################
        
        # Get numerical quadrature nodes and weights
        nodes,weights = np.polynomial.legendre.leggauss(N_QUAD_PTS)
        
        # Rescale for integration interval from [-1,1] to [-pi,pi]
        nodes = nodes * np.pi
        weights = weights * 0.5
        
        # 'givens' will fix some parameters of Theano functions compiled below
        givens = [(Q,nodes),(quad_weights,weights)]

        # 'ins' will set the inputs of Theano functions compiled below
        #   Note: 'extra_ins' will be passed as values of object attributes
        #   of the 'ResonanceEquations' class 'defined below
        extra_ins = [m1,m2,j,k,tau_alpha_0,K1,K2,p]
        ins = [dyvars] + extra_ins
        

        # Define flows and jacobians.

        #  Conservative flow
        gradHtot = T.grad(Htot,wrt=dyvars)
        hessHtot = theano.gradient.hessian(Htot,wrt=dyvars)
        Jtens = T.as_tensor(np.pad(getOmegaMatrix(2),(0,1),'constant'))
        H_flow_vec = Jtens.dot(gradHtot)
        H_flow_jac = Jtens.dot(hessHtot)
        
        #  Dissipative flow
        dis_flow_vec = T.stack(sigma1dot_dis,sigma2dot_dis,I1dot_dis,I2dot_dis,amddot_dis)
        dis_flow_jac = theano.gradient.jacobian(dis_flow_vec,dyvars)
        
        
        # Extras
        dis_timescales = [tau_a1_0,tau_a2_0,tau_e1,tau_e2]
        orbels = [a1,e1,sigma1*k,a2,e2,sigma2*k]
        ##########################
        # Compile Theano functions
        ##########################
        
        if not DEBUG:
            # Note that compiling can take a while
            #  so I've put a debugging switch here 
            #  to skip evaluating these functions when
            #  desired.
            Rav_fn = theano.function(
                inputs=ins,
                outputs=Rav,
                givens=givens,
                on_unused_input='ignore'
            )
            Hpert_av_fn = theano.function(
                inputs=ins,
                outputs=Hpert,
                givens=givens,
                on_unused_input='ignore'
            )
            Htot_fn = theano.function(
                inputs=ins,
                outputs=Htot,
                givens=givens,
                on_unused_input='ignore'
            )
            
            H_flow_vec_fn = theano.function(
                inputs=ins,
                outputs=H_flow_vec,
                givens=givens,
                on_unused_input='ignore'
            )
            
            H_flow_jac_fn = theano.function(
                inputs=ins,
                outputs=H_flow_jac,
                givens=givens,
                on_unused_input='ignore'
            )
            
            dis_flow_vec_fn = theano.function(
                inputs=ins,
                outputs=dis_flow_vec,
                givens=givens,
                on_unused_input='ignore'
            )
            
            dis_flow_jac_fn = theano.function(
                inputs=ins,
                outputs=dis_flow_jac,
                givens=givens,
                on_unused_input='ignore'
            )

            dis_timescales_fn =theano.function(
                inputs=extra_ins,
                outputs=dis_timescales,
                givens=givens,
                on_unused_input='ignore'
            )

            orbels_fn = theano.function(
                inputs=ins,
                outputs=orbels,
                givens=givens,
                on_unused_input='ignore'
            )

        else:
            return  [lambda x: x for _ in range(8)]
        
        return Rav_fn,Hpert_av_fn,Htot_fn,H_flow_vec_fn,H_flow_jac_fn,dis_flow_vec_fn,dis_flow_jac_fn,dis_timescales_fn,orbels_fn
    Q22 = matrix[y1, x1]

    den12 = (x0-x1) / (y0-y1)
    den21 = (x0-x1) / (y1-y0)

    a0 = Q11 * x1*y1 / den12 + Q12 * x1*y0 / den21 + Q21 * x0*y1 / den21 + Q22 * x0*y0 / den12
    a1 = Q11 * y1 / den21 + Q12 * y0 / den12 + Q21 * y1 / den12 + Q22 * y0 / den21
    a2 = Q11 * x1 / den21 + Q12 * x1 / den12 + Q21 * x0 / den12 + Q22 * x0 / den21
    a3 = Q11 / den12 + Q12 / den21 + Q21 / den21 + Q22 / den12

    return a0, a1, a2, a3


# Theano operations
temp_vector, den_vector = tt.dvectors('temp_vector', 'den_vector')
temp_scalar, den_scalar = tt.dscalars('temp_scalar', 'den_scalar')
indexing_Qxx_ttfunction = function(inputs=[temp_vector, temp_scalar, den_vector, den_scalar],
                               outputs=indexing_Qxx_tt(temp_vector, temp_scalar, den_vector, den_scalar))

x, y = tt.dscalars('x', 'y')
x0_limit, y0_limit, x1_limit, y1_limit = tt.dscalars('x0_limit', 'y0_limit', 'x1_limit', 'y1_limit')
matrixGrid = tt.dmatrix('matrixGrid')

bilinearInterpolationttfunction = function(inputs=[x, y, matrixGrid, x0_limit, y0_limit, x1_limit, y1_limit],
                               outputs=biLinearInterpolation_v2_tt(x, y, matrixGrid, x0_limit, y0_limit, x1_limit, y1_limit))

biLinearInterpolation_CoeffsFunction_tt = function(inputs=[x, y, matrixGrid, x0_limit, y0_limit, x1_limit, y1_limit],
                               outputs=biLinearInterpolation_Coeffs_tt(x, y, matrixGrid, x0_limit, y0_limit, x1_limit, y1_limit))

# Numpy steps
idx_temp, idx_den = indexing_Qxx(temp_range, temp_true, den_range, den_true)
def _get_compiled_theano_functions():
    # Planet masses: m1,m2
    m1, m2 = T.dscalars(2)
    mstar = 1
    mu1 = m1 * mstar / (mstar + m1)
    mu2 = m2 * mstar / (mstar + m2)
    eta1 = mstar + m1
    eta2 = mstar + m2
    beta1 = mu1 * T.sqrt(eta1 / mstar) / (mu1 + mu2)
    beta2 = mu2 * T.sqrt(eta2 / mstar) / (mu1 + mu2)

    # Dynamical variables:
    dyvars = T.vector()
    l1, l2, y1, y2, Omega, L1, L2, x1, x2, Rtilde = [
        dyvars[i] for i in range(10)
    ]

    Gamma1 = 0.5 * (x1 * x1 + y1 * y1)
    Gamma2 = 0.5 * (x2 * x2 + y2 * y2)
    gamma1 = T.arctan2(y1, x1)
    gamma2 = T.arctan2(y2, x2)

    Cz = -1 * Rtilde

    R1 = Gamma1
    R2 = Gamma2
    R = L1 + L2 - R1 - R2 - Cz
    G1 = L1 - Gamma1
    G2 = L2 - Gamma2

    r2_by_r1 = (L2 - L1 - R2 + R1) / (L1 + L2 - R1 - R2 - R)
    rho1 = 0.5 * R * (1 + r2_by_r1)
    rho2 = 0.5 * R * (1 - r2_by_r1)

    a1 = (L1 / beta1)**2
    e1 = T.sqrt(1 - (1 - (Gamma1 / L1))**2)

    a2 = (L2 / beta2)**2
    e2 = T.sqrt(1 - (1 - (Gamma2 / L2))**2)

    cos_inc1 = 1 - rho1 / G1
    cos_inc2 = 1 - rho2 / G2
    inc1 = T.arccos(cos_inc1)
    inc2 = T.arccos(cos_inc2)

    l1_r = l1 - Omega
    l2_r = l2 - Omega

    Omega1_r = T.constant(np.pi / 2) - Omega
    Omega2_r = Omega1_r - T.constant(np.pi)

    pomega1 = -1 * gamma1
    pomega2 = -1 * gamma2

    pomega1_r = pomega1 - Omega
    pomega2_r = pomega2 - Omega

    omega1 = pomega1_r - Omega1_r
    omega2 = pomega2_r - Omega2_r

    Hkep = -0.5 * T.sqrt(eta1) * beta1 / a1 - 0.5 * T.sqrt(eta2) * beta2 / a2

    ko = KeplerOp()
    M1 = l1_r - pomega1_r
    M2 = l2_r - pomega2_r
    sinf1, cosf1 = ko(M1, e1 + T.zeros_like(M1))
    sinf2, cosf2 = ko(M2, e2 + T.zeros_like(M2))
    #
    n1 = T.sqrt(eta1 / mstar) * a1**(-3 / 2)
    n2 = T.sqrt(eta2 / mstar) * a2**(-3 / 2)
    Hint_dir, Hint_ind, r1, r2, v1, v2 = calc_Hint_components_sinf_cosf(
        a1, a2, e1, e2, inc1, inc2, omega1, omega2, Omega1_r, Omega2_r, n1, n2,
        sinf1, cosf1, sinf2, cosf2)
    eps = m1 * m2 / (mu1 + mu2) / T.sqrt(mstar)
    Hpert = (Hint_dir + Hint_ind / mstar)
    Htot = Hkep + eps * Hpert

    #####################################################
    # Set parameters for compiling functions with Theano
    #####################################################

    # 'ins' will set the inputs of Theano functions compiled below
    #   Note: 'extra_ins' will be passed as values of object attributes
    #   of the 'ResonanceEquations' class 'defined below
    extra_ins = [m1, m2]
    givens = []
    ins = [dyvars] + extra_ins
    orbels = [
        a1, e1, inc1, l1_r, pomega1_r, Omega1_r, a2, e2, inc2, l2_r, pomega2_r,
        Omega2_r
    ]
    orbels_dict = dict(
        zip([
            'a1', 'e1', 'inc1', 'l1', 'pomega1', 'Omega1', 'a2', 'e2', 'inc2',
            'l2', 'pomega2', 'Omega2'
        ], orbels))
    actions = [L1, L2, Gamma1, Gamma2, rho1, rho2]
    actions_dict = dict(
        zip(['L1', 'L2', 'Gamma1', 'Gamma2', 'Q1', 'Q2'], actions))
    #  Conservative flow
    gradHtot = T.grad(Htot, wrt=dyvars)
    hessHtot = theano.gradient.hessian(Htot, wrt=dyvars)
    Jtens = T.as_tensor(_get_Omega_matrix(5))
    H_flow_vec = Jtens.dot(gradHtot)
    H_flow_jac = Jtens.dot(hessHtot)

    ##########################
    # Compile Theano functions
    ##########################
    orbels_fn = theano.function(inputs=ins,
                                outputs=orbels_dict,
                                givens=givens,
                                on_unused_input='ignore')
    actions_fn = theano.function(inputs=ins,
                                 outputs=actions_dict,
                                 givens=givens,
                                 on_unused_input='ignore')
    rv1_fn = theano.function(inputs=ins,
                             outputs=r1 + v1,
                             givens=givens,
                             on_unused_input='ignore')
    rv2_fn = theano.function(inputs=ins,
                             outputs=r2 + v2,
                             givens=givens,
                             on_unused_input='ignore')

    Htot_fn = theano.function(inputs=ins,
                              outputs=Htot,
                              givens=givens,
                              on_unused_input='ignore')

    Hpert_fn = theano.function(inputs=ins,
                               outputs=Hpert,
                               givens=givens,
                               on_unused_input='ignore')

    Hpert_components_fn = theano.function(inputs=ins,
                                          outputs=[Hint_dir, Hint_ind],
                                          givens=givens,
                                          on_unused_input='ignore')

    H_flow_vec_fn = theano.function(inputs=ins,
                                    outputs=H_flow_vec,
                                    givens=givens,
                                    on_unused_input='ignore')

    H_flow_jac_fn = theano.function(inputs=ins,
                                    outputs=H_flow_jac,
                                    givens=givens,
                                    on_unused_input='ignore')
    return dict({
        'orbital_elements': orbels_fn,
        'actions': actions_fn,
        'Hamiltonian': Htot_fn,
        'Hpert': Hpert_fn,
        'Hpert_components': Hpert_components_fn,
        'Hamiltonian_flow': H_flow_vec_fn,
        'Hamiltonian_flow_jacobian': H_flow_jac_fn,
        'positions_and_velocities1': rv1_fn,
        'positions_and_velocities2': rv2_fn
    })
예제 #45
0
#!/usr/bin/env python
from theano import function
import theano.tensor as T
from theano.tensor import shared_randomstreams
import numpy as np
import numpy.random
from scipy.special import gammaincinv
from numpy.linalg import norm

# tensor stand-in for np.random.RandomState
rngT = shared_randomstreams.RandomStreams()
rng = numpy.random.RandomState()

# {{{ Fastfood Params }}}
n, d = T.dscalars('n', 'd')
# transform dimensions to be a power of 2
d0, n0 = d, n
l = T.ceil(T.log2(d))  # TODO cast to int
d = 2**l
k = T.ceil(n / d)  # TODO cast to int
n = d * k
# generate parameter 'matrices'
B = rng.choice([-1, 1], size=(k, d))
G = rng.normal(size=(k, d), dtype=np.float64)
PI = np.array([rng.permutation(d) for _ in xrange(k)]).T
S = np.empty((k * d, 1), dtype=np.float64)
# generate scaling matrix, S
for i in xrange(k):
    for j in xrange(d):
        p1 = rng.uniform(size=d)
        p2 = d / 2
"""

2016-07-04-15:52:19

arhik

"""
"""
    The aim of this script is to show you how to set the default values of an
    Argument
"""

import theano.tensor as T
from theano import In, function

x, y = T.dscalars('x', 'y')
z = x + y
f = function([x, In(y, value=1)], z)
print(f(23))
예제 #47
0
Computing multiple things
"""
# shorthand definition of vars
a, b = T.dmatrices('a', 'b')
diff = a - b
# NOTE: we do not need to use a, b again - diff is already a formed expression
abs_diff = abs(diff)
diff_squared = diff ** 2
f = theano.function([a, b], [diff, abs_diff, diff_squared])
print(f([[1, 1], [1, 1],], [[0, 1], [2, 3]])) # has 3 outputs

"""
Default values
"""
from theano import In
x, y = T.dscalars('x', 'y')
z = x + y
# NOTE: you can do even more complex stuff with In(), not only default values
# NOTE: default values always come AFTER the other inputs with no defaults
f = theano.function([x, In(y, value=1)], z)
print(f(33)) # 34
print(f(33, 2)) # 35

w = T.dscalar('w')
z2 = (x + y)*w
f2 = theano.function([x, In(y, value=1), In(w, value=2, name='w_by_name')], z2)
print(f2(33)) # 68
print(f2(33, 2)) # 70
print(f2(33, 0, 1)) # 33
# NOTE: the above w_by_name allows us to specify w's value at another position
# than that of the original w (just like in regular languages). w_by_name overrides
예제 #48
0
#!/usr/bin/env python
from theano import function
import theano.tensor as T
from theano.tensor import shared_randomstreams
import numpy as np
import numpy.random
from scipy.special import gammaincinv
from numpy.linalg import norm

# tensor stand-in for np.random.RandomState
rngT = shared_randomstreams.RandomStreams()
rng = numpy.random.RandomState()

# {{{ Fastfood Params }}}
n, d = T.dscalars('n', 'd')
# transform dimensions to be a power of 2
d0, n0 = d, n
l = T.ceil(T.log2(d))  # TODO cast to int
d = 2**l
k = T.ceil(n/d)  # TODO cast to int
n = d*k
# generate parameter 'matrices'
B = rng.choice([-1, 1], size=(k, d))
G = rng.normal(size=(k, d), dtype=np.float64)
PI = np.array([rng.permutation(d) for _ in xrange(k)]).T
S = np.empty((k*d, 1), dtype=np.float64)
# generate scaling matrix, S
for i in xrange(k):
    for j in xrange(d):
        p1 = rng.uniform(size=d)
        p2 = d/2
import numpy as np
from scipy import optimize
import theano
import theano.tensor as tt

# Read xlsx file
workbook = xlrd.open_workbook('../Data/Dataset.xlsx')
sheet = workbook.sheet_by_name('daily_average')
species = 'Pm_RN_S'#'Pm_RN_S' 'Am_RN_S' 'Nd_RN_S' 'Qc_RN_S' 'Qg_SN_S'

# Get data
keys = np.asarray(list(sheet.row_values(0)), dtype='str')
get_data = lambda lab: np.asarray(sheet.col_values(np.where(keys == lab)[0][0])[1:])

''' Priors '''
alpha, bs, c, g1, kxmax, p50, s0, Z = tt.dscalars('alpha', 'bs', 'c', 'g1', 'kxmax', 'p50', 's0', 'Z')

''' Data '''
Tod = get_data('T')
Iod = get_data('I')
Rfod = get_data('Rf')
Dod = get_data('D')
vnod = get_data(species)

''' Other parameters '''
ca = 400
Kc = 460
q = 0.3
R = 8.314
Jmax = 80
Vcmax = 30
	def __init__(self):
		
		# ------------------- #
		# ---  variables  --- #
		# ------------------- #
		
		# focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p
		
		focus = T.dscalar('focus') # focus length od camera
		
		# variables of device state
		xt, yt, zt = T.dscalars('xt', 'yt', 'zt') # position
		ox, oy, oz = T.dscalars('ox', 'oy', 'oz') # orientation
		
		# variables of landmark state
		xi, yi, zi = T.dscalars('xi', 'yi', 'zi') # Device position at first observation
		theta, phi = T.dscalars('theta', 'phi') # theta, phi (Azimuth & elevation of the ray at first observation)
		p = T.dscalar('p') # d_inv (Inverse depth at first observation. 0.1 means depth is 10 meter.)
		
		# ------------------- #
		# --- observation --- #
		# ------------------- #
		# T.sin(ox)
		# T.cos(ox)
		# T.sin(oy)
		# T.cos(oy)
		# T.sin(oz)
		# T.cos(oz)
		# T.sin(theta)
		# T.cos(theta)
		# T.sin(phi)
		# T.cos(phi)
		
		# --- # h_ = [hx, hy, hz].T in the global coordinates --- #
		h_x = p*(xi - xt) + T.cos(phi)*T.sin(theta)
		h_y = p*(yi - yt) - T.sin(phi)
		h_z = p*(zi - zt) + T.cos(phi)*T.cos(theta)
		
		# ---- hx, hy, hz ---- #
		hx = (T.cos(oy)*T.cos(oz)) * h_x + (T.cos(oy)*T.sin(oz)) * h_y + (-T.sin(oy)) * h_z
		hy = (-T.cos(ox)*T.sin(oz)+T.sin(ox)*T.sin(oy)*T.cos(oz)) * h_x + (T.cos(ox)*T.cos(oz)+T.sin(ox)*T.sin(oy)*T.sin(oz)) * h_y + (T.sin(ox)*T.cos(oy)) * h_z
		hz = (T.sin(ox)*T.sin(oz)+T.cos(ox)*T.sin(oy)*T.cos(oz)) * h_x + (-T.sin(ox)*T.cos(oz) + T.cos(ox)*T.sin(oy)*T.sin(oz)) * h_y + (T.cos(ox)*T.cos(oy)) * h_z
		
		# --- h1, h2 --- #
		h1 = - (focus * hx / hz)
		h2 = focus * hy / hz
		
		self.fh1 = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=h1)
		self.fh2 = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=h2)
		
		# partial derivative
		dh1xt = T.grad(cost=h1, wrt=xt)
		dh1yt = T.grad(cost=h1, wrt=yt)
		dh1zt = T.grad(cost=h1, wrt=zt)
		dh1ox = T.grad(cost=h1, wrt=ox)
		dh1oy = T.grad(cost=h1, wrt=oy)
		dh1oz = T.grad(cost=h1, wrt=oz)
		dh1xi = T.grad(cost=h1, wrt=xi)
		dh1yi = T.grad(cost=h1, wrt=yi)
		dh1zi = T.grad(cost=h1, wrt=zi)
		dh1theta = T.grad(cost=h1, wrt=theta)
		dh1phi = T.grad(cost=h1, wrt=phi)
		dh1p = T.grad(cost=h1, wrt=p)
		
		dh2xt = T.grad(cost=h2, wrt=xt)
		dh2yt = T.grad(cost=h2, wrt=yt)
		dh2zt = T.grad(cost=h2, wrt=zt)
		dh2ox = T.grad(cost=h2, wrt=ox)
		dh2oy = T.grad(cost=h2, wrt=oy)
		dh2oz = T.grad(cost=h2, wrt=oz)
		dh2xi = T.grad(cost=h2, wrt=xi)
		dh2yi = T.grad(cost=h2, wrt=yi)
		dh2zi = T.grad(cost=h2, wrt=zi)
		dh2theta = T.grad(cost=h2, wrt=theta)
		dh2phi = T.grad(cost=h2, wrt=phi)
		dh2p = T.grad(cost=h2, wrt=p)
		
		# function of partial derivative
		self.fdh1xt = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1xt)
		self.fdh1yt = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1yt)
		self.fdh1zt = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1zt)
		self.fdh1ox = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1ox)
		self.fdh1oy = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1oy)
		self.fdh1oz = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1oz)
		self.fdh1xi = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1xi)
		self.fdh1yi = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1yi)
		self.fdh1zi = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1zi)
		self.fdh1theta = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1theta)
		self.fdh1phi = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1phi)
		self.fdh1p = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh1p)
		
		self.fdh2xt = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2xt)
		self.fdh2yt = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2yt)
		self.fdh2zt = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2zt)
		self.fdh2ox = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2ox)
		self.fdh2oy = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2oy)
		self.fdh2oz = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2oz)
		self.fdh2xi = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2xi)
		self.fdh2yi = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2yi)
		self.fdh2zi = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2zi)
		self.fdh2theta = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2theta)
		self.fdh2phi = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2phi)
		self.fdh2p = theano.function(inputs=[focus, xt, yt, zt, ox, oy, oz, xi, yi, zi, theta, phi, p], outputs=dh2p)
예제 #51
0
    def __init__(self):
        # Dictionary to store the functions for the fitting
        self.emFlux_ttMethods = dict(H1r=self.H1_emisTensor,
                                     He1r=self.He1_emisTensor,
                                     He2r=self.He2_emisTensor,
                                     metals=self.metal_emisTensor,
                                     O2_7319A_b=self.corO2_7319_emisTensor)

        # All input values scalars
        emisRatio, cHbeta, flambda, abund, ftau, continuum, O2_abund, O3_abund, Te_high = tt.dscalars(
            'emisRatio', 'cHbeta', 'flambda', 'abund', 'ftau', 'continuum',
            'O2_abund', 'O3_abund', 'Te_high')

        # Dictionary to store the compiled functions for the fitting
        self.emFluxTensors = dict(
            H1r=function(
                inputs=[emisRatio, cHbeta, flambda, abund, ftau, continuum],
                outputs=self.emFlux_ttMethods['H1r'](emisRatio, cHbeta,
                                                     flambda, abund, ftau,
                                                     continuum),
                on_unused_input='ignore'),
            He1r=function(
                inputs=[emisRatio, cHbeta, flambda, abund, ftau, continuum],
                outputs=self.emFlux_ttMethods['He1r'](emisRatio, cHbeta,
                                                      flambda, abund, ftau,
                                                      continuum),
                on_unused_input='ignore'),
            He2r=function(
                inputs=[emisRatio, cHbeta, flambda, abund, ftau, continuum],
                outputs=self.emFlux_ttMethods['He2r'](emisRatio, cHbeta,
                                                      flambda, abund, ftau,
                                                      continuum),
                on_unused_input='ignore'),
            metals=function(
                inputs=[emisRatio, cHbeta, flambda, abund, ftau, continuum],
                outputs=self.emFlux_ttMethods['metals'](emisRatio, cHbeta,
                                                        flambda, abund, ftau,
                                                        continuum),
                on_unused_input='ignore'),
            O2_7319A_b=function(inputs=[
                emisRatio, cHbeta, flambda, O2_abund, O3_abund, Te_high
            ],
                                outputs=self.emFlux_ttMethods['O2_7319A_b'](
                                    emisRatio, cHbeta, flambda, O2_abund,
                                    O3_abund, Te_high),
                                on_unused_input='ignore'))