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