We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
ParamResolver is slow
Reconstructing a circuit op-wise and replacing all parametrized ops with new ops containing parameter updates is 10-50x faster than using `cirq.ParamResolver` with sympy  symbols...

Example code to reproduce:
```
from timeit import default_timer as timer
import numpy as np
import sympy
import cirq


def update_params(circuit, params):
    """Competitor method to cirq.ParamResolver."""
    new_op_tree = []
    for op, param in zip(circuit.all_operations(), params):
        new_op_tree.append(op.gate._with_exponent(param/np.pi)(*op.qubits))
    return cirq.Circuit.from_ops(new_op_tree)


trials = 100
for depth in [10, 15, 20]:
    sympy_circuit = cirq.Circuit.from_ops([cirq.Rx(sympy.Symbol(str(k)))(cirq.LineQubit(0)) for k in range(depth)])
    random_params = np.random.randn(trials, depth)
    # time twenty runs
    start = timer()
    for j in range(trials):
        resolver = dict(zip([str(k) for k in range(depth)], random_params[j]))
        wf1 = cirq.Simulator().simulate(sympy_circuit, param_resolver=resolver).final_state
    end = timer() - start
    print(f"{depth} parameters, {trials} trials using Sympy+ParamResolver: {end} seconds")

    start = timer()
    for j in range(trials):
        float_circuit = update_params(sympy_circuit, random_params[j])
        wf2 = cirq.Simulator().simulate(float_circuit).final_state
    end = timer() - start
    print(f"{depth} parameters, {trials} trials using reconstructed circuit: {end} seconds")
```
produced (cirq v0.5.0, Windows 10 + core i7 gen 7 processor)
```
>>> 10 parameters, 100 trials using Sympy+ParamResolver: 2.408036000095308 seconds
>>> 10 parameters, 100 trials using reconstructed circuit: 0.1671589999459684 seconds
>>> 15 parameters, 100 trials using Sympy+ParamResolver: 4.347879000008106 seconds
>>> 15 parameters, 100 trials using reconstructed circuit: 0.25207799999043345 seconds
>>> 20 parameters, 100 trials using Sympy+ParamResolver: 7.1194350000005215 seconds
>>> 20 parameters, 100 trials using reconstructed circuit: 0.31734399998094887 seconds
```
Some plots of how this scales with large numbers of parameters (generated from a different script using the same `update_params` method):
![image](https://user-images.githubusercontent.com/14928221/62160823-b23ca400-b2c9-11e9-9073-666989fdea44.png)


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

{"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@@ -15,6 +15,7 @@\n \"\"\"Resolves ParameterValues to assigned values.\"\"\"\n \n from typing import Any, Dict, Iterator, Optional, TYPE_CHECKING, Union, cast\n+import numpy as np\n import sympy\n from cirq._compat import proper_repr\n from cirq._doc import document\n@@ -113,6 +114,27 @@\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", "issue": "ParamResolver is slow\nReconstructing a circuit op-wise and replacing all parametrized ops with new ops containing parameter updates is 10-50x faster than using `cirq.ParamResolver` with sympy  symbols...\r\n\r\nExample code to reproduce:\r\n```\r\nfrom timeit import default_timer as timer\r\nimport numpy as np\r\nimport sympy\r\nimport cirq\r\n\r\n\r\ndef update_params(circuit, params):\r\n    \"\"\"Competitor method to cirq.ParamResolver.\"\"\"\r\n    new_op_tree = []\r\n    for op, param in zip(circuit.all_operations(), params):\r\n        new_op_tree.append(op.gate._with_exponent(param/np.pi)(*op.qubits))\r\n    return cirq.Circuit.from_ops(new_op_tree)\r\n\r\n\r\ntrials = 100\r\nfor depth in [10, 15, 20]:\r\n    sympy_circuit = cirq.Circuit.from_ops([cirq.Rx(sympy.Symbol(str(k)))(cirq.LineQubit(0)) for k in range(depth)])\r\n    random_params = np.random.randn(trials, depth)\r\n    # time twenty runs\r\n    start = timer()\r\n    for j in range(trials):\r\n        resolver = dict(zip([str(k) for k in range(depth)], random_params[j]))\r\n        wf1 = cirq.Simulator().simulate(sympy_circuit, param_resolver=resolver).final_state\r\n    end = timer() - start\r\n    print(f\"{depth} parameters, {trials} trials using Sympy+ParamResolver: {end} seconds\")\r\n\r\n    start = timer()\r\n    for j in range(trials):\r\n        float_circuit = update_params(sympy_circuit, random_params[j])\r\n        wf2 = cirq.Simulator().simulate(float_circuit).final_state\r\n    end = timer() - start\r\n    print(f\"{depth} parameters, {trials} trials using reconstructed circuit: {end} seconds\")\r\n```\r\nproduced (cirq v0.5.0, Windows 10 + core i7 gen 7 processor)\r\n```\r\n>>> 10 parameters, 100 trials using Sympy+ParamResolver: 2.408036000095308 seconds\r\n>>> 10 parameters, 100 trials using reconstructed circuit: 0.1671589999459684 seconds\r\n>>> 15 parameters, 100 trials using Sympy+ParamResolver: 4.347879000008106 seconds\r\n>>> 15 parameters, 100 trials using reconstructed circuit: 0.25207799999043345 seconds\r\n>>> 20 parameters, 100 trials using Sympy+ParamResolver: 7.1194350000005215 seconds\r\n>>> 20 parameters, 100 trials using reconstructed circuit: 0.31734399998094887 seconds\r\n```\r\nSome plots of how this scales with large numbers of parameters (generated from a different script using the same `update_params` method):\r\n![image](https://user-images.githubusercontent.com/14928221/62160823-b23ca400-b2c9-11e9-9073-666989fdea44.png)\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 sympy\nfrom cirq._compat import proper_repr\nfrom cirq._doc import document\n\nif TYPE_CHECKING:\n    import cirq\n\n\nParamDictType = Dict[Union[str, sympy.Symbol], Union[float, str, sympy.Basic]]\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 sympy.Symbols to actual values.\n\n    A Symbol is a wrapped parameter name (str). A ParamResolver is an object\n    that can be used to assign values for these keys.\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[sympy.Basic, float, str]) -> 'cirq.TParamVal':\n        \"\"\"Attempt to resolve a Symbol, string, or float 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        sympy.Symbols are first checked for exact match in the parameter\n        dictionary.  Otherwise, the symbol 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 sympy.Symbol or name or float to try to resolve into just\n                a float.\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        # 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.\"\"\"\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[Union[str, sympy.Symbol], Union[float, str, sympy.Basic]]\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 sympy.Symbols to actual values.\n\n    A Symbol is a wrapped parameter name (str). A ParamResolver is an object\n    that can be used to assign values for these keys.\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[sympy.Basic, float, str]) -> 'cirq.TParamVal':\n        \"\"\"Attempt to resolve a Symbol, string, or float 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        sympy.Symbols are first checked for exact match in the parameter\n        dictionary.  Otherwise, the symbol 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 sympy.Symbol or name or float to try to resolve into just\n                a float.\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"}]}