예제 #1
0
 def test_simple_case(self):
     """Test trivial case."""
     bit = cirq.GridQubit(0, 0)
     circuit = cirq.Circuit(
         cirq.X(bit)**sympy.Symbol('alpha'),
         cirq.Y(bit)**sympy.Symbol('alpha'),
         cirq.Z(bit)**sympy.Symbol('alpha'),
     )
     inputs = util.convert_to_tensor([circuit])
     symbols = tf.convert_to_tensor(['alpha'])
     new = tf.convert_to_tensor(['new'])
     res = tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, new)
     output = util.from_tensor(res)
     correct_00 = cirq.Circuit(
         cirq.X(bit)**sympy.Symbol('new'),
         cirq.Y(bit)**sympy.Symbol('alpha'),
         cirq.Z(bit)**sympy.Symbol('alpha'),
     )
     correct_01 = cirq.Circuit(
         cirq.X(bit)**sympy.Symbol('alpha'),
         cirq.Y(bit)**sympy.Symbol('new'),
         cirq.Z(bit)**sympy.Symbol('alpha'),
     )
     correct_02 = cirq.Circuit(
         cirq.X(bit)**sympy.Symbol('alpha'),
         cirq.Y(bit)**sympy.Symbol('alpha'),
         cirq.Z(bit)**sympy.Symbol('new'),
     )
     self.assertEqual(correct_00, output[0][0][0])
     self.assertEqual(correct_01, output[0][0][1])
     self.assertEqual(correct_02, output[0][0][2])
    def _infer_impl(self, in_mp):
        self.sympy_data_ = {}
        self.out_mp_.graph.ClearField('value_info')
        self._apply_suggested_merge_to_graph_input()
        input_symbols = set()
        for i in self.out_mp_.graph.input:
            input_symbols.update([
                d for d in get_shape_from_type_proto(i.type) if type(d) == str
            ])
        for s in input_symbols:
            if s in self.suggested_merge_:
                s_merge = self.suggested_merge_[s]
                assert s_merge in self.symbolic_dims_
                self.symbolic_dims_[s] = self.symbolic_dims_[s_merge]
            else:
                self.symbolic_dims_[s] = sympy.Symbol(s, integer=True)

        # create a temporary ModelProto for single node inference
        # note that we remove initializer to have faster inference
        # for tensor ops like Reshape/Tile/Expand that read initializer, we need to do sympy computation based inference anyways
        self.tmp_mp_ = onnx.ModelProto()
        self.tmp_mp_.CopyFrom(self.out_mp_)
        self.tmp_mp_.graph.ClearField('initializer')

        for node in self.out_mp_.graph.node:
            assert all([i in self.known_vi_ for i in node.input if i])
            self._onnx_infer_single_node(node)
            if node.op_type in self.dispatcher_:
                self.dispatcher_[node.op_type](node)

            if self.verbose_ > 2:
                print(node.op_type + ': ' + node.name)
            for i_o in range(len(node.output)):
                out_type = self.known_vi_[node.output[i_o]].type
                out_shape = get_shape_from_type_proto(
                    self.known_vi_[node.output[i_o]].type)
                out_type_undefined = out_type.tensor_type.elem_type == onnx.TensorProto.UNDEFINED
                if self.verbose_ > 2:
                    print('  {}: {} {}'.format(
                        node.output[i_o], str(out_shape), self.known_vi_[
                            node.output[i_o]].type.tensor_type.elem_type))
                    if node.output[i_o] in self.sympy_data_:
                        print('  Sympy Data: ' +
                              str(self.sympy_data_[node.output[i_o]]))
                if None in out_shape or out_type_undefined:
                    if self.auto_merge_:
                        if node.op_type in [
                                'Add', 'Sub', 'Mul', 'Div', 'MatMul', 'Concat',
                                'Where'
                        ]:
                            shapes = [
                                self._get_shape(node, i)
                                for i in range(len(node.input))
                            ]
                            if node.op_type == 'MatMul':
                                # only support auto merge for MatMul for dim < rank-2 when rank > 2
                                assert len(shapes[0]) > 2 and dim_idx[0] < len(
                                    shapes[0]) - 2
                                assert len(shapes[1]) > 2 and dim_idx[1] < len(
                                    shapes[1]) - 2
                        elif node.op_type == 'Expand':
                            # auto merge for cases like Expand([min(batch, 1), min(seq, 512)], [batch, seq])
                            shapes = [
                                self._get_shape(node, 0),
                                self._get_value(node, 1)
                            ]
                        else:
                            shapes = []

                        if shapes:
                            for idx in range(len(out_shape)):
                                if out_shape[idx] is not None:
                                    continue
                                dim_idx = [
                                    len(s) - len(out_shape) + idx
                                    for s in shapes
                                ]
                                assert all([d >= 0 for d in dim_idx])
                                self._add_suggested_merge([
                                    str(s[i]) for s, i in zip(shapes, dim_idx)
                                ])
                            self.run_ = True
                        else:
                            self.run_ = False
                    else:
                        self.run_ = False

                    if self.verbose_ > 0 or not self.auto_merge_ or out_type_undefined:
                        print('Stopping at incomplete shape inference at ' +
                              node.op_type + ': ' + node.name)
                        print('node inputs:')
                        for i in node.input:
                            print(self.known_vi_[i])
                        print('node outputs:')
                        for o in node.output:
                            print(self.known_vi_[o])
                        if self.auto_merge_ and not out_type_undefined:
                            print('Merging: ' + str(self.suggested_merge_))
                    return False

        self.run_ = False
        return True
예제 #3
0
파일: utils.py 프로젝트: gouarin/pylbm_ui
 def __new__(self, v):
     return RelaxationParameterFinal(v, sp.Symbol(symb))
예제 #4
0
def comparison_plot(f,
                    u,
                    Omega,
                    filename='tmp',
                    plot_title='',
                    ymin=None,
                    ymax=None,
                    u_legend='approximation',
                    points=None,
                    point_values=None,
                    points_legend=None,
                    legend_loc='upper right',
                    show=True):
    """Compare f(x) and u(x) for x in Omega in a plot."""
    x = sym.Symbol('x')
    print('f:', f)
    print('u:', u)

    f = sym.lambdify([x], f, modules="numpy")
    u = sym.lambdify([x], u, modules="numpy")
    if len(Omega) != 2:
        raise ValueError('Omega=%s must be an interval (2-list)' % str(Omega))
    # When doing symbolics, Omega can easily contain symbolic expressions,
    # assume .evalf() will work in that case to obtain numerical
    # expressions, which then must be converted to float before calling
    # linspace below
    if not isinstance(Omega[0], (int, float)):
        Omega[0] = float(Omega[0].evalf())
    if not isinstance(Omega[1], (int, float)):
        Omega[1] = float(Omega[1].evalf())

    resolution = 601  # no of points in plot (high resolution)
    xcoor = np.linspace(Omega[0], Omega[1], resolution)
    # Vectorized functions expressions does not work with
    # lambdify'ed functions without the modules="numpy"
    exact = f(xcoor)
    approx = u(xcoor)
    plt.figure()
    plt.plot(xcoor, approx, '-')
    plt.plot(xcoor, exact, '--')
    legends = [u_legend, 'exact']
    if points is not None:
        if point_values is None:
            # Use f
            plt.plot(points, f(points), 'ko')
        else:
            # Use supplied points
            plt.plot(points, point_values, 'ko')
        if points_legend is not None:
            legends.append(points_legend)
        else:
            legends.append('points')
    plt.legend(legends, loc=legend_loc)
    plt.title(plot_title)
    plt.xlabel('x')
    if ymin is not None and ymax is not None:
        plt.axis([xcoor[0], xcoor[-1], ymin, ymax])
    plt.savefig(filename + '.pdf')
    plt.savefig(filename + '.png')
    if show:
        plt.show()
예제 #5
0
import sympy as sym
from math import *
x = sym.Symbol('x')
t = sym.Symbol('t')
print(sym.diff(x**5))
b = 1
a = 0
x = sym.expand((b - a) / 2 * t)
exp = x.expand()
print(exp)
print(exp.subs(t, 1))
예제 #6
0
please tell me, many thanks!


To do:
* 将证明过程对象化,便于处理,打印(英文版,中文版),
* 其他连接词的转换
* 处理简单的, 有一定模式的自然语言, 形成命题推理
'''

import re
import sympy
from random import  randint
from collections import namedtuple


NON = sympy.Symbol('~')
CONTAIN = sympy.Symbol('>')
AND = sympy .Symbol('&')
OR = sysmpy.Symbol('|')
EQUAL = sysmpy.Symbol('-')
LEFT = sympy.Symbol('(')
RIGHT = sympy.Symbol(')')

CONN=[NON,CONTAIN,LEFT,RIGHT]


PAIR = namedtuple('pair',['pre','suf'])

def non(p):
    li = p.getPreOrderLst()
    if li[0]==NON:return formula(li[1:])
예제 #7
0
파일: limits.py 프로젝트: zqhuang/SYSU_GR
## example of differentiation
import sympy as sym
x = sym.Symbol('x')
y = sym.Symbol('y')
print(sym.limit((sym.log(1 + x) - x) / x**2, x, 0))
예제 #8
0
파일: sr.py 프로젝트: nikhil-garg/PySR
def get_hof(equation_file=None,
            n_features=None,
            variable_names=None,
            extra_sympy_mappings=None):
    """Get the equations from a hall of fame file. If no arguments
    entered, the ones used previously from a call to PySR will be used."""

    global global_n_features
    global global_equation_file
    global global_variable_names
    global global_extra_sympy_mappings

    if equation_file is None: equation_file = global_equation_file
    if n_features is None: n_features = global_n_features
    if variable_names is None: variable_names = global_variable_names
    if extra_sympy_mappings is None:
        extra_sympy_mappings = global_extra_sympy_mappings

    global_equation_file = equation_file
    global_n_features = n_features
    global_variable_names = variable_names
    global_extra_sympy_mappings = extra_sympy_mappings

    try:
        output = pd.read_csv(equation_file + '.bkup', sep="|")
    except FileNotFoundError:
        print("Couldn't find equation file!")
        return pd.DataFrame()

    scores = []
    lastMSE = None
    lastComplexity = 0
    sympy_format = []
    lambda_format = []
    use_custom_variable_names = (len(variable_names) != 0)
    local_sympy_mappings = {**extra_sympy_mappings, **sympy_mappings}

    if use_custom_variable_names:
        sympy_symbols = [
            sympy.Symbol(variable_names[i]) for i in range(n_features)
        ]
    else:
        sympy_symbols = [sympy.Symbol('x%d' % i) for i in range(n_features)]

    for i in range(len(output)):
        eqn = sympify(output.loc[i, 'Equation'], locals=local_sympy_mappings)
        sympy_format.append(eqn)
        lambda_format.append(lambdify(sympy_symbols, eqn))
        curMSE = output.loc[i, 'MSE']
        curComplexity = output.loc[i, 'Complexity']

        if lastMSE is None:
            cur_score = 0.0
        else:
            cur_score = -np.log(curMSE / lastMSE) / (curComplexity -
                                                     lastComplexity)

        scores.append(cur_score)
        lastMSE = curMSE
        lastComplexity = curComplexity

    output['score'] = np.array(scores)
    output['sympy_format'] = sympy_format
    output['lambda_format'] = lambda_format

    return output[[
        'Complexity', 'MSE', 'score', 'Equation', 'sympy_format',
        'lambda_format'
    ]]
예제 #9
0
    #因子矩阵
    fac_mat = pd.DataFrame({'Ri': Ri, 'MKT': MKT, 'SMB': SMB, 'HML': HML})

    # 计算沪深300 alpha & beta(三因子模型)
    model_se_3 = smf.ols('Ri ~ MKT + SMB + HML', data=fac_mat)
    result_se_3 = model_se_3.fit()  # 拟合
    #result_se_3.summary()
    alpha_series_3.append(result_se_3.params[0])

    alpha_1 = result_se_3.params[0]
    MKT_1 = result_se_3.params['MKT']
    SMB_1 = result_se_3.params['SMB']
    HML_1 = result_se_3.params['HML']

    #定义符号变量
    e1 = sympy.Symbol('e1')
    e2 = sympy.Symbol('e2')
    e3 = sympy.Symbol('e3')
    m_ad = MKT - np.ones(len(Rm)) * e1
    s_ad = SMB - np.ones(len(Rm)) * e2
    h_ad = HML - np.ones(len(Rm)) * e3

    #计算alpha标准差
    N = len(Rm)
    M = Matrix([np.ones(len(Rm)), m_ad, s_ad, h_ad])
    M = M.T  #因子矩阵
    beta_m = Matrix([alpha_1, MKT_1, SMB_1, HML_1])
    beta_m = beta_m.T  #暴露度矩阵
    L = sympy.simplify(M.T * M)
    L_1 = L**(-1)
    L_1 = L_1.evalf(subs={e1: 0, e2: 0, e3: 0})
                return False
    return True

def f(x):
    return x * sp.tan(x) - 1/3

def fi(x):
    return sp.atan(1 / (3 * x))

def df(x):
    return x*(np.tan(x)**2 + 1) + np.tan(x)

def dfi(x):
    return -1/(3*x**2*(1 + 1/(9*x**2)))

x = sp.Symbol('x')
print('f(x)   = %s' % f(x))
print("f'(x)  = %s" % sp.diff(f(x), x))
print('fi(x)  = tan(0.58*x + 0.1)**0.5')
print("fi'(x) = %s\n" % sp.diff(fi(x), x))

print('Stage of root separation:')
a = 0.1
b = 2
eps = 1e-5

while b - a > 0.1:
    print(' a = %f, f(a) = %f' % (a, f(a)))
    print(' b = %f, f(b) = %f' % (b, f(b)))
    middle = (b + a) / 2
    print(' length = %f, f(middle) = %f\n' % (b - a, f(middle)))
예제 #11
0
# -*- coding: utf-8 -*-
# This file difines the pipeline to calculate a concrete example
#    1. Substitute [R,S,T,P] in general examples and get specific value.
#    2. Save the values to file
#    3. (Optional) Solve expressions according to these values.
import sympy as sym
from z3 import *
import pandas as pd
import numpy as np

_R = 3
_S = 0
_T = 5
_P = 1

p1 = sym.Symbol('p1')
p2 = sym.Symbol('p2')
p3 = sym.Symbol('p3')
p4 = sym.Symbol('p4')
R = sym.Symbol('R', constant=True)
S = sym.Symbol('S', constant=True)
T = sym.Symbol('T', constant=True)
P = sym.Symbol('P', constant=True)

df = pd.read_excel('SymbolicSubstraction.xlsx', sheet_name='Sheet1')
concrete_table = np.zeros((df.shape[0], df.shape[0]), dtype=object)

for i in range(0, df.shape[0]):
    for j in range(0, df.shape[0]):
        if (df.iat[i, j] == 0):
            continue
#T# the following code shows how to make simple logical statements

#T# to make logical statements, the sympy package is used
import sympy

#T# a simple logical statement is created as a symbol
p = sympy.Symbol('p')
q = sympy.Symbol('q')

#T# the logical values True and False can be substituted into the symbols
p.subs(p, sympy.S.true)  # True
q.subs(q, sympy.S.false) # False
예제 #13
0
    def test_complex_pad(self):
        """Test trickier padding."""
        bit = cirq.GridQubit(0, 0)
        bit2 = cirq.GridQubit(0, 1)
        circuit = cirq.Circuit(
            cirq.X(bit)**sympy.Symbol('alpha'),
            cirq.Y(bit)**sympy.Symbol('alpha'),
            cirq.Z(bit)**sympy.Symbol('alpha'),
            cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
        circuit2 = cirq.Circuit(
            cirq.X(bit)**sympy.Symbol('beta'),
            cirq.Y(bit)**sympy.Symbol('beta'),
            cirq.Z(bit)**sympy.Symbol('beta'),
            cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
        circuit3 = cirq.Circuit(
            cirq.X(bit)**sympy.Symbol('alpha'),
            cirq.Y(bit)**sympy.Symbol('alpha'),
            cirq.Z(bit)**sympy.Symbol('alpha'),
            cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
        inputs = util.convert_to_tensor([circuit, circuit2, circuit3])
        symbols = tf.convert_to_tensor(['alpha', 'beta', 'gamma'])
        new = tf.convert_to_tensor(['new', 'old', 'nothing'])
        res = tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, new)
        output = util.from_tensor(res)

        correct_000 = cirq.Circuit(
            cirq.X(bit)**sympy.Symbol('new'),
            cirq.Y(bit)**sympy.Symbol('alpha'),
            cirq.Z(bit)**sympy.Symbol('alpha'),
            cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
        correct_001 = cirq.Circuit(
            cirq.X(bit)**sympy.Symbol('alpha'),
            cirq.Y(bit)**sympy.Symbol('new'),
            cirq.Z(bit)**sympy.Symbol('alpha'),
            cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
        correct_002 = cirq.Circuit(
            cirq.X(bit)**sympy.Symbol('alpha'),
            cirq.Y(bit)**sympy.Symbol('alpha'),
            cirq.Z(bit)**sympy.Symbol('new'),
            cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
        correct_003 = cirq.Circuit(
            cirq.X(bit)**sympy.Symbol('alpha'),
            cirq.Y(bit)**sympy.Symbol('alpha'),
            cirq.Z(bit)**sympy.Symbol('alpha'),
            cirq.XX(bit, bit2)**sympy.Symbol('new'))

        self.assertEqual(correct_000, output[0][0][0])
        self.assertEqual(correct_001, output[0][0][1])
        self.assertEqual(correct_002, output[0][0][2])
        self.assertEqual(correct_003, output[0][0][3])

        self.assertEqual(correct_000, output[2][0][0])
        self.assertEqual(correct_001, output[2][0][1])
        self.assertEqual(correct_002, output[2][0][2])
        self.assertEqual(correct_003, output[2][0][3])

        correct_110 = cirq.Circuit(
            cirq.X(bit)**sympy.Symbol('old'),
            cirq.Y(bit)**sympy.Symbol('beta'),
            cirq.Z(bit)**sympy.Symbol('beta'),
            cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
        correct_111 = cirq.Circuit(
            cirq.X(bit)**sympy.Symbol('beta'),
            cirq.Y(bit)**sympy.Symbol('old'),
            cirq.Z(bit)**sympy.Symbol('beta'),
            cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
        correct_112 = cirq.Circuit(
            cirq.X(bit)**sympy.Symbol('beta'),
            cirq.Y(bit)**sympy.Symbol('beta'),
            cirq.Z(bit)**sympy.Symbol('old'),
            cirq.XX(bit, bit2)**sympy.Symbol('alpha'))
        correct_113 = cirq.Circuit()

        self.assertEqual(correct_110, output[1][1][0])
        self.assertEqual(correct_111, output[1][1][1])
        self.assertEqual(correct_112, output[1][1][2])
        self.assertEqual(correct_113, output[1][1][3])

        correct_100 = cirq.Circuit(
            cirq.X(bit)**sympy.Symbol('beta'),
            cirq.Y(bit)**sympy.Symbol('beta'),
            cirq.Z(bit)**sympy.Symbol('beta'),
            cirq.XX(bit, bit2)**sympy.Symbol('new'))
        correct_101 = cirq.Circuit()
        correct_102 = cirq.Circuit()
        correct_103 = cirq.Circuit()

        self.assertEqual(correct_100, output[1][0][0])
        self.assertEqual(correct_101, output[1][0][1])
        self.assertEqual(correct_102, output[1][0][2])
        self.assertEqual(correct_103, output[1][0][3])

        correct_220 = cirq.Circuit()
        correct_221 = cirq.Circuit()
        correct_222 = cirq.Circuit()
        correct_223 = cirq.Circuit()

        self.assertEqual(correct_220, output[2][2][0])
        self.assertEqual(correct_221, output[2][2][1])
        self.assertEqual(correct_222, output[2][2][2])
        self.assertEqual(correct_223, output[2][2][3])

        correct = cirq.Circuit()
        for i in range(3):
            for j in range(3):
                for k in range(3):
                    if i != j and (not (i == 2 and j == 0)) \
                        and (not (i == 1 and j == 0)):
                        self.assertEqual(correct, output[i][j][k])
예제 #14
0
 def test_weight_coefficient(self):
     """Test that scalar multiples of trivial case work."""
     bit = cirq.GridQubit(0, 0)
     circuit = cirq.Circuit(
         cirq.X(bit)**(sympy.Symbol('alpha') * 2.0),
         cirq.Y(bit)**(sympy.Symbol('alpha') * 3.0),
         cirq.Z(bit)**(sympy.Symbol('alpha') * 4.0),
     )
     inputs = util.convert_to_tensor([circuit])
     symbols = tf.convert_to_tensor(['alpha'])
     new = tf.convert_to_tensor(['new'])
     res = tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, new)
     output = util.from_tensor(res)
     correct_00 = cirq.Circuit(
         cirq.X(bit)**(sympy.Symbol('new') * 2.0),
         cirq.Y(bit)**(sympy.Symbol('alpha') * 3.0),
         cirq.Z(bit)**(sympy.Symbol('alpha') * 4.0),
     )
     correct_01 = cirq.Circuit(
         cirq.X(bit)**(sympy.Symbol('alpha') * 2.0),
         cirq.Y(bit)**(sympy.Symbol('new') * 3.0),
         cirq.Z(bit)**(sympy.Symbol('alpha') * 4.0),
     )
     correct_02 = cirq.Circuit(
         cirq.X(bit)**(sympy.Symbol('alpha') * 2.0),
         cirq.Y(bit)**(sympy.Symbol('alpha') * 3.0),
         cirq.Z(bit)**(sympy.Symbol('new') * 4.0),
     )
     self.assertEqual(correct_00, output[0][0][0])
     self.assertEqual(correct_01, output[0][0][1])
     self.assertEqual(correct_02, output[0][0][2])
예제 #15
0
        if not cmp(e.subs(n, i), 0):
            return False, i
    return True, -1

def rearrange(e, n):
    """'e' is assumed to be a list of exponential polynomial terms"""
    pos, neg = [], []
    for t in e:
        poly = sp.poly(t[0], gens=n)
        lc = sp.LC(poly, gens=n)
        if lc > 0: pos.append(t)
        elif lc < 0: neg.append(t)
    return pos, neg

if __name__ =='__main__':
    n = sp.Symbol('n')
    close = sp.Matrix([[n], [1]])
    conds = [PolyCondition(n - 50, strict=True)]
    validate(close, conds, [1], n)
    # A = [sp.Matrix([[1, 1], [0, 1]]), sp.Matrix([[1, 2], [0, 1]])]
    # x0 = sp.Matrix([0, 1])
    # from condition import PolyCondition
    # _PRS_x0, _PRS_x1 = sp.symbols('_PRS_x0 _PRS_x1')
    # conds = [PolyCondition(50 - _PRS_x0, strict=True)]
    # res = exhaust_pattern(A, x0, conds, [0])
    # print(res)
    # n = sp.Symbol('n')
    # # e = 0.2**n + 0.3**n + .4**n + n**2 + 100*n
    # e = -n**2 + 2
    # res = ep_ge_0(e, n)
    # print(res)
예제 #16
0
  def generate_code():
    name = LiveKalman.name
    dim_state = LiveKalman.initial_x.shape[0]
    dim_state_err = LiveKalman.initial_P_diag.shape[0]

    state_sym = sp.MatrixSymbol('state', dim_state, 1)
    state = sp.Matrix(state_sym)
    x, y, z = state[States.ECEF_POS, :]
    q = state[States.ECEF_ORIENTATION, :]
    v = state[States.ECEF_VELOCITY, :]
    vx, vy, vz = v
    omega = state[States.ANGULAR_VELOCITY, :]
    vroll, vpitch, vyaw = omega
    roll_bias, pitch_bias, yaw_bias = state[States.GYRO_BIAS, :]
    odo_scale = state[States.ODO_SCALE, :][0,:]
    acceleration = state[States.ACCELERATION, :]
    imu_angles = state[States.IMU_OFFSET, :]

    dt = sp.Symbol('dt')

    # calibration and attitude rotation matrices
    quat_rot = quat_rotate(*q)

    # Got the quat predict equations from here
    # A New Quaternion-Based Kalman Filter for
    # Real-Time Attitude Estimation Using the Two-Step
    # Geometrically-Intuitive Correction Algorithm
    A = 0.5 * sp.Matrix([[0, -vroll, -vpitch, -vyaw],
                         [vroll, 0, vyaw, -vpitch],
                         [vpitch, -vyaw, 0, vroll],
                         [vyaw, vpitch, -vroll, 0]])
    q_dot = A * q

    # Time derivative of the state as a function of state
    state_dot = sp.Matrix(np.zeros((dim_state, 1)))
    state_dot[States.ECEF_POS, :] = v
    state_dot[States.ECEF_ORIENTATION, :] = q_dot
    state_dot[States.ECEF_VELOCITY, 0] = quat_rot * acceleration

    # Basic descretization, 1st order intergrator
    # Can be pretty bad if dt is big
    f_sym = state + dt * state_dot

    state_err_sym = sp.MatrixSymbol('state_err', dim_state_err, 1)
    state_err = sp.Matrix(state_err_sym)
    quat_err = state_err[States.ECEF_ORIENTATION_ERR, :]
    v_err = state_err[States.ECEF_VELOCITY_ERR, :]
    omega_err = state_err[States.ANGULAR_VELOCITY_ERR, :]
    acceleration_err = state_err[States.ACCELERATION_ERR, :]

    # Time derivative of the state error as a function of state error and state
    quat_err_matrix = euler_rotate(quat_err[0], quat_err[1], quat_err[2])
    q_err_dot = quat_err_matrix * quat_rot * (omega + omega_err)
    state_err_dot = sp.Matrix(np.zeros((dim_state_err, 1)))
    state_err_dot[States.ECEF_POS_ERR, :] = v_err
    state_err_dot[States.ECEF_ORIENTATION_ERR, :] = q_err_dot
    state_err_dot[States.ECEF_VELOCITY_ERR, :] = quat_err_matrix * quat_rot * (acceleration + acceleration_err)
    f_err_sym = state_err + dt * state_err_dot

    # Observation matrix modifier
    H_mod_sym = sp.Matrix(np.zeros((dim_state, dim_state_err)))
    H_mod_sym[States.ECEF_POS, States.ECEF_POS_ERR] = np.eye(States.ECEF_POS.stop - States.ECEF_POS.start)
    H_mod_sym[States.ECEF_ORIENTATION, States.ECEF_ORIENTATION_ERR] = 0.5 * quat_matrix_r(state[3:7])[:, 1:]
    H_mod_sym[States.ECEF_ORIENTATION.stop:, States.ECEF_ORIENTATION_ERR.stop:] = np.eye(dim_state - States.ECEF_ORIENTATION.stop)

    # these error functions are defined so that say there
    # is a nominal x and true x:
    # true x = err_function(nominal x, delta x)
    # delta x = inv_err_function(nominal x, true x)
    nom_x = sp.MatrixSymbol('nom_x', dim_state, 1)
    true_x = sp.MatrixSymbol('true_x', dim_state, 1)
    delta_x = sp.MatrixSymbol('delta_x', dim_state_err, 1)

    err_function_sym = sp.Matrix(np.zeros((dim_state, 1)))
    delta_quat = sp.Matrix(np.ones(4))
    delta_quat[1:, :] = sp.Matrix(0.5 * delta_x[States.ECEF_ORIENTATION_ERR, :])
    err_function_sym[States.ECEF_POS, :] = sp.Matrix(nom_x[States.ECEF_POS, :] + delta_x[States.ECEF_POS_ERR, :])
    err_function_sym[States.ECEF_ORIENTATION, 0] = quat_matrix_r(nom_x[States.ECEF_ORIENTATION, 0]) * delta_quat
    err_function_sym[States.ECEF_ORIENTATION.stop:, :] = sp.Matrix(nom_x[States.ECEF_ORIENTATION.stop:, :] + delta_x[States.ECEF_ORIENTATION_ERR.stop:, :])

    inv_err_function_sym = sp.Matrix(np.zeros((dim_state_err, 1)))
    inv_err_function_sym[States.ECEF_POS_ERR, 0] = sp.Matrix(-nom_x[States.ECEF_POS, 0] + true_x[States.ECEF_POS, 0])
    delta_quat = quat_matrix_r(nom_x[States.ECEF_ORIENTATION, 0]).T * true_x[States.ECEF_ORIENTATION, 0]
    inv_err_function_sym[States.ECEF_ORIENTATION_ERR, 0] = sp.Matrix(2 * delta_quat[1:])
    inv_err_function_sym[States.ECEF_ORIENTATION_ERR.stop:, 0] = sp.Matrix(-nom_x[States.ECEF_ORIENTATION.stop:, 0] + true_x[States.ECEF_ORIENTATION.stop:, 0])

    eskf_params = [[err_function_sym, nom_x, delta_x],
                   [inv_err_function_sym, nom_x, true_x],
                   H_mod_sym, f_err_sym, state_err_sym]
    #
    # Observation functions
    #
    imu_rot = euler_rotate(*imu_angles)
    h_gyro_sym = imu_rot * sp.Matrix([vroll + roll_bias,
                                      vpitch + pitch_bias,
                                      vyaw + yaw_bias])

    pos = sp.Matrix([x, y, z])
    gravity = quat_rot.T * ((EARTH_GM / ((x**2 + y**2 + z**2)**(3.0 / 2.0))) * pos)
    h_acc_sym = imu_rot * (gravity + acceleration)
    h_phone_rot_sym = sp.Matrix([vroll, vpitch, vyaw])

    speed = sp.sqrt(vx**2 + vy**2 + vz**2)
    h_speed_sym = sp.Matrix([speed * odo_scale])

    h_pos_sym = sp.Matrix([x, y, z])
    h_imu_frame_sym = sp.Matrix(imu_angles)

    h_relative_motion = sp.Matrix(quat_rot.T * v)

    obs_eqs = [[h_speed_sym, ObservationKind.ODOMETRIC_SPEED, None],
               [h_gyro_sym, ObservationKind.PHONE_GYRO, None],
               [h_phone_rot_sym, ObservationKind.NO_ROT, None],
               [h_acc_sym, ObservationKind.PHONE_ACCEL, None],
               [h_pos_sym, ObservationKind.ECEF_POS, None],
               [h_relative_motion, ObservationKind.CAMERA_ODO_TRANSLATION, None],
               [h_phone_rot_sym, ObservationKind.CAMERA_ODO_ROTATION, None],
               [h_imu_frame_sym, ObservationKind.IMU_FRAME, None]]

    gen_code(name, f_sym, dt, state_sym, obs_eqs, dim_state, dim_state_err, eskf_params)
예제 #17
0
from all_funcs import *
import sympy


def foo(a, b):
    return a * b + a + b


a = sympy.Symbol('a')
b = sympy.Symbol('b')
e = foo(a, b)
print e
print e.diff(a)
# result = degreeNPolyMultiVar([2,a,b], [1,2,1])
# print result
예제 #18
0
class CarKalman():
    name = 'car'

    x_initial = np.array([
        1.0,
        15.0,
        0.0,
        0.0,
        10.0,
        0.0,
        0.0,
        0.0,
    ])

    # state covariance
    P_initial = np.diag([
        .1**2,
        .1**2,
        math.radians(0.1)**2,
        math.radians(0.1)**2,
        10**2,
        10**2,
        1**2,
        1**2,
    ])

    # process noise
    Q = np.diag([
        (.05 / 10)**2,
        .0001**2,
        math.radians(0.01)**2,
        math.radians(0.2)**2,
        .1**2,
        .1**2,
        math.radians(0.1)**2,
        math.radians(0.1)**2,
    ])

    obs_noise = {
        ObservationKind.ROAD_FRAME_XY_SPEED: np.diag([0.1**2, 0.1**2]),
        ObservationKind.ROAD_FRAME_YAW_RATE:
        np.atleast_2d(math.radians(0.1)**2),
        ObservationKind.STEER_ANGLE: np.atleast_2d(math.radians(0.1)**2),
        ObservationKind.ANGLE_OFFSET_FAST: np.atleast_2d(math.radians(5.0)**2),
        ObservationKind.STEER_RATIO: np.atleast_2d(50.0**2),
        ObservationKind.STIFFNESS: np.atleast_2d(50.0**2),
    }

    maha_test_kinds = [
    ]  # [ObservationKind.ROAD_FRAME_YAW_RATE, ObservationKind.ROAD_FRAME_XY_SPEED]
    global_vars = [
        sp.Symbol('mass'),
        sp.Symbol('rotational_inertia'),
        sp.Symbol('center_to_front'),
        sp.Symbol('center_to_rear'),
        sp.Symbol('stiffness_front'),
        sp.Symbol('stiffness_rear'),
    ]

    @staticmethod
    def generate_code():
        dim_state = CarKalman.x_initial.shape[0]
        name = CarKalman.name
        maha_test_kinds = CarKalman.maha_test_kinds

        # globals
        m, j, aF, aR, cF_orig, cR_orig = CarKalman.global_vars

        # make functions and jacobians with sympy
        # state variables
        state_sym = sp.MatrixSymbol('state', dim_state, 1)
        state = sp.Matrix(state_sym)

        # Vehicle model constants
        x = state[States.STIFFNESS, :][0, 0]

        cF, cR = x * cF_orig, x * cR_orig
        angle_offset = state[States.ANGLE_OFFSET, :][0, 0]
        angle_offset_fast = state[States.ANGLE_OFFSET_FAST, :][0, 0]
        sa = state[States.STEER_ANGLE, :][0, 0]

        sR = state[States.STEER_RATIO, :][0, 0]
        u, v = state[States.VELOCITY, :]
        r = state[States.YAW_RATE, :][0, 0]

        A = sp.Matrix(np.zeros((2, 2)))
        A[0, 0] = -(cF + cR) / (m * u)
        A[0, 1] = -(cF * aF - cR * aR) / (m * u) - u
        A[1, 0] = -(cF * aF - cR * aR) / (j * u)
        A[1, 1] = -(cF * aF**2 + cR * aR**2) / (j * u)

        B = sp.Matrix(np.zeros((2, 1)))
        B[0, 0] = cF / m / sR
        B[1, 0] = (cF * aF) / j / sR

        x = sp.Matrix([v, r])  # lateral velocity, yaw rate
        x_dot = A * x + B * (sa - angle_offset - angle_offset_fast)

        dt = sp.Symbol('dt')
        state_dot = sp.Matrix(np.zeros((dim_state, 1)))
        state_dot[States.VELOCITY.start + 1, 0] = x_dot[0]
        state_dot[States.YAW_RATE.start, 0] = x_dot[1]

        # Basic descretization, 1st order integrator
        # Can be pretty bad if dt is big
        f_sym = state + dt * state_dot

        #
        # Observation functions
        #
        obs_eqs = [
            [sp.Matrix([r]), ObservationKind.ROAD_FRAME_YAW_RATE, None],
            [sp.Matrix([u, v]), ObservationKind.ROAD_FRAME_XY_SPEED, None],
            [sp.Matrix([sa]), ObservationKind.STEER_ANGLE, None],
            [
                sp.Matrix([angle_offset_fast]),
                ObservationKind.ANGLE_OFFSET_FAST, None
            ],
            [sp.Matrix([sR]), ObservationKind.STEER_RATIO, None],
            [sp.Matrix([x]), ObservationKind.STIFFNESS, None],
        ]

        gen_code(name,
                 f_sym,
                 dt,
                 state_sym,
                 obs_eqs,
                 dim_state,
                 dim_state,
                 maha_test_kinds=maha_test_kinds,
                 global_vars=CarKalman.global_vars)

    def __init__(self):
        self.dim_state = self.x_initial.shape[0]

        # init filter
        self.filter = EKF_sym(self.name,
                              self.Q,
                              self.x_initial,
                              self.P_initial,
                              self.dim_state,
                              self.dim_state,
                              maha_test_kinds=self.maha_test_kinds,
                              global_vars=self.global_vars)

    @property
    def x(self):
        return self.filter.state()

    @property
    def P(self):
        return self.filter.covs()

    def predict(self, t):
        return self.filter.predict(t)

    def rts_smooth(self, estimates):
        return self.filter.rts_smooth(estimates, norm_quats=False)

    def get_R(self, kind, n):
        obs_noise = self.obs_noise[kind]
        dim = obs_noise.shape[0]
        R = np.zeros((n, dim, dim))
        for i in range(n):
            R[i, :, :] = obs_noise
        return R

    def init_state(self, state, covs_diag=None, covs=None, filter_time=None):
        if covs_diag is not None:
            P = np.diag(covs_diag)
        elif covs is not None:
            P = covs
        else:
            P = self.filter.covs()
        self.filter.init_state(state, P, filter_time)

    def predict_and_observe(self, t, kind, data):
        if len(data) > 0:
            data = np.atleast_2d(data)
        self.filter.predict_and_update_batch(t, kind, data,
                                             self.get_R(kind, len(data)))
예제 #19
0
                    'float_value': half_turns
                }
            },
        },
        'qubits': [{
            'id': '1_2'
        }],
    })

    assert _single_qubit_gate_set().serialize_op(gate.on(q)) == expected


@pytest.mark.parametrize(
    ('gate', 'axis_half_turns', 'half_turns'),
    [
        (cirq.X**sympy.Symbol('a'), 0.0, 'a'),
        (cirq.Y**sympy.Symbol('b'), 0.5, 'b'),
        (cirq.PhasedXPowGate(exponent=sympy.Symbol('a'),
                             phase_exponent=0.25), 0.25, 'a'),
    ],
)
def test_serialize_xy_parameterized_half_turns(gate, axis_half_turns,
                                               half_turns):
    q = cirq.GridQubit(1, 2)
    expected = op_proto({
        'gate': {
            'id': 'xy'
        },
        'args': {
            'axis_half_turns': {
                'arg_value': {
예제 #20
0
    def generate_code():
        dim_state = CarKalman.x_initial.shape[0]
        name = CarKalman.name
        maha_test_kinds = CarKalman.maha_test_kinds

        # globals
        m, j, aF, aR, cF_orig, cR_orig = CarKalman.global_vars

        # make functions and jacobians with sympy
        # state variables
        state_sym = sp.MatrixSymbol('state', dim_state, 1)
        state = sp.Matrix(state_sym)

        # Vehicle model constants
        x = state[States.STIFFNESS, :][0, 0]

        cF, cR = x * cF_orig, x * cR_orig
        angle_offset = state[States.ANGLE_OFFSET, :][0, 0]
        angle_offset_fast = state[States.ANGLE_OFFSET_FAST, :][0, 0]
        sa = state[States.STEER_ANGLE, :][0, 0]

        sR = state[States.STEER_RATIO, :][0, 0]
        u, v = state[States.VELOCITY, :]
        r = state[States.YAW_RATE, :][0, 0]

        A = sp.Matrix(np.zeros((2, 2)))
        A[0, 0] = -(cF + cR) / (m * u)
        A[0, 1] = -(cF * aF - cR * aR) / (m * u) - u
        A[1, 0] = -(cF * aF - cR * aR) / (j * u)
        A[1, 1] = -(cF * aF**2 + cR * aR**2) / (j * u)

        B = sp.Matrix(np.zeros((2, 1)))
        B[0, 0] = cF / m / sR
        B[1, 0] = (cF * aF) / j / sR

        x = sp.Matrix([v, r])  # lateral velocity, yaw rate
        x_dot = A * x + B * (sa - angle_offset - angle_offset_fast)

        dt = sp.Symbol('dt')
        state_dot = sp.Matrix(np.zeros((dim_state, 1)))
        state_dot[States.VELOCITY.start + 1, 0] = x_dot[0]
        state_dot[States.YAW_RATE.start, 0] = x_dot[1]

        # Basic descretization, 1st order integrator
        # Can be pretty bad if dt is big
        f_sym = state + dt * state_dot

        #
        # Observation functions
        #
        obs_eqs = [
            [sp.Matrix([r]), ObservationKind.ROAD_FRAME_YAW_RATE, None],
            [sp.Matrix([u, v]), ObservationKind.ROAD_FRAME_XY_SPEED, None],
            [sp.Matrix([sa]), ObservationKind.STEER_ANGLE, None],
            [
                sp.Matrix([angle_offset_fast]),
                ObservationKind.ANGLE_OFFSET_FAST, None
            ],
            [sp.Matrix([sR]), ObservationKind.STEER_RATIO, None],
            [sp.Matrix([x]), ObservationKind.STIFFNESS, None],
        ]

        gen_code(name,
                 f_sym,
                 dt,
                 state_sym,
                 obs_eqs,
                 dim_state,
                 dim_state,
                 maha_test_kinds=maha_test_kinds,
                 global_vars=CarKalman.global_vars)
예제 #21
0
import sympy
import sys
from sympy.utilities.codegen import codegen
from sympy.printing import print_ccode

#The Data
M = sympy.Symbol('M')
m = sympy.Symbol('m')
E = sympy.Symbol('E')

#The Parameters
e = sympy.Symbol('a.error')
h = sympy.Symbol('a.freq')
F = sympy.Symbol('a.f')

#An array of the parameters.
params = [h, e, F]

#The three componenents of the likelihood function. H00 is homozygous for the major allele, H01 heterozygous, and H11 homozygous minor.

lnc = sympy.Symbol('lnc')
lne = sympy.Symbol('lne')
lneh = sympy.Symbol('lneh')
lnch = sympy.Symbol('lnch')

#H00=( h**2.+h*(1.-h)*F)*sympy.exp( lnc*M+lne*(m+e1+e2) )
#H01=2.*h*(1.-h)*(1.-F)*sympy.exp( lnch*(M+m)+lneh*(e1+e2) )
#H11=( (1.-h)**2.+h*(1.-h)*F)*sympy.exp( lnc*m+lne*(M+e1+e2) )

#H00=( (h)**2.+h*(1.-h)*F)*( ( (1.- e)**M)*(( e/3.)**(m+E) ) )
#H01=2.*h*(1.-h)*(1.-F)*( ( ( (1.- e)/2.+( e/6.) )**(M+m) )*( ( e/3.)**(E) ) )#-0.00001
        for j in range(n):
            A[i][j] = g3(l, r, 10, al[j] * bt[i])
    return A


def getD(b, f):
    d = []
    for beta in bt:
        beta = beta.subs('s', 'x')
        q = beta * f
        q = q.subs('x', 's')
        d.append(g3(l, r, 10, q))
    return d


x = sp.Symbol('x')
s = sp.Symbol('s')
ker = (x * s * s - 1) * sp.cos(x * s + 1)
f = 2 * x + 3
lmbd = 3/5
l, r, count = 0., 1., 9
al, bt = interpolate(l, r, count, ker)
A = np.array(getA(al, bt, count), dtype=np.float)
d = np.array(getD(bt, f), dtype=np.float)
c = np.linalg.solve(np.eye(count) - lmbd * A, d)
u = 0
for i in range(count):
    u += al[i] * c[i]
u *= lmbd
u += f
u = sp.expand(u.subs('s', 'x'))
예제 #23
0
def test_namespace_type():
    # lambdify had a bug where it would reject modules of type unicode
    # on Python 2.
    x = sympy.Symbol('x')
    lambdify(x, x, modules=u'math')
예제 #24
0
         'string_value': 'abc'
     }
 }),
 (float, 1, {
     'arg_value': {
         'float_value': 1.0
     }
 }),
 (List[bool], [True, False], {
     'arg_value': {
         'bool_values': {
             'values': [True, False]
         }
     }
 }),
 (sympy.Symbol, sympy.Symbol('x'), {
     'symbol': 'x'
 }),
 (
     float,
     sympy.Symbol('x') - sympy.Symbol('y'),
     {
         'func': {
             'type':
             'add',
             'args': [
                 {
                     'symbol': 'x'
                 },
                 {
                     'func': {
예제 #25
0
        # That means can not find next step due to the limit of a
        if t == 0:
            print("t == 0 ")
            break
        x = x + t * directionValue
        fValue = GetValue(f, args, x)
        fStack.append(fValue)
    print("The optimize solution: " + str(x))
    print("error = ", end="")
    print(np.linalg.norm(dfValue, 2))
    print("Iteration times = " + str(len(fStack)))
    return eStack


if __name__ == "__test__":
    X1 = sp.Symbol("x1")
    X2 = sp.Symbol("x2")
    args = np.array((X1, X2))
    # function
    f = sp.exp(X1 + 3 * X2 - 0.1) + sp.exp(X1 - 3 * X2 - 0.1) + sp.exp(-X1 -
                                                                       0.1)
    # Init point
    x0 = np.array([1, 1])
    # Error range
    e = 10**-10
    a = 10**-1
    b = 10**-1
    eStack = Search(f, args, a, b, x0, e)

if __name__ == "__main__":
    X1 = sp.Symbol("x1")
예제 #26
0
def default_circuit():
    return cirq.FrozenCircuit(
        cirq.X(cirq.GridQubit(1, 1))**sympy.Symbol('k'),
        cirq.X(cirq.GridQubit(1, 2)).with_tags(DEFAULT_TOKEN),
        cirq.measure(cirq.GridQubit(1, 1), key='m'),
    )
예제 #27
0
def syms(vars):
    items = []
    for var in vars:
        items.append(sp.Symbol(var))
    return items
예제 #28
0
import sympy as sym
import numpy as np
from matplotlib import pyplot as plt
import pickle

num_nrns = 2
# SYMBOLIC VARIABLES
x = sym.Symbol("x")
V = sym.MatrixSymbol("V", 1, num_nrns)
H = sym.MatrixSymbol("H", 1, num_nrns)
M = sym.MatrixSymbol("M", 1, num_nrns)
Z_inh = sym.MatrixSymbol("Z_inh", num_nrns,
                         num_nrns * num_nrns)  # V sensitivity to W_inh
Y_inh = sym.MatrixSymbol("Y_inh", num_nrns,
                         num_nrns * num_nrns)  # M sensitivity to W_inh
W_inh = sym.MatrixSymbol("W_inh", 1, num_nrns * num_nrns)

# MODEL PARAMETERS
V_half = sym.Symbol("V_half")
k_v = 4.0
k_ad = 0.9
C = 20
g_ad = 10.0
g_l = 2.8
g_SynE = 10.0
g_SynI = 60.0
E_K = -85.0
E_L = -60
E_SynE = 0.0
E_SynI = -75.0
tau_ad = 2000
예제 #29
0
파일: utils.py 프로젝트: gouarin/pylbm_ui
 def __new__(self, v):
     return RealParameterFinal(v, sp.Symbol(symb))
예제 #30
0
    def test_decompose_with_complex_circuit(self):
        """Test decompose with complex circuit."""
        names = ['CLAE', 'HRYV', 'IRKB', 'LKRV', 'PJOU', 'CJKX', 'NASW']
        # Test circuit has a Moment with 1) FSimGate & PhasedXPowGate,
        # 2) PhasedXPowGate & ISwapPowGate and 3) FSimGate & ISwapPowGate.
        # Be careful, they are not decomposed if not parameterized.
        circuit_batch = [
            cirq.Circuit([
                cirq.Moment(operations=[
                    cirq.FSimGate(theta=0.10338130973488413 *
                                  sympy.Symbol('CLAE'),
                                  phi=0.10338130973488413 *
                                  sympy.Symbol('IRKB')).
                    on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)),
                    cirq.PhasedXPowGate(phase_exponent=1.0,
                                        exponent=0.86426029696045281 *
                                        sympy.Symbol('HRYV')).on(
                                            cirq.GridQubit(0, 1)),
                ]),
                cirq.Moment(operations=[
                    cirq.Y.on(cirq.GridQubit(0, 3)),
                    cirq.Z.on(cirq.GridQubit(0, 0)),
                    cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 1),
                                                     cirq.GridQubit(0, 2)),
                ]),
                cirq.Moment(operations=[
                    (cirq.CNOT**(0.92874230274398684 * sympy.Symbol('IRKB'))
                     ).on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 2)),
                ]),
                cirq.Moment(operations=[
                    cirq.PhasedXPowGate(phase_exponent=sympy.Symbol('PJOU'),
                                        exponent=0.2081415255258906 *
                                        sympy.Symbol('LKRV')).on(
                                            cirq.GridQubit(0, 2)),
                    (cirq.ISWAP**(0.32860954996781722 * sympy.Symbol('PJOU'))
                     ).on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 3)),
                ]),
                cirq.Moment(operations=[
                    cirq.PhasedXPowGate(phase_exponent=sympy.Symbol(
                        'CJKX')).on(cirq.GridQubit(0, 1)),
                    cirq.ZZ.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 3)),
                    (cirq.X**(0.6826594585474709 *
                              sympy.Symbol('HRYV'))).on(cirq.GridQubit(0, 2)),
                ]),
                cirq.Moment(operations=[
                    (cirq.ZZ**(0.18781276022427218 * sympy.Symbol('PJOU'))
                     ).on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 3)),
                ]),
                cirq.Moment(operations=[
                    cirq.Y.on(cirq.GridQubit(0, 0)),
                ]),
                cirq.Moment(operations=[
                    cirq.FSimGate(theta=0.13793763138552417 *
                                  sympy.Symbol('CJKX'),
                                  phi=0.13793763138552417 *
                                  sympy.Symbol('PJOU')).
                    on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)),
                    (cirq.ISWAP**(0.028165738453673095 * sympy.Symbol('NASW'))
                     ).on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)),
                ]),
                cirq.Moment(operations=[
                    cirq.FSimGate(theta=0.74356520426349459 *
                                  sympy.Symbol('CJKX'),
                                  phi=0.74356520426349459 *
                                  sympy.Symbol('NASW')).
                    on(cirq.GridQubit(0, 3), cirq.GridQubit(0, 0)),
                ]),
                cirq.Moment(operations=[
                    cirq.CNOT.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 2)),
                    cirq.SWAP.on(cirq.GridQubit(0, 3), cirq.GridQubit(0, 1)),
                ]),
                cirq.Moment(operations=[
                    cirq.H.on(cirq.GridQubit(0, 3)),
                    cirq.H.on(cirq.GridQubit(0, 2)),
                    cirq.CNOT.on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 0)),
                ]),
                cirq.Moment(operations=[
                    cirq.CNOT.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)),
                    cirq.YY.on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)),
                ]),
                cirq.Moment(operations=[
                    cirq.CZ.on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 0)),
                    cirq.CNOT.on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)),
                ]),
                cirq.Moment(operations=[
                    cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 0),
                                                     cirq.GridQubit(0, 2)),
                    cirq.CNOT.on(cirq.GridQubit(0, 3), cirq.GridQubit(0, 1)),
                ]),
                cirq.Moment(operations=[
                    cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 0),
                                                     cirq.GridQubit(0, 3)),
                    cirq.SWAP.on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 1)),
                ]),
                cirq.Moment(operations=[
                    cirq.Y.on(cirq.GridQubit(0, 0)),
                    cirq.PhasedXPowGate(
                        phase_exponent=1.0).on(cirq.GridQubit(0, 2)),
                    cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 1),
                                                     cirq.GridQubit(0, 3)),
                ]),
            ])
        ]

        # Decompose programs.
        inputs = util.convert_to_tensor(circuit_batch)
        outputs = tfq_ps_util_ops.tfq_ps_decompose(inputs)
        decomposed_programs = util.from_tensor(outputs)
        self.assertEqual(len(decomposed_programs), len(circuit_batch))

        # Original programs has parameterized ISP, PXP, FSIM, but this result
        # has no such gates at all. All parameterized gates have at most two
        # eigenvalues. There are still ISwap and PhasedX(1.0) because they are
        # not parameterized, which doesn't affect ParameterShift differentiation
        # at all.
        for program in decomposed_programs:
            for moment in program:
                for gate_op in moment:
                    # Consider parameterized gates only
                    if cirq.is_parameterized(gate_op.gate):
                        # Check I. The gate should have _eigen_components.
                        self.assertTrue(
                            hasattr(gate_op.gate, '_eigen_components'))
                        # Check II. The gate should have two eigen values.
                        self.assertEqual(len(gate_op.gate._eigen_components()),
                                         2, gate_op.gate)
        # Now all programs don't have ISWAP & PhasedXPowGate because ISWAP has
        # 3 eigenvalues and PhasedXPowGate doesn't have _eigen_components.
        # Check if two programs are identical.
        rand_resolver = {name: np.random.random() for name in names}
        self.assertAllClose(cirq.unitary(
            cirq.resolve_parameters(circuit_batch[0], rand_resolver)),
                            cirq.unitary(
                                cirq.resolve_parameters(
                                    decomposed_programs[0], rand_resolver)),
                            atol=1e-5)