diffpy.utils 3.6.1rc0__py3-none-any.whl → 3.7.0rc0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,178 @@
1
+ import functools
2
+ import warnings
3
+
4
+ # Deprecated decorator is available for Python 3.13+, once
5
+ # Support for earlier versions is dropped, this custom
6
+ # implementation can be removed.
7
+ try:
8
+ from warnings import deprecated as _builtin_deprecated
9
+ except ImportError:
10
+ _builtin_deprecated = None
11
+
12
+
13
+ def deprecated(message, *, category=DeprecationWarning, stacklevel=1):
14
+ """Deprecation decorator for functions and classes that is
15
+ compatible with Python versions prior to 3.13.
16
+
17
+ Examples
18
+ --------
19
+ Basic usage with a deprecated function:
20
+
21
+ .. code-block:: python
22
+
23
+ from diffpy.utils._deprecator import (
24
+ deprecated, build_deprecation_message
25
+ )
26
+
27
+ deprecation_warning = build_deprecation_message("diffpy.utils",
28
+ "old_function",
29
+ "new_function",
30
+ "4.0.0")
31
+
32
+ @deprecated(deprecation_warning)
33
+ def old_function(x, y):
34
+ '''This function is deprecated and will be removed in version
35
+ 4.0.0. Please use new_function instead'''
36
+ return new_function(x, y)
37
+
38
+ def new_function(x, y):
39
+ return x + y
40
+
41
+ old_function(1, 2) # Works but emits DeprecationWarning
42
+ new_function(1, 2) # Works, no warning
43
+
44
+
45
+ Deprecating a class:
46
+
47
+ .. code-block:: python
48
+
49
+ from diffpy.utils._deprecator import (
50
+ deprecated, build_deprecation_message
51
+ )
52
+ deprecation_warning = build_deprecation_message("diffpy.utils",
53
+ "OldAtom",
54
+ "NewAtom",
55
+ "4.0.0")
56
+
57
+ @deprecated(deprecation_warning)
58
+ class OldAtom:
59
+ def __new__(cls, *args, **kwargs):
60
+ warnings.warn(
61
+ "OldAtom is deprecated and will be removed in
62
+ version 4.0.0. Use NewClass instead.",
63
+ DeprecationWarning,
64
+ stacklevel=2,
65
+ )
66
+ return NewAtom(*args, **kwargs)
67
+
68
+ class NewAtom:
69
+ def __init__(self, symbol):
70
+ self.symbol = symbol
71
+
72
+ a = OldAtom("C") # Works but emits DeprecationWarning
73
+ b = NewAtom("C") # Works with no warning
74
+ """
75
+ if _builtin_deprecated is not None:
76
+ return _builtin_deprecated(
77
+ message, category=category, stacklevel=stacklevel
78
+ )
79
+ if not isinstance(message, str):
80
+ raise TypeError(
81
+ f"Expected an object of type str for 'message', not "
82
+ f"{type(message).__name__!r}"
83
+ )
84
+
85
+ def decorator(obj):
86
+ setattr(obj, "__deprecated__", message)
87
+ if callable(obj):
88
+
89
+ @functools.wraps(obj)
90
+ def wrapper(*args, **kwargs):
91
+ warnings.warn(message, category, stacklevel=stacklevel + 1)
92
+ return obj(*args, **kwargs)
93
+
94
+ return wrapper
95
+ raise TypeError(
96
+ "deprecated decorator can only be applied to functions or classes"
97
+ )
98
+
99
+ return decorator
100
+
101
+
102
+ def build_deprecation_message(
103
+ old_base, old_name, new_name, removal_version, new_base=None
104
+ ):
105
+ """Generate a deprecation message.
106
+
107
+ Parameters
108
+ ----------
109
+ old_base : str
110
+ The base module or class where the deprecated item resides.
111
+ This will look like the import statement used in the code
112
+ currently
113
+ old_name : str
114
+ The name of the deprecated item.
115
+ new_name : str
116
+ The name of the new item to use.
117
+ removal_version : str
118
+ The version when the deprecated item will be removed.
119
+ new_base : str Optional. Defaults to old_base.
120
+ The base module or class where the new item resides.
121
+ This will look like the import statement that
122
+ will be used in the code moving forward. If not specified,
123
+ the new base defaults to the old one.
124
+
125
+ Returns
126
+ -------
127
+ str
128
+ A formatted deprecation message.
129
+ """
130
+ if new_base is None:
131
+ new_base = old_base
132
+ return (
133
+ f"'{old_base}.{old_name}' is deprecated and will be removed in "
134
+ f"version {removal_version}. Please use '{new_base}.{new_name}' "
135
+ f"instead."
136
+ )
137
+
138
+
139
+ def generate_deprecation_docstring(new_name, removal_version, new_base=None):
140
+ """Generate a docstring for copy-pasting into a deprecated function.
141
+
142
+ This function will print the text to the terminal for copy-pasting.
143
+
144
+ Parameters
145
+ ----------
146
+ new_name : str
147
+ The name of the new function or class to replace the existing one.
148
+ removal_version : str
149
+ The version when the deprecated item is targeted for removal,
150
+ e.g., 4.0.0.
151
+ new_base : str, optional
152
+ The new base for importing. The new import statement would look like
153
+ "from new_base import new_name". Defaults to None.
154
+
155
+ Example
156
+ -------
157
+ >>> from diffpy.utils._deprecator import generate_deprecation_docstring
158
+ >>> generate_deprecation_docstring("new_name", "4.0.0")
159
+
160
+ The message looks like:
161
+ This function has been deprecated and will be removed in version
162
+ {removal_version}. Please use {new_base}.{new_name} instead.
163
+
164
+
165
+ Returns
166
+ -------
167
+ None
168
+ """
169
+ if new_base is None:
170
+ function_location = new_name
171
+ else:
172
+ function_location = f"{new_base}.{new_name}"
173
+ print(
174
+ f"This function has been deprecated and will be removed in version "
175
+ f"{removal_version}.\n"
176
+ f"Please use {function_location} instead."
177
+ )
178
+ return
@@ -108,18 +108,18 @@ class DiffractionObject:
108
108
 
109
109
  Parameters
110
110
  ----------
111
- xarray : ndarray
111
+ xarray : ``ndarray``
112
112
  The independent variable array containing "q", "tth", or "d" values.
113
- yarray : ndarray
113
+ yarray : ``ndarray``
114
114
  The dependent variable array corresponding to intensity values.
115
115
  xtype : str
116
116
  The type of the independent variable in `xarray`. Must be one of
117
117
  {*XQUANTITIES}.
118
- wavelength : float, optional, default is None.
118
+ wavelength : float, ``optional``, default is None.
119
119
  The wavelength of the incoming beam, specified in angstroms (Å)
120
- scat_quantity : str, optional, default is an empty string "".
120
+ scat_quantity : str, ``optional``, default is an empty string "".
121
121
  The type of scattering experiment (e.g., "x-ray", "neutron").
122
- name : str, optional, default is an empty string "".
122
+ name : str, ``optional``, default is an empty string "".
123
123
  The name or label for the scattering data.
124
124
  metadata : dict, optional, default is an empty dictionary {}
125
125
  The additional metadata associated with the diffraction object.
@@ -211,8 +211,8 @@ class DiffractionObject:
211
211
  return True
212
212
 
213
213
  def __add__(self, other):
214
- """Add a scalar value or another DiffractionObject to the yarray of the
215
- DiffractionObject.
214
+ """Add a scalar value or another DiffractionObject to the yarray
215
+ of the DiffractionObject.
216
216
 
217
217
  Parameters
218
218
  ----------
@@ -262,8 +262,8 @@ class DiffractionObject:
262
262
  __radd__ = __add__
263
263
 
264
264
  def __sub__(self, other):
265
- """Subtract scalar value or another DiffractionObject to the yarray of
266
- the DiffractionObject.
265
+ """Subtract scalar value or another DiffractionObject to the
266
+ yarray of the DiffractionObject.
267
267
 
268
268
  This method behaves similarly to the `__add__` method, but performs
269
269
  subtraction instead of addition. For details on parameters, returns
@@ -290,8 +290,8 @@ class DiffractionObject:
290
290
  __rsub__ = __sub__
291
291
 
292
292
  def __mul__(self, other):
293
- """Multiply a scalar value or another DiffractionObject with the yarray
294
- of this DiffractionObject.
293
+ """Multiply a scalar value or another DiffractionObject with the
294
+ yarray of this DiffractionObject.
295
295
 
296
296
  This method behaves similarly to the `__add__` method, but performs
297
297
  multiplication instead of addition. For details on parameters,
@@ -318,8 +318,8 @@ class DiffractionObject:
318
318
  __rmul__ = __mul__
319
319
 
320
320
  def __truediv__(self, other):
321
- """Divide the yarray of this DiffractionObject by a scalar value or
322
- another DiffractionObject.
321
+ """Divide the yarray of this DiffractionObject by a scalar value
322
+ or another DiffractionObject.
323
323
 
324
324
  This method behaves similarly to the `__add__` method, but performs
325
325
  division instead of addition. For details on parameters, returns,
@@ -360,7 +360,7 @@ class DiffractionObject:
360
360
 
361
361
  Returns
362
362
  -------
363
- ndarray
363
+ ``ndarray``
364
364
  The shape (len(data), 4) 2D array with columns containing the `
365
365
  yarray` (intensity) and the `xarray` values in q, tth, and d.
366
366
 
@@ -386,7 +386,7 @@ class DiffractionObject:
386
386
  Returns
387
387
  -------
388
388
  input_xtype : str
389
- The type of `xarray`, which must be one of {*XQUANTITIES}.
389
+ The type of `xarray`, which must be one of ``{*XQUANTITIES}``.
390
390
  """
391
391
  return self._input_xtype
392
392
 
@@ -400,7 +400,7 @@ class DiffractionObject:
400
400
 
401
401
  Returns
402
402
  -------
403
- uuid : UUID
403
+ uuid : ``UUID``
404
404
  The unique identifier of the DiffractionObject instance.
405
405
  """
406
406
  return self._uuid
@@ -409,17 +409,17 @@ class DiffractionObject:
409
409
  def uuid(self, _):
410
410
  raise AttributeError(_setter_wmsg("uuid"))
411
411
 
412
- def get_array_index(self, xtype, xvalue):
413
- """Return the index of the closest value in the array associated with
412
+ def get_array_index(self, xvalue, xtype=None):
413
+ f"""Return the index of the closest value in the array associated with
414
414
  the specified xtype and the value provided.
415
415
 
416
416
  Parameters
417
417
  ----------
418
- xtype : str
419
- The type of the independent variable in `xarray`. Must be one
420
- of {*XQUANTITIES}.
421
418
  xvalue : float
422
419
  The value of the xtype to find the closest index for.
420
+ xtype : str, optional
421
+ The type of the independent variable in `xarray`. Must be one
422
+ of {*XQUANTITIES, }. Default is {self._input_xtype}
423
423
 
424
424
  Returns
425
425
  -------
@@ -427,8 +427,11 @@ class DiffractionObject:
427
427
  The index of the closest value in the array associated with the
428
428
  specified xtype and the value provided.
429
429
  """
430
-
431
- xtype = self._input_xtype
430
+ if xtype is None:
431
+ xtype = self._input_xtype
432
+ else:
433
+ if xtype not in XQUANTITIES:
434
+ raise ValueError(_xtype_wmsg(xtype))
432
435
  xarray = self.on_xtype(xtype)[0]
433
436
  if len(xarray) == 0:
434
437
  raise ValueError(
@@ -471,31 +474,34 @@ class DiffractionObject:
471
474
  return self.on_d(), "d"
472
475
 
473
476
  def on_q(self):
474
- """Return the tuple of two 1D numpy arrays containing q and y data.
477
+ """Return the tuple of two 1D numpy arrays containing q and y
478
+ data.
475
479
 
476
480
  Returns
477
481
  -------
478
- (q-array, y-array) : tuple of ndarray
482
+ (q-array, y-array) : tuple of ``ndarray``
479
483
  The tuple containing two 1D numpy arrays with q and y data
480
484
  """
481
485
  return [self.all_arrays[:, 1], self.all_arrays[:, 0]]
482
486
 
483
487
  def on_tth(self):
484
- """Return the tuple of two 1D numpy arrays containing tth and y data.
488
+ """Return the tuple of two 1D numpy arrays containing tth and y
489
+ data.
485
490
 
486
491
  Returns
487
492
  -------
488
- (tth-array, y-array) : tuple of ndarray
493
+ (tth-array, y-array) : tuple of ``ndarray``
489
494
  The tuple containing two 1D numpy arrays with tth and y data
490
495
  """
491
496
  return [self.all_arrays[:, 2], self.all_arrays[:, 0]]
492
497
 
493
498
  def on_d(self):
494
- """Return the tuple of two 1D numpy arrays containing d and y data.
499
+ """Return the tuple of two 1D numpy arrays containing d and y
500
+ data.
495
501
 
496
502
  Returns
497
503
  -------
498
- (d-array, y-array) : tuple of ndarray
504
+ (d-array, y-array) : tuple of ``ndarray``
499
505
  The tuple containing two 1D numpy arrays with d and y data
500
506
  """
501
507
  return [self.all_arrays[:, 3], self.all_arrays[:, 0]]
@@ -503,8 +509,8 @@ class DiffractionObject:
503
509
  def scale_to(
504
510
  self, target_diff_object, q=None, tth=None, d=None, offset=None
505
511
  ):
506
- """Return a new diffraction object which is the current object but
507
- rescaled in y to the target.
512
+ """Return a new diffraction object which is the current object
513
+ but rescaled in y to the target.
508
514
 
509
515
  By default, if `q`, `tth`, or `d` are not provided, scaling is
510
516
  based on the max intensity from each object. Otherwise, y-value in
@@ -519,12 +525,12 @@ class DiffractionObject:
519
525
  target_diff_object: DiffractionObject
520
526
  The diffraction object you want to scale the current one onto.
521
527
 
522
- q, tth, d : float, optional, default is None
528
+ q, tth, d : float, ``optional``, default is None
523
529
  The value of the x-array where you want the curves to line up
524
530
  vertically. Specify a value on one of the allowed grids, q, tth,
525
531
  or d), e.g., q=10.
526
532
 
527
- offset : float, optional, default is None
533
+ offset : float, ``optional``, default is None
528
534
  The offset to add to the scaled y-values.
529
535
 
530
536
  Returns
@@ -565,22 +571,23 @@ class DiffractionObject:
565
571
  return scaled_do
566
572
 
567
573
  def on_xtype(self, xtype):
568
- """Return a tuple of two 1D numpy arrays containing x and y data.
574
+ """Return a tuple of two 1D numpy arrays containing x and y
575
+ data.
569
576
 
570
577
  Parameters
571
578
  ----------
572
579
  xtype : str
573
580
  The type of quantity for the independent variable chosen from
574
- {*XQUANTITIES, }
581
+ ``{*XQUANTITIES, }``
575
582
 
576
583
  Raises
577
584
  ------
578
585
  ValueError
579
- Raised when the specified xtype is not among {*XQUANTITIES, }
586
+ Raised when the specified xtype is not among ``{*XQUANTITIES, }``
580
587
 
581
588
  Returns
582
589
  -------
583
- (xarray, yarray) : tuple of ndarray
590
+ (xarray, yarray) : tuple of ``ndarray``
584
591
  The tuple containing two 1D numpy arrays with x and y data for
585
592
  the specified xtype.
586
593
  """
@@ -594,16 +601,17 @@ class DiffractionObject:
594
601
  raise ValueError(_xtype_wmsg(xtype))
595
602
 
596
603
  def dump(self, filepath, xtype=None):
597
- """Dump the xarray and yarray of the diffraction object to a two-column
598
- file, with the associated information included in the header.
604
+ """Dump the xarray and yarray of the diffraction object to a
605
+ two-column file, with the associated information included in the
606
+ header.
599
607
 
600
608
  Parameters
601
609
  ----------
602
610
  filepath : str
603
611
  The filepath where the diffraction object will be dumped
604
- xtype : str, optional, default is q
612
+ xtype : str, ``optional``, default is q
605
613
  The type of quantity for the independent variable chosen from
606
- {*XQUANTITIES, }
614
+ ``{*XQUANTITIES, }``
607
615
 
608
616
  Examples
609
617
  --------
@@ -6,10 +6,18 @@
6
6
  # (c) 2010 The Trustees of Columbia University
7
7
  # in the City of New York. All rights reserved.
8
8
  #
9
- # File coded by: Chris Farrow
9
+ # File coded by: Simon Billinge
10
10
  #
11
11
  # See AUTHORS.txt for a list of people who contributed.
12
12
  # See LICENSE_DANSE.txt for license information.
13
13
  #
14
14
  ##############################################################################
15
15
  """Various utilities related to data parsing and manipulation."""
16
+
17
+ # this allows load_data to be imported from diffpy.utils.parsers
18
+ # it is needed during deprecation of the old loadData structure
19
+ # when we remove loadData we can move all the parser functionality
20
+ # a parsers.py module (like tools.py) and remove this if we want
21
+ from .loaddata import load_data
22
+
23
+ __all__ = ["load_data"]