[3b4243d] | 1 | """ |
---|
| 2 | SAS data representations. |
---|
| 3 | |
---|
| 4 | Plotting functions for data sets: |
---|
| 5 | |
---|
| 6 | :func:`plot_data` plots the data file. |
---|
| 7 | |
---|
| 8 | :func:`plot_theory` plots a calculated result from the model. |
---|
| 9 | |
---|
| 10 | Wrappers for the sasview data loader and data manipulations: |
---|
| 11 | |
---|
| 12 | :func:`load_data` loads a sasview data file. |
---|
| 13 | |
---|
| 14 | :func:`set_beam_stop` masks the beam stop from the data. |
---|
| 15 | |
---|
| 16 | :func:`set_half` selects the right or left half of the data, which can |
---|
| 17 | be useful for shear measurements which have not been properly corrected |
---|
| 18 | for path length and reflections. |
---|
| 19 | |
---|
| 20 | :func:`set_top` cuts the top part off the data. |
---|
| 21 | |
---|
| 22 | |
---|
| 23 | Empty data sets for evaluating models without data: |
---|
| 24 | |
---|
| 25 | :func:`empty_data1D` creates an empty dataset, which is useful for plotting |
---|
| 26 | a theory function before the data is measured. |
---|
| 27 | |
---|
| 28 | :func:`empty_data2D` creates an empty 2D dataset. |
---|
| 29 | |
---|
| 30 | Note that the empty datasets use a minimal representation of the SasView |
---|
| 31 | objects so that models can be run without SasView on the path. You could |
---|
| 32 | also use these for your own data loader. |
---|
| 33 | |
---|
| 34 | """ |
---|
| 35 | import traceback |
---|
| 36 | |
---|
[7ae2b7f] | 37 | import numpy as np # type: ignore |
---|
[3b4243d] | 38 | |
---|
[a839b22] | 39 | # pylint: disable=unused-import |
---|
[a5b8477] | 40 | try: |
---|
| 41 | from typing import Union, Dict, List, Optional |
---|
| 42 | except ImportError: |
---|
| 43 | pass |
---|
| 44 | else: |
---|
| 45 | Data = Union["Data1D", "Data2D", "SesansData"] |
---|
[a839b22] | 46 | # pylint: enable=unused-import |
---|
[a5b8477] | 47 | |
---|
[74b0495] | 48 | def load_data(filename, index=0): |
---|
[a5b8477] | 49 | # type: (str) -> Data |
---|
[3b4243d] | 50 | """ |
---|
| 51 | Load data using a sasview loader. |
---|
| 52 | """ |
---|
[7ae2b7f] | 53 | from sas.sascalc.dataloader.loader import Loader # type: ignore |
---|
[3b4243d] | 54 | loader = Loader() |
---|
[630156b] | 55 | # Allow for one part in multipart file |
---|
| 56 | if '[' in filename: |
---|
| 57 | filename, indexstr = filename[:-1].split('[') |
---|
| 58 | index = int(indexstr) |
---|
| 59 | datasets = loader.load(filename) |
---|
[09141ff] | 60 | if not datasets: # None or [] |
---|
[3b4243d] | 61 | raise IOError("Data %r could not be loaded" % filename) |
---|
[630156b] | 62 | if not isinstance(datasets, list): |
---|
| 63 | datasets = [datasets] |
---|
[74b0495] | 64 | for data in datasets: |
---|
| 65 | if hasattr(data, 'x'): |
---|
| 66 | data.qmin, data.qmax = data.x.min(), data.x.max() |
---|
| 67 | data.mask = (np.isnan(data.y) if data.y is not None |
---|
[e65c3ba] | 68 | else np.zeros_like(data.x, dtype='bool')) |
---|
[74b0495] | 69 | elif hasattr(data, 'qx_data'): |
---|
| 70 | data.mask = ~data.mask |
---|
| 71 | return datasets[index] if index != 'all' else datasets |
---|
[3b4243d] | 72 | |
---|
| 73 | |
---|
| 74 | def set_beam_stop(data, radius, outer=None): |
---|
[a5b8477] | 75 | # type: (Data, float, Optional[float]) -> None |
---|
[3b4243d] | 76 | """ |
---|
| 77 | Add a beam stop of the given *radius*. If *outer*, make an annulus. |
---|
| 78 | """ |
---|
[4e00c13] | 79 | from sas.sascalc.dataloader.manipulations import Ringcut |
---|
[3b4243d] | 80 | if hasattr(data, 'qx_data'): |
---|
| 81 | data.mask = Ringcut(0, radius)(data) |
---|
| 82 | if outer is not None: |
---|
| 83 | data.mask += Ringcut(outer, np.inf)(data) |
---|
| 84 | else: |
---|
| 85 | data.mask = (data.x < radius) |
---|
| 86 | if outer is not None: |
---|
| 87 | data.mask |= (data.x >= outer) |
---|
| 88 | |
---|
| 89 | |
---|
| 90 | def set_half(data, half): |
---|
[a5b8477] | 91 | # type: (Data, str) -> None |
---|
[3b4243d] | 92 | """ |
---|
| 93 | Select half of the data, either "right" or "left". |
---|
| 94 | """ |
---|
[4e00c13] | 95 | from sas.sascalc.dataloader.manipulations import Boxcut |
---|
[3b4243d] | 96 | if half == 'right': |
---|
| 97 | data.mask += \ |
---|
| 98 | Boxcut(x_min=-np.inf, x_max=0.0, y_min=-np.inf, y_max=np.inf)(data) |
---|
| 99 | if half == 'left': |
---|
| 100 | data.mask += \ |
---|
| 101 | Boxcut(x_min=0.0, x_max=np.inf, y_min=-np.inf, y_max=np.inf)(data) |
---|
| 102 | |
---|
| 103 | |
---|
| 104 | def set_top(data, cutoff): |
---|
[a5b8477] | 105 | # type: (Data, float) -> None |
---|
[3b4243d] | 106 | """ |
---|
| 107 | Chop the top off the data, above *cutoff*. |
---|
| 108 | """ |
---|
[4e00c13] | 109 | from sas.sascalc.dataloader.manipulations import Boxcut |
---|
[3b4243d] | 110 | data.mask += \ |
---|
| 111 | Boxcut(x_min=-np.inf, x_max=np.inf, y_min=-np.inf, y_max=cutoff)(data) |
---|
| 112 | |
---|
| 113 | |
---|
| 114 | class Data1D(object): |
---|
[299edd2] | 115 | """ |
---|
| 116 | 1D data object. |
---|
| 117 | |
---|
| 118 | Note that this definition matches the attributes from sasview, with |
---|
| 119 | some generic 1D data vectors and some SAS specific definitions. Some |
---|
| 120 | refactoring to allow consistent naming conventions between 1D, 2D and |
---|
| 121 | SESANS data would be helpful. |
---|
| 122 | |
---|
| 123 | **Attributes** |
---|
| 124 | |
---|
| 125 | *x*, *dx*: $q$ vector and gaussian resolution |
---|
| 126 | |
---|
| 127 | *y*, *dy*: $I(q)$ vector and measurement uncertainty |
---|
| 128 | |
---|
| 129 | *mask*: values to include in plotting/analysis |
---|
| 130 | |
---|
| 131 | *dxl*: slit widths for slit smeared data, with *dx* ignored |
---|
| 132 | |
---|
| 133 | *qmin*, *qmax*: range of $q$ values in *x* |
---|
| 134 | |
---|
| 135 | *filename*: label for the data line |
---|
| 136 | |
---|
| 137 | *_xaxis*, *_xunit*: label and units for the *x* axis |
---|
| 138 | |
---|
| 139 | *_yaxis*, *_yunit*: label and units for the *y* axis |
---|
| 140 | """ |
---|
[a839b22] | 141 | def __init__(self, |
---|
| 142 | x=None, # type: Optional[np.ndarray] |
---|
| 143 | y=None, # type: Optional[np.ndarray] |
---|
| 144 | dx=None, # type: Optional[np.ndarray] |
---|
| 145 | dy=None # type: Optional[np.ndarray] |
---|
| 146 | ): |
---|
| 147 | # type: (...) -> None |
---|
[3b4243d] | 148 | self.x, self.y, self.dx, self.dy = x, y, dx, dy |
---|
| 149 | self.dxl = None |
---|
[69ec80f] | 150 | self.filename = None |
---|
| 151 | self.qmin = x.min() if x is not None else np.NaN |
---|
| 152 | self.qmax = x.max() if x is not None else np.NaN |
---|
[2c1bb7b0] | 153 | # TODO: why is 1D mask False and 2D mask True? |
---|
| 154 | self.mask = (np.isnan(y) if y is not None |
---|
[eafc9fa] | 155 | else np.zeros_like(x, 'b') if x is not None |
---|
[2c1bb7b0] | 156 | else None) |
---|
[69ec80f] | 157 | self._xaxis, self._xunit = "x", "" |
---|
| 158 | self._yaxis, self._yunit = "y", "" |
---|
[3b4243d] | 159 | |
---|
| 160 | def xaxis(self, label, unit): |
---|
[a5b8477] | 161 | # type: (str, str) -> None |
---|
[3b4243d] | 162 | """ |
---|
| 163 | set the x axis label and unit |
---|
| 164 | """ |
---|
| 165 | self._xaxis = label |
---|
| 166 | self._xunit = unit |
---|
| 167 | |
---|
| 168 | def yaxis(self, label, unit): |
---|
[a5b8477] | 169 | # type: (str, str) -> None |
---|
[3b4243d] | 170 | """ |
---|
| 171 | set the y axis label and unit |
---|
| 172 | """ |
---|
| 173 | self._yaxis = label |
---|
| 174 | self._yunit = unit |
---|
| 175 | |
---|
[a5b8477] | 176 | class SesansData(Data1D): |
---|
[40a87fa] | 177 | """ |
---|
| 178 | SESANS data object. |
---|
| 179 | |
---|
| 180 | This is just :class:`Data1D` with a wavelength parameter. |
---|
| 181 | |
---|
| 182 | *x* is spin echo length and *y* is polarization (P/P0). |
---|
| 183 | """ |
---|
[a5b8477] | 184 | def __init__(self, **kw): |
---|
| 185 | Data1D.__init__(self, **kw) |
---|
| 186 | self.lam = None # type: Optional[np.ndarray] |
---|
[3b4243d] | 187 | |
---|
| 188 | class Data2D(object): |
---|
[299edd2] | 189 | """ |
---|
| 190 | 2D data object. |
---|
| 191 | |
---|
| 192 | Note that this definition matches the attributes from sasview. Some |
---|
| 193 | refactoring to allow consistent naming conventions between 1D, 2D and |
---|
| 194 | SESANS data would be helpful. |
---|
| 195 | |
---|
| 196 | **Attributes** |
---|
| 197 | |
---|
| 198 | *qx_data*, *dqx_data*: $q_x$ matrix and gaussian resolution |
---|
| 199 | |
---|
| 200 | *qy_data*, *dqy_data*: $q_y$ matrix and gaussian resolution |
---|
| 201 | |
---|
| 202 | *data*, *err_data*: $I(q)$ matrix and measurement uncertainty |
---|
| 203 | |
---|
| 204 | *mask*: values to exclude from plotting/analysis |
---|
| 205 | |
---|
| 206 | *qmin*, *qmax*: range of $q$ values in *x* |
---|
| 207 | |
---|
| 208 | *filename*: label for the data line |
---|
| 209 | |
---|
| 210 | *_xaxis*, *_xunit*: label and units for the *x* axis |
---|
| 211 | |
---|
| 212 | *_yaxis*, *_yunit*: label and units for the *y* axis |
---|
| 213 | |
---|
| 214 | *_zaxis*, *_zunit*: label and units for the *y* axis |
---|
| 215 | |
---|
| 216 | *Q_unit*, *I_unit*: units for Q and intensity |
---|
| 217 | |
---|
| 218 | *x_bins*, *y_bins*: grid steps in *x* and *y* directions |
---|
| 219 | """ |
---|
[a839b22] | 220 | def __init__(self, |
---|
| 221 | x=None, # type: Optional[np.ndarray] |
---|
| 222 | y=None, # type: Optional[np.ndarray] |
---|
| 223 | z=None, # type: Optional[np.ndarray] |
---|
| 224 | dx=None, # type: Optional[np.ndarray] |
---|
| 225 | dy=None, # type: Optional[np.ndarray] |
---|
| 226 | dz=None # type: Optional[np.ndarray] |
---|
| 227 | ): |
---|
| 228 | # type: (...) -> None |
---|
[69ec80f] | 229 | self.qx_data, self.dqx_data = x, dx |
---|
| 230 | self.qy_data, self.dqy_data = y, dy |
---|
| 231 | self.data, self.err_data = z, dz |
---|
[c094758] | 232 | self.mask = (np.isnan(z) if z is not None |
---|
| 233 | else np.zeros_like(x, dtype='bool') if x is not None |
---|
[2c1bb7b0] | 234 | else None) |
---|
[69ec80f] | 235 | self.q_data = np.sqrt(x**2 + y**2) |
---|
| 236 | self.qmin = 1e-16 |
---|
| 237 | self.qmax = np.inf |
---|
[3b4243d] | 238 | self.detector = [] |
---|
| 239 | self.source = Source() |
---|
[69ec80f] | 240 | self.Q_unit = "1/A" |
---|
| 241 | self.I_unit = "1/cm" |
---|
[299edd2] | 242 | self.xaxis("Q_x", "1/A") |
---|
| 243 | self.yaxis("Q_y", "1/A") |
---|
| 244 | self.zaxis("Intensity", "1/cm") |
---|
[69ec80f] | 245 | self._xaxis, self._xunit = "x", "" |
---|
| 246 | self._yaxis, self._yunit = "y", "" |
---|
| 247 | self._zaxis, self._zunit = "z", "" |
---|
| 248 | self.x_bins, self.y_bins = None, None |
---|
[40a87fa] | 249 | self.filename = None |
---|
[3b4243d] | 250 | |
---|
| 251 | def xaxis(self, label, unit): |
---|
[a5b8477] | 252 | # type: (str, str) -> None |
---|
[3b4243d] | 253 | """ |
---|
| 254 | set the x axis label and unit |
---|
| 255 | """ |
---|
| 256 | self._xaxis = label |
---|
| 257 | self._xunit = unit |
---|
| 258 | |
---|
| 259 | def yaxis(self, label, unit): |
---|
[a5b8477] | 260 | # type: (str, str) -> None |
---|
[3b4243d] | 261 | """ |
---|
| 262 | set the y axis label and unit |
---|
| 263 | """ |
---|
| 264 | self._yaxis = label |
---|
| 265 | self._yunit = unit |
---|
| 266 | |
---|
| 267 | def zaxis(self, label, unit): |
---|
[a5b8477] | 268 | # type: (str, str) -> None |
---|
[3b4243d] | 269 | """ |
---|
| 270 | set the y axis label and unit |
---|
| 271 | """ |
---|
| 272 | self._zaxis = label |
---|
| 273 | self._zunit = unit |
---|
| 274 | |
---|
| 275 | |
---|
| 276 | class Vector(object): |
---|
[299edd2] | 277 | """ |
---|
| 278 | 3-space vector of *x*, *y*, *z* |
---|
| 279 | """ |
---|
[3b4243d] | 280 | def __init__(self, x=None, y=None, z=None): |
---|
[a5b8477] | 281 | # type: (float, float, Optional[float]) -> None |
---|
[3b4243d] | 282 | self.x, self.y, self.z = x, y, z |
---|
| 283 | |
---|
| 284 | class Detector(object): |
---|
[69ec80f] | 285 | """ |
---|
| 286 | Detector attributes. |
---|
| 287 | """ |
---|
| 288 | def __init__(self, pixel_size=(None, None), distance=None): |
---|
[a5b8477] | 289 | # type: (Tuple[float, float], float) -> None |
---|
[69ec80f] | 290 | self.pixel_size = Vector(*pixel_size) |
---|
| 291 | self.distance = distance |
---|
[3b4243d] | 292 | |
---|
| 293 | class Source(object): |
---|
[69ec80f] | 294 | """ |
---|
| 295 | Beam attributes. |
---|
| 296 | """ |
---|
| 297 | def __init__(self): |
---|
[a5b8477] | 298 | # type: () -> None |
---|
[69ec80f] | 299 | self.wavelength = np.NaN |
---|
| 300 | self.wavelength_unit = "A" |
---|
[3b4243d] | 301 | |
---|
| 302 | |
---|
[d18582e] | 303 | def empty_data1D(q, resolution=0.0): |
---|
[a5b8477] | 304 | # type: (np.ndarray, float) -> Data1D |
---|
[3b4243d] | 305 | """ |
---|
| 306 | Create empty 1D data using the given *q* as the x value. |
---|
| 307 | |
---|
| 308 | *resolution* dq/q defaults to 5%. |
---|
| 309 | """ |
---|
| 310 | |
---|
| 311 | #Iq = 100 * np.ones_like(q) |
---|
| 312 | #dIq = np.sqrt(Iq) |
---|
| 313 | Iq, dIq = None, None |
---|
[d18582e] | 314 | q = np.asarray(q) |
---|
[3b4243d] | 315 | data = Data1D(q, Iq, dx=resolution * q, dy=dIq) |
---|
| 316 | data.filename = "fake data" |
---|
| 317 | return data |
---|
| 318 | |
---|
| 319 | |
---|
[d18582e] | 320 | def empty_data2D(qx, qy=None, resolution=0.0): |
---|
[a5b8477] | 321 | # type: (np.ndarray, Optional[np.ndarray], float) -> Data2D |
---|
[3b4243d] | 322 | """ |
---|
| 323 | Create empty 2D data using the given mesh. |
---|
| 324 | |
---|
| 325 | If *qy* is missing, create a square mesh with *qy=qx*. |
---|
| 326 | |
---|
| 327 | *resolution* dq/q defaults to 5%. |
---|
| 328 | """ |
---|
| 329 | if qy is None: |
---|
| 330 | qy = qx |
---|
[d18582e] | 331 | qx, qy = np.asarray(qx), np.asarray(qy) |
---|
[69ec80f] | 332 | # 5% dQ/Q resolution |
---|
[3b4243d] | 333 | Qx, Qy = np.meshgrid(qx, qy) |
---|
| 334 | Qx, Qy = Qx.flatten(), Qy.flatten() |
---|
[a5b8477] | 335 | Iq = 100 * np.ones_like(Qx) # type: np.ndarray |
---|
[3b4243d] | 336 | dIq = np.sqrt(Iq) |
---|
| 337 | if resolution != 0: |
---|
| 338 | # https://www.ncnr.nist.gov/staff/hammouda/distance_learning/chapter_15.pdf |
---|
| 339 | # Should have an additional constant which depends on distances and |
---|
| 340 | # radii of the aperture, pixel dimensions and wavelength spread |
---|
| 341 | # Instead, assume radial dQ/Q is constant, and perpendicular matches |
---|
| 342 | # radial (which instead it should be inverse). |
---|
| 343 | Q = np.sqrt(Qx**2 + Qy**2) |
---|
[69ec80f] | 344 | dqx = resolution * Q |
---|
| 345 | dqy = resolution * Q |
---|
[ac21c7f] | 346 | else: |
---|
[69ec80f] | 347 | dqx = dqy = None |
---|
[3b4243d] | 348 | |
---|
[69ec80f] | 349 | data = Data2D(x=Qx, y=Qy, z=Iq, dx=dqx, dy=dqy, dz=dIq) |
---|
[ce166d3] | 350 | data.x_bins = qx |
---|
| 351 | data.y_bins = qy |
---|
[69ec80f] | 352 | data.filename = "fake data" |
---|
| 353 | |
---|
| 354 | # pixel_size in mm, distance in m |
---|
| 355 | detector = Detector(pixel_size=(5, 5), distance=4) |
---|
| 356 | data.detector.append(detector) |
---|
[3b4243d] | 357 | data.source.wavelength = 5 # angstroms |
---|
| 358 | data.source.wavelength_unit = "A" |
---|
| 359 | return data |
---|
| 360 | |
---|
| 361 | |
---|
[013adb7] | 362 | def plot_data(data, view='log', limits=None): |
---|
[a5b8477] | 363 | # type: (Data, str, Optional[Tuple[float, float]]) -> None |
---|
[3b4243d] | 364 | """ |
---|
| 365 | Plot data loaded by the sasview loader. |
---|
[299edd2] | 366 | |
---|
| 367 | *data* is a sasview data object, either 1D, 2D or SESANS. |
---|
| 368 | |
---|
| 369 | *view* is log or linear. |
---|
| 370 | |
---|
| 371 | *limits* sets the intensity limits on the plot; if None then the limits |
---|
| 372 | are inferred from the data. |
---|
[3b4243d] | 373 | """ |
---|
| 374 | # Note: kind of weird using the plot result functions to plot just the |
---|
| 375 | # data, but they already handle the masking and graph markup already, so |
---|
| 376 | # do not repeat. |
---|
[a769b54] | 377 | if hasattr(data, 'isSesans') and data.isSesans: |
---|
[69ec80f] | 378 | _plot_result_sesans(data, None, None, use_data=True, limits=limits) |
---|
[e3571cb] | 379 | elif hasattr(data, 'qx_data') and not getattr(data, 'radial', False): |
---|
[69ec80f] | 380 | _plot_result2D(data, None, None, view, use_data=True, limits=limits) |
---|
[3b4243d] | 381 | else: |
---|
[69ec80f] | 382 | _plot_result1D(data, None, None, view, use_data=True, limits=limits) |
---|
[3b4243d] | 383 | |
---|
| 384 | |
---|
[a839b22] | 385 | def plot_theory(data, # type: Data |
---|
| 386 | theory, # type: Optional[np.ndarray] |
---|
| 387 | resid=None, # type: Optional[np.ndarray] |
---|
| 388 | view='log', # type: str |
---|
| 389 | use_data=True, # type: bool |
---|
| 390 | limits=None, # type: Optional[np.ndarray] |
---|
| 391 | Iq_calc=None # type: Optional[np.ndarray] |
---|
| 392 | ): |
---|
| 393 | # type: (...) -> None |
---|
[299edd2] | 394 | """ |
---|
| 395 | Plot theory calculation. |
---|
| 396 | |
---|
| 397 | *data* is needed to define the graph properties such as labels and |
---|
| 398 | units, and to define the data mask. |
---|
| 399 | |
---|
| 400 | *theory* is a matrix of the same shape as the data. |
---|
| 401 | |
---|
| 402 | *view* is log or linear |
---|
| 403 | |
---|
| 404 | *use_data* is True if the data should be plotted as well as the theory. |
---|
| 405 | |
---|
| 406 | *limits* sets the intensity limits on the plot; if None then the limits |
---|
| 407 | are inferred from the data. |
---|
[a5b8477] | 408 | |
---|
| 409 | *Iq_calc* is the raw theory values without resolution smearing |
---|
[299edd2] | 410 | """ |
---|
[a769b54] | 411 | if hasattr(data, 'isSesans') and data.isSesans: |
---|
[69ec80f] | 412 | _plot_result_sesans(data, theory, resid, use_data=True, limits=limits) |
---|
[e3571cb] | 413 | elif hasattr(data, 'qx_data') and not getattr(data, 'radial', False): |
---|
[69ec80f] | 414 | _plot_result2D(data, theory, resid, view, use_data, limits=limits) |
---|
[3b4243d] | 415 | else: |
---|
[ea75043] | 416 | _plot_result1D(data, theory, resid, view, use_data, |
---|
| 417 | limits=limits, Iq_calc=Iq_calc) |
---|
[3b4243d] | 418 | |
---|
| 419 | |
---|
[40a87fa] | 420 | def protect(func): |
---|
[a5b8477] | 421 | # type: (Callable) -> Callable |
---|
[299edd2] | 422 | """ |
---|
| 423 | Decorator to wrap calls in an exception trapper which prints the |
---|
| 424 | exception and continues. Keyboard interrupts are ignored. |
---|
| 425 | """ |
---|
[3b4243d] | 426 | def wrapper(*args, **kw): |
---|
[eafc9fa] | 427 | """ |
---|
[5c962df] | 428 | Trap and print errors from function. |
---|
| 429 | """ |
---|
[3b4243d] | 430 | try: |
---|
[40a87fa] | 431 | return func(*args, **kw) |
---|
[ee8f734] | 432 | except Exception: |
---|
[3b4243d] | 433 | traceback.print_exc() |
---|
| 434 | |
---|
| 435 | return wrapper |
---|
| 436 | |
---|
| 437 | |
---|
| 438 | @protect |
---|
[a839b22] | 439 | def _plot_result1D(data, # type: Data1D |
---|
| 440 | theory, # type: Optional[np.ndarray] |
---|
| 441 | resid, # type: Optional[np.ndarray] |
---|
| 442 | view, # type: str |
---|
| 443 | use_data, # type: bool |
---|
| 444 | limits=None, # type: Optional[Tuple[float, float]] |
---|
| 445 | Iq_calc=None # type: Optional[np.ndarray] |
---|
| 446 | ): |
---|
| 447 | # type: (...) -> None |
---|
[3b4243d] | 448 | """ |
---|
| 449 | Plot the data and residuals for 1D data. |
---|
| 450 | """ |
---|
[7ae2b7f] | 451 | import matplotlib.pyplot as plt # type: ignore |
---|
| 452 | from numpy.ma import masked_array, masked # type: ignore |
---|
[3b4243d] | 453 | |
---|
[e3571cb] | 454 | if getattr(data, 'radial', False): |
---|
[e65c3ba] | 455 | data.x = data.q_data |
---|
| 456 | data.y = data.data |
---|
[e3571cb] | 457 | |
---|
[69ec80f] | 458 | use_data = use_data and data.y is not None |
---|
| 459 | use_theory = theory is not None |
---|
| 460 | use_resid = resid is not None |
---|
[ea75043] | 461 | use_calc = use_theory and Iq_calc is not None |
---|
| 462 | num_plots = (use_data or use_theory) + use_calc + use_resid |
---|
[40a87fa] | 463 | non_positive_x = (data.x <= 0.0).any() |
---|
[3b4243d] | 464 | |
---|
| 465 | scale = data.x**4 if view == 'q4' else 1.0 |
---|
[ced5bd2] | 466 | xscale = yscale = 'linear' if view == 'linear' else 'log' |
---|
[3b4243d] | 467 | |
---|
[69ec80f] | 468 | if use_data or use_theory: |
---|
[1d61d07] | 469 | if num_plots > 1: |
---|
| 470 | plt.subplot(1, num_plots, 1) |
---|
| 471 | |
---|
[9404dd3] | 472 | #print(vmin, vmax) |
---|
[644430f] | 473 | all_positive = True |
---|
| 474 | some_present = False |
---|
[69ec80f] | 475 | if use_data: |
---|
[644430f] | 476 | mdata = masked_array(data.y, data.mask.copy()) |
---|
[3b4243d] | 477 | mdata[~np.isfinite(mdata)] = masked |
---|
| 478 | if view is 'log': |
---|
| 479 | mdata[mdata <= 0] = masked |
---|
[092cb3c] | 480 | plt.errorbar(data.x, scale*mdata, yerr=data.dy, fmt='.') |
---|
[d15a908] | 481 | all_positive = all_positive and (mdata > 0).all() |
---|
[644430f] | 482 | some_present = some_present or (mdata.count() > 0) |
---|
| 483 | |
---|
[3b4243d] | 484 | |
---|
[69ec80f] | 485 | if use_theory: |
---|
[e78edc4] | 486 | # Note: masks merge, so any masked theory points will stay masked, |
---|
| 487 | # and the data mask will be added to it. |
---|
[644430f] | 488 | mtheory = masked_array(theory, data.mask.copy()) |
---|
| 489 | mtheory[~np.isfinite(mtheory)] = masked |
---|
[3b4243d] | 490 | if view is 'log': |
---|
[d15a908] | 491 | mtheory[mtheory <= 0] = masked |
---|
[09e9e13] | 492 | plt.plot(data.x, scale*mtheory, '-') |
---|
[d15a908] | 493 | all_positive = all_positive and (mtheory > 0).all() |
---|
[644430f] | 494 | some_present = some_present or (mtheory.count() > 0) |
---|
| 495 | |
---|
[013adb7] | 496 | if limits is not None: |
---|
| 497 | plt.ylim(*limits) |
---|
[69ec80f] | 498 | |
---|
[ced5bd2] | 499 | |
---|
| 500 | xscale = ('linear' if not some_present or non_positive_x |
---|
| 501 | else view if view is not None |
---|
| 502 | else 'log') |
---|
| 503 | yscale = ('linear' |
---|
| 504 | if view == 'q4' or not some_present or not all_positive |
---|
| 505 | else view if view is not None |
---|
| 506 | else 'log') |
---|
| 507 | plt.xscale(xscale) |
---|
[092cb3c] | 508 | plt.xlabel("$q$/A$^{-1}$") |
---|
[ced5bd2] | 509 | plt.yscale(yscale) |
---|
[644430f] | 510 | plt.ylabel('$I(q)$') |
---|
[09e9e13] | 511 | title = ("data and model" if use_theory and use_data |
---|
| 512 | else "data" if use_data |
---|
| 513 | else "model") |
---|
| 514 | plt.title(title) |
---|
[3b4243d] | 515 | |
---|
[ea75043] | 516 | if use_calc: |
---|
| 517 | # Only have use_calc if have use_theory |
---|
| 518 | plt.subplot(1, num_plots, 2) |
---|
| 519 | qx, qy, Iqxy = Iq_calc |
---|
[40a87fa] | 520 | plt.pcolormesh(qx, qy[qy > 0], np.log10(Iqxy[qy > 0, :])) |
---|
[ea75043] | 521 | plt.xlabel("$q_x$/A$^{-1}$") |
---|
| 522 | plt.xlabel("$q_y$/A$^{-1}$") |
---|
[d6f5da6] | 523 | plt.xscale('log') |
---|
| 524 | plt.yscale('log') |
---|
[ea75043] | 525 | #plt.axis('equal') |
---|
| 526 | |
---|
[69ec80f] | 527 | if use_resid: |
---|
[644430f] | 528 | mresid = masked_array(resid, data.mask.copy()) |
---|
| 529 | mresid[~np.isfinite(mresid)] = masked |
---|
| 530 | some_present = (mresid.count() > 0) |
---|
[69ec80f] | 531 | |
---|
| 532 | if num_plots > 1: |
---|
[ea75043] | 533 | plt.subplot(1, num_plots, use_calc + 2) |
---|
[09e9e13] | 534 | plt.plot(data.x, mresid, '.') |
---|
[092cb3c] | 535 | plt.xlabel("$q$/A$^{-1}$") |
---|
[3b4243d] | 536 | plt.ylabel('residuals') |
---|
[09e9e13] | 537 | plt.title('(model - Iq)/dIq') |
---|
[ced5bd2] | 538 | plt.xscale(xscale) |
---|
| 539 | plt.yscale('linear') |
---|
[3b4243d] | 540 | |
---|
| 541 | |
---|
| 542 | @protect |
---|
[a839b22] | 543 | def _plot_result_sesans(data, # type: SesansData |
---|
| 544 | theory, # type: Optional[np.ndarray] |
---|
| 545 | resid, # type: Optional[np.ndarray] |
---|
| 546 | use_data, # type: bool |
---|
| 547 | limits=None # type: Optional[Tuple[float, float]] |
---|
| 548 | ): |
---|
| 549 | # type: (...) -> None |
---|
[299edd2] | 550 | """ |
---|
| 551 | Plot SESANS results. |
---|
| 552 | """ |
---|
[7ae2b7f] | 553 | import matplotlib.pyplot as plt # type: ignore |
---|
[69ec80f] | 554 | use_data = use_data and data.y is not None |
---|
| 555 | use_theory = theory is not None |
---|
| 556 | use_resid = resid is not None |
---|
| 557 | num_plots = (use_data or use_theory) + use_resid |
---|
| 558 | |
---|
| 559 | if use_data or use_theory: |
---|
[fa79f5c] | 560 | is_tof = data.lam is not None and (data.lam != data.lam[0]).any() |
---|
[69ec80f] | 561 | if num_plots > 1: |
---|
| 562 | plt.subplot(1, num_plots, 1) |
---|
| 563 | if use_data: |
---|
[84db7a5] | 564 | if is_tof: |
---|
[a5b8477] | 565 | plt.errorbar(data.x, np.log(data.y)/(data.lam*data.lam), |
---|
| 566 | yerr=data.dy/data.y/(data.lam*data.lam)) |
---|
[84db7a5] | 567 | else: |
---|
| 568 | plt.errorbar(data.x, data.y, yerr=data.dy) |
---|
[3b4243d] | 569 | if theory is not None: |
---|
[84db7a5] | 570 | if is_tof: |
---|
[09e9e13] | 571 | plt.plot(data.x, np.log(theory)/(data.lam*data.lam), '-') |
---|
[84db7a5] | 572 | else: |
---|
[09e9e13] | 573 | plt.plot(data.x, theory, '-') |
---|
[013adb7] | 574 | if limits is not None: |
---|
| 575 | plt.ylim(*limits) |
---|
[84db7a5] | 576 | |
---|
| 577 | plt.xlabel('spin echo length ({})'.format(data._xunit)) |
---|
| 578 | if is_tof: |
---|
[40a87fa] | 579 | plt.ylabel(r'(Log (P/P$_0$))/$\lambda^2$') |
---|
[84db7a5] | 580 | else: |
---|
| 581 | plt.ylabel('polarization (P/P0)') |
---|
| 582 | |
---|
[3b4243d] | 583 | |
---|
| 584 | if resid is not None: |
---|
[69ec80f] | 585 | if num_plots > 1: |
---|
| 586 | plt.subplot(1, num_plots, (use_data or use_theory) + 1) |
---|
[3b4243d] | 587 | plt.plot(data.x, resid, 'x') |
---|
[84db7a5] | 588 | plt.xlabel('spin echo length ({})'.format(data._xunit)) |
---|
[3b4243d] | 589 | plt.ylabel('residuals (P/P0)') |
---|
| 590 | |
---|
| 591 | |
---|
| 592 | @protect |
---|
[a839b22] | 593 | def _plot_result2D(data, # type: Data2D |
---|
| 594 | theory, # type: Optional[np.ndarray] |
---|
| 595 | resid, # type: Optional[np.ndarray] |
---|
| 596 | view, # type: str |
---|
| 597 | use_data, # type: bool |
---|
| 598 | limits=None # type: Optional[Tuple[float, float]] |
---|
| 599 | ): |
---|
| 600 | # type: (...) -> None |
---|
[3b4243d] | 601 | """ |
---|
| 602 | Plot the data and residuals for 2D data. |
---|
| 603 | """ |
---|
[7ae2b7f] | 604 | import matplotlib.pyplot as plt # type: ignore |
---|
[69ec80f] | 605 | use_data = use_data and data.data is not None |
---|
| 606 | use_theory = theory is not None |
---|
| 607 | use_resid = resid is not None |
---|
| 608 | num_plots = use_data + use_theory + use_resid |
---|
[3b4243d] | 609 | |
---|
| 610 | # Put theory and data on a common colormap scale |
---|
[69ec80f] | 611 | vmin, vmax = np.inf, -np.inf |
---|
[a5b8477] | 612 | target = None # type: Optional[np.ndarray] |
---|
[69ec80f] | 613 | if use_data: |
---|
| 614 | target = data.data[~data.mask] |
---|
| 615 | datamin = target[target > 0].min() if view == 'log' else target.min() |
---|
| 616 | datamax = target.max() |
---|
| 617 | vmin = min(vmin, datamin) |
---|
| 618 | vmax = max(vmax, datamax) |
---|
| 619 | if use_theory: |
---|
| 620 | theorymin = theory[theory > 0].min() if view == 'log' else theory.min() |
---|
| 621 | theorymax = theory.max() |
---|
| 622 | vmin = min(vmin, theorymin) |
---|
| 623 | vmax = max(vmax, theorymax) |
---|
| 624 | |
---|
| 625 | # Override data limits from the caller |
---|
| 626 | if limits is not None: |
---|
[013adb7] | 627 | vmin, vmax = limits |
---|
[3b4243d] | 628 | |
---|
[69ec80f] | 629 | # Plot data |
---|
| 630 | if use_data: |
---|
| 631 | if num_plots > 1: |
---|
| 632 | plt.subplot(1, num_plots, 1) |
---|
[3b4243d] | 633 | _plot_2d_signal(data, target, view=view, vmin=vmin, vmax=vmax) |
---|
| 634 | plt.title('data') |
---|
[2d81cfe] | 635 | h = plt.colorbar() |
---|
| 636 | h.set_label('$I(q)$') |
---|
[3b4243d] | 637 | |
---|
[69ec80f] | 638 | # plot theory |
---|
| 639 | if use_theory: |
---|
| 640 | if num_plots > 1: |
---|
| 641 | plt.subplot(1, num_plots, use_data+1) |
---|
[3b4243d] | 642 | _plot_2d_signal(data, theory, view=view, vmin=vmin, vmax=vmax) |
---|
| 643 | plt.title('theory') |
---|
[2d81cfe] | 644 | h = plt.colorbar() |
---|
| 645 | h.set_label(r'$\log_{10}I(q)$' if view == 'log' |
---|
| 646 | else r'$q^4 I(q)$' if view == 'q4' |
---|
| 647 | else '$I(q)$') |
---|
[3b4243d] | 648 | |
---|
[69ec80f] | 649 | # plot resid |
---|
| 650 | if use_resid: |
---|
| 651 | if num_plots > 1: |
---|
| 652 | plt.subplot(1, num_plots, use_data+use_theory+1) |
---|
[3b4243d] | 653 | _plot_2d_signal(data, resid, view='linear') |
---|
| 654 | plt.title('residuals') |
---|
[2d81cfe] | 655 | h = plt.colorbar() |
---|
| 656 | h.set_label(r'$\Delta I(q)$') |
---|
[3b4243d] | 657 | |
---|
| 658 | |
---|
| 659 | @protect |
---|
[a839b22] | 660 | def _plot_2d_signal(data, # type: Data2D |
---|
| 661 | signal, # type: np.ndarray |
---|
| 662 | vmin=None, # type: Optional[float] |
---|
| 663 | vmax=None, # type: Optional[float] |
---|
| 664 | view='log' # type: str |
---|
| 665 | ): |
---|
| 666 | # type: (...) -> Tuple[float, float] |
---|
[3b4243d] | 667 | """ |
---|
| 668 | Plot the target value for the data. This could be the data itself, |
---|
| 669 | the theory calculation, or the residuals. |
---|
| 670 | |
---|
| 671 | *scale* can be 'log' for log scale data, or 'linear'. |
---|
| 672 | """ |
---|
[7ae2b7f] | 673 | import matplotlib.pyplot as plt # type: ignore |
---|
| 674 | from numpy.ma import masked_array # type: ignore |
---|
[3b4243d] | 675 | |
---|
| 676 | image = np.zeros_like(data.qx_data) |
---|
| 677 | image[~data.mask] = signal |
---|
| 678 | valid = np.isfinite(image) |
---|
| 679 | if view == 'log': |
---|
| 680 | valid[valid] = (image[valid] > 0) |
---|
[a839b22] | 681 | if vmin is None: |
---|
| 682 | vmin = image[valid & ~data.mask].min() |
---|
| 683 | if vmax is None: |
---|
| 684 | vmax = image[valid & ~data.mask].max() |
---|
[3b4243d] | 685 | image[valid] = np.log10(image[valid]) |
---|
| 686 | elif view == 'q4': |
---|
| 687 | image[valid] *= (data.qx_data[valid]**2+data.qy_data[valid]**2)**2 |
---|
[a839b22] | 688 | if vmin is None: |
---|
| 689 | vmin = image[valid & ~data.mask].min() |
---|
| 690 | if vmax is None: |
---|
| 691 | vmax = image[valid & ~data.mask].max() |
---|
[013adb7] | 692 | else: |
---|
[a839b22] | 693 | if vmin is None: |
---|
| 694 | vmin = image[valid & ~data.mask].min() |
---|
| 695 | if vmax is None: |
---|
| 696 | vmax = image[valid & ~data.mask].max() |
---|
[013adb7] | 697 | |
---|
[3b4243d] | 698 | image[~valid | data.mask] = 0 |
---|
| 699 | #plottable = Iq |
---|
| 700 | plottable = masked_array(image, ~valid | data.mask) |
---|
[7824276] | 701 | # Divide range by 10 to convert from angstroms to nanometers |
---|
[ea75043] | 702 | xmin, xmax = min(data.qx_data), max(data.qx_data) |
---|
| 703 | ymin, ymax = min(data.qy_data), max(data.qy_data) |
---|
[013adb7] | 704 | if view == 'log': |
---|
[a839b22] | 705 | vmin_scaled, vmax_scaled = np.log10(vmin), np.log10(vmax) |
---|
[fbb9397] | 706 | else: |
---|
| 707 | vmin_scaled, vmax_scaled = vmin, vmax |
---|
[ce166d3] | 708 | plt.imshow(plottable.reshape(len(data.x_bins), len(data.y_bins)), |
---|
[ea75043] | 709 | interpolation='nearest', aspect=1, origin='lower', |
---|
[fbb9397] | 710 | extent=[xmin, xmax, ymin, ymax], |
---|
| 711 | vmin=vmin_scaled, vmax=vmax_scaled) |
---|
[ea75043] | 712 | plt.xlabel("$q_x$/A$^{-1}$") |
---|
| 713 | plt.ylabel("$q_y$/A$^{-1}$") |
---|
[013adb7] | 714 | return vmin, vmax |
---|
[3b4243d] | 715 | |
---|
| 716 | def demo(): |
---|
[a5b8477] | 717 | # type: () -> None |
---|
[299edd2] | 718 | """ |
---|
| 719 | Load and plot a SAS dataset. |
---|
| 720 | """ |
---|
[3b4243d] | 721 | data = load_data('DEC07086.DAT') |
---|
| 722 | set_beam_stop(data, 0.004) |
---|
| 723 | plot_data(data) |
---|
[7ae2b7f] | 724 | import matplotlib.pyplot as plt # type: ignore |
---|
| 725 | plt.show() |
---|
[3b4243d] | 726 | |
---|
| 727 | |
---|
| 728 | if __name__ == "__main__": |
---|
| 729 | demo() |
---|