-
Notifications
You must be signed in to change notification settings - Fork 3
/
bound_dist.py
209 lines (148 loc) · 9.68 KB
/
bound_dist.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
import os
import gc
import sys
import tqdm
import time
import fitsio
import argparse
import multiprocessing
import numpy as np
import astropy.io.fits as fits
import matplotlib.pyplot as plt
from scipy.spatial import KDTree
from astropy.table import Table
from multiprocessing import Pool
from runtime import calc_runtime
from findfile import findfile, overwrite_check, call_signature
from config import Configuration
from fillfactor import collate_fillfactors
from params import oversample_nrealisations, sphere_radius
def process_one(run, pid=0):
split = run[0]
complement = run[1]
'''
try:
pid = multiprocessing.current_process().name.ljust(20)
except Exception as e:
print(e)
'''
dd, ii = complement.query(split, k=1)
# del points
return dd.tolist(), ii.tolist()
def bound_dist(log, field, dryrun, prefix, survey, nproc, realz, nooverwrite, collate=True):
start = time.time()
if collate:
# Collate multiple n8 measurements from N>1 oversampled realizations into the 0th realization.
# Note: null op if already applied.
collate_fillfactors(realzs=np.arange(oversample_nrealisations), field=field, survey=survey, dryrun=dryrun, prefix=prefix, write=True)
# https://www.dur.ac.uk/icc/cosma/cosma5/
fpath = findfile(ftype='randoms_n8', dryrun=dryrun, field=field, survey=survey, prefix=prefix)
opath = findfile(ftype='randoms_bd', dryrun=dryrun, field=field, survey=survey, prefix=prefix)
if log:
logfile = findfile(ftype='randoms_bd', dryrun=False, field=field, survey=survey, prefix=prefix, log=True)
print(f'Logging to {logfile}')
sys.stdout = open(logfile, 'w')
if nooverwrite:
overwrite_check(opath)
call_signature(dryrun, sys.argv)
# Output is sorted by fillfactor.py;
body = Table.read(fpath)
boundary = Table.read(fpath, 'BOUNDARY')
body.sort('CARTESIAN_X')
boundary.sort('CARTESIAN_X')
bids = boundary['BOUNDID']
boundary = np.c_[boundary['CARTESIAN_X'], boundary['CARTESIAN_Y'], boundary['CARTESIAN_Z']]
body = np.c_[body['CARTESIAN_X'], body['CARTESIAN_Y'], body['CARTESIAN_Z']]
runtime = calc_runtime(start, 'Reading {:.2f}M randoms'.format(len(body) / 1.e6), xx=body)
split_idx = np.arange(len(body))
split_idx = np.array_split(split_idx, 8 * nproc)
nchunk = len(split_idx)
runs = []
for i, idx in enumerate(split_idx):
split = body[idx]
xmin = split[:,0].min()
xmax = split[:,0].max()
buff = .2 # Mpc
# Boundary complement.
# TODO HARDCODE
complement = (boundary[:,0] > (xmin - sphere_radius - buff)) & (boundary[:,0] < (xmax + sphere_radius + buff))
complement = boundary[complement]
cmin = complement[:,0].min()
cmax = complement[:,0].max()
print('{:d}\t{:.4f}\t{:.4f}\t{:.4f}\t{:.4f}\t{:d}\t{:d}'.format(i, xmin, xmax, cmin, cmax, len(split), len(complement)))
# leafsize=5
split = [x for x in split]
complement = KDTree(complement)
runs.append([split, complement])
runtime = calc_runtime(start, 'Created boundary trees.')
runtime = calc_runtime(start, 'POOL: Querying bound dist for body points of {} splits.'.format(nchunk))
now = time.time()
results = [process_one(runs[0], pid=0)]
split_time = time.time() - now
split_time /= 60.
runtime = calc_runtime(start, 'POOL: Expected runtime of {:.3f}.'.format(nchunk * split_time))
# https://britishgeologicalsurvey.github.io/science/python-forking-vs-spawn/
with multiprocessing.get_context('spawn').Pool(nproc) as pool:
for result in tqdm.tqdm(pool.imap(process_one, iterable=runs[1:]), total=len(runs[1:])):
results.append(result)
pool.close()
# https://stackoverflow.com/questions/38271547/when-should-we-call-multiprocessing-pool-join
pool.join()
runtime = calc_runtime(start, 'POOL: Done with queries')
flat_result = []
flat_ii = []
for rr in results:
flat_result += rr[0]
flat_ii += rr[1]
rand = Table.read(fpath)
rand.sort('CARTESIAN_X')
# print(len(rand))
# print(len(flat_result))
rand['BOUND_DIST'] = np.array(flat_result)
rand['BOUNDID'] = bids[np.array(flat_ii)]
rand['FILLFACTOR_POISSON'] = rand['FILLFACTOR']
rand['FILLFACTOR'][rand['BOUND_DIST'].data > sphere_radius] = 1.
# CHANGE: Protect against exactly zero fillfactor (causes division errors).
rand['FILLFACTOR'] = np.clip(rand['FILLFACTOR'], 1.e-99, None)
runtime = calc_runtime(start, 'Shuffling')
# randomise rows.
idx = np.arange(len(rand))
idx = np.random.choice(idx, size=len(idx), replace=False)
rand = rand[idx]
# Bound dist.
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.query.html#scipy.spatial.KDTree.query
runtime = calc_runtime(start, 'Writing {}'.format(opath), xx=rand)
rand.write(opath, format='fits', overwrite=True)
runtime = calc_runtime(start, 'Finished')
if log:
sys.stdout.close()
if __name__ == '__main__':
'''
Script to calculate the maximum distance [Mpc/h] of each random from the boundary.
'''
np.random.seed(314)
parser = argparse.ArgumentParser(description='Find boundary distance for all randoms in a specified field..')
parser.add_argument('--log', help='Create a log file of stdout.', action='store_true')
parser.add_argument('-f', '--field', type=str, help='Select equatorial GAMA field: G9, G12, G15', required=True)
parser.add_argument('-d', '--dryrun', help='Dryrun.', action='store_true')
parser.add_argument('-s', '--survey', help='Select survey.', default='gama')
parser.add_argument('--prefix', help='filename prefix', default='randoms')
parser.add_argument('--nooverwrite', help='Do not overwrite outputs if on disk', action='store_true')
parser.add_argument('--config', help='Path to configuration file', type=str, default=findfile('config'))
parser.add_argument('--nproc', type=int, help='Number of processors', default=12)
parser.add_argument('--realz', type=int, help='Realisation', default=0)
args = parser.parse_args()
log = args.log
field = args.field.upper()
dryrun = args.dryrun
prefix = args.prefix
survey = args.survey.lower()
nproc = args.nproc
realz = args.realz
nooverwrite = args.nooverwrite
'''
config = Configuration(args.config)
config.update_attributes('bound_dist', args)
config.write()
'''
bound_dist(log, field, dryrun, prefix, survey, nproc, realz, nooverwrite)