Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions cirq-google/cirq_google/engine/engine_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,6 @@ async def _await_result_async(self) -> quantum.QuantumResult:

def _get_job_results_v1(self, result: v1.program_pb2.Result) -> Sequence[EngineResult]:
job_id = self.id()
job_finished = self.update_time()

trial_results = []
for sweep_result in result.sweep_results:
Expand All @@ -332,19 +331,17 @@ def _get_job_results_v1(self, result: v1.program_pb2.Result) -> Sequence[EngineR
params=cirq.ParamResolver(result.params.assignments),
measurements=measurements,
job_id=job_id,
job_finished_time=job_finished,
)
)
return trial_results

def _get_job_results_v2(self, result: v2.result_pb2.Result) -> Sequence[EngineResult]:
sweep_results = v2.results_from_proto(result)
job_id = self.id()
job_finished = self.update_time()

# Flatten to single list to match to sampler api.
return [
EngineResult.from_result(result, job_id=job_id, job_finished_time=job_finished)
EngineResult.from_result(result, job_id=job_id)
for sweep_result in sweep_results
for result in sweep_result
]
Expand Down
2 changes: 0 additions & 2 deletions cirq-google/cirq_google/engine/engine_processor_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,6 @@ def test_run_sweep_params_with_unary_rpcs(client):
assert results[i].measurements == {'q': np.array([[0]], dtype='uint8')}
for result in results:
assert result.job_id == job.id()
assert result.job_finished_time is not None
assert results == cirq.read_json(json_text=cirq.to_json(results))

client().create_program_async.assert_called_once()
Expand Down Expand Up @@ -943,7 +942,6 @@ def test_run_sweep_params_with_stream_rpcs(client):
assert results[i].measurements == {'q': np.array([[0]], dtype='uint8')}
for result in results:
assert result.job_id == job.id()
assert result.job_finished_time is not None
assert results == cirq.read_json(json_text=cirq.to_json(results))

client().run_job_over_stream.assert_called_once()
Expand Down
1 change: 0 additions & 1 deletion cirq-google/cirq_google/engine/engine_program_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,6 @@ def test_run_delegation(create_job_async, get_results_async):
params=cirq.ParamResolver({'a': 1.0}),
measurements={'q': np.array([[False], [True], [True], [False]], dtype=bool)},
job_id='steve',
job_finished_time=dt,
)


Expand Down
25 changes: 5 additions & 20 deletions cirq-google/cirq_google/engine/engine_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

from __future__ import annotations

import datetime
from typing import Any, Mapping, TYPE_CHECKING

from cirq import study
Expand All @@ -32,14 +31,12 @@ class EngineResult(study.ResultDict):

Additional Attributes:
job_id: A string job identifier.
job_finished_time: A timestamp for when the job finished.
"""

def __init__(
self,
*, # Forces keyword args.
job_id: str,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This resource seems to map to a QuantumResult API resource, but the class doesn't contain the unique identifier for that resource - job_id is only unique within a QuantumProgram parent, which is only unique within a GCP project.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, that's a pre-existing issue, but I could add more fields while I am here. What else should we add, if anything?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

project_id and program_id should be included as well and match the values in the parent EngineJob. Feel free to leave as a followup or file a bug since it's out of scope of this change if you aren't going to lazy load the timestamp of the job's completion.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I will do that in a follow-up.

job_finished_time: datetime.datetime,
params: study.ParamResolver | None = None,
measurements: Mapping[str, np.ndarray] | None = None,
records: Mapping[str, np.ndarray] | None = None,
Expand All @@ -48,7 +45,6 @@ def __init__(

Args:
job_id: A string job identifier.
job_finished_time: A timestamp for when the job finished; will be converted to UTC.
params: A ParamResolver of settings used for this result.
measurements: A dictionary from measurement gate key to measurement
results. See `cirq.ResultDict`.
Expand All @@ -57,44 +53,36 @@ def __init__(
"""
super().__init__(params=params, measurements=measurements, records=records)
self.job_id = job_id
self.job_finished_time = job_finished_time

@classmethod
def from_result(cls, result: cirq.Result, *, job_id: str, job_finished_time: datetime.datetime):
def from_result(cls, result: cirq.Result, *, job_id: str):
if isinstance(result, study.ResultDict):
# optimize by using private methods
return cls(
params=result._params,
measurements=result._measurements,
records=result._records,
job_id=job_id,
job_finished_time=job_finished_time,
)
else:
return cls(
params=result.params,
measurements=result.measurements,
records=result.records,
job_id=job_id,
job_finished_time=job_finished_time,
)

def __eq__(self, other):
if not isinstance(other, EngineResult):
return False

return (
super().__eq__(other)
and self.job_id == other.job_id
and self.job_finished_time == other.job_finished_time
)
return super().__eq__(other) and self.job_id == other.job_id

def __repr__(self) -> str:
return (
f'cirq_google.EngineResult(params={self.params!r}, '
f'records={self._record_dict_repr()}, '
f'job_id={self.job_id!r}, '
f'job_finished_time={self.job_finished_time!r})'
f'job_id={self.job_id!r})'
)

@classmethod
Expand All @@ -104,11 +92,8 @@ def _json_namespace_(cls) -> str:
def _json_dict_(self) -> dict[str, Any]:
d = super()._json_dict_()
d['job_id'] = self.job_id
d['job_finished_time'] = self.job_finished_time
return d

@classmethod
def _from_json_dict_(cls, params, records, job_id, job_finished_time, **kwargs):
return cls._from_packed_records(
params=params, records=records, job_id=job_id, job_finished_time=job_finished_time
)
def _from_json_dict_(cls, params, records, job_id, **kwargs):
return cls._from_packed_records(params=params, records=records, job_id=job_id)
11 changes: 2 additions & 9 deletions cirq-google/cirq_google/engine/engine_result_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,11 @@
def test_engine_result():
res = cg.EngineResult(
job_id='my_job_id',
job_finished_time=_DT,
params=None,
measurements={'a': np.array([[0, 0], [1, 1]]), 'b': np.array([[0, 0, 0], [1, 1, 1]])},
)

assert res.job_id == 'my_job_id'
assert res.job_finished_time <= datetime.datetime.now(tz=datetime.timezone.utc)
assert res.measurements['a'].shape == (2, 2)

cirq.testing.assert_equivalent_repr(res, global_vals={'cirq_google': cg})
Expand All @@ -46,7 +44,6 @@ def test_engine_result():
def test_engine_result_from_result_dict():
res = cg.EngineResult(
job_id='my_job_id',
job_finished_time=_DT,
params=None,
measurements={'a': np.array([[0, 0], [1, 1]]), 'b': np.array([[0, 0, 0], [1, 1, 1]])},
)
Expand All @@ -57,27 +54,24 @@ def test_engine_result_from_result_dict():
)
assert res2 != res
assert res != res2
assert res == cg.EngineResult.from_result(res2, job_id='my_job_id', job_finished_time=_DT)
assert res == cg.EngineResult.from_result(res2, job_id='my_job_id')


def test_engine_result_eq():
res1 = cg.EngineResult(
job_id='my_job_id',
job_finished_time=_DT,
params=None,
measurements={'a': np.array([[0, 0], [1, 1]]), 'b': np.array([[0, 0, 0], [1, 1, 1]])},
)
res2 = cg.EngineResult(
job_id='my_job_id',
job_finished_time=_DT,
params=None,
measurements={'a': np.array([[0, 0], [1, 1]]), 'b': np.array([[0, 0, 0], [1, 1, 1]])},
)
assert res1 == res2

res3 = cg.EngineResult(
job_id='my_other_job_id',
job_finished_time=_DT,
params=None,
measurements={'a': np.array([[0, 0], [1, 1]]), 'b': np.array([[0, 0, 0], [1, 1, 1]])},
)
Expand Down Expand Up @@ -105,10 +99,9 @@ def data(self) -> pd.DataFrame: # pragma: no cover
def test_engine_result_from_result():
res = cg.EngineResult(
job_id='my_job_id',
job_finished_time=_DT,
params=None,
measurements={'a': np.array([[0, 0], [1, 1]]), 'b': np.array([[0, 0, 0], [1, 1, 1]])},
)

res2 = MyResult()
assert res == cg.EngineResult.from_result(res2, job_id='my_job_id', job_finished_time=_DT)
assert res == cg.EngineResult.from_result(res2, job_id='my_job_id')
14 changes: 2 additions & 12 deletions cirq-google/cirq_google/engine/simulated_local_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
from __future__ import annotations

import concurrent.futures
import datetime
from typing import cast, Sequence

import duet
Expand All @@ -35,21 +34,12 @@ def _flatten_results(batch_results: Sequence[Sequence[EngineResult]]) -> list[En


def _to_engine_results(
batch_results: Sequence[Sequence[cirq.Result]],
*,
job_id: str,
job_finished_time: datetime.datetime | None = None,
batch_results: Sequence[Sequence[cirq.Result]], *, job_id: str
) -> list[list[EngineResult]]:
"""Convert cirq.Result from simulators into (simulated) EngineResults."""

if job_finished_time is None:
job_finished_time = datetime.datetime.now(tz=datetime.timezone.utc)

return [
[
EngineResult.from_result(result, job_id=job_id, job_finished_time=job_finished_time)
for result in batch
]
[EngineResult.from_result(result, job_id=job_id) for result in batch]
for batch in batch_results
]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,5 @@
]
}
},
"job_id": "my_job_id",
"job_finished_time": {
"cirq_type": "datetime.datetime",
"timestamp": 1648801425.0
}
}
"job_id": "my_job_id"
}
Original file line number Diff line number Diff line change
@@ -1 +1 @@
cirq_google.EngineResult(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[True, True, False, True, False]], [[False, True, True, False, False]], [[True, False, True, False, True]]], dtype=np.dtype('bool'))}, job_id='my_job_id', job_finished_time=datetime.datetime(2022, 4, 1, 8, 23, 45, tzinfo=datetime.timezone.utc))
cirq_google.EngineResult(params=cirq.ParamResolver({sympy.Symbol('a'): 0.5}), records={'m': np.array([[[True, True, False, True, False]], [[False, True, True, False, False]], [[True, False, True, False, True]]], dtype=np.dtype('bool'))}, job_id='my_job_id')