[baa79c2] | 1 | """ |
---|
| 2 | Kernel Call Details |
---|
| 3 | =================== |
---|
| 4 | |
---|
| 5 | When calling sas computational kernels with polydispersity there are a |
---|
| 6 | number of details that need to be sent to the caller. This includes the |
---|
| 7 | list of polydisperse parameters, the number of points in the polydispersity |
---|
| 8 | weight distribution, and which parameter is the "theta" parameter for |
---|
| 9 | polar coordinate integration. The :class:`CallDetails` object maintains |
---|
| 10 | this data. Use :func:`build_details` to build a *details* object which |
---|
| 11 | can be passed to one of the computational kernels. |
---|
| 12 | """ |
---|
| 13 | |
---|
[a738209] | 14 | from __future__ import print_function |
---|
| 15 | |
---|
[7ae2b7f] | 16 | import numpy as np # type: ignore |
---|
[9eb3632] | 17 | from numpy import pi, cos, sin |
---|
| 18 | |
---|
| 19 | try: |
---|
| 20 | np.meshgrid([]) |
---|
| 21 | meshgrid = np.meshgrid |
---|
[725ee36] | 22 | except Exception: |
---|
[9eb3632] | 23 | # CRUFT: np.meshgrid requires multiple vectors |
---|
| 24 | def meshgrid(*args): |
---|
| 25 | if len(args) > 1: |
---|
| 26 | return np.meshgrid(*args) |
---|
| 27 | else: |
---|
| 28 | return [np.asarray(v) for v in args] |
---|
[7ae2b7f] | 29 | |
---|
| 30 | try: |
---|
| 31 | from typing import List |
---|
| 32 | except ImportError: |
---|
| 33 | pass |
---|
[8d62008] | 34 | else: |
---|
| 35 | from .modelinfo import ModelInfo |
---|
[7ae2b7f] | 36 | |
---|
[d2fc9a4] | 37 | |
---|
| 38 | class CallDetails(object): |
---|
[baa79c2] | 39 | """ |
---|
| 40 | Manage the polydispersity information for the kernel call. |
---|
| 41 | |
---|
| 42 | Conceptually, a polydispersity calculation is an integral over a mesh |
---|
| 43 | in n-D space where n is the number of polydisperse parameters. In order |
---|
| 44 | to keep the program responsive, and not crash the GPU, only a portion |
---|
| 45 | of the mesh is computed at a time. Meshes with a large number of points |
---|
| 46 | will therefore require many calls to the polydispersity loop. Restarting |
---|
| 47 | a nested loop in the middle requires that the indices of the individual |
---|
| 48 | mesh dimensions can be computed for the current loop location. This |
---|
| 49 | is handled by the *pd_stride* vector, with n//stride giving the loop |
---|
| 50 | index and n%stride giving the position in the sub loops. |
---|
| 51 | |
---|
| 52 | One of the parameters may be the latitude. When integrating in polar |
---|
| 53 | coordinates, the total circumference decreases as latitude varies from |
---|
| 54 | pi r^2 at the equator to 0 at the pole, and the weight associated |
---|
| 55 | with a range of phi values needs to be scaled by this circumference. |
---|
| 56 | This scale factor needs to be updated each time the theta value |
---|
| 57 | changes. *theta_par* indicates which of the values in the parameter |
---|
| 58 | vector is the latitude parameter, or -1 if there is no latitude |
---|
| 59 | parameter in the model. In practice, the normalization term cancels |
---|
| 60 | if the latitude is not a polydisperse parameter. |
---|
| 61 | """ |
---|
[7ae2b7f] | 62 | parts = None # type: List["CallDetails"] |
---|
[d2fc9a4] | 63 | def __init__(self, model_info): |
---|
[8d62008] | 64 | # type: (ModelInfo) -> None |
---|
[d2fc9a4] | 65 | parameters = model_info.parameters |
---|
| 66 | max_pd = parameters.max_pd |
---|
[a738209] | 67 | |
---|
| 68 | # Structure of the call details buffer: |
---|
| 69 | # pd_par[max_pd] pd params in order of length |
---|
| 70 | # pd_length[max_pd] length of each pd param |
---|
| 71 | # pd_offset[max_pd] offset of pd values in parameter array |
---|
| 72 | # pd_stride[max_pd] index of pd value in loop = n//stride[k] |
---|
[bde38b5] | 73 | # num_eval total length of pd loop |
---|
| 74 | # num_weights total length of the weight vector |
---|
[a738209] | 75 | # num_active number of pd params |
---|
| 76 | # theta_par parameter number for theta parameter |
---|
[bde38b5] | 77 | self.buffer = np.empty(4*max_pd + 4, 'i4') |
---|
[d2fc9a4] | 78 | |
---|
| 79 | # generate views on different parts of the array |
---|
[baa79c2] | 80 | self._pd_par = self.buffer[0 * max_pd:1 * max_pd] |
---|
| 81 | self._pd_length = self.buffer[1 * max_pd:2 * max_pd] |
---|
| 82 | self._pd_offset = self.buffer[2 * max_pd:3 * max_pd] |
---|
| 83 | self._pd_stride = self.buffer[3 * max_pd:4 * max_pd] |
---|
[d2fc9a4] | 84 | |
---|
| 85 | # theta_par is fixed |
---|
[a738209] | 86 | self.theta_par = parameters.theta_offset |
---|
[d2fc9a4] | 87 | |
---|
[bde38b5] | 88 | # offset and length are for all parameters, not just pd parameters |
---|
| 89 | # They are not sent to the kernel function, though they could be. |
---|
| 90 | # They are used by the composite models (sum and product) to |
---|
| 91 | # figure out offsets into the combined value list. |
---|
| 92 | self.offset = None # type: np.ndarray |
---|
| 93 | self.length = None # type: np.ndarray |
---|
| 94 | |
---|
| 95 | # keep hold of ifno show() so we can break a values vector |
---|
| 96 | # into the individual components |
---|
| 97 | self.info = model_info |
---|
| 98 | |
---|
[d2fc9a4] | 99 | @property |
---|
[baa79c2] | 100 | def pd_par(self): |
---|
| 101 | """List of polydisperse parameters""" |
---|
| 102 | return self._pd_par |
---|
[d2fc9a4] | 103 | |
---|
| 104 | @property |
---|
[baa79c2] | 105 | def pd_length(self): |
---|
| 106 | """Number of weights for each polydisperse parameter""" |
---|
| 107 | return self._pd_length |
---|
[d2fc9a4] | 108 | |
---|
| 109 | @property |
---|
[baa79c2] | 110 | def pd_offset(self): |
---|
| 111 | """Offsets for the individual weight vectors in the set of weights""" |
---|
| 112 | return self._pd_offset |
---|
[d2fc9a4] | 113 | |
---|
| 114 | @property |
---|
[baa79c2] | 115 | def pd_stride(self): |
---|
| 116 | """Stride in the pd mesh for each pd dimension""" |
---|
| 117 | return self._pd_stride |
---|
[d2fc9a4] | 118 | |
---|
| 119 | @property |
---|
[bde38b5] | 120 | def num_eval(self): |
---|
[baa79c2] | 121 | """Total size of the pd mesh""" |
---|
| 122 | return self.buffer[-4] |
---|
| 123 | |
---|
[bde38b5] | 124 | @num_eval.setter |
---|
| 125 | def num_eval(self, v): |
---|
[40a87fa] | 126 | """Total size of the pd mesh""" |
---|
[baa79c2] | 127 | self.buffer[-4] = v |
---|
[d2fc9a4] | 128 | |
---|
| 129 | @property |
---|
[bde38b5] | 130 | def num_weights(self): |
---|
[baa79c2] | 131 | """Total length of all the weight vectors""" |
---|
| 132 | return self.buffer[-3] |
---|
| 133 | |
---|
[bde38b5] | 134 | @num_weights.setter |
---|
| 135 | def num_weights(self, v): |
---|
[40a87fa] | 136 | """Total length of all the weight vectors""" |
---|
[baa79c2] | 137 | self.buffer[-3] = v |
---|
[d2fc9a4] | 138 | |
---|
| 139 | @property |
---|
[baa79c2] | 140 | def num_active(self): |
---|
| 141 | """Number of active polydispersity loops""" |
---|
| 142 | return self.buffer[-2] |
---|
| 143 | |
---|
[d2fc9a4] | 144 | @num_active.setter |
---|
[baa79c2] | 145 | def num_active(self, v): |
---|
[40a87fa] | 146 | """Number of active polydispersity loops""" |
---|
[baa79c2] | 147 | self.buffer[-2] = v |
---|
[d2fc9a4] | 148 | |
---|
| 149 | @property |
---|
[baa79c2] | 150 | def theta_par(self): |
---|
| 151 | """Location of the theta parameter in the parameter vector""" |
---|
| 152 | return self.buffer[-1] |
---|
| 153 | |
---|
[a738209] | 154 | @theta_par.setter |
---|
[baa79c2] | 155 | def theta_par(self, v): |
---|
[40a87fa] | 156 | """Location of the theta parameter in the parameter vector""" |
---|
[baa79c2] | 157 | self.buffer[-1] = v |
---|
[d2fc9a4] | 158 | |
---|
[bde38b5] | 159 | def show(self, values=None): |
---|
[baa79c2] | 160 | """Print the polydispersity call details to the console""" |
---|
[bde38b5] | 161 | print("===== %s details ===="%self.info.name) |
---|
| 162 | print("num_active:%d num_eval:%d num_weights:%d theta=%d" |
---|
| 163 | % (self.num_active, self.num_eval, self.num_weights, self.theta_par)) |
---|
| 164 | if self.pd_par.size: |
---|
| 165 | print("pd_par", self.pd_par) |
---|
| 166 | print("pd_length", self.pd_length) |
---|
| 167 | print("pd_offset", self.pd_offset) |
---|
| 168 | print("pd_stride", self.pd_stride) |
---|
| 169 | if values is not None: |
---|
| 170 | nvalues = self.info.parameters.nvalues |
---|
| 171 | print("scale, background", values[:2]) |
---|
| 172 | print("val", values[2:nvalues]) |
---|
| 173 | print("pd", values[nvalues:nvalues+self.num_weights]) |
---|
| 174 | print("wt", values[nvalues+self.num_weights:nvalues+2*self.num_weights]) |
---|
| 175 | print("offsets", self.offset) |
---|
| 176 | |
---|
| 177 | |
---|
| 178 | def make_details(model_info, length, offset, num_weights): |
---|
[6dc78e4] | 179 | # type: (ModelInfo, np.ndarray, np.ndarray, int) -> CallDetails |
---|
[baa79c2] | 180 | """ |
---|
| 181 | Return a :class:`CallDetails` object for a polydisperse calculation |
---|
[bde38b5] | 182 | of the model defined by *model_info*. Polydispersity is defined by |
---|
| 183 | the *length* of the polydispersity distribution for each parameter |
---|
| 184 | and the *offset* of the distribution in the polydispersity array. |
---|
| 185 | Monodisperse parameters should use a polydispersity length of one |
---|
| 186 | with weight 1.0. *num_weights* is the total length of the polydispersity |
---|
| 187 | array. |
---|
[baa79c2] | 188 | """ |
---|
[bde38b5] | 189 | #pars = model_info.parameters.call_parameters[2:model_info.parameters.npars+2] |
---|
| 190 | #print(", ".join(str(i)+"-"+p.id for i,p in enumerate(pars))) |
---|
| 191 | #print("len:",length) |
---|
| 192 | #print("off:",offset) |
---|
| 193 | |
---|
| 194 | # Check that we arn't using too many polydispersity loops |
---|
| 195 | num_active = np.sum(length > 1) |
---|
[9eb3632] | 196 | max_pd = model_info.parameters.max_pd |
---|
| 197 | if num_active > max_pd: |
---|
[d2fc9a4] | 198 | raise ValueError("Too many polydisperse parameters") |
---|
| 199 | |
---|
[bde38b5] | 200 | # Decreasing list of polydpersity lengths |
---|
[a738209] | 201 | # Note: the reversing view, x[::-1], does not require a copy |
---|
[bde38b5] | 202 | idx = np.argsort(length)[::-1][:max_pd] |
---|
| 203 | pd_stride = np.cumprod(np.hstack((1, length[idx]))) |
---|
[d2fc9a4] | 204 | |
---|
| 205 | call_details = CallDetails(model_info) |
---|
[9eb3632] | 206 | call_details.pd_par[:max_pd] = idx |
---|
[bde38b5] | 207 | call_details.pd_length[:max_pd] = length[idx] |
---|
| 208 | call_details.pd_offset[:max_pd] = offset[idx] |
---|
[9eb3632] | 209 | call_details.pd_stride[:max_pd] = pd_stride[:-1] |
---|
[bde38b5] | 210 | call_details.num_eval = pd_stride[-1] |
---|
| 211 | call_details.num_weights = num_weights |
---|
[d2fc9a4] | 212 | call_details.num_active = num_active |
---|
[bde38b5] | 213 | call_details.length = length |
---|
| 214 | call_details.offset = offset |
---|
[d2fc9a4] | 215 | #call_details.show() |
---|
| 216 | return call_details |
---|
[9eb3632] | 217 | |
---|
| 218 | |
---|
[bde38b5] | 219 | ZEROS = tuple([0.]*31) |
---|
| 220 | def make_kernel_args(kernel, pairs): |
---|
[9eb3632] | 221 | # type: (Kernel, Tuple[List[np.ndarray], List[np.ndarray]]) -> Tuple[CallDetails, np.ndarray, bool] |
---|
| 222 | """ |
---|
| 223 | Converts (value, weight) pairs into parameters for the kernel call. |
---|
| 224 | |
---|
| 225 | Returns a CallDetails object indicating the polydispersity, a data object |
---|
| 226 | containing the different values, and the magnetic flag indicating whether |
---|
| 227 | any magnetic magnitudes are non-zero. Magnetic vectors (M0, phi, theta) are |
---|
| 228 | converted to rectangular coordinates (mx, my, mz). |
---|
| 229 | """ |
---|
[bde38b5] | 230 | npars = kernel.info.parameters.npars |
---|
| 231 | nvalues = kernel.info.parameters.nvalues |
---|
| 232 | scalars = [v[0][0] for v in pairs] |
---|
| 233 | values, weights = zip(*pairs[2:npars+2]) if npars else ((),()) |
---|
| 234 | length = np.array([len(w) for w in weights]) |
---|
| 235 | offset = np.cumsum(np.hstack((0, length))) |
---|
| 236 | call_details = make_details(kernel.info, length, offset[:-1], offset[-1]) |
---|
| 237 | # Pad value array to a 32 value boundaryd |
---|
| 238 | data_len = nvalues + 2*sum(len(v) for v in values) |
---|
| 239 | extra = (32 - data_len%32)%32 |
---|
| 240 | data = np.hstack((scalars,) + values + weights + ZEROS[:extra]) |
---|
| 241 | data = data.astype(kernel.dtype) |
---|
[9eb3632] | 242 | is_magnetic = convert_magnetism(kernel.info.parameters, data) |
---|
| 243 | #call_details.show() |
---|
| 244 | return call_details, data, is_magnetic |
---|
| 245 | |
---|
[bde38b5] | 246 | |
---|
[9eb3632] | 247 | def convert_magnetism(parameters, values): |
---|
| 248 | """ |
---|
[baa79c2] | 249 | Convert magnetism values from polar to rectangular coordinates. |
---|
[9eb3632] | 250 | |
---|
| 251 | Returns True if any magnetism is present. |
---|
| 252 | """ |
---|
| 253 | mag = values[parameters.nvalues-3*parameters.nmagnetic:parameters.nvalues] |
---|
| 254 | mag = mag.reshape(-1, 3) |
---|
[40a87fa] | 255 | scale = mag[:,0] |
---|
| 256 | if np.any(scale): |
---|
| 257 | theta, phi = mag[:, 1]*pi/180., mag[:, 2]*pi/180. |
---|
[9eb3632] | 258 | cos_theta = cos(theta) |
---|
[40a87fa] | 259 | mag[:, 0] = scale*cos_theta*cos(phi) # mx |
---|
| 260 | mag[:, 1] = scale*sin(theta) # my |
---|
| 261 | mag[:, 2] = -scale*cos_theta*sin(phi) # mz |
---|
[9eb3632] | 262 | return True |
---|
| 263 | else: |
---|
| 264 | return False |
---|
[bde38b5] | 265 | |
---|
| 266 | |
---|
| 267 | def dispersion_mesh(model_info, pars): |
---|
| 268 | # type: (ModelInfo) -> Tuple[List[np.ndarray], List[np.ndarray]] |
---|
| 269 | """ |
---|
| 270 | Create a mesh grid of dispersion parameters and weights. |
---|
| 271 | |
---|
| 272 | Returns [p1,p2,...],w where pj is a vector of values for parameter j |
---|
| 273 | and w is a vector containing the products for weights for each |
---|
| 274 | parameter set in the vector. |
---|
| 275 | """ |
---|
| 276 | value, weight = zip(*pars) |
---|
[6dc78e4] | 277 | #weight = [w if len(w)>0 else [1.] for w in weight] |
---|
[bde38b5] | 278 | weight = np.vstack([v.flatten() for v in meshgrid(*weight)]) |
---|
| 279 | weight = np.prod(weight, axis=0) |
---|
| 280 | value = [v.flatten() for v in meshgrid(*value)] |
---|
| 281 | lengths = [par.length for par in model_info.parameters.kernel_parameters |
---|
| 282 | if par.type == 'volume'] |
---|
| 283 | if any(n > 1 for n in lengths): |
---|
| 284 | pars = [] |
---|
| 285 | offset = 0 |
---|
| 286 | for n in lengths: |
---|
| 287 | pars.append(np.vstack(value[offset:offset+n]) |
---|
| 288 | if n > 1 else value[offset]) |
---|
| 289 | offset += n |
---|
| 290 | value = pars |
---|
| 291 | return value, weight |
---|