def test_flattener_value_of():
    flattener = flatten_expressions._ParamFlattener({'c': 5, 'x1': 'x1'})
    assert flattener.value_of(9) == 9
    assert flattener.value_of('c') == 5
    assert flattener.value_of(sympy.Symbol('c')) == 5
    # Twice
    assert (flattener.value_of(sympy.Symbol('c') / 2 +
                               1) == sympy.Symbol('<c/2 + 1>'))
    assert (flattener.value_of(sympy.Symbol('c') / 2 +
                               1) == sympy.Symbol('<c/2 + 1>'))
    # Collisions between the string representation of different expressions
    # This tests the unusual case where str(expr1) == str(expr2) doesn't imply
    # expr1 == expr2.  In this case it would be incorrect to flatten to the same
    # symbol because the two expression will evaluate to different values.
    # Also tests that '_#' is appended when avoiding collisions.
    assert (flattener.value_of(
        sympy.Symbol('c') /
        sympy.Symbol('2 + 1')) == sympy.Symbol('<c/2 + 1>_1'))
    assert (flattener.value_of(sympy.Symbol('c/2') +
                               1) == sympy.Symbol('<c/2 + 1>_2'))

    assert (cirq.flatten([sympy.Symbol('c') / 2 + 1,
                          sympy.Symbol('c/2') + 1])[0] == [
                              sympy.Symbol('<c/2 + 1>'),
                              sympy.Symbol('<c/2 + 1>_1')
                          ])
Пример #2
0
def test_flatten_circuit():
    qubit = cirq.LineQubit(0)
    a = sympy.Symbol('a')
    circuit = cirq.Circuit(cirq.X(qubit)**a, cirq.X(qubit)**(1 + a / 2))

    c_flat, expr_map = cirq.flatten(circuit)

    c_expected = cirq.Circuit(
        cirq.X(qubit)**a,
        cirq.X(qubit)**sympy.Symbol('<a/2 + 1>'))
    assert c_flat == c_expected
    assert isinstance(expr_map, cirq.ExpressionMap)
    assert expr_map == {a: a, 1 + a / 2: sympy.Symbol('<a/2 + 1>')}