We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
float32 parameters leads to significant performance loss of parameter resolver
**Description of the issue**
Calling `cirq.resolve_parameters` to resolve the parameters of a symbolic circuit with `np.float32` parameters leads to a significant performance loss. I ran into this bug while working on loading circuit parameters from a `.npy` file on [this TensorQuantum Dataset PR](https://github.com/tensorflow/quantum/pull/304). Verifying that the circuits produced the expected wave functions took ~30 minutes on the CI, since we have to check hundreds of circuits. On further investigation, I discovered that the parameters were 32-bit, and casting them to 64-bit decreased the parameter resolve time by a large margin.

**How to reproduce the issue**

```python

import cirq
import sympy
import time
import numpy as np
from collections import namedtuple
import matplotlib.pyplot as plt


def unique_name():
    """Generator to generate an infinite number of unique names.

    Yields:
        Python `str` of the form "theta_<integer>".

    """
    num = 0
    while True:
        yield "theta_" + str(num)
        num += 1


def time_resolve_param(dtype, nspins, max_depth):
    depth_grid = list(range(2, max_depth, 2))
    times = []
    for depth in depth_grid:
        qubits = cirq.GridQubit.rect(nspins, 1)

        # Symbolic parameters
        name_generator = unique_name()
        symbol_names = [next(name_generator) for _ in range(depth)]
        symbols = [sympy.Symbol(name) for name in symbol_names]

        # Random values with dtype
        params = np.random.randn(2 * depth).astype(dtype)
        params = dict(zip(symbol_names, params.flatten()))

        # Define the circuit.
        circuit = cirq.Circuit(cirq.H.on_each(qubits))
        zipped_qubits = list(zip(qubits, qubits[1:]))
        for d in range(depth):
            for q1, q2 in zipped_qubits:
                circuit.append(cirq.ZZ(q1, q2)**(symbols[d]))

        # Resolve parameters and time
        resolve_start = time.time()
        param_resolver = cirq.resolve_parameters(circuit, params)
        t_param = time.time() - resolve_start
        times.append(t_param)

    return depth_grid, times


if __name__ == "__main__":
    NSPINS = 10
    MAXDEPTH = 50
    grid, times_32 = time_resolve_param(np.float32, NSPINS, MAXDEPTH)
    _, times_64 = time_resolve_param(np.float64, NSPINS, MAXDEPTH)

    plt.plot(grid, times_32, label='np.float32')
    plt.plot(grid, times_64, label='np.float64')
    plt.xlabel('circuit depth')
    plt.ylabel('time (s)')
    plt.legend()
    plt.grid()
    plt.show()


```
This produces the following figure

![float32_vs_float64_paramresolver](https://user-images.githubusercontent.com/32705838/94204975-4edbe100-fe90-11ea-9d2a-630f10e31aba.png)

As we can see, with increasing circuit depth the time it takes to resolve the 32-bit parameters creates a massive slowdown.

**Cirq version**
Cirq 0.8.2


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `cirq/study/resolver.py`
Content:
```
1 # Copyright 2018 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 
15 """Resolves ParameterValues to assigned values."""
16 
17 from typing import Any, Dict, Iterator, Optional, TYPE_CHECKING, Union, cast
18 import numpy as np
19 import sympy
20 from cirq._compat import proper_repr
21 from cirq._doc import document
22 
23 if TYPE_CHECKING:
24     import cirq
25 
26 
27 ParamDictType = Dict['cirq.TParamKey', 'cirq.TParamVal']
28 document(
29     ParamDictType,  # type: ignore
30     """Dictionary from symbols to values.""")
31 
32 ParamResolverOrSimilarType = Union['cirq.ParamResolver', ParamDictType, None]
33 document(
34     ParamResolverOrSimilarType,  # type: ignore
35     """Something that can be used to turn parameters into values.""")
36 
37 
38 class ParamResolver:
39     """Resolves parameters to actual values.
40 
41     A parameter is a variable whose value has not been determined.
42     A ParamResolver is an object that can be used to assign values for these
43     variables.
44 
45     ParamResolvers are hashable.
46 
47     Attributes:
48         param_dict: A dictionary from the ParameterValue key (str) to its
49             assigned value.
50     """
51 
52     def __new__(cls, param_dict: 'cirq.ParamResolverOrSimilarType' = None):
53         if isinstance(param_dict, ParamResolver):
54             return param_dict
55         return super().__new__(cls)
56 
57     def __init__(self,
58                  param_dict: 'cirq.ParamResolverOrSimilarType' = None) -> None:
59         if hasattr(self, 'param_dict'):
60             return  # Already initialized. Got wrapped as part of the __new__.
61 
62         self._param_hash: Optional[int] = None
63         self.param_dict = cast(ParamDictType,
64                                {} if param_dict is None else param_dict)
65 
66     def value_of(self,
67                  value: Union['cirq.TParamKey', float]) -> 'cirq.TParamVal':
68         """Attempt to resolve a parameter to its assigned value.
69 
70         Floats are returned without modification.  Strings are resolved via
71         the parameter dictionary with exact match only.  Otherwise, strings
72         are considered to be sympy.Symbols with the name as the input string.
73 
74         A sympy.Symbol is first checked for exact match in the parameter
75         dictionary. Otherwise, it is treated as a sympy.Basic.
76 
77         A sympy.Basic is resolved using sympy substitution.
78 
79         Note that passing a formula to this resolver can be slow due to the
80         underlying sympy library.  For circuits relying on quick performance,
81         it is recommended that all formulas are flattened before-hand using
82         cirq.flatten or other means so that formula resolution is avoided.
83         If unable to resolve a sympy.Symbol, returns it unchanged.
84         If unable to resolve a name, returns a sympy.Symbol with that name.
85 
86         Args:
87             value: The parameter to try to resolve.
88 
89         Returns:
90             The value of the parameter as resolved by this resolver.
91         """
92         # Input is a float, no resolution needed: return early
93         if isinstance(value, float):
94             return value
95 
96         # Handles 2 cases:
97         # Input is a string and maps to a number in the dictionary
98         # Input is a symbol and maps to a number in the dictionary
99         # In both cases, return it directly.
100         if value in self.param_dict:
101             param_value = self.param_dict[value]
102             if isinstance(param_value, (float, int)):
103                 return param_value
104 
105         # Input is a string and is not in the dictionary.
106         # Treat it as a symbol instead.
107         if isinstance(value, str):
108             # If the string is in the param_dict as a value, return it.
109             # Otherwise, try using the symbol instead.
110             return self.value_of(sympy.Symbol(value))
111 
112         # Input is a symbol (sympy.Symbol('a')) and its string maps to a number
113         # in the dictionary ({'a': 1.0}).  Return it.
114         if (isinstance(value, sympy.Symbol) and value.name in self.param_dict):
115             param_value = self.param_dict[value.name]
116             if isinstance(param_value, (float, int)):
117                 return param_value
118 
119         # The following resolves common sympy expressions
120         # If sympy did its job and wasn't slower than molasses,
121         # we wouldn't need the following block.
122         if isinstance(value, sympy.Add):
123             summation = self.value_of(value.args[0])
124             for addend in value.args[1:]:
125                 summation += self.value_of(addend)
126             return summation
127         if isinstance(value, sympy.Mul):
128             product = self.value_of(value.args[0])
129             for factor in value.args[1:]:
130                 product *= self.value_of(factor)
131             return product
132         if isinstance(value, sympy.Pow) and len(value.args) == 2:
133             return np.power(self.value_of(value.args[0]),
134                             self.value_of(value.args[1]))
135         if value == sympy.pi:
136             return np.pi
137         if value == sympy.S.NegativeOne:
138             return -1
139 
140         # Input is either a sympy formula or the dictionary maps to a
141         # formula.  Use sympy to resolve the value.
142         # Note that sympy.subs() is slow, so we want to avoid this and
143         # only use it for cases that require complicated resolution.
144         if isinstance(value, sympy.Basic):
145             v = value.subs(self.param_dict)
146             if v.free_symbols:
147                 return v
148             elif sympy.im(v):
149                 return complex(v)
150             else:
151                 return float(v)
152 
153         # No known way to resolve this variable, return unchanged.
154         return value
155 
156     def __iter__(self) -> Iterator[Union[str, sympy.Symbol]]:
157         return iter(self.param_dict)
158 
159     def __bool__(self) -> bool:
160         return bool(self.param_dict)
161 
162     def __getitem__(self,
163                     key: Union[sympy.Basic, float, str]) -> 'cirq.TParamVal':
164         return self.value_of(key)
165 
166     def __hash__(self) -> int:
167         if self._param_hash is None:
168             self._param_hash = hash(frozenset(self.param_dict.items()))
169         return self._param_hash
170 
171     def __eq__(self, other):
172         if not isinstance(other, ParamResolver):
173             return NotImplemented
174         return self.param_dict == other.param_dict
175 
176     def __ne__(self, other):
177         return not self == other
178 
179     def __repr__(self) -> str:
180         param_dict_repr = ('{' + ', '.join([
181             f'{proper_repr(k)}: {proper_repr(v)}'
182             for k, v in self.param_dict.items()
183         ]) + '}')
184         return f'cirq.ParamResolver({param_dict_repr})'
185 
186     def _json_dict_(self) -> Dict[str, Any]:
187         return {
188             'cirq_type': self.__class__.__name__,
189             # JSON requires mappings to have keys of basic types.
190             'param_dict': list(self.param_dict.items())
191         }
192 
193     @classmethod
194     def _from_json_dict_(cls, param_dict, **kwargs):
195         return cls(dict(param_dict))
196
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/cirq/study/resolver.py b/cirq/study/resolver.py
--- a/cirq/study/resolver.py
+++ b/cirq/study/resolver.py
@@ -13,7 +13,7 @@
 # limitations under the License.
 
 """Resolves ParameterValues to assigned values."""
-
+import numbers
 from typing import Any, Dict, Iterator, Optional, TYPE_CHECKING, Union, cast
 import numpy as np
 import sympy
@@ -89,9 +89,11 @@
         Returns:
             The value of the parameter as resolved by this resolver.
         """
-        # Input is a float, no resolution needed: return early
-        if isinstance(value, float):
-            return value
+
+        # Input is a pass through type, no resolution needed: return early
+        v = _sympy_pass_through(value)
+        if v is not None:
+            return v
 
         # Handles 2 cases:
         # Input is a string and maps to a number in the dictionary
@@ -99,8 +101,9 @@
         # In both cases, return it directly.
         if value in self.param_dict:
             param_value = self.param_dict[value]
-            if isinstance(param_value, (float, int)):
-                return param_value
+            v = _sympy_pass_through(param_value)
+            if v is not None:
+                return v
 
         # Input is a string and is not in the dictionary.
         # Treat it as a symbol instead.
@@ -111,10 +114,11 @@
 
         # Input is a symbol (sympy.Symbol('a')) and its string maps to a number
         # in the dictionary ({'a': 1.0}).  Return it.
-        if (isinstance(value, sympy.Symbol) and value.name in self.param_dict):
+        if isinstance(value, sympy.Symbol) and value.name in self.param_dict:
             param_value = self.param_dict[value.name]
-            if isinstance(param_value, (float, int)):
-                return param_value
+            v = _sympy_pass_through(param_value)
+            if v is not None:
+                return v
 
         # The following resolves common sympy expressions
         # If sympy did its job and wasn't slower than molasses,
@@ -132,10 +136,6 @@
         if isinstance(value, sympy.Pow) and len(value.args) == 2:
             return np.power(self.value_of(value.args[0]),
                             self.value_of(value.args[1]))
-        if value == sympy.pi:
-            return np.pi
-        if value == sympy.S.NegativeOne:
-            return -1
 
         # Input is either a sympy formula or the dictionary maps to a
         # formula.  Use sympy to resolve the value.
@@ -193,3 +193,15 @@
     @classmethod
     def _from_json_dict_(cls, param_dict, **kwargs):
         return cls(dict(param_dict))
+
+
+def _sympy_pass_through(val: Any) -> Optional[Any]:
+    if isinstance(val, numbers.Number) and not isinstance(val, sympy.Basic):
+        return val
+    if isinstance(val, sympy.core.numbers.IntegerConstant):
+        return val.p
+    if isinstance(val, sympy.core.numbers.RationalConstant):
+        return val.p / val.q
+    if val == sympy.pi:
+        return np.pi
+    return None

{"golden_diff": "diff --git a/cirq/study/resolver.py b/cirq/study/resolver.py\n--- a/cirq/study/resolver.py\n+++ b/cirq/study/resolver.py\n@@ -13,7 +13,7 @@\n # limitations under the License.\n \n \"\"\"Resolves ParameterValues to assigned values.\"\"\"\n-\n+import numbers\n from typing import Any, Dict, Iterator, Optional, TYPE_CHECKING, Union, cast\n import numpy as np\n import sympy\n@@ -89,9 +89,11 @@\n         Returns:\n             The value of the parameter as resolved by this resolver.\n         \"\"\"\n-        # Input is a float, no resolution needed: return early\n-        if isinstance(value, float):\n-            return value\n+\n+        # Input is a pass through type, no resolution needed: return early\n+        v = _sympy_pass_through(value)\n+        if v is not None:\n+            return v\n \n         # Handles 2 cases:\n         # Input is a string and maps to a number in the dictionary\n@@ -99,8 +101,9 @@\n         # In both cases, return it directly.\n         if value in self.param_dict:\n             param_value = self.param_dict[value]\n-            if isinstance(param_value, (float, int)):\n-                return param_value\n+            v = _sympy_pass_through(param_value)\n+            if v is not None:\n+                return v\n \n         # Input is a string and is not in the dictionary.\n         # Treat it as a symbol instead.\n@@ -111,10 +114,11 @@\n \n         # Input is a symbol (sympy.Symbol('a')) and its string maps to a number\n         # in the dictionary ({'a': 1.0}).  Return it.\n-        if (isinstance(value, sympy.Symbol) and value.name in self.param_dict):\n+        if isinstance(value, sympy.Symbol) and value.name in self.param_dict:\n             param_value = self.param_dict[value.name]\n-            if isinstance(param_value, (float, int)):\n-                return param_value\n+            v = _sympy_pass_through(param_value)\n+            if v is not None:\n+                return v\n \n         # The following resolves common sympy expressions\n         # If sympy did its job and wasn't slower than molasses,\n@@ -132,10 +136,6 @@\n         if isinstance(value, sympy.Pow) and len(value.args) == 2:\n             return np.power(self.value_of(value.args[0]),\n                             self.value_of(value.args[1]))\n-        if value == sympy.pi:\n-            return np.pi\n-        if value == sympy.S.NegativeOne:\n-            return -1\n \n         # Input is either a sympy formula or the dictionary maps to a\n         # formula.  Use sympy to resolve the value.\n@@ -193,3 +193,15 @@\n     @classmethod\n     def _from_json_dict_(cls, param_dict, **kwargs):\n         return cls(dict(param_dict))\n+\n+\n+def _sympy_pass_through(val: Any) -> Optional[Any]:\n+    if isinstance(val, numbers.Number) and not isinstance(val, sympy.Basic):\n+        return val\n+    if isinstance(val, sympy.core.numbers.IntegerConstant):\n+        return val.p\n+    if isinstance(val, sympy.core.numbers.RationalConstant):\n+        return val.p / val.q\n+    if val == sympy.pi:\n+        return np.pi\n+    return None\n", "issue": "float32 parameters leads to significant performance loss of parameter resolver\n**Description of the issue**\r\nCalling `cirq.resolve_parameters` to resolve the parameters of a symbolic circuit with `np.float32` parameters leads to a significant performance loss. I ran into this bug while working on loading circuit parameters from a `.npy` file on [this TensorQuantum Dataset PR](https://github.com/tensorflow/quantum/pull/304). Verifying that the circuits produced the expected wave functions took ~30 minutes on the CI, since we have to check hundreds of circuits. On further investigation, I discovered that the parameters were 32-bit, and casting them to 64-bit decreased the parameter resolve time by a large margin.\r\n\r\n**How to reproduce the issue**\r\n\r\n```python\r\n\r\nimport cirq\r\nimport sympy\r\nimport time\r\nimport numpy as np\r\nfrom collections import namedtuple\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef unique_name():\r\n    \"\"\"Generator to generate an infinite number of unique names.\r\n\r\n    Yields:\r\n        Python `str` of the form \"theta_<integer>\".\r\n\r\n    \"\"\"\r\n    num = 0\r\n    while True:\r\n        yield \"theta_\" + str(num)\r\n        num += 1\r\n\r\n\r\ndef time_resolve_param(dtype, nspins, max_depth):\r\n    depth_grid = list(range(2, max_depth, 2))\r\n    times = []\r\n    for depth in depth_grid:\r\n        qubits = cirq.GridQubit.rect(nspins, 1)\r\n\r\n        # Symbolic parameters\r\n        name_generator = unique_name()\r\n        symbol_names = [next(name_generator) for _ in range(depth)]\r\n        symbols = [sympy.Symbol(name) for name in symbol_names]\r\n\r\n        # Random values with dtype\r\n        params = np.random.randn(2 * depth).astype(dtype)\r\n        params = dict(zip(symbol_names, params.flatten()))\r\n\r\n        # Define the circuit.\r\n        circuit = cirq.Circuit(cirq.H.on_each(qubits))\r\n        zipped_qubits = list(zip(qubits, qubits[1:]))\r\n        for d in range(depth):\r\n            for q1, q2 in zipped_qubits:\r\n                circuit.append(cirq.ZZ(q1, q2)**(symbols[d]))\r\n\r\n        # Resolve parameters and time\r\n        resolve_start = time.time()\r\n        param_resolver = cirq.resolve_parameters(circuit, params)\r\n        t_param = time.time() - resolve_start\r\n        times.append(t_param)\r\n\r\n    return depth_grid, times\r\n\r\n\r\nif __name__ == \"__main__\":\r\n    NSPINS = 10\r\n    MAXDEPTH = 50\r\n    grid, times_32 = time_resolve_param(np.float32, NSPINS, MAXDEPTH)\r\n    _, times_64 = time_resolve_param(np.float64, NSPINS, MAXDEPTH)\r\n\r\n    plt.plot(grid, times_32, label='np.float32')\r\n    plt.plot(grid, times_64, label='np.float64')\r\n    plt.xlabel('circuit depth')\r\n    plt.ylabel('time (s)')\r\n    plt.legend()\r\n    plt.grid()\r\n    plt.show()\r\n\r\n\r\n```\r\nThis produces the following figure\r\n\r\n![float32_vs_float64_paramresolver](https://user-images.githubusercontent.com/32705838/94204975-4edbe100-fe90-11ea-9d2a-630f10e31aba.png)\r\n\r\nAs we can see, with increasing circuit depth the time it takes to resolve the 32-bit parameters creates a massive slowdown.\r\n\r\n**Cirq version**\r\nCirq 0.8.2\r\n\n", "before_files": [{"content": "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Resolves ParameterValues to assigned values.\"\"\"\n\nfrom typing import Any, Dict, Iterator, Optional, TYPE_CHECKING, Union, cast\nimport numpy as np\nimport sympy\nfrom cirq._compat import proper_repr\nfrom cirq._doc import document\n\nif TYPE_CHECKING:\n    import cirq\n\n\nParamDictType = Dict['cirq.TParamKey', 'cirq.TParamVal']\ndocument(\n    ParamDictType,  # type: ignore\n    \"\"\"Dictionary from symbols to values.\"\"\")\n\nParamResolverOrSimilarType = Union['cirq.ParamResolver', ParamDictType, None]\ndocument(\n    ParamResolverOrSimilarType,  # type: ignore\n    \"\"\"Something that can be used to turn parameters into values.\"\"\")\n\n\nclass ParamResolver:\n    \"\"\"Resolves parameters to actual values.\n\n    A parameter is a variable whose value has not been determined.\n    A ParamResolver is an object that can be used to assign values for these\n    variables.\n\n    ParamResolvers are hashable.\n\n    Attributes:\n        param_dict: A dictionary from the ParameterValue key (str) to its\n            assigned value.\n    \"\"\"\n\n    def __new__(cls, param_dict: 'cirq.ParamResolverOrSimilarType' = None):\n        if isinstance(param_dict, ParamResolver):\n            return param_dict\n        return super().__new__(cls)\n\n    def __init__(self,\n                 param_dict: 'cirq.ParamResolverOrSimilarType' = None) -> None:\n        if hasattr(self, 'param_dict'):\n            return  # Already initialized. Got wrapped as part of the __new__.\n\n        self._param_hash: Optional[int] = None\n        self.param_dict = cast(ParamDictType,\n                               {} if param_dict is None else param_dict)\n\n    def value_of(self,\n                 value: Union['cirq.TParamKey', float]) -> 'cirq.TParamVal':\n        \"\"\"Attempt to resolve a parameter to its assigned value.\n\n        Floats are returned without modification.  Strings are resolved via\n        the parameter dictionary with exact match only.  Otherwise, strings\n        are considered to be sympy.Symbols with the name as the input string.\n\n        A sympy.Symbol is first checked for exact match in the parameter\n        dictionary. Otherwise, it is treated as a sympy.Basic.\n\n        A sympy.Basic is resolved using sympy substitution.\n\n        Note that passing a formula to this resolver can be slow due to the\n        underlying sympy library.  For circuits relying on quick performance,\n        it is recommended that all formulas are flattened before-hand using\n        cirq.flatten or other means so that formula resolution is avoided.\n        If unable to resolve a sympy.Symbol, returns it unchanged.\n        If unable to resolve a name, returns a sympy.Symbol with that name.\n\n        Args:\n            value: The parameter to try to resolve.\n\n        Returns:\n            The value of the parameter as resolved by this resolver.\n        \"\"\"\n        # Input is a float, no resolution needed: return early\n        if isinstance(value, float):\n            return value\n\n        # Handles 2 cases:\n        # Input is a string and maps to a number in the dictionary\n        # Input is a symbol and maps to a number in the dictionary\n        # In both cases, return it directly.\n        if value in self.param_dict:\n            param_value = self.param_dict[value]\n            if isinstance(param_value, (float, int)):\n                return param_value\n\n        # Input is a string and is not in the dictionary.\n        # Treat it as a symbol instead.\n        if isinstance(value, str):\n            # If the string is in the param_dict as a value, return it.\n            # Otherwise, try using the symbol instead.\n            return self.value_of(sympy.Symbol(value))\n\n        # Input is a symbol (sympy.Symbol('a')) and its string maps to a number\n        # in the dictionary ({'a': 1.0}).  Return it.\n        if (isinstance(value, sympy.Symbol) and value.name in self.param_dict):\n            param_value = self.param_dict[value.name]\n            if isinstance(param_value, (float, int)):\n                return param_value\n\n        # The following resolves common sympy expressions\n        # If sympy did its job and wasn't slower than molasses,\n        # we wouldn't need the following block.\n        if isinstance(value, sympy.Add):\n            summation = self.value_of(value.args[0])\n            for addend in value.args[1:]:\n                summation += self.value_of(addend)\n            return summation\n        if isinstance(value, sympy.Mul):\n            product = self.value_of(value.args[0])\n            for factor in value.args[1:]:\n                product *= self.value_of(factor)\n            return product\n        if isinstance(value, sympy.Pow) and len(value.args) == 2:\n            return np.power(self.value_of(value.args[0]),\n                            self.value_of(value.args[1]))\n        if value == sympy.pi:\n            return np.pi\n        if value == sympy.S.NegativeOne:\n            return -1\n\n        # Input is either a sympy formula or the dictionary maps to a\n        # formula.  Use sympy to resolve the value.\n        # Note that sympy.subs() is slow, so we want to avoid this and\n        # only use it for cases that require complicated resolution.\n        if isinstance(value, sympy.Basic):\n            v = value.subs(self.param_dict)\n            if v.free_symbols:\n                return v\n            elif sympy.im(v):\n                return complex(v)\n            else:\n                return float(v)\n\n        # No known way to resolve this variable, return unchanged.\n        return value\n\n    def __iter__(self) -> Iterator[Union[str, sympy.Symbol]]:\n        return iter(self.param_dict)\n\n    def __bool__(self) -> bool:\n        return bool(self.param_dict)\n\n    def __getitem__(self,\n                    key: Union[sympy.Basic, float, str]) -> 'cirq.TParamVal':\n        return self.value_of(key)\n\n    def __hash__(self) -> int:\n        if self._param_hash is None:\n            self._param_hash = hash(frozenset(self.param_dict.items()))\n        return self._param_hash\n\n    def __eq__(self, other):\n        if not isinstance(other, ParamResolver):\n            return NotImplemented\n        return self.param_dict == other.param_dict\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __repr__(self) -> str:\n        param_dict_repr = ('{' + ', '.join([\n            f'{proper_repr(k)}: {proper_repr(v)}'\n            for k, v in self.param_dict.items()\n        ]) + '}')\n        return f'cirq.ParamResolver({param_dict_repr})'\n\n    def _json_dict_(self) -> Dict[str, Any]:\n        return {\n            'cirq_type': self.__class__.__name__,\n            # JSON requires mappings to have keys of basic types.\n            'param_dict': list(self.param_dict.items())\n        }\n\n    @classmethod\n    def _from_json_dict_(cls, param_dict, **kwargs):\n        return cls(dict(param_dict))\n", "path": "cirq/study/resolver.py"}], "after_files": [{"content": "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Resolves ParameterValues to assigned values.\"\"\"\nimport numbers\nfrom typing import Any, Dict, Iterator, Optional, TYPE_CHECKING, Union, cast\nimport numpy as np\nimport sympy\nfrom cirq._compat import proper_repr\nfrom cirq._doc import document\n\nif TYPE_CHECKING:\n    import cirq\n\n\nParamDictType = Dict['cirq.TParamKey', 'cirq.TParamVal']\ndocument(\n    ParamDictType,  # type: ignore\n    \"\"\"Dictionary from symbols to values.\"\"\")\n\nParamResolverOrSimilarType = Union['cirq.ParamResolver', ParamDictType, None]\ndocument(\n    ParamResolverOrSimilarType,  # type: ignore\n    \"\"\"Something that can be used to turn parameters into values.\"\"\")\n\n\nclass ParamResolver:\n    \"\"\"Resolves parameters to actual values.\n\n    A parameter is a variable whose value has not been determined.\n    A ParamResolver is an object that can be used to assign values for these\n    variables.\n\n    ParamResolvers are hashable.\n\n    Attributes:\n        param_dict: A dictionary from the ParameterValue key (str) to its\n            assigned value.\n    \"\"\"\n\n    def __new__(cls, param_dict: 'cirq.ParamResolverOrSimilarType' = None):\n        if isinstance(param_dict, ParamResolver):\n            return param_dict\n        return super().__new__(cls)\n\n    def __init__(self,\n                 param_dict: 'cirq.ParamResolverOrSimilarType' = None) -> None:\n        if hasattr(self, 'param_dict'):\n            return  # Already initialized. Got wrapped as part of the __new__.\n\n        self._param_hash: Optional[int] = None\n        self.param_dict = cast(ParamDictType,\n                               {} if param_dict is None else param_dict)\n\n    def value_of(self,\n                 value: Union['cirq.TParamKey', float]) -> 'cirq.TParamVal':\n        \"\"\"Attempt to resolve a parameter to its assigned value.\n\n        Floats are returned without modification.  Strings are resolved via\n        the parameter dictionary with exact match only.  Otherwise, strings\n        are considered to be sympy.Symbols with the name as the input string.\n\n        A sympy.Symbol is first checked for exact match in the parameter\n        dictionary. Otherwise, it is treated as a sympy.Basic.\n\n        A sympy.Basic is resolved using sympy substitution.\n\n        Note that passing a formula to this resolver can be slow due to the\n        underlying sympy library.  For circuits relying on quick performance,\n        it is recommended that all formulas are flattened before-hand using\n        cirq.flatten or other means so that formula resolution is avoided.\n        If unable to resolve a sympy.Symbol, returns it unchanged.\n        If unable to resolve a name, returns a sympy.Symbol with that name.\n\n        Args:\n            value: The parameter to try to resolve.\n\n        Returns:\n            The value of the parameter as resolved by this resolver.\n        \"\"\"\n\n        # Input is a pass through type, no resolution needed: return early\n        v = _sympy_pass_through(value)\n        if v is not None:\n            return v\n\n        # Handles 2 cases:\n        # Input is a string and maps to a number in the dictionary\n        # Input is a symbol and maps to a number in the dictionary\n        # In both cases, return it directly.\n        if value in self.param_dict:\n            param_value = self.param_dict[value]\n            v = _sympy_pass_through(param_value)\n            if v is not None:\n                return v\n\n        # Input is a string and is not in the dictionary.\n        # Treat it as a symbol instead.\n        if isinstance(value, str):\n            # If the string is in the param_dict as a value, return it.\n            # Otherwise, try using the symbol instead.\n            return self.value_of(sympy.Symbol(value))\n\n        # Input is a symbol (sympy.Symbol('a')) and its string maps to a number\n        # in the dictionary ({'a': 1.0}).  Return it.\n        if isinstance(value, sympy.Symbol) and value.name in self.param_dict:\n            param_value = self.param_dict[value.name]\n            v = _sympy_pass_through(param_value)\n            if v is not None:\n                return v\n\n        # The following resolves common sympy expressions\n        # If sympy did its job and wasn't slower than molasses,\n        # we wouldn't need the following block.\n        if isinstance(value, sympy.Add):\n            summation = self.value_of(value.args[0])\n            for addend in value.args[1:]:\n                summation += self.value_of(addend)\n            return summation\n        if isinstance(value, sympy.Mul):\n            product = self.value_of(value.args[0])\n            for factor in value.args[1:]:\n                product *= self.value_of(factor)\n            return product\n        if isinstance(value, sympy.Pow) and len(value.args) == 2:\n            return np.power(self.value_of(value.args[0]),\n                            self.value_of(value.args[1]))\n\n        # Input is either a sympy formula or the dictionary maps to a\n        # formula.  Use sympy to resolve the value.\n        # Note that sympy.subs() is slow, so we want to avoid this and\n        # only use it for cases that require complicated resolution.\n        if isinstance(value, sympy.Basic):\n            v = value.subs(self.param_dict)\n            if v.free_symbols:\n                return v\n            elif sympy.im(v):\n                return complex(v)\n            else:\n                return float(v)\n\n        # No known way to resolve this variable, return unchanged.\n        return value\n\n    def __iter__(self) -> Iterator[Union[str, sympy.Symbol]]:\n        return iter(self.param_dict)\n\n    def __bool__(self) -> bool:\n        return bool(self.param_dict)\n\n    def __getitem__(self,\n                    key: Union[sympy.Basic, float, str]) -> 'cirq.TParamVal':\n        return self.value_of(key)\n\n    def __hash__(self) -> int:\n        if self._param_hash is None:\n            self._param_hash = hash(frozenset(self.param_dict.items()))\n        return self._param_hash\n\n    def __eq__(self, other):\n        if not isinstance(other, ParamResolver):\n            return NotImplemented\n        return self.param_dict == other.param_dict\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __repr__(self) -> str:\n        param_dict_repr = ('{' + ', '.join([\n            f'{proper_repr(k)}: {proper_repr(v)}'\n            for k, v in self.param_dict.items()\n        ]) + '}')\n        return f'cirq.ParamResolver({param_dict_repr})'\n\n    def _json_dict_(self) -> Dict[str, Any]:\n        return {\n            'cirq_type': self.__class__.__name__,\n            # JSON requires mappings to have keys of basic types.\n            'param_dict': list(self.param_dict.items())\n        }\n\n    @classmethod\n    def _from_json_dict_(cls, param_dict, **kwargs):\n        return cls(dict(param_dict))\n\n\ndef _sympy_pass_through(val: Any) -> Optional[Any]:\n    if isinstance(val, numbers.Number) and not isinstance(val, sympy.Basic):\n        return val\n    if isinstance(val, sympy.core.numbers.IntegerConstant):\n        return val.p\n    if isinstance(val, sympy.core.numbers.RationalConstant):\n        return val.p / val.q\n    if val == sympy.pi:\n        return np.pi\n    return None\n", "path": "cirq/study/resolver.py"}]}