Exemple #1
0
def serialize(serializer: str, num_gates: int, nesting_depth: int) -> int:
    """"Runs a round-trip of the serializer."""
    circuit = cirq.Circuit()
    for _ in range(num_gates):
        which = np.random.choice(['expz', 'expw', 'exp11'])
        if which == 'expw':
            q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS))
            circuit.append(
                cirq.PhasedXPowGate(phase_exponent=np.random.random(),
                                    exponent=np.random.random()).on(q1))
        elif which == 'expz':
            q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS))
            circuit.append(cirq.Z(q1)**np.random.random())
        elif which == 'exp11':
            q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS - 1))
            q2 = cirq.GridQubit(0, q1.col + 1)
            circuit.append(cirq.CZ(q1, q2)**np.random.random())
    cs = [circuit]
    for _ in range(1, nesting_depth):
        fc = cs[-1].freeze()
        cs.append(cirq.Circuit(fc.to_op(), fc.to_op()))
    test_circuit = cs[-1]

    if serializer == _JSON:
        json_data = cirq.to_json(test_circuit)
        assert json_data is not None
        data_size = len(json_data)
        cirq.read_json(json_text=json_data)
    elif serializer == _JSON_GZIP:
        gzip_data = cirq.to_json_gzip(test_circuit)
        assert gzip_data is not None
        data_size = len(gzip_data)
        cirq.read_json_gzip(gzip_raw=gzip_data)
    return data_size
Exemple #2
0
def test_to_from_json_gzip():
    a, b = cirq.LineQubit.range(2)
    test_circuit = cirq.Circuit(cirq.H(a), cirq.CX(a, b))
    gzip_data = cirq.to_json_gzip(test_circuit)
    unzip_circuit = cirq.read_json_gzip(gzip_raw=gzip_data)
    assert test_circuit == unzip_circuit

    with pytest.raises(ValueError):
        _ = cirq.read_json_gzip(io.StringIO(), gzip_raw=gzip_data)
    with pytest.raises(ValueError):
        _ = cirq.read_json_gzip()
Exemple #3
0
def test_execute(tmpdir, run_id_in):
    rt_config = cg.QuantumRuntimeConfiguration(
        processor_record=cg.SimulatedProcessorWithLocalDeviceRecord('rainbow'),
        run_id=run_id_in,
        qubit_placer=cg.NaiveQubitPlacer(),
    )
    executable_group = cg.QuantumExecutableGroup(_get_quantum_executables())
    returned_exegroup_result = cg.execute(rt_config=rt_config,
                                          executable_group=executable_group,
                                          base_data_dir=tmpdir)
    run_id = returned_exegroup_result.shared_runtime_info.run_id
    if run_id_in is not None:
        assert run_id_in == run_id
    else:
        assert isinstance(uuid.UUID(run_id), uuid.UUID)

    manual_exegroup_result = _load_result_by_hand(tmpdir, run_id)
    egr_record: cg.ExecutableGroupResultFilesystemRecord = cirq.read_json_gzip(
        f'{tmpdir}/{run_id}/ExecutableGroupResultFilesystemRecord.json.gz')
    exegroup_result: cg.ExecutableGroupResult = egr_record.load(
        base_data_dir=tmpdir)
    helper_loaded_result = cg.ExecutableGroupResultFilesystemRecord.from_json(
        run_id=run_id, base_data_dir=tmpdir).load(base_data_dir=tmpdir)

    # TODO(gh-4699): Don't null-out device once it's serializable.
    assert isinstance(returned_exegroup_result.shared_runtime_info.device,
                      cirq.Device)
    returned_exegroup_result.shared_runtime_info.device = None

    assert returned_exegroup_result == exegroup_result
    assert manual_exegroup_result == exegroup_result
    assert helper_loaded_result == exegroup_result
def test_execute(tmpdir, run_id_in, patch_cirq_default_resolvers):
    assert patch_cirq_default_resolvers
    rt_config = cg.QuantumRuntimeConfiguration(
        processor=_MockEngineProcessor(),
        run_id=run_id_in,
        qubit_placer=cg.NaiveQubitPlacer(),
    )
    executable_group = cg.QuantumExecutableGroup(_get_quantum_executables())
    returned_exegroup_result = cg.execute(rt_config=rt_config,
                                          executable_group=executable_group,
                                          base_data_dir=tmpdir)
    run_id = returned_exegroup_result.shared_runtime_info.run_id
    if run_id_in is not None:
        assert run_id_in == run_id
    else:
        assert isinstance(uuid.UUID(run_id), uuid.UUID)

    manual_exegroup_result = _load_result_by_hand(tmpdir, run_id)
    egr_record: cg.ExecutableGroupResultFilesystemRecord = cirq.read_json_gzip(
        f'{tmpdir}/{run_id}/ExecutableGroupResultFilesystemRecord.json.gz')
    exegroup_result: cg.ExecutableGroupResult = egr_record.load(
        base_data_dir=tmpdir)

    # TODO(gh-4699): Don't null-out device once it's serializable.
    assert isinstance(returned_exegroup_result.shared_runtime_info.device,
                      cg.SerializableDevice)
    returned_exegroup_result.shared_runtime_info.device = None

    assert returned_exegroup_result == exegroup_result
    assert manual_exegroup_result == exegroup_result
Exemple #5
0
def test_filesystem_saver(tmpdir, patch_cirq_default_resolvers):
    assert patch_cirq_default_resolvers
    run_id = 'asdf'
    fs_saver = _FilesystemSaver(base_data_dir=tmpdir, run_id=run_id)

    rt_config = cg.QuantumRuntimeConfiguration(
        processor=_MockEngineProcessor(), run_id=run_id)
    shared_rt_info = cg.SharedRuntimeInfo(run_id=run_id)
    fs_saver.initialize(rt_config, shared_rt_info=shared_rt_info)

    # Test 1: assert fs_saver.initialize() has worked.
    rt_config2 = cirq.read_json_gzip(
        f'{tmpdir}/{run_id}/QuantumRuntimeConfiguration.json.gz')
    shared_rt_info2 = cirq.read_json_gzip(
        f'{tmpdir}/{run_id}/SharedRuntimeInfo.json.gz')
    assert rt_config == rt_config2
    assert shared_rt_info == shared_rt_info2

    # Test 2: assert `consume_result()` works.
    # you shouldn't actually mutate run_id in the shared runtime info, but we want to test
    # updating the shared rt info object:
    shared_rt_info.run_id = 'updated_run_id'
    exe_result = cg.ExecutableResult(
        spec=None,
        runtime_info=cg.RuntimeInfo(execution_index=0),
        raw_data=cirq.Result(params=cirq.ParamResolver({}),
                             measurements={'z': np.ones((100, 5))}),
    )
    fs_saver.consume_result(exe_result=exe_result,
                            shared_rt_info=shared_rt_info)

    shared_rt_info3 = cirq.read_json_gzip(
        f'{tmpdir}/{run_id}/SharedRuntimeInfo.json.gz')
    exe_result3 = cirq.read_json_gzip(
        f'{tmpdir}/{run_id}/ExecutableResult.0.json.gz')
    assert shared_rt_info == shared_rt_info3
    assert exe_result == exe_result3

    # Test 3: assert loading egr_record works.
    egr_record: cg.ExecutableGroupResultFilesystemRecord = cirq.read_json_gzip(
        f'{fs_saver.data_dir}/ExecutableGroupResultFilesystemRecord.json.gz')
    assert egr_record == fs_saver.egr_record
    exegroup_result: cg.ExecutableGroupResult = egr_record.load(
        base_data_dir=tmpdir)
    assert exegroup_result.shared_runtime_info == shared_rt_info
    assert exegroup_result.runtime_configuration == rt_config
    assert exegroup_result.executable_results[0] == exe_result
Exemple #6
0
def test_pathlib_paths(tmpdir):
    path = pathlib.Path(tmpdir) / 'op.json'
    cirq.to_json(cirq.X, path)
    assert cirq.read_json(path) == cirq.X

    gzip_path = pathlib.Path(tmpdir) / 'op.gz'
    cirq.to_json_gzip(cirq.X, gzip_path)
    assert cirq.read_json_gzip(gzip_path) == cirq.X
def _load_result_by_hand(tmpdir: str, run_id: str) -> cg.ExecutableGroupResult:
    """Load `ExecutableGroupResult` "by hand" without using
    `ExecutableGroupResultFilesystemRecord`."""
    rt_config = cirq.read_json_gzip(f'{tmpdir}/{run_id}/QuantumRuntimeConfiguration.json.gz')
    shared_rt_info = cirq.read_json_gzip(f'{tmpdir}/{run_id}/SharedRuntimeInfo.json.gz')
    fns = glob.glob(f'{tmpdir}/{run_id}/ExecutableResult.*.json.gz')
    fns = sorted(
        fns,
        key=lambda s: int(cast(Any, re.search(r'ExecutableResult\.(\d+)\.json\.gz$', s)).group(1)),
    )
    assert len(fns) == 3
    exe_results: List[cg.ExecutableResult] = [cirq.read_json_gzip(fn) for fn in fns]
    return cg.ExecutableGroupResult(
        runtime_configuration=rt_config,
        shared_runtime_info=shared_rt_info,
        executable_results=exe_results,
    )
Exemple #8
0
    def load(self, *, base_data_dir: str = ".") -> 'cg.ExecutableGroupResult':
        """Using the filename references in this dataclass, load a `cg.ExecutableGroupResult`
        from its constituent parts.

        Args:
            base_data_dir: The base data directory. Files should be found at
                {base_data_dir}/{run_id}/{this class's paths}
        """
        data_dir = f"{base_data_dir}/{self.run_id}"
        from cirq_google.workflow.quantum_runtime import ExecutableGroupResult

        return ExecutableGroupResult(
            runtime_configuration=cirq.read_json_gzip(
                f'{data_dir}/{self.runtime_configuration_path}'),
            shared_runtime_info=cirq.read_json_gzip(
                f'{data_dir}/{self.shared_runtime_info_path}'),
            executable_results=[
                cirq.read_json_gzip(f'{data_dir}/{exe_path}')
                for exe_path in self.executable_result_paths
            ],
        )
Exemple #9
0
def test_op_roundtrip_filename(tmpdir):
    filename = f'{tmpdir}/op.json'
    q = cirq.LineQubit(5)
    op1 = cirq.rx(0.123).on(q)
    cirq.to_json(op1, filename)
    assert os.path.exists(filename)
    op2 = cirq.read_json(filename)
    assert op1 == op2

    gzip_filename = f'{tmpdir}/op.gz'
    cirq.to_json_gzip(op1, gzip_filename)
    assert os.path.exists(gzip_filename)
    op3 = cirq.read_json_gzip(gzip_filename)
    assert op1 == op3
Exemple #10
0
def test_op_roundtrip_file_obj(tmpdir):
    filename = f'{tmpdir}/op.json'
    q = cirq.LineQubit(5)
    op1 = cirq.rx(0.123).on(q)
    with open(filename, 'w+') as file:
        cirq.to_json(op1, file)
        assert os.path.exists(filename)
        file.seek(0)
        op2 = cirq.read_json(file)
        assert op1 == op2

    gzip_filename = f'{tmpdir}/op.gz'
    with open(gzip_filename, 'w+b') as gzip_file:
        cirq.to_json_gzip(op1, gzip_file)
        assert os.path.exists(gzip_filename)
        gzip_file.seek(0)
        op3 = cirq.read_json_gzip(gzip_file)
        assert op1 == op3
Exemple #11
0
    def from_json(
            cls,
            *,
            run_id: str,
            base_data_dir: str = "."
    ) -> 'ExecutableGroupResultFilesystemRecord':
        fn = f'{base_data_dir}/{run_id}/ExecutableGroupResultFilesystemRecord.json.gz'
        egr_record = cirq.read_json_gzip(fn)
        if not isinstance(egr_record, cls):
            raise ValueError(
                f"The file located at {fn} is not an `ExecutableGroupFilesystemRecord`."
            )
        if egr_record.run_id != run_id:
            raise ValueError(
                f"The loaded run_id {run_id} does not match the provided run_id {run_id}"
            )

        return egr_record
def test_execute(tmpdir, rt_config):
    executable_group = cg.QuantumExecutableGroup(_get_quantum_executables())
    returned_exegroup_result = cg.execute(
        rt_config=rt_config, executable_group=executable_group, base_data_dir=tmpdir
    )
    run_id = returned_exegroup_result.shared_runtime_info.run_id
    if rt_config.run_id is not None:
        assert run_id == 'unit-test'
    else:
        assert isinstance(uuid.UUID(run_id), uuid.UUID)

    start_dt = returned_exegroup_result.shared_runtime_info.run_start_time
    end_dt = returned_exegroup_result.shared_runtime_info.run_end_time
    assert end_dt > start_dt
    assert end_dt <= datetime.datetime.now(tz=datetime.timezone.utc)

    manual_exegroup_result = _load_result_by_hand(tmpdir, run_id)
    egr_record: cg.ExecutableGroupResultFilesystemRecord = cirq.read_json_gzip(
        f'{tmpdir}/{run_id}/ExecutableGroupResultFilesystemRecord.json.gz'
    )
    exegroup_result: cg.ExecutableGroupResult = egr_record.load(base_data_dir=tmpdir)
    helper_loaded_result = cg.ExecutableGroupResultFilesystemRecord.from_json(
        run_id=run_id, base_data_dir=tmpdir
    ).load(base_data_dir=tmpdir)

    # TODO(gh-4699): Don't null-out device once it's serializable.
    assert isinstance(returned_exegroup_result.shared_runtime_info.device, cirq.Device)
    returned_exegroup_result.shared_runtime_info.device = None

    assert returned_exegroup_result == exegroup_result
    assert manual_exegroup_result == exegroup_result
    assert helper_loaded_result == exegroup_result

    exe_result = returned_exegroup_result.executable_results[0]
    assert 'placement' in exe_result.runtime_info.timings_s
    assert 'run' in exe_result.runtime_info.timings_s
Exemple #13
0
def _assert_json_roundtrip(o, tmpdir):
    cirq.to_json_gzip(o, f'{tmpdir}/o.json')
    o2 = cirq.read_json_gzip(f'{tmpdir}/o.json')
    assert o == o2
def _cg_read_json_gzip(fn):
    return cirq.read_json_gzip(fn,
                               resolvers=[_testing_resolver] +
                               cirq.DEFAULT_RESOLVERS)