|
| 1 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 2 | +# you may not use this file except in compliance with the License. |
| 3 | +# You may obtain a copy of the License at |
| 4 | +# |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# |
| 7 | +# Unless required by applicable law or agreed to in writing, software |
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +# See the License for the specific language governing permissions and |
| 11 | +# limitations under the License. |
| 12 | +""" |
| 13 | +Module containing NumPy-like and SciPy-like numerical backends. |
| 14 | +""" |
| 15 | + |
| 16 | +import os |
| 17 | + |
| 18 | +import numpy as default_np |
| 19 | +import scipy.linalg as default_la |
| 20 | + |
| 21 | +from tensornetwork.backend_contextmanager import \ |
| 22 | + set_default_backend |
| 23 | + |
| 24 | +import oqupy.config as oc |
| 25 | + |
| 26 | +# store instances of the initialized backends |
| 27 | +# this way, `oqupy.config` remains unchanged |
| 28 | +# and `ocupy.config.DEFAULT_BACKEND` is used |
| 29 | +# when NumPy and LinAlg are initialized |
| 30 | +NUMERICAL_BACKEND_INSTANCES = {} |
| 31 | + |
| 32 | +def get_numerical_backends( |
| 33 | + backend_name: str, |
| 34 | + ): |
| 35 | + """Function to get numerical backend. |
| 36 | +
|
| 37 | + Parameters |
| 38 | + ---------- |
| 39 | + backend_name: str |
| 40 | + Name of the backend. Options are `'jax'` and `'numpy'`. |
| 41 | +
|
| 42 | + Returns |
| 43 | + ------- |
| 44 | + backends: list |
| 45 | + NumPy and LinAlg backends. |
| 46 | + """ |
| 47 | + |
| 48 | + _bn = backend_name.lower() |
| 49 | + if _bn in NUMERICAL_BACKEND_INSTANCES: |
| 50 | + set_default_backend(_bn) |
| 51 | + return NUMERICAL_BACKEND_INSTANCES[_bn] |
| 52 | + assert _bn in ['jax', 'numpy'], \ |
| 53 | + "currently supported backends are `'jax'` and `'numpy'`" |
| 54 | + |
| 55 | + if 'jax' in _bn: |
| 56 | + try: |
| 57 | + # explicitly import and configure jax |
| 58 | + import jax |
| 59 | + import jax.numpy as jnp |
| 60 | + import jax.scipy.linalg as jla |
| 61 | + jax.config.update('jax_enable_x64', True) |
| 62 | + |
| 63 | + # # TODO: GPU memory allocation (default is 0.75) |
| 64 | + # os.environ['XLA_PYTHON_CLIENT_ALLOCATOR'] = 'platform' |
| 65 | + # os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION'] = '.5' |
| 66 | + |
| 67 | + # set TensorNetwork backend |
| 68 | + set_default_backend('jax') |
| 69 | + |
| 70 | + NUMERICAL_BACKEND_INSTANCES['jax'] = [jnp, jla] |
| 71 | + return NUMERICAL_BACKEND_INSTANCES['jax'] |
| 72 | + except ImportError: |
| 73 | + print("JAX not installed, defaulting to NumPy") |
| 74 | + |
| 75 | + # set TensorNetwork backend |
| 76 | + set_default_backend('numpy') |
| 77 | + |
| 78 | + NUMERICAL_BACKEND_INSTANCES['numpy'] = [default_np, default_la] |
| 79 | + return NUMERICAL_BACKEND_INSTANCES['numpy'] |
| 80 | + |
| 81 | +class NumPy: |
| 82 | + """ |
| 83 | + The NumPy backend employing |
| 84 | + dynamic switching through `oqupy.config`. |
| 85 | + """ |
| 86 | + def __init__(self, |
| 87 | + backend_name=oc.DEFAULT_BACKEND, |
| 88 | + ): |
| 89 | + """Getter for the backend.""" |
| 90 | + self.backend = get_numerical_backends(backend_name)[0] |
| 91 | + |
| 92 | + @property |
| 93 | + def dtype_complex(self) -> default_np.dtype: |
| 94 | + """Getter for the complex datatype.""" |
| 95 | + return oc.NumPyDtypeComplex |
| 96 | + |
| 97 | + @property |
| 98 | + def dtype_float(self) -> default_np.dtype: |
| 99 | + """Getter for the float datatype.""" |
| 100 | + return oc.NumPyDtypeFloat |
| 101 | + |
| 102 | + def __getattr__(self, |
| 103 | + name: str, |
| 104 | + ): |
| 105 | + """Return the backend's default attribute.""" |
| 106 | + return getattr(self.backend, name) |
| 107 | + |
| 108 | + def update(self, |
| 109 | + array, |
| 110 | + indices: tuple, |
| 111 | + values, |
| 112 | + ) -> default_np.ndarray: |
| 113 | + """Option to update select indices of an array with given values.""" |
| 114 | + if not isinstance(array, default_np.ndarray): |
| 115 | + return array.at[indices].set(values) |
| 116 | + array[indices] = values |
| 117 | + return array |
| 118 | + |
| 119 | + def get_random_floats(self, |
| 120 | + seed, |
| 121 | + shape, |
| 122 | + ): |
| 123 | + """Method to obtain random floats with a given seed and shape.""" |
| 124 | + random_floats = default_np.random.default_rng(seed).random(shape, \ |
| 125 | + dtype=default_np.float64) |
| 126 | + return self.backend.array(random_floats, dtype=self.dtype_float) |
| 127 | + |
| 128 | +class LinAlg: |
| 129 | + """ |
| 130 | + The Linear Algebra backend employing |
| 131 | + dynamic switching through `oqupy.config`. |
| 132 | + """ |
| 133 | + def __init__(self, |
| 134 | + backend_name=oc.DEFAULT_BACKEND, |
| 135 | + ): |
| 136 | + """Getter for the backend.""" |
| 137 | + self.backend = get_numerical_backends(backend_name)[1] |
| 138 | + |
| 139 | + def __getattr__(self, |
| 140 | + name: str, |
| 141 | + ): |
| 142 | + """Return the backend's default attribute.""" |
| 143 | + return getattr(self.backend, name) |
| 144 | + |
| 145 | +# setup libraries using environment variable |
| 146 | +# fall back to oqupy.config.DEFAULT_BACKEND |
| 147 | +try: |
| 148 | + BACKEND_NAME = os.environ[oc.BACKEND_ENV_VAR] |
| 149 | +except KeyError: |
| 150 | + BACKEND_NAME = oc.DEFAULT_BACKEND |
| 151 | +np = NumPy(backend_name=BACKEND_NAME) |
| 152 | +la = LinAlg(backend_name=BACKEND_NAME) |
| 153 | + |
| 154 | +def set_numerical_backends( |
| 155 | + backend_name: str |
| 156 | + ): |
| 157 | + """Function to set numerical backend. |
| 158 | +
|
| 159 | + Parameters |
| 160 | + ---------- |
| 161 | + backend_name: str |
| 162 | + Name of the backend. Options are `'jax'` and `'numpy'`. |
| 163 | + """ |
| 164 | + backends = get_numerical_backends(backend_name) |
| 165 | + np.backend = backends[0] |
| 166 | + la.backend = backends[1] |
0 commit comments