[eafc9fa] | 1 | """ |
---|
| 2 | Python driver for python kernels |
---|
| 3 | |
---|
| 4 | Calls the kernel with a vector of $q$ values for a single parameter set. |
---|
| 5 | Polydispersity is supported by looping over different parameter sets and |
---|
| 6 | summing the results. The interface to :class:`PyModel` matches those for |
---|
| 7 | :class:`kernelcl.GpuModel` and :class:`kerneldll.DllModel`. |
---|
| 8 | """ |
---|
[a738209] | 9 | from __future__ import division, print_function |
---|
| 10 | |
---|
[7ae2b7f] | 11 | import numpy as np # type: ignore |
---|
| 12 | from numpy import pi, cos #type: ignore |
---|
[b3f6bc3] | 13 | |
---|
[4bfd277] | 14 | from . import details |
---|
[c85db69] | 15 | from .generate import F64 |
---|
[f619de7] | 16 | from .kernel import KernelModel, Kernel |
---|
[b3f6bc3] | 17 | |
---|
[e62a134] | 18 | try: |
---|
[c1a888b] | 19 | from typing import Union, Callable |
---|
[e62a134] | 20 | except: |
---|
| 21 | pass |
---|
| 22 | else: |
---|
| 23 | DType = Union[None, str, np.dtype] |
---|
| 24 | |
---|
[f619de7] | 25 | class PyModel(KernelModel): |
---|
[eafc9fa] | 26 | """ |
---|
| 27 | Wrapper for pure python models. |
---|
| 28 | """ |
---|
[17bbadd] | 29 | def __init__(self, model_info): |
---|
[6d6508e] | 30 | # Make sure Iq and Iqxy are available and vectorized |
---|
| 31 | _create_default_functions(model_info) |
---|
[17bbadd] | 32 | self.info = model_info |
---|
[3c56da87] | 33 | |
---|
[1e2a1ba] | 34 | def make_kernel(self, q_vectors): |
---|
[eafc9fa] | 35 | q_input = PyInput(q_vectors, dtype=F64) |
---|
[6d6508e] | 36 | kernel = self.info.Iqxy if q_input.is_2d else self.info.Iq |
---|
[3c56da87] | 37 | return PyKernel(kernel, self.info, q_input) |
---|
| 38 | |
---|
[f734e7d] | 39 | def release(self): |
---|
[eafc9fa] | 40 | """ |
---|
| 41 | Free resources associated with the model. |
---|
| 42 | """ |
---|
[f734e7d] | 43 | pass |
---|
| 44 | |
---|
[b3f6bc3] | 45 | class PyInput(object): |
---|
| 46 | """ |
---|
| 47 | Make q data available to the gpu. |
---|
| 48 | |
---|
| 49 | *q_vectors* is a list of q vectors, which will be *[q]* for 1-D data, |
---|
| 50 | and *[qx, qy]* for 2-D data. Internally, the vectors will be reallocated |
---|
| 51 | to get the best performance on OpenCL, which may involve shifting and |
---|
| 52 | stretching the array to better match the memory architecture. Additional |
---|
| 53 | points will be evaluated with *q=1e-3*. |
---|
| 54 | |
---|
| 55 | *dtype* is the data type for the q vectors. The data type should be |
---|
| 56 | set to match that of the kernel, which is an attribute of |
---|
| 57 | :class:`GpuProgram`. Note that not all kernels support double |
---|
| 58 | precision, so even if the program was created for double precision, |
---|
| 59 | the *GpuProgram.dtype* may be single precision. |
---|
| 60 | |
---|
| 61 | Call :meth:`release` when complete. Even if not called directly, the |
---|
| 62 | buffer will be released when the data object is freed. |
---|
| 63 | """ |
---|
| 64 | def __init__(self, q_vectors, dtype): |
---|
| 65 | self.nq = q_vectors[0].size |
---|
| 66 | self.dtype = dtype |
---|
[eafc9fa] | 67 | self.is_2d = (len(q_vectors) == 2) |
---|
[48fbd50] | 68 | if self.is_2d: |
---|
| 69 | self.q = np.empty((self.nq, 2), dtype=dtype) |
---|
| 70 | self.q[:, 0] = q_vectors[0] |
---|
| 71 | self.q[:, 1] = q_vectors[1] |
---|
| 72 | else: |
---|
| 73 | self.q = np.empty(self.nq, dtype=dtype) |
---|
| 74 | self.q[:self.nq] = q_vectors[0] |
---|
[b3f6bc3] | 75 | |
---|
| 76 | def release(self): |
---|
[eafc9fa] | 77 | """ |
---|
| 78 | Free resources associated with the model inputs. |
---|
| 79 | """ |
---|
[48fbd50] | 80 | self.q = None |
---|
[b3f6bc3] | 81 | |
---|
[f619de7] | 82 | class PyKernel(Kernel): |
---|
[b3f6bc3] | 83 | """ |
---|
| 84 | Callable SAS kernel. |
---|
| 85 | |
---|
| 86 | *kernel* is the DllKernel object to call. |
---|
| 87 | |
---|
[17bbadd] | 88 | *model_info* is the module information |
---|
[b3f6bc3] | 89 | |
---|
[3c56da87] | 90 | *q_input* is the DllInput q vectors at which the kernel should be |
---|
[b3f6bc3] | 91 | evaluated. |
---|
| 92 | |
---|
| 93 | The resulting call method takes the *pars*, a list of values for |
---|
| 94 | the fixed parameters to the kernel, and *pd_pars*, a list of (value,weight) |
---|
| 95 | vectors for the polydisperse parameters. *cutoff* determines the |
---|
| 96 | integration limits: any points with combined weight less than *cutoff* |
---|
| 97 | will not be calculated. |
---|
| 98 | |
---|
| 99 | Call :meth:`release` when done with the kernel instance. |
---|
| 100 | """ |
---|
[17bbadd] | 101 | def __init__(self, kernel, model_info, q_input): |
---|
[6e7ff6d] | 102 | self.dtype = np.dtype('d') |
---|
[17bbadd] | 103 | self.info = model_info |
---|
[3c56da87] | 104 | self.q_input = q_input |
---|
| 105 | self.res = np.empty(q_input.nq, q_input.dtype) |
---|
[6e7ff6d] | 106 | self.kernel = kernel |
---|
| 107 | self.dim = '2d' if q_input.is_2d else '1d' |
---|
| 108 | |
---|
[6d6508e] | 109 | partable = model_info.parameters |
---|
[6e7ff6d] | 110 | kernel_parameters = (partable.iqxy_parameters if q_input.is_2d |
---|
| 111 | else partable.iq_parameters) |
---|
| 112 | volume_parameters = partable.form_volume_parameters |
---|
| 113 | |
---|
| 114 | # Create an array to hold the parameter values. There will be a |
---|
| 115 | # single array whose values are updated as the calculator goes |
---|
| 116 | # through the loop. Arguments to the kernel and volume functions |
---|
| 117 | # will use views into this vector, relying on the fact that a |
---|
| 118 | # an array of no dimensions acts like a scalar. |
---|
[a8a7f08] | 119 | parameter_vector = np.empty(len(partable.call_parameters)-2, 'd') |
---|
[6e7ff6d] | 120 | |
---|
| 121 | # Create views into the array to hold the arguments |
---|
[a8a7f08] | 122 | offset = 0 |
---|
[6e7ff6d] | 123 | kernel_args, volume_args = [], [] |
---|
| 124 | for p in partable.kernel_parameters: |
---|
| 125 | if p.length == 1: |
---|
| 126 | # Scalar values are length 1 vectors with no dimensions. |
---|
| 127 | v = parameter_vector[offset:offset+1].reshape(()) |
---|
[b3f6bc3] | 128 | else: |
---|
[6e7ff6d] | 129 | # Vector values are simple views. |
---|
| 130 | v = parameter_vector[offset:offset+p.length] |
---|
| 131 | offset += p.length |
---|
| 132 | if p in kernel_parameters: |
---|
| 133 | kernel_args.append(v) |
---|
| 134 | if p in volume_parameters: |
---|
[a8a7f08] | 135 | volume_args.append(v) |
---|
[6e7ff6d] | 136 | |
---|
| 137 | # Hold on to the parameter vector so we can use it to call kernel later. |
---|
| 138 | # This may also be required to preserve the views into the vector. |
---|
| 139 | self._parameter_vector = parameter_vector |
---|
| 140 | |
---|
| 141 | # Generate a closure which calls the kernel with the views into the |
---|
| 142 | # parameter array. |
---|
| 143 | if q_input.is_2d: |
---|
[6d6508e] | 144 | form = model_info.Iqxy |
---|
[6e7ff6d] | 145 | qx, qy = q_input.q[:,0], q_input.q[:,1] |
---|
| 146 | self._form = lambda: form(qx, qy, *kernel_args) |
---|
[b3f6bc3] | 147 | else: |
---|
[6d6508e] | 148 | form = model_info.Iq |
---|
[6e7ff6d] | 149 | q = q_input.q |
---|
| 150 | self._form = lambda: form(q, *kernel_args) |
---|
| 151 | |
---|
| 152 | # Generate a closure which calls the form_volume if it exists. |
---|
[6d6508e] | 153 | form_volume = model_info.form_volume |
---|
[6e7ff6d] | 154 | self._volume = ((lambda: form_volume(*volume_args)) if form_volume |
---|
| 155 | else (lambda: 1.0)) |
---|
| 156 | |
---|
[a738209] | 157 | def __call__(self, call_details, values, cutoff): |
---|
[4bfd277] | 158 | assert isinstance(call_details, details.CallDetails) |
---|
[6e7ff6d] | 159 | res = _loops(self._parameter_vector, self._form, self._volume, |
---|
[a738209] | 160 | self.q_input.nq, call_details, values, cutoff) |
---|
[b3f6bc3] | 161 | return res |
---|
| 162 | |
---|
| 163 | def release(self): |
---|
[eafc9fa] | 164 | """ |
---|
| 165 | Free resources associated with the kernel. |
---|
| 166 | """ |
---|
[f619de7] | 167 | self.q_input.release() |
---|
[3c56da87] | 168 | self.q_input = None |
---|
[b3f6bc3] | 169 | |
---|
[a738209] | 170 | def _loops(parameters, form, form_volume, nq, details, |
---|
| 171 | values, cutoff): |
---|
[9a943d0] | 172 | # type: (np.ndarray, Callable[[], np.ndarray], Callable[[], float], int, details.CallDetails, np.ndarray, np.ndarray, float) -> None |
---|
[f734e7d] | 173 | ################################################################ |
---|
| 174 | # # |
---|
| 175 | # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # |
---|
| 176 | # !! !! # |
---|
| 177 | # !! KEEP THIS CODE CONSISTENT WITH KERNEL_TEMPLATE.C !! # |
---|
| 178 | # !! !! # |
---|
| 179 | # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # |
---|
| 180 | # # |
---|
| 181 | ################################################################ |
---|
[a738209] | 182 | NPARS = len(parameters) |
---|
| 183 | parameters[:] = values[2:NPARS+2] |
---|
[6e7ff6d] | 184 | scale, background = values[0], values[1] |
---|
[a738209] | 185 | if details.num_active == 0: |
---|
[6e7ff6d] | 186 | norm = float(form_volume()) |
---|
| 187 | if norm > 0.0: |
---|
| 188 | return (scale/norm)*form() + background |
---|
[b3f6bc3] | 189 | else: |
---|
[6e7ff6d] | 190 | return np.ones(nq, 'd')*background |
---|
| 191 | |
---|
[a738209] | 192 | pd_value = values[2+NPARS:2+NPARS+details.pd_sum] |
---|
| 193 | pd_weight = values[2+NPARS+details.pd_sum:] |
---|
| 194 | |
---|
| 195 | pd_norm = 0.0 |
---|
[6e7ff6d] | 196 | spherical_correction = 1.0 |
---|
[a738209] | 197 | partial_weight = np.NaN |
---|
| 198 | weight =np.NaN |
---|
| 199 | |
---|
| 200 | p0_par = details.pd_par[0] |
---|
| 201 | p0_is_theta = (p0_par == details.theta_par) |
---|
| 202 | p0_length = details.pd_length[0] |
---|
| 203 | p0_index = p0_length |
---|
| 204 | p0_offset = details.pd_offset[0] |
---|
| 205 | |
---|
| 206 | pd_par = details.pd_par[:details.num_active] |
---|
| 207 | pd_offset = details.pd_offset[:details.num_active] |
---|
| 208 | pd_stride = details.pd_stride[:details.num_active] |
---|
| 209 | pd_length = details.pd_length[:details.num_active] |
---|
| 210 | |
---|
[6e7ff6d] | 211 | total = np.zeros(nq, 'd') |
---|
[a738209] | 212 | for loop_index in range(details.pd_prod): |
---|
[6e7ff6d] | 213 | # update polydispersity parameter values |
---|
[a738209] | 214 | if p0_index == p0_length: |
---|
| 215 | pd_index = (loop_index//pd_stride)%pd_length |
---|
| 216 | parameters[pd_par] = pd_value[pd_offset+pd_index] |
---|
| 217 | partial_weight = np.prod(pd_weight[pd_offset+pd_index][1:]) |
---|
| 218 | if details.theta_par >= 0: |
---|
| 219 | spherical_correction = max(abs(cos(pi/180 * parameters[details.theta_par])), 1e-6) |
---|
| 220 | p0_index = loop_index%p0_length |
---|
| 221 | |
---|
| 222 | weight = partial_weight * pd_weight[p0_offset + p0_index] |
---|
| 223 | parameters[p0_par] = pd_value[p0_offset + p0_index] |
---|
| 224 | if p0_is_theta: |
---|
| 225 | spherical_correction = max(abs(cos(pi/180 * parameters[p0_par])), 1e-6) |
---|
| 226 | p0_index += 1 |
---|
[6e7ff6d] | 227 | if weight > cutoff: |
---|
| 228 | # Call the scattering function |
---|
| 229 | # Assume that NaNs are only generated if the parameters are bad; |
---|
| 230 | # exclude all q for that NaN. Even better would be to have an |
---|
| 231 | # INVALID expression like the C models, but that is too expensive. |
---|
| 232 | I = form() |
---|
[4c2c535] | 233 | if np.isnan(I).any(): continue |
---|
[b3f6bc3] | 234 | |
---|
[6e7ff6d] | 235 | # update value and norm |
---|
| 236 | weight *= spherical_correction |
---|
| 237 | total += weight * I |
---|
[a738209] | 238 | pd_norm += weight * form_volume() |
---|
[b3f6bc3] | 239 | |
---|
[a738209] | 240 | if pd_norm > 0.0: |
---|
| 241 | return (scale/pd_norm)*total + background |
---|
[6e7ff6d] | 242 | else: |
---|
| 243 | return np.ones(nq, 'd')*background |
---|
[6d6508e] | 244 | |
---|
| 245 | |
---|
[4bfd277] | 246 | def _create_default_functions(model_info): |
---|
| 247 | """ |
---|
| 248 | Autogenerate missing functions, such as Iqxy from Iq. |
---|
| 249 | |
---|
| 250 | This only works for Iqxy when Iq is written in python. :func:`make_source` |
---|
| 251 | performs a similar role for Iq written in C. This also vectorizes |
---|
| 252 | any functions that are not already marked as vectorized. |
---|
| 253 | """ |
---|
| 254 | _create_vector_Iq(model_info) |
---|
| 255 | _create_vector_Iqxy(model_info) # call create_vector_Iq() first |
---|
| 256 | |
---|
[6d6508e] | 257 | |
---|
| 258 | def _create_vector_Iq(model_info): |
---|
| 259 | """ |
---|
| 260 | Define Iq as a vector function if it exists. |
---|
| 261 | """ |
---|
| 262 | Iq = model_info.Iq |
---|
| 263 | if callable(Iq) and not getattr(Iq, 'vectorized', False): |
---|
[4bfd277] | 264 | #print("vectorizing Iq") |
---|
[6d6508e] | 265 | def vector_Iq(q, *args): |
---|
| 266 | """ |
---|
| 267 | Vectorized 1D kernel. |
---|
| 268 | """ |
---|
| 269 | return np.array([Iq(qi, *args) for qi in q]) |
---|
| 270 | vector_Iq.vectorized = True |
---|
| 271 | model_info.Iq = vector_Iq |
---|
| 272 | |
---|
| 273 | def _create_vector_Iqxy(model_info): |
---|
| 274 | """ |
---|
| 275 | Define Iqxy as a vector function if it exists, or default it from Iq(). |
---|
| 276 | """ |
---|
| 277 | Iq, Iqxy = model_info.Iq, model_info.Iqxy |
---|
[4bfd277] | 278 | if callable(Iqxy): |
---|
| 279 | if not getattr(Iqxy, 'vectorized', False): |
---|
| 280 | #print("vectorizing Iqxy") |
---|
| 281 | def vector_Iqxy(qx, qy, *args): |
---|
| 282 | """ |
---|
| 283 | Vectorized 2D kernel. |
---|
| 284 | """ |
---|
| 285 | return np.array([Iqxy(qxi, qyi, *args) for qxi, qyi in zip(qx, qy)]) |
---|
| 286 | vector_Iqxy.vectorized = True |
---|
| 287 | model_info.Iqxy = vector_Iqxy |
---|
[6d6508e] | 288 | elif callable(Iq): |
---|
[4bfd277] | 289 | #print("defaulting Iqxy") |
---|
[6d6508e] | 290 | # Iq is vectorized because create_vector_Iq was already called. |
---|
| 291 | def default_Iqxy(qx, qy, *args): |
---|
| 292 | """ |
---|
| 293 | Default 2D kernel. |
---|
| 294 | """ |
---|
| 295 | return Iq(np.sqrt(qx**2 + qy**2), *args) |
---|
| 296 | default_Iqxy.vectorized = True |
---|
| 297 | model_info.Iqxy = default_Iqxy |
---|
| 298 | |
---|