-
Notifications
You must be signed in to change notification settings - Fork 11
/
dataset.py
1582 lines (1350 loc) · 55.5 KB
/
dataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import gemmi
import numpy as np
import pandas as pd
from pandas._libs import lib
from pandas.api.types import is_complex_dtype
from reciprocalspaceship import concat, dtypes
from reciprocalspaceship.dataseries import DataSeries
from reciprocalspaceship.decorators import (
cellify,
inplace,
range_indexed,
spacegroupify,
)
from reciprocalspaceship.dtypes.base import MTZDtype, MTZInt32Dtype
from reciprocalspaceship.utils import (
apply_to_hkl,
assign_with_binedges,
bin_by_percentile,
canonicalize_phases,
compute_structurefactor_multiplicity,
from_structurefactor,
get_reciprocal_grid_size,
hkl_to_asu,
hkl_to_observed,
in_asu,
is_absent,
is_centric,
phase_shift,
to_structurefactor,
)
class DataSet(pd.DataFrame):
"""
Representation of a crystallographic dataset.
A DataSet object provides a tabular representation of reflection data.
Reflections are conventionally indexed by Miller indices (rows), but
can also be indexed by additional metadata. Per-reflection data can be
stored as columns. For additional information about inherited methods
and attributes, please see the `Pandas.DataFrame documentation`_.
.. _Pandas.DataFrame documentation: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html
"""
_metadata = ["_spacegroup", "_cell", "_index_dtypes", "_merged"]
# -------------------------------------------------------------------
# __init__ method
def __init__(
self,
data=None,
index=None,
columns=None,
dtype=None,
copy=False,
spacegroup=None,
cell=None,
merged=None,
):
self._index_dtypes = {}
self._spacegroup = None
self._cell = None
self._merged = None
# Construct DataSet from gemmi.Mtz object
if isinstance(data, gemmi.Mtz):
from reciprocalspaceship import io
dataset = io.from_gemmi(data)
data = dataset
super().__init__(
data=data, index=index, columns=columns, dtype=dtype, copy=copy
)
# Copy over _metadata if present in provided data
if isinstance(data, DataSet):
self.__finalize__(data)
# Provided values for DataSet _metadata take precedence
if spacegroup is not None:
self.spacegroup = spacegroup
if cell is not None:
self.cell = cell
if merged is not None:
self.merged = merged
return
# -------------------------------------------------------------------
# Attributes
@property
def _constructor(self):
return DataSet
@property
def _constructor_sliced(self):
return DataSeries
@property
def spacegroup(self):
"""Crystallographic space group"""
return self._spacegroup
@spacegroup.setter
@spacegroupify("sg")
def spacegroup(self, sg):
self._spacegroup = sg
@property
def cell(self):
"""Unit cell parameters (a, b, c, alpha, beta, gamma)"""
return self._cell
@cell.setter
@cellify("uc")
def cell(self, uc):
self._cell = uc
@property
def merged(self):
"""Whether DataSet contains merged reflection data (boolean)"""
return self._merged
@merged.setter
def merged(self, val):
self._merged = val
@property
def centrics(self):
"""Access centric reflections in DataSet"""
if "CENTRIC" in self:
return self.loc[self.CENTRIC]
return self.loc[self.label_centrics().CENTRIC]
@property
def acentrics(self):
"""Access acentric reflections in DataSet"""
if "CENTRIC" in self:
return self.loc[~self.CENTRIC]
return self.loc[~self.label_centrics().CENTRIC]
@property
def reindexing_ops(self):
"""Possible reindexing operations (merohedral twin laws) for DataSet"""
return gemmi.find_twin_laws(
self.cell, self.spacegroup, max_obliq=1e-6, all_ops=False
)
# -------------------------------------------------------------------
# Methods
def find_twin_laws(self, max_obliq=1.0, all_ops=False):
"""
Find merohedral and pseudo-merohedral twin laws for cell and spacegroup of
DataSet given an obliquity threshold (degrees).
Notes
-----
- With `max_obliq=1e-6` and `all_ops=False`, this method returns the same operators
as `DataSet.reindexing_ops`
- For additional information, see the `GEMMI symmetry page`_.
.. _GEMMI symmetry page: https://gemmi.readthedocs.io/en/latest/symmetry.html#twinning
Parameters
----------
max_obliq : float
Obliquity threshold (in degrees) as defined in Le Page, J Appl Cryst (1982).
(default: 1.0)
all_ops : bool
Whether to return all twin operators. If False, only non-redundant operators
are returned (coset representative).
Returns
-------
List of gemmi.Op
"""
return gemmi.find_twin_laws(
self.cell, self.spacegroup, max_obliq=max_obliq, all_ops=all_ops
)
@inplace
def _index_from_names(self, names, inplace=False):
"""Helper method for decorators"""
if names == [None] and self.index.names != [None]:
self.reset_index(inplace=True)
elif names != [None] and self.index.names == [None]:
self.set_index(names, inplace=True)
elif names != self.index.names:
self.reset_index(inplace=True)
self.set_index(names, inplace=True)
return self
def set_index(
self, keys, drop=True, append=False, inplace=False, verify_integrity=False
):
"""
Set the DataSet index using existing columns.
Set the DataSet index (row labels) using one or more existing
columns or arrays (of the correct length). The index can replace
the existing index or expand on it.
Parameters
----------
keys : label or array-like or list of labels/arrays
This parameter can be either a single column key, a single
array of the same length as the calling DataSet, or a list
containing an arbitrary combination of column keys and arrays.
drop : bool
Whether to delete columns to be used as the new index.
append : bool
Whether to append columns to existing index.
inplace : bool
Modify the DataFrame in place (do not create a new object).
verify_integrity : bool
Check the new index for duplicates. Otherwise defer the check
until necessary. Setting to False will improve the performance
of this method
Returns
-------
DataSet or None
DataSet with the new index or None if `inplace=True`
See Also
--------
DataSet.reset_index : Reset index
"""
if not isinstance(keys, list):
keys = [keys]
# Copy dtypes of keys to cache
for key in keys:
if isinstance(key, str):
self._index_dtypes[key] = self[key].dtype.name
elif isinstance(key, (pd.Index, pd.Series)):
self._index_dtypes[key.name] = key.dtype.name
elif isinstance(key, (np.ndarray, list)):
continue
else:
raise ValueError(
f"{key} is not an instance of type str, np.ndarray, pd.Index, pd.Series, or list"
)
return super().set_index(
keys,
drop=drop,
append=append,
inplace=inplace,
verify_integrity=verify_integrity,
)
def reset_index(
self, level=None, drop=False, inplace=False, col_level=0, col_fill=""
):
"""
Reset the index or a specific level of a MultiIndex.
Reset the index to use a numbered RangeIndex. Using the `level`
argument, it is possible to reset one or more levels of a MultiIndex.
Parameters
----------
level : int, str, tuple, list
Only remove given levels from the index. Defaults to all levels
drop : bool
Do not try to insert index into dataframe columns.
inplace ; bool
Modify the DataSet in place (do not create a new object).
col_level : int or str
If the columns have multiple levels, determines which level
the labels are inserted into. By default it is inserted into
the first level.
col_fill : object
If the columns have multiple levels, determines how the other
levels are named. If None then the index name is repeated.
Returns
-------
DataSet or None
DataSet with the new index or None if `inplace=True`
See Also
--------
DataSet.set_index : Set index
"""
# GH#6: Handle level argument to reset_index
columns = level
if level is None:
columns = list(self.index.names)
def _handle_cached_dtypes(dataset, columns, drop):
"""Use _index_dtypes to restore dtypes"""
if drop:
for key in columns:
if key in dataset._index_dtypes:
dataset._index_dtypes.pop(key)
else:
for key in columns:
if key in dataset._index_dtypes:
dtype = dataset._index_dtypes.pop(key)
dataset[key] = dataset[key].astype(dtype)
return dataset
if inplace:
super().reset_index(
level,
drop=drop,
inplace=inplace,
col_level=col_level,
col_fill=col_fill,
)
_handle_cached_dtypes(self, columns, drop)
return
else:
dataset = super().reset_index(
level,
drop=drop,
inplace=inplace,
col_level=col_level,
col_fill=col_fill,
)
dataset._index_dtypes = dataset._index_dtypes.copy()
dataset = _handle_cached_dtypes(dataset, columns, drop)
return dataset
def to_numpy(self, dtype=None, copy=False, na_value=lib.no_default):
"""
Convert the DataSet to a NumPy array.
This method will attempt to infer a consensus numpy dtype from the dtypes
of the DataSet columns. If the DataSet is composed of all `int32`-backed
MTZ dtypes and does contain NaN values, the returned `dtype` will be `int32`.
For all other combinations of `MTZDtype`, the returned dtype will be `float32`.
If the DataSet contains dtypes other than `MTZDtype`, the default Pandas
behavior is used (see `Pandas documentation`_).
.. _Pandas documentation: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_numpy.html
Parameters
----------
dtype : str or np.dtype
The dtype to pass to `np.asarray()`
copy : bool
Whether to ensure that the returned value is not a view on another array.
Note that `copy=False` does not ensure that `to_numpy()` is no-copy. Rather,
`copy=True` ensure that a copy is made, even if not strictly necessary.
(default: False)
na_value : Any
The value to use for missing values. The default value depends on `dtype` and
the dtypes of the DataSet columns.
Returns
-------
np.ndarray
"""
if dtype is None:
dtype_list = [self.dtypes[k] for k in self]
# If all dtypes are MTZInt32Dtype, we can coerce to either int32 or float32
if all([isinstance(d, MTZInt32Dtype) for d in dtype_list]):
if not any([self[k].hasnans for k in self]):
return super().to_numpy(dtype="int32", copy=copy, na_value=na_value)
else:
return super().to_numpy(
dtype="float32", copy=copy, na_value=na_value
)
# All MTZDtypes can be represented as float32
if all([isinstance(d, MTZDtype) for d in dtype_list]):
return super().to_numpy(dtype="float32", copy=copy, na_value=na_value)
# Use Pandas default behavior
return super().to_numpy(dtype=dtype, copy=copy, na_value=na_value)
@classmethod
def from_gemmi(cls, gemmiMtz):
"""
Creates DataSet object from gemmi.Mtz object.
If the gemmi.Mtz object contains an M/ISYM column and contains duplicated
Miller indices, an unmerged DataSet will be constructed. The Miller indices
will be mapped to their observed values, and a partiality flag will be
extracted and stored as a boolean column with the label, ``PARTIAL``.
Otherwise, a merged DataSet will be constructed.
If columns are found with the ``MTZInt`` dtype and are labeled ``PARTIAL``
or ``CENTRIC``, these will be interpreted as boolean flags used to
label partial or centric reflections, respectively.
Parameters
----------
gemmiMtz : gemmi.Mtz
Returns
-------
DataSet
"""
return cls(gemmiMtz)
def to_gemmi(
self,
skip_problem_mtztypes=False,
project_name="reciprocalspaceship",
crystal_name="reciprocalspaceship",
dataset_name="reciprocalspaceship",
):
"""
Creates gemmi.Mtz object from DataSet object.
If ``dataset.merged == False``, the reflections will be mapped to the
reciprocal space ASU, and a M/ISYM column will be constructed.
If boolean flags with the label ``PARTIAL`` or ``CENTRIC`` are found
in the DataSet, these will be cast to the ``MTZInt`` dtype, and included
in the gemmi.Mtz object.
Parameters
----------
skip_problem_mtztypes : bool
Whether to skip columns in DataSet that do not have specified
MTZ datatypes
project_name : str
Project name to assign to MTZ file
crystal_name : str
Crystal name to assign to MTZ file
dataset_name : str
Dataset name to assign to MTZ file
Returns
-------
gemmi.Mtz
"""
from reciprocalspaceship import io
return io.to_gemmi(
self, skip_problem_mtztypes, project_name, crystal_name, dataset_name
)
def to_pickle(self, path, *args, **kwargs):
"""
Pickle object to file.
This can be useful for saving non-MTZ compatible data files for future use. For additional documentation on accepted arguments, see the
`Pandas DataFrame.to_pickle() API <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_pickle.html>`_.
Parameters
----------
path : str
File path where the pickled object will be stored.
See Also
--------
read_pickle() : Load pickled reciprocalspaceship object from file.
"""
return super().to_pickle(path, *args, **kwargs)
def to_structurefactor(self, sf_key, phase_key):
"""
Convert structure factor amplitudes and phases to complex structure
factors
Parameters
----------
sf_key : str
Column label for structure factor amplitudes
phase_key : str
Column label for phases
Returns
-------
rs.DataSeries
Complex structure factors
See Also
--------
DataSet.from_structurefactor : Convert complex structure factor to amplitude and phase
"""
sfs = to_structurefactor(self[sf_key], self[phase_key])
return DataSeries(sfs, index=self.index)
def from_structurefactor(self, sf_key):
"""
Convert complex structure factors to structure factor amplitudes
and phases
Parameters
----------
sf_key : str
Column label for complex structure factors
Returns
-------
(sf, phase) : tuple of DataSeris
Tuple of DataSeries for the structure factor amplitudes and
phases corresponding to the complex structure factors
See Also
--------
DataSet.to_structurefactor : Convert amplitude and phase to complex structure factor
"""
return from_structurefactor(self[sf_key])
def merge(self, *args, check_isomorphous=True, **kwargs):
"""
Merge DataSet or named DataSeries using a database-style join on
columns or indices.
For additional documentation on accepted arguments, see the
`Pandas DataFrame.merge() API <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html>`_.
Parameters
----------
check_isomorphous : bool
If True, the spacegroup and cell attributes of DataSets in `other`
will be compared to those of the calling DataSet to ensure
they are isomorphous.
Returns
-------
rs.DataSet
See Also
--------
DataSet.join : Similar method with support for lists of ``rs`` objects
"""
right = kwargs.get("right", args[0])
if check_isomorphous and isinstance(right, DataSet):
if not self.is_isomorphous(right):
raise ValueError("`right` DataSet is not isomorphous")
result = super().merge(*args, **kwargs)
return result.__finalize__(self)
def join(self, *args, check_isomorphous=True, **kwargs):
"""
Join DataSets or named DataSeries using a database-style join on
columns or indices. This method can be used to join lists ``rs`` objects
to a given DataSet.
For additional documentation on accepted arguments, see the
`Pandas DataFrame.join() API <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html>`_.
Parameters
----------
check_isomorphous : bool
If True, the spacegroup and cell attributes of DataSets in `other`
will be compared to those of the calling DataSet to ensure
they are isomorphous.
Returns
-------
rs.DataSet
See Also
--------
DataSet.merge : Similar method with added flexibility for distinct column labels
"""
other = kwargs.get("other", args[0])
if check_isomorphous:
if isinstance(other, (list, tuple)):
for o in other:
if isinstance(o, DataSet) and not self.is_isomorphous(o):
raise ValueError("DataSet in `other` is not isomorphous")
else:
if isinstance(other, DataSet) and not self.is_isomorphous(other):
raise ValueError("`other` DataSet is not isomorphous")
result = super().join(*args, **kwargs)
return result.__finalize__(self)
def write_mtz(
self,
mtzfile,
skip_problem_mtztypes=False,
project_name="reciprocalspaceship",
crystal_name="reciprocalspaceship",
dataset_name="reciprocalspaceship",
):
"""
Write DataSet to MTZ file.
If ``DataSet.merged == False``, the reflections will be mapped to the
reciprocal space ASU, and a M/ISYM column will be constructed.
If boolean flags with the label ``PARTIAL`` or ``CENTRIC`` are found
in the DataSet, these will be cast to the ``MTZInt`` dtype, and included
in the output MTZ file.
Parameters
----------
mtzfile : str or file
name of an mtz file or a file object
skip_problem_mtztypes : bool
Whether to skip columns in DataSet that do not have specified
MTZ datatypes
project_name : str
Project name to assign to MTZ file
crystal_name : str
Crystal name to assign to MTZ file
dataset_name : str
Dataset name to assign to MTZ file
"""
from reciprocalspaceship import io
return io.write_mtz(
self,
mtzfile,
skip_problem_mtztypes,
project_name,
crystal_name,
dataset_name,
)
def select_mtzdtype(self, dtype):
"""
Return subset of DataSet’s columns that are of the given dtype.
Parameters
----------
dtype : str or instance of MTZDtype
Single-letter MTZ code, name, or MTZDtype instance to return
Returns
-------
DataSet
Subset of the DataSet with columns matching the requested dtype. If
no columns of the requested dtype are found, an empty DataSet is
returned.
Raises
------
ValueError
If `dtype` is not a string nor a MTZDtype instance
"""
if isinstance(dtype, MTZDtype):
return self[[k for k in self if isinstance(self.dtypes[k], type(dtype))]]
elif isinstance(dtype, str):
# One-letter code
if len(dtype) == 1:
return self[
[
k
for k in self
if hasattr(self[k].dtype, "mtztype")
and self[k].dtype.mtztype == dtype
]
]
else:
return self[[k for k in self if self[k].dtype.name == dtype]]
raise ValueError(
f"dtype must be a str or MTZDtype instance. Called with: {dtype}"
)
def get_phase_keys(self):
"""
Return column labels for data with Phase dtype.
Returns
-------
keys : list of strings
list of column labels with ``Phase`` dtype
"""
keys = [k for k in self if isinstance(self.dtypes[k], dtypes.PhaseDtype)]
return keys
def get_complex_keys(self):
"""
Return columns labels for data with complex dtype.
Returns
-------
keys : list of strings
list of column labels with complex dtype
"""
keys = [k for k in self if is_complex_dtype(self.dtypes[k])]
return keys
def get_m_isym_keys(self):
"""
Return column labels for data with M/ISYM dtype.
Returns
-------
key : list of strings
list of column labels with ``M/ISYM`` dtype
"""
keys = [k for k in self if isinstance(self.dtypes[k], dtypes.M_IsymDtype)]
return keys
@inplace
@range_indexed
def apply_symop(self, symop, inplace=False):
"""
Apply symmetry operation to all reflections in DataSet object.
Parameters
----------
symop : str, gemmi.Op
Gemmi symmetry operation or string representing symmetry op
inplace : bool
Whether to return a new DataFrame or make the change in place
"""
if isinstance(symop, str):
symop = gemmi.Op(symop)
elif not isinstance(symop, gemmi.Op):
raise ValueError(f"Provided symop is not of type gemmi.Op")
dataset = self
# Handle phase flips associated with Friedel operator
if symop.det_rot() < 0:
phic = -1
else:
phic = 1
# Apply symop to generate new HKL indices and phase shifts
H = dataset.get_hkls()
hkl = apply_to_hkl(H, symop)
phase_shifts = phase_shift(H, symop)
dataset[["H", "K", "L"]] = hkl
dataset[["H", "K", "L"]] = dataset[["H", "K", "L"]].astype(
dtypes.HKLIndexDtype()
)
# Shift phases according to symop
for key in dataset.get_phase_keys():
dataset[key] = phic * (dataset[key] - np.rad2deg(phase_shifts))
dataset[key] = canonicalize_phases(dataset[key], deg=True)
for key in dataset.get_complex_keys():
dataset[key] *= np.exp(-1j * phase_shifts)
if symop.det_rot() < 0:
dataset[key] = np.conjugate(dataset[key])
return dataset
def get_hkls(self):
"""
Get the Miller indices in the DataSet as a ndarray.
Returns
-------
hkl : ndarray, shape=(n_reflections, 3)
Miller indices in DataSet
"""
hkl = self.reset_index()[["H", "K", "L"]].to_numpy(dtype=np.int32)
return hkl
@inplace
def label_centrics(self, inplace=False):
"""
Label centric reflections in DataSet. A new column of
booleans, "CENTRIC", is added to the object.
Parameters
----------
inplace : bool
Whether to add the column in place or to return a copy
"""
if self.spacegroup is None:
raise ValueError("DataSet space group must be set to label absences")
self["CENTRIC"] = is_centric(self.get_hkls(), self.spacegroup)
return self
@inplace
def label_absences(self, inplace=False):
"""
Label systematically absent reflections in DataSet. A new column
of booleans, "ABSENT", is added to the object.
Parameters
----------
inplace : bool
Whether to add the column in place or to return a copy
"""
if self.spacegroup is None:
raise ValueError("DataSet space group must be set to label absences")
self["ABSENT"] = is_absent(self.get_hkls(), self.spacegroup)
return self
@inplace
def remove_absences(self, inplace=False):
"""
Remove systematically absent reflections in DataSet.
Parameters
----------
inplace : bool
Whether to add the column in place or to return a copy
Returns
-------
DataSet
"""
mask = is_absent(self.get_hkls(), self.spacegroup)
idx = self.index[mask]
self.drop(index=idx, inplace=True)
return self
@inplace
def infer_mtz_dtypes(self, inplace=False, index=True):
"""
Infers MTZ dtypes from column names and underlying data. This
method iterates over each column in the DataSet and tries to infer
its proper MTZ dtype based on common MTZ naming conventions.
If a given column is already a MTZDtype, its type will be unchanged.
If index is True, the MTZ dtypes will be inferred for named columns
in the index.
Parameters
----------
inplace : bool
Whether to modify the dtypes in place or to return a copy
index : bool
Infer MTZ dtypes for named column(s) in the DataSet index
Returns
-------
DataSet
See Also
--------
DataSeries.infer_mtz_dtype : Infer MTZ dtype for DataSeries
"""
# See GH#2: Handle unnamed Index objects such as RangeIndex
if index:
index_keys = list(filter(None, self.index.names))
if index_keys:
self.reset_index(inplace=True, level=index_keys)
for c in self:
self[c] = self[c].infer_mtz_dtype()
if index and index_keys:
self.set_index(index_keys, inplace=True)
return self
@inplace
def compute_dHKL(self, inplace=False):
"""
Compute the real space lattice plane spacing, d, associated with
the HKL indices in the object.
Parameters
----------
inplace : bool
Whether to add the column in place or return a copy
"""
dHKL = self.cell.calculate_d_array(self.get_hkls())
self["dHKL"] = DataSeries(dHKL, dtype="R", index=self.index)
return self
@inplace
def compute_multiplicity(self, inplace=False, include_centering=True):
"""
Compute the multiplicity of reflections in DataSet. A new column of
floats, "EPSILON", is added to the object.
Parameters
----------
inplace : bool
Whether to add the column in place or to return a copy
include_centering : bool
Whether to include centering operations in the multiplicity calculation.
The default is to include them.
"""
epsilon = compute_structurefactor_multiplicity(
self.get_hkls(), self.spacegroup, include_centering
)
self["EPSILON"] = DataSeries(epsilon, dtype="I", index=self.index)
return self
@inplace
def assign_resolution_bins(
self,
bins=20,
inplace=False,
return_labels=True,
format_str=".2f",
return_edges=False,
):
"""
Assign reflections in DataSet to resolution bins.
Notes
-----
- If bin edges are provided, any reflections outside of the specified range
are dropped.
Parameters
----------
bins : int, list, or np.ndarray
Number of bins or bin edges to use when assigning resolution bins. If
bin edges are provided, they must be monotonic (default: 20)
inplace : bool
Whether to add the column in place or return a copy (default: False)
return_labels : bool
Whether to return a list of labels corresponding to the edges
of each resolution bin (default: True)
format_str : str
Format string for constructing bin labels
return_edges : bool
Whether to return bin edges that define the resolution bin boundaries.
The bin edges are returned as a 1-dimensional array with `bins + 1` entries
(default: False)
Returns
-------
(DataSet, list), (DataSet, ndarray), (DataSet, list, ndarray) or DataSet
"""
dHKL = self.compute_dHKL()["dHKL"]
if isinstance(bins, int):
assignments, edges = bin_by_percentile(dHKL, bins=bins, ascending=False)
else:
# Use bin edges for assignments and drop reflections outside of range
mask = (dHKL >= min(bins)) & (dHKL <= max(bins))
assignments = assign_with_binedges(dHKL[mask], bin_edges=bins)
edges = np.array(bins)
self._update_inplace(self.loc[mask])
self.loc[:, "bin"] = DataSeries(assignments, dtype="I", index=self.index)
# Package return values
result = [self]
if return_labels:
labels = [
f"{e1:{format_str}} - {e2:{format_str}}"
for e1, e2 in zip(edges[:-1], edges[1:])
]
result.append(labels)
if return_edges:
result.append(edges)
if len(result) == 1:
return self
return tuple(result)
def stack_anomalous(
self, plus_labels=None, minus_labels=None, suffixes=("(+)", "(-)")
):
"""
Convert data from two-column anomalous format to one-column
format. Intensities, structure factor amplitudes, or other data
are converted from separate columns corresponding to a single
Miller index to the same data column at different rows indexed
by the Friedel-plus or Friedel-minus Miller index.
This method will return a DataSet with, at most, twice as many rows as the
original -- one row for each Friedel pair. In most cases, the resulting
DataSet will be smaller, because centric reflections will not be stacked.
For a merged DataSet, this has the effect of mapping reflections
from the positive reciprocal space ASU to the positive and negative
reciprocal space ASU, for Friedel-plus and Friedel-minus reflections,
respectively.
Notes
-----
- A ValueError is raised if invoked with an unmerged DataSet
- It is assumed that Friedel-plus column labels are suffixed with (+),
and that Friedel-minus column labels are suffixed with (-)
- A ValueError is raised if stripping suffixes will lead to a duplicate
column name
- Corresponding column labels are expected to be given in the same order
Parameters
----------
plus_labels: str or list-like
Column label or list of column labels of data associated with
Friedel-plus reflections
minus_labels: str or list-like
Column label or list of column labels of data associated with
Friedel-minus reflections
suffixes: list of strings
Suffixes to identify column labels associated with Friedel-plus
and Friedel-minus reflections. Only consulted if plus_labels and
minus_labels are None. Defaults to ("(+)", "(-)")
Returns
-------
DataSet
See Also
--------
DataSet.unstack_anomalous : Opposite of stack_anomalous
"""
if not self.merged:
raise ValueError(
"DataSet.stack_anomalous() cannot be called with unmerged data"
)
# Make sure suffixes are valid