1# Copyright 2020 The Cirq Developers
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14#
15import dataclasses
16import datetime
17from typing import Any, Dict, Optional, TYPE_CHECKING
18
19if TYPE_CHECKING:
20    import cirq_google
21    import cirq
22    import cirq_google.api.v2.calibration_pb2 as calibration_pb2
23
24
25@dataclasses.dataclass
26class CalibrationResult:
27    """Python implementation of the proto found in
28    cirq_google.api.v2.calibration_pb2.CalibrationLayerResult for use
29    in Engine calls.
30
31    Note that, if these fields are not filled out by the calibration API,
32    they will be set to the default values in the proto, as defined here:
33    https://developers.google.com/protocol-buffers/docs/proto3#default
34    These defaults will converted to `None` by the API client.
35    """
36
37    code: 'calibration_pb2.CalibrationLayerCode'
38    error_message: Optional[str]
39    token: Optional[str]
40    valid_until: Optional[datetime.datetime]
41    metrics: 'cirq_google.Calibration'
42
43    @classmethod
44    def _from_json_dict_(
45        cls,
46        code: 'calibration_pb2.CalibrationLayerCode',
47        error_message: Optional[str],
48        token: Optional[str],
49        utc_valid_until: float,
50        metrics: 'cirq_google.Calibration',
51        **kwargs,
52    ) -> 'CalibrationResult':
53        """Magic method for the JSON serialization protocol."""
54        valid_until = (
55            datetime.datetime.utcfromtimestamp(utc_valid_until)
56            if utc_valid_until is not None
57            else None
58        )
59        return cls(code, error_message, token, valid_until, metrics)
60
61    def _json_dict_(self) -> Dict[str, Any]:
62        """Magic method for the JSON serialization protocol."""
63        utc_valid_until = (
64            self.valid_until.replace(tzinfo=datetime.timezone.utc).timestamp()
65            if self.valid_until is not None
66            else None
67        )
68        return {
69            'cirq_type': 'CalibrationResult',
70            'code': self.code,
71            'error_message': self.error_message,
72            'token': self.token,
73            'utc_valid_until': utc_valid_until,
74            'metrics': self.metrics,
75        }
76