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 | class MeasureIABox(MeasureWBox, MeasureMultipolesBox, MeasureWBoxJackknife, MeasureMBoxJackknife, MeasureJackknife,
MeasureGalaxyContributionsBox, CheckInput):
r"""Manages the IA correlation function measurement methods used in the MeasureIA package based on speed and input.
This class is used to call the methods that measure $w_{gg}$, $w_{g+}$ and multipoles for simulations in cartesian
coordinates. Depending on the input parameters, various correlations incl covariance estimates are measured for
given data.
Methods
-------
measure_xi_w()
Compute projected correlations $w_{gg}$ and/or $w_{g+}$.
measure_xi_multipoles()
Compute multipoles of the correlation functions, $\tilde{\xi}_{gg,0}$ and/or $\tilde{\xi}_{g+,2}$.
Notes
-----
Inherits attributes from 'SimInfo', where 'boxsize', 'L_0p5' and 'snap_group' are used in this class.
Inherits attributes from 'MeasureIABase', where 'data', 'output_file_name', 'periodicity', 'Num_position',
'Num_shape', 'r_min', 'r_max', 'num_bins_r', 'num_bins_pi', 'r_bins', 'pi_bins', 'mu_r_bins' are used.
"""
def __init__(
self,
data,
output_file_name,
simulation=None,
snapshot=None,
separation_limits=[0.1, 20.0],
num_bins_r=8,
num_bins_pi=20,
pi_max=None,
boxsize=None,
periodicity=True,
num_nodes=1,
positions_density_sample_name="Position",
positions_shape_sample_name="Position_shape_sample",
axis_direction_name="Axis_Direction",
axis_ratio_name="q",
axis_direction_density_sample_name="Axis_Direction_density_sample",
axis_ratio_density_sample_name="q_density_sample",
line_of_sight_index_name="LOS",
weight_density_sample_name="weight",
weight_shape_sample_name="weight_shape_sample",
num_overlap=None,
binning="log",
):
"""
The __init__ method of the MeasureIABox class.
Parameters
----------
num_nodes : int, optional
Number of cores to be used in multiprocessing. Default is 1.
positions_density_sample_name : str, optional
Name of the key in the data dictionary that contains the positions of the density sample.
positions_shape_sample_name : str, optional
Name of the key in the data dictionary that contains the positions of the shape sample.
axis_direction_name : str, optional
Name of the key in the data dictionary that contains the axis direction vectors of the shape sample.
axis_ratio_name : str, optional
Name of the key in the data dictionary that contains the axis ratios of the shape sample.
axis_direction_density_sample_name : str, optional
Name of the key in the data dictionary that contains the axis direction vectors of the **density**
sample. Only needed for shape-shape ('++') correlations, which require shapes on both members of a
pair; leave it out for 'g+', 'gg' or 'both'. Must be supplied together with
`axis_ratio_density_sample_name`.
axis_ratio_density_sample_name : str, optional
Name of the key in the data dictionary that contains the axis ratios of the **density** sample.
See `axis_direction_density_sample_name`.
line_of_sight_index_name : str, optional
Name of the key in the data dictionary that contains the column index of the line of sight in the
position vectors.
weight_density_sample_name : str, optional
Name of the key in the data dictionary that contains the weights of the density sample.
weight_shape_sample_name : str, optional
Name of the key in the data dictionary that contains the weights of the shape sample.
num_overlap : int or NoneType, optional
Number of objects present in *both* the position and the shape sample. The analytic
RR is normalised by ``W_position * W_shape - W_overlap``, with ``W`` the weight sums
and ``W_overlap`` the summed weight products of the shared objects, because a shape
galaxy cannot pair with itself and the pair loop already drops that self-pair (the
separation window starts at ``r_min > 0``). Default None, which measures the overlap
from the coordinates and is what you want for real data, where the shape sample is
normally drawn from the position sample. Pass an integer to override it -- most
usefully ``0``, which reproduces the convention external codes such as halotools
and corr_pc use, where the two samples are treated as independent. The override is an
object count, converted to a weighted overlap by scaling it with both samples' mean
weights (exact for unit weights; 0 stays 0). An override is applied uniformly, so the
per-jackknife-region adjustment is only made in the default (measured) mode.
binning : str, optional
Spacing of the (projected) separation bins between the separation_limits: 'log' for logarithmically
spaced bins or 'linear' for linearly spaced bins (e.g. around the BAO peak). Default is 'log'.
Notes
-----
Constructor parameters 'data', 'output_file_name', 'simulation', 'snapshot', 'separation_limits', 'num_bins_r',
'num_bins_pi', 'pi_max', 'boxsize', 'periodicity' and 'binning' are passed to MeasureIABase.
The data dictionary (and any mask dictionaries passed to the measurement methods) may use any key names;
they are given through the *_name parameters and translated to the internal default names on input.
"""
self._input_name_map = {
positions_density_sample_name: "Position",
positions_shape_sample_name: "Position_shape_sample",
axis_direction_name: "Axis_Direction",
axis_ratio_name: "q",
axis_direction_density_sample_name: "Axis_Direction_density_sample",
axis_ratio_density_sample_name: "q_density_sample",
line_of_sight_index_name: "LOS",
weight_density_sample_name: "weight",
weight_shape_sample_name: "weight_shape_sample",
}
if output_file_name is not None:
self.check_paths([output_file_name])
if data is not None:
self.check_dict(data, [positions_density_sample_name, positions_shape_sample_name, axis_direction_name,
axis_ratio_name, line_of_sight_index_name])
self.check_type_input_data(data,
(positions_density_sample_name, positions_shape_sample_name, axis_direction_name,
axis_ratio_name, line_of_sight_index_name))
# optional, and only used by shape-shape correlations
self.has_density_sample_shapes = self.check_density_sample_shapes(
data, (positions_density_sample_name, axis_direction_density_sample_name,
axis_ratio_density_sample_name), "box")
data = self.rename_input_keys(data, self._input_name_map)
else:
self.has_density_sample_shapes = False
super().__init__(data, output_file_name, simulation, snapshot, separation_limits, num_bins_r, num_bins_pi,
pi_max, boxsize, periodicity, binning)
if self.data is not None and self.boxsize is not None:
self.check_units_coordinates(self.data["Position"], self.boxsize)
if not (isinstance(num_nodes, (int, np.integer)) and not isinstance(num_nodes, bool) and num_nodes >= 1):
raise ValueError(f"num_nodes must be an integer >= 1, got {num_nodes!r}.")
self.num_nodes = num_nodes
if num_overlap is not None and not (isinstance(num_overlap, (int, np.integer))
and not isinstance(num_overlap, bool) and num_overlap >= 0):
raise ValueError(f"num_overlap must be None or an integer >= 0, got {num_overlap!r}.")
self._num_overlap_override = num_overlap
self.randoms_data = None
self.data_dir = None
self.num_samples = None
return
@staticmethod
def _validate_measure_options(corr_type, ellipticity, num_jk, has_density_sample_shapes=True):
"""Validate the user-facing option strings and ``num_jk`` up front, before any pair
counting. Previously ``corr_type`` was only checked at the reduction stage (after the
full count) with a ``KeyError``, ``ellipticity`` only inside the backends, and a
negative ``num_jk`` was silently treated as 0; all now raise a uniform ``ValueError``.
``has_density_sample_shapes`` reports whether the catalogue carries shapes on the
density sample; a shape-shape correlation is refused without them, here rather than
after a full pair count."""
if corr_type not in CORR_TYPES:
raise ValueError(f"Unknown corr_type {corr_type!r}. Choose from {sorted(CORR_TYPES)}.")
if corr_type in SHAPE_SHAPE_CORR_TYPES and not has_density_sample_shapes:
raise ValueError(
f"corr_type={corr_type!r} correlates the shapes of both samples, so the density "
f"sample needs shapes of its own. Supply 'Axis_Direction_density_sample' and "
f"'q_density_sample' (or the names you gave the constructor).")
if ellipticity not in ("distortion", "ellipticity"):
raise ValueError(
f"Unknown ellipticity {ellipticity!r}. Choose from ['distortion', 'ellipticity'].")
if not (isinstance(num_jk, (int, np.integer)) and not isinstance(num_jk, bool) and num_jk >= 0):
raise ValueError(f"num_jk must be an integer >= 0, got {num_jk!r}.")
@worker_pool.pooled
def measure_xi_w(self, dataset_name, corr_type, num_jk=0, temp_file_path=None, masks=None,
ellipticity='distortion', chunk_size=1000, responsivity=True):
r"""Measures $\xi_{gg}$, $\xi_{g+}$ and $w_{gg}$, $w_{g+}$ including jackknife covariance if desired.
Manages the various _measure_xi_rp_pi_box method options in MeasureWBox and MeasureWBoxJackknife.
Parameters
----------
dataset_name : str
Name of the dataset in the output file.
corr_type : str
Type of correlation to be measured. Choose from [g+, gg, both, ++, all].
'both' means g+ and gg; '++' is the shape-shape correlation (which also yields the
cross-cross signal and the parity null) and needs shapes on the density sample;
'all' is g+, gg and ++ together.
num_jk : int, optional
Number of jackknife regions (needs to be x^3, with x an int) for the covariance measurement.
Default is 0 (no covariance).
temp_file_path : str or NoneType, optional
Path to where the data is temporarily stored [file name generated automatically].
masks : dict or NoneType, optional
Directory of mask information in the same form as the data dictionary, where the masks are placed over
the data to apply selections. Default is None.
chunk_size: int, optional
Size of the chunks of data sent to each multiprocessing node. If larger, more RAM is needed per node.
Default is 1000.
ellipticity : str, optional
Definition of ellipticity. Choose from 'distortion', defined as (1-q^2)/(1+q^2), or 'ellipticity', defined
as (1-q)/(1+q). Default is 'distortion'.
responsivity : bool, optional
If True (default), the g+ shape signal is calibrated by the responsivity factor 2R, with
R = <w (1 - e^2 / 2)> / <w> the weighted shear responsivity (R falls back to 0.5, i.e. no correction,
when False or when the shape weights sum to zero). Use the default for raw shape distortions derived
from axis ratios; set to False when the input shapes are already calibrated shears. Only the g+
correlations are affected; the clustering (gg) signal is unchanged. Default is True.
"""
self._validate_measure_options(corr_type, ellipticity, num_jk,
getattr(self, "has_density_sample_shapes", False))
# tells pair_kernel (via the backends) to accumulate the shape-shape products too;
# an attribute rather than an argument because the multiprocessing backends pickle
# ``self`` into their workers and read their options off it the same way
self._shape_mode = "both" if corr_type in SHAPE_SHAPE_CORR_TYPES else True
self.responsivity_correction = responsivity
masks = self.rename_input_keys(masks, self._input_name_map)
if num_jk > 0:
try:
assert sympy.integer_nthroot(num_jk, 3)[1]
L = sympy.integer_nthroot(num_jk, 3)[0]
self.check_jackknife_max_separation(num_jk, self.boxsize, self.r_max, self.num_bins_r)
except AssertionError:
raise ValueError(
f"Use x^3 as input for num_jk, with x as an int. {float(int(num_jk ** (1. / 3)))},{num_jk ** (1. / 3)}")
if temp_file_path == False:
temp_storage = False
temp_file_path = None
else:
temp_storage = True
if temp_storage and temp_file_path == None:
raise ValueError(
"Input temp_file_path for faster computation. Do not want to save data temporarily? Input file_path_tree=False.")
if self.data is not None and "RA" in self.data:
raise TypeError("Given data is lightcone data (contains 'RA'). Use MeasureIALightcone instead.")
if num_jk > 0: # include covariance
if corr_type == "gg": # DD-only pair counting, skips shape/ellipticity computation
if self.num_nodes > 1 and temp_storage:
self._count_pairs_xi_rp_pi_box_jk_multiprocessing(masks=masks, L_subboxes=L,
dataset_name=dataset_name,
return_output=False,
num_nodes=self.num_nodes,
jk_group_name=f"{dataset_name}_jk{num_jk}",
chunk_size=chunk_size,
temp_file_path=temp_file_path)
elif temp_storage:
self._count_pairs_xi_rp_pi_box_jk_tree(masks=masks, L_subboxes=L, dataset_name=dataset_name,
return_output=False,
jk_group_name=f"{dataset_name}_jk{num_jk}")
else:
self._count_pairs_xi_rp_pi_box_jk_brute(masks=masks, L_subboxes=L, dataset_name=dataset_name,
return_output=False,
jk_group_name=f"{dataset_name}_jk{num_jk}")
elif self.num_nodes > 1 and temp_storage:
self._measure_xi_rp_pi_box_jk_multiprocessing(masks=masks, L_subboxes=L, dataset_name=dataset_name,
return_output=False,
num_nodes=self.num_nodes,
jk_group_name=f"{dataset_name}_jk{num_jk}",
chunk_size=chunk_size, ellipticity=ellipticity,
temp_file_path=temp_file_path)
elif temp_storage:
self._measure_xi_rp_pi_box_jk_tree(masks=masks, L_subboxes=L, dataset_name=dataset_name,
return_output=False, ellipticity=ellipticity,
jk_group_name=f"{dataset_name}_jk{num_jk}")
else:
self._measure_xi_rp_pi_box_jk_brute(masks=masks, L_subboxes=L, dataset_name=dataset_name,
return_output=False, ellipticity=ellipticity,
jk_group_name=f"{dataset_name}_jk{num_jk}")
self._measure_w_g_i(corr_type=corr_type, dataset_name=dataset_name, return_output=False)
for i in np.arange(num_jk):
self._measure_w_g_i(corr_type=corr_type, dataset_name=f"{dataset_name}_{i}",
jk_group_name=f"{dataset_name}_jk{num_jk}", return_output=False)
corr_group = [w_name for _, w_name in W_PRODUCTS[corr_type]]
self._combine_jackknife_information(dataset_name=dataset_name, jk_group_name=f"{dataset_name}_jk{num_jk}",
corr_group=corr_group, num_box=num_jk)
else: # no covariance
if corr_type == "gg": # DD-only pair counting, skips shape/ellipticity computation
if self.num_nodes > 1 and temp_storage:
self._count_pairs_xi_rp_pi_box_multiprocessing(dataset_name=dataset_name,
temp_file_path=temp_file_path,
masks=masks, return_output=False,
num_nodes=self.num_nodes, chunk_size=chunk_size)
elif temp_storage:
self._count_pairs_xi_rp_pi_box_tree(masks=masks, dataset_name=dataset_name, return_output=False)
else:
self._count_pairs_xi_rp_pi_box_brute(masks=masks, dataset_name=dataset_name, return_output=False)
elif self.num_nodes > 1 and temp_storage:
self._measure_xi_rp_pi_box_multiprocessing(dataset_name=dataset_name, temp_file_path=temp_file_path,
masks=masks, return_output=False, num_nodes=self.num_nodes,
chunk_size=chunk_size, ellipticity=ellipticity)
elif temp_storage:
self._measure_xi_rp_pi_box_tree(masks=masks, dataset_name=dataset_name,
return_output=False, ellipticity=ellipticity)
else:
self._measure_xi_rp_pi_box_brute(masks=masks, dataset_name=dataset_name,
return_output=False, ellipticity=ellipticity)
self._measure_w_g_i(corr_type=corr_type, dataset_name=dataset_name, return_output=False)
return
@worker_pool.pooled
def measure_xi_multipoles(self, dataset_name, corr_type, num_jk=0, temp_file_path=None, masks=None, rp_cut=None,
ellipticity='distortion', chunk_size=1000, responsivity=True):
r"""Measures $\xi_{gg}$, $\xi_{g+}$ and $\tilde{\xi}_{gg,0}$, $\tilde{\xi}_{g+,2}$ including jackknife covariance
if desired. Manages the various _measure_xi_r_mur_box method options in MeasureMultipolesBox and
MeasureMultipolesBoxJackknife.
Parameters
----------
dataset_name : str
Name of the dataset in the output file.
corr_type : str
Type of correlation to be measured. Choose from [g+, gg, both, ++, all].
'both' means g+ and gg; '++' is the shape-shape correlation (which also yields the
cross-cross signal and the parity null) and needs shapes on the density sample;
'all' is g+, gg and ++ together.
num_jk : int, optional
Number of jackknife regions (needs to be x^3, with x an int) for the covariance measurement. Default is 0 (no covariance).
temp_file_path : str or NoneType, optional
Path to where the data is temporarily stored [file name generated automatically].
masks : dict or NoneType, optional
Directory of mask information in the same form as the data dictionary, where the masks are placed over
the data to apply selections. Default is None.
rp_cut : float or NoneType, optional
Applies a minimum r_p value condition for pairs to be included. Default is None.
chunk_size: int, optional
Size of the chunks of data sent to each multiprocessing node. If larger, more RAM is needed per node.
ellipticity : str, optional
Definition of ellipticity. Choose from 'distortion', defined as (1-q^2)/(1+q^2), or 'ellipticity', defined
as (1-q)/(1+q). Default is 'distortion'.
"""
self._validate_measure_options(corr_type, ellipticity, num_jk,
getattr(self, "has_density_sample_shapes", False))
# tells pair_kernel (via the backends) to accumulate the shape-shape products too;
# an attribute rather than an argument because the multiprocessing backends pickle
# ``self`` into their workers and read their options off it the same way
self._shape_mode = "both" if corr_type in SHAPE_SHAPE_CORR_TYPES else True
self.responsivity_correction = responsivity
masks = self.rename_input_keys(masks, self._input_name_map)
if num_jk > 0:
try:
assert sympy.integer_nthroot(num_jk, 3)[1]
L = sympy.integer_nthroot(num_jk, 3)[0]
self.check_jackknife_max_separation(num_jk, self.boxsize, self.r_max, self.num_bins_r)
except AssertionError:
raise ValueError(
f"Use x^3 as input for num_jk, with x as an int. {float(int(num_jk ** (1. / 3)))},{num_jk ** (1. / 3)}")
if temp_file_path == False:
temp_storage = False
temp_file_path = None
else:
temp_storage = True
if temp_storage and temp_file_path == None:
raise ValueError(
"Input temp_file_path for faster computation. Do not want to save data temporarily? Input file_path_tree=False.")
if self.data is not None and "RA" in self.data:
raise TypeError("Given data is lightcone data (contains 'RA'). Use MeasureIALightcone instead.")
if num_jk > 0: # include covariance
if corr_type == "gg": # DD-only pair counting, skips shape/ellipticity computation
if self.num_nodes > 1 and temp_storage:
self._count_pairs_xi_r_mur_box_jk_multiprocessing(masks=masks, L_subboxes=L,
dataset_name=dataset_name,
return_output=False, rp_cut=rp_cut,
num_nodes=self.num_nodes,
jk_group_name=f"{dataset_name}_jk{num_jk}",
chunk_size=chunk_size,
temp_file_path=temp_file_path)
elif temp_storage:
self._count_pairs_xi_r_mur_box_jk_tree(masks=masks, L_subboxes=L, dataset_name=dataset_name,
return_output=False, rp_cut=rp_cut,
jk_group_name=f"{dataset_name}_jk{num_jk}")
else:
self._count_pairs_xi_r_mur_box_jk_brute(masks=masks, L_subboxes=L, dataset_name=dataset_name,
return_output=False, rp_cut=rp_cut,
jk_group_name=f"{dataset_name}_jk{num_jk}")
elif self.num_nodes > 1 and temp_storage:
self._measure_xi_r_mur_box_jk_multiprocessing(masks=masks, L_subboxes=L, dataset_name=dataset_name,
return_output=False, rp_cut=rp_cut,
num_nodes=self.num_nodes,
jk_group_name=f"{dataset_name}_jk{num_jk}",
chunk_size=chunk_size, ellipticity=ellipticity,
temp_file_path=temp_file_path)
elif temp_storage:
self._measure_xi_r_mur_box_jk_tree(masks=masks, L_subboxes=L, dataset_name=dataset_name,
return_output=False, rp_cut=rp_cut, ellipticity=ellipticity,
jk_group_name=f"{dataset_name}_jk{num_jk}")
else:
self._measure_xi_r_mur_box_jk_brute(masks=masks, L_subboxes=L, dataset_name=dataset_name,
return_output=False, rp_cut=rp_cut, ellipticity=ellipticity,
jk_group_name=f"{dataset_name}_jk{num_jk}")
self._measure_multipoles(corr_type=corr_type, dataset_name=dataset_name, return_output=False)
for i in np.arange(num_jk):
self._measure_multipoles(corr_type=corr_type, dataset_name=f"{dataset_name}_{i}",
jk_group_name=f"{dataset_name}_jk{num_jk}", return_output=False)
corr_group = [m_name for _, m_name, _ in M_PRODUCTS[corr_type]]
self._combine_jackknife_information(dataset_name=dataset_name, jk_group_name=f"{dataset_name}_jk{num_jk}",
corr_group=corr_group, num_box=num_jk)
else: # no covariance
if corr_type == "gg": # DD-only pair counting, skips shape/ellipticity computation
if self.num_nodes > 1 and temp_storage:
self._count_pairs_xi_r_mur_box_multiprocessing(dataset_name=dataset_name,
temp_file_path=temp_file_path,
masks=masks, return_output=False, rp_cut=rp_cut,
num_nodes=self.num_nodes, chunk_size=chunk_size)
elif temp_storage:
self._count_pairs_xi_r_mur_box_tree(masks=masks, dataset_name=dataset_name,
return_output=False, rp_cut=rp_cut)
else:
self._count_pairs_xi_r_mur_box_brute(masks=masks, dataset_name=dataset_name,
return_output=False, rp_cut=rp_cut)
elif self.num_nodes > 1 and temp_storage:
self._measure_xi_r_mur_box_multiprocessing(dataset_name=dataset_name, temp_file_path=temp_file_path,
masks=masks, return_output=False, rp_cut=rp_cut,
num_nodes=self.num_nodes,
chunk_size=chunk_size, ellipticity=ellipticity)
elif temp_storage:
self._measure_xi_r_mur_box_tree(masks=masks, dataset_name=dataset_name,
return_output=False, rp_cut=rp_cut,
ellipticity=ellipticity)
else:
self._measure_xi_r_mur_box_brute(masks=masks, dataset_name=dataset_name,
return_output=False, rp_cut=rp_cut, ellipticity=ellipticity)
self._measure_multipoles(corr_type=corr_type, dataset_name=dataset_name, return_output=False)
return
|