示例#1
0
def test_parse_matrix_failures():
    with pytest.raises(ValueError, match='Not surrounded by {{}}'):
        _ = parse_matrix('1')
    with pytest.raises(ValueError, match='Not surrounded by {{}}'):
        _ = parse_matrix('{{1}')
    with pytest.raises(ValueError, match='Not surrounded by {{}}'):
        _ = parse_matrix('{1}}')
    with pytest.raises(ValueError, match='Not surrounded by {{}}'):
        _ = parse_matrix('1}}')
    with pytest.raises(ValueError, match='Failed to parse complex'):
        _ = parse_matrix('{{x}}')
示例#2
0
def test_parse_matrix():
    s = np.sqrt(0.5)
    np.testing.assert_allclose(parse_matrix('{{√½,√½},{-√½,√½}}'),
                               np.array([[s, s], [-s, s]]),
                               atol=1e-8)
    np.testing.assert_allclose(parse_matrix('{{√½,√½i},{√½i,√½}}'),
                               np.array([[s, s * 1j], [s * 1j, s]]),
                               atol=1e-8)
    np.testing.assert_allclose(parse_matrix('{{1,-i},{i,1+i}}'),
                               np.array([[1, -1j], [1j, 1 + 1j]]),
                               atol=1e-8)
示例#3
0
def _register_custom_gate(gate_json: Any, registry: Dict[str, CellMaker]):
    if not isinstance(gate_json, Dict):
        raise ValueError(
            f'Custom gate json must be a dictionary.\n' f'Custom gate json={gate_json!r}.'
        )

    if 'id' not in gate_json:
        raise ValueError(
            f'Custom gate json must have an id key.\n' f'Custom gate json={gate_json!r}.'
        )
    identifier = gate_json['id']
    if identifier in registry:
        raise ValueError(f'Custom gate with duplicate identifier: {identifier!r}')

    if 'matrix' in gate_json and 'circuit' in gate_json:
        raise ValueError(
            f'Custom gate json cannot have both a matrix and a circuit.\n'
            f'Custom gate json={gate_json!r}.'
        )

    if 'matrix' in gate_json:
        if not isinstance(gate_json['matrix'], str):
            raise ValueError(
                f'Custom gate matrix json must be a string.\n' f'Custom gate json={gate_json!r}.'
            )
        gate = ops.MatrixGate(parse_matrix(gate_json['matrix']))
        registry[identifier] = CellMaker(
            identifier=identifier,
            size=gate.num_qubits(),
            maker=lambda args: gate(*args.qubits[::-1]),
        )

    elif 'circuit' in gate_json:
        comp = _parse_cols_into_composite_cell(gate_json['circuit'], registry)
        registry[identifier] = CellMaker(
            identifier=identifier,
            size=comp.height,
            maker=lambda args: comp.with_line_qubits_mapped_to(list(args.qubits)),
        )

    else:
        raise ValueError(
            f'Custom gate json must have a matrix or a circuit.\n'
            f'Custom gate json={gate_json!r}.'
        )