-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmesh_collections.py
1732 lines (1532 loc) · 74 KB
/
mesh_collections.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
from __future__ import print_function, division
from collections import OrderedDict, namedtuple
from copy import copy
import h5py
import json
import numpy as np
import os
from nbodykit import logging
from nbodykit.base.mesh import MeshSource
from nbodykit.source.mesh.field import FieldMesh
from pmesh.pm import RealField, ComplexField
from measured_stats import MeasuredPower1D, MeasuredPower2D
from nbkit03_utils import get_cstat, get_cstats_string, print_cstats
import nbkit03_utils
"""
Store a collection of nbdodykit MeshSource objects, e.g. RealField objects.
The MeshSource objects are saved as columns of Grid, with names given by strings,
so we can easily apply actions on many MeshSource objects.
Note: We store the same instances, so modifying meshsource elsewhere will change
the data stored here. We recommend deleting meshsource always after storing it here.
TODO: Rename to MeshSourceDict.
"""
class Grid(object):
"""
A class for storing and manipulating collections of 3D grids (instances of MeshSource).
"""
def __init__(self,
fname=None,
read_columns=None,
meshsource=None,
column=None,
column_info=None,
Ngrid=None,
boxsize=None):
"""
Initialize an instance of the class. Have several options:
1) Specify fname to read data from file. Can use read_columns to select columns.
2) Specify meshsource, column, Ngrid and boxsize to fill data.
In earlier version, used numpy structured array. Now just use dict.
Parameters
----------
fname : None or string
File name of hdf5 file that contains a grid to be read in.
read_columns : None or sequence of strings
Columns to read from file. If None, read all columns.
Example: read_columns=('delta_x',).
meshsource : None or instance of nbodykit MeshSource or pmesh.pm.RealField
or pmesh.pm.ComplexField
Initial MeshSource shape (Ngrid,Ngrid,Ngrid). Will be stored
in self.G[column].
column : None or string
Column where to store grid_array.
column_info : None or dict
Optional dict to save info about the stored field.
Ngrid : None or integer
Number of grid points per dimension, e.g. 128.
boxsize : None or float
Box size in Mpc/h.
"""
from nbodykit import CurrentMPIComm
self.comm = CurrentMPIComm.get()
self.logger = logging.getLogger(str(self.__class__.__name__))
# check args a bit (not extensively so be careful)
if not ((read_columns is None) or
(type(read_columns) == tuple) or type(read_columns) == list):
print("read_columns:", read_columns)
raise Exception("read_columns must be None or sequence")
# initialize
if fname is not None:
# read grid and store it in self.G
self.init_grid_from_bigfile(fname,
columns=read_columns,
#mode='real'
)
else:
# init from grid_array supplied as argument, which should be MeshSource object
print("type of meshsource:", type(meshsource))
if isinstance(meshsource, RealField) or isinstance(
meshsource, ComplexField):
# convert to nbkit FieldMesh (which is subclass of MeshSource)
meshsource = FieldMesh(meshsource)
assert isinstance(meshsource, MeshSource)
assert np.all(
meshsource.attrs['Nmesh'] == np.array([Ngrid, Ngrid, Ngrid]))
assert np.all(meshsource.attrs['BoxSize'] == np.array(
[boxsize, boxsize, boxsize]))
self._Ngrid = Ngrid
self._boxsize = boxsize
self._base_dtype = meshsource.dtype
#dtype = np.dtype( [ (column, self.base_dtype) ] )
#self.G = np.empty( (Ngrid**3,), dtype=dtype )
# store as dict instead of structured array
self.G = OrderedDict()
self.G[column] = copy(meshsource)
self.column_infos = {}
self.column_infos[column] = column_info
if isinstance(self, RealGrid):
self._mode = 'real'
elif isinstance(self, ComplexGrid):
self._mode = 'complex'
else:
raise Exception("Must be RealGrid or ComplexGrid")
print_cstats(self.G[column].compute(mode=self.mode),
prefix="Init with column %s. " % column,
logger=self.logger)
# Some read-only properties that shall not be changed once instance is initialized.
@property
def Ngrid(self):
return self._Ngrid
@property
def boxsize(self):
return self._boxsize
@property
def mode(self):
return self._mode
# @property
# def base_dtype(self):
# return self._base_dtype
# @property
# def shape(self):
# return self._shape
# @staticmethod
def get_dtype_of_columns(self, columns):
pass
# dtype_list = []
# for col in columns:
# dtype_list.append( (col, self.base_dtype) )
# dtype = np.dtype(dtype_list)
# print("Created dtype:", dtype)
# return dtype
def save_to_bigfile(self,
fname,
columns=None,
new_dataset_for_each_column=False,
overwrite_file_if_exists=True,
print_column_info=False):
"""
Save grid columns to bigfile file. If columns is None, save all columns.
If file exists, overwrite.
Columns here mean entries of grid.G. They are not bigfile columns. They are
saved as different blocks in bigfile file.
"""
# see https://nbodykit.readthedocs.io/en/latest/api/_autosummary/nbodykit.base.mesh.html#nbodykit.base.mesh.MeshSource.save
import bigfile
import warnings
import json
from nbodykit.utils import JSONEncoder
from pmesh.pm import BaseComplexField
if self.comm.rank == 0:
self.logger.info("Try writing to %s" % fname)
if isinstance(self, RealGrid):
mode = 'real'
elif isinstance(self, ComplexGrid):
mode = 'complex'
else:
raise Exception("can only save RealGrid or ComplexGrid")
# fname = os.path.expandvars(fname)
# print("Writing %s" % fname)
# if overwrite_file_if_exists and os.path.exists(fname):
# os.remove(fname)
# if os.path.dirname(fname) != '':
# if not os.path.exists(os.path.dirname(fname)):
# os.makedirs(os.path.dirname(fname))
if columns is None:
columns = self.G.keys()
if self.comm.rank == 0:
self.logger.info("Writing GridColumns %s" % str(columns))
if overwrite_file_if_exists or (not os.path.exists(fname)):
# write to new file
create = True
else:
create = False
if not new_dataset_for_each_column:
raise Exception("only implemented new_dataset_for_each_column=True")
# figure out bigfile issue
# https://github.com/rainwoodman/bigfile/blob/b135ea5ef7d5bbdcab0a0086058bb99ebc95684f/bigfile/__init__.py#L179
assert self.comm == self.G[columns[0]].comm
tmp_cmean = self.G[columns[0]].to_field().cmean()
self.logger.info('cmean0: %s' % tmp_cmean)
self.logger.info('fname: %s' % fname)
myset = set(self.comm.allgather(fname))
self.logger.info('myset: %s' % myset)
# save to file
with bigfile.FileMPI(self.comm, fname, create=create) as ff:
for grid_col in columns:
dataset = grid_col
# convert MeshSource to field
field = self.G[grid_col].compute(mode=mode)
data = np.empty(shape=field.size, dtype=field.dtype)
# Ravel the field to 'C'-order, partitioned by MPI ranks. Save the result to flatiter.
field.ravel(out=data)
with ff.create_from_array(dataset, data) as bb:
if isinstance(field, RealField):
bb.attrs['ndarray.shape'] = field.pm.Nmesh
bb.attrs['BoxSize'] = field.pm.BoxSize
bb.attrs['Nmesh'] = field.pm.Nmesh
elif isinstance(field, BaseComplexField):
bb.attrs[
'ndarray.shape'] = field.Nmesh, field.Nmesh, field.Nmesh // 2 + 1
bb.attrs['BoxSize'] = field.pm.BoxSize
bb.attrs['Nmesh'] = field.pm.Nmesh
for key in field.attrs:
# do not override the above values -- they are vectors (from pm)
if key in bb.attrs: continue
value = field.attrs[key]
try:
bb.attrs[key] = value
except ValueError:
try:
json_str = 'json://' + json.dumps(
value, cls=JSONEncoder)
bb.attrs[key] = json_str
except:
warnings.warn(
"attribute %s of type %s is unsupported and lost while saving MeshSource"
% (key, type(value)))
bb.attrs['Ngrid'] = self.Ngrid
bb.attrs['boxsize'] = self.boxsize
if self.column_infos not in [None, {}]:
if print_column_info:
self.logger.info("column_info: %s" %
str(self.column_infos[grid_col]))
if False:
# comment out b/c RSDFactor is not dumped properly
bb.attrs['grid_column_info'] = json.dumps(
self.column_infos[grid_col])
if self.comm.rank == 0:
self.logger.info("Wrote GridColumns %s" % str(columns))
self.logger.info("to bigfile %s" % fname)
def init_grid_from_bigfile(self,
fname,
columns=None,
mode='real',
print_column_info=True):
"""
Read GridColumns columns from bigfile blocks and initialize grid instance.
If columns is None, read all columns.
"""
from nbodykit.source.mesh.bigfile import BigFileMesh
self._mode = mode
if self.comm.rank == 0:
self.logger.info("Try to init grid by reading %s" % fname)
if columns is None:
# read all columns
subfolders = [
di for di in os.listdir(fname)
if os.path.isdir(os.path.join(fname, di))
]
columns = subfolders
if self.comm.rank == 0:
self.logger.info("Columns to read: %s" % str(columns))
counter = -1
for column in columns:
counter += 1
bfmesh = BigFileMesh(path=fname, dataset=column)
# scalar attrs are saved and read as 0-dimensional arrays. convert them back to scalars
for k, v in bfmesh.attrs.items():
if type(v) == np.ndarray and v.shape == ():
bfmesh.attrs[k] = v[()]
#if self.comm.rank == 0:
# self.logger.info("Attrs of %s:\n%s" % (column,str(bfmesh.attrs)))
if counter == 0:
self._Ngrid = bfmesh.attrs['Ngrid']
self._boxsize = bfmesh.attrs['boxsize']
self.G = OrderedDict()
self.column_infos = OrderedDict()
else:
assert self._Ngrid == bfmesh.attrs['Ngrid']
assert self._boxsize == bfmesh.attrs['boxsize']
colinfo = {}
if 'grid_column_info' in bfmesh.attrs:
colinfo = json.loads(bfmesh.attrs['grid_column_info'])
# read the data, convert to RealField or ComplexField, then to FieldMesh object, and store in self.G
self.append_column(column,
FieldMesh(bfmesh.compute(mode=mode)),
column_info=colinfo,
print_column_info=print_column_info)
assert isinstance(self.G[column], MeshSource)
#print("shape:", self.G[column].to_field().shape)
assert np.all(self.G[column].attrs['Nmesh'] == np.array(
[self.Ngrid, self.Ngrid, self.Ngrid]))
assert np.all(self.G[column].attrs['BoxSize'] == np.array(
[self.boxsize, self.boxsize, self.boxsize]))
if self.comm.rank == 0:
self.logger.info("Read Ngrid=%d, boxsize=%g Mpc/h" %
(self.Ngrid, self.boxsize))
self.logger.info("Read columns: %s" % str(self.G.keys()))
self.logger.info("Done reading %s" % fname)
def append_column(self,
column_name,
column_data,
column_info=None,
print_column_info=True):
"""
column_name : string
String corresponding to the name of the new column.
column_data : MeshSource object, or RealField or ComplexField
Data to store.
"""
if isinstance(column_data, RealField) or isinstance(
column_data, ComplexField):
print('%d ya' % self.comm.rank)
self.G[column_name] = FieldMesh(copy(column_data))
elif isinstance(column_data, MeshSource):
self.G[column_name] = copy(column_data)
else:
raise Exception(
"Invalid data type for column_data. Name: %s, type: %s" %
(column_name, type(column_data)))
#self.G[column_name] = copy(column_data)
self.column_infos[column_name] = column_info
print_cstats(self.G[column_name].compute(mode=self.mode),
prefix='Append %s. ' % column_name,
logger=self.logger)
if print_column_info:
if self.comm.rank == 0:
self.logger.info("attrs: %s" % str(self.G[column_name].attrs))
self.logger.info("column_info: %s" %
str(self.column_infos[column_name]))
# np.sqrt(np.mean(column_data**2)), np.min(column_data),
# np.mean(column_data), np.max(column_data))
def print_summary_stats(self, column):
print_cstats(self.G[column].compute(),
prefix="Stats of %s: " % column,
logger=self.logger)
# column_data = self.G[column]
# print(str(self.__class__.__name__)+": Summary stats of "+column+": rms, min, mean, max:",
# np.sqrt(np.mean(column_data**2)), np.min(column_data),
# np.mean(column_data), np.max(column_data))
def drop_column(self, column_name):
"""
column_name : string
String corresponding to the name of the column to be dropped.
"""
if self.has_column(column_name):
del self.G[column_name]
del self.column_infos[column_name]
if self.comm.rank == 0:
self.logger.info("Dropped column %s" % column_name)
def drop_all_except(self, columns_to_keep):
"""
columns_to_keep : list
List of columns to keep. All other columns will be dropped.
"""
colnames = self.G.keys()
for col in colnames:
if col not in columns_to_keep:
self.drop_column(col)
def has_column(self, column_name, throw_exception_if_False=False):
if self.G is None:
return False
else:
return (column_name in self.G.keys())
def rename_column(self, orig_name, new_name):
self.append_column(new_name, self.G[orig_name])
self.drop_column(orig_name)
def check_column_exists(self, column_name):
if not self.has_column(column_name):
raise Exception("Could not find column %s. Allowed columns: %s" %
(column_name, str(self.G.keys())))
def G3d(self, column):
"""
Return self.G[column], reshaped to 3d array (Ngrid,Ngrid,Ngrid).
"""
raise Exception(
"G3d(column) is not implemented any more b/c we store FieldMesh object now"
)
#return self.G[column].reshape((self.Ngrid,self.Ngrid,self.Ngrid))
def append_columns_from_bigfile(
self,
fname,
columns=None,
replace_existing_col=True,
raise_exception_if_column_does_not_exist=True):
"""
Read bigfile grid and append to existing grid instance.
"""
if self.comm.rank == 0:
self.logger.info("Append columns from %s" % fname)
if isinstance(self, RealGrid):
mode = 'real'
elif isinstance(self, ComplexGrid):
mode = 'complex'
else:
raise Exception('Must be instance of RealGrid or ComplexGrid')
subfolders = [
di for di in os.listdir(fname)
if os.path.isdir(os.path.join(fname, di))
]
if columns is None:
# read all columns
columns = subfolders
if self.comm.rank == 0:
self.logger.info("Reading columns %s" % str(columns))
for col in columns:
if (not replace_existing_col) and (self.G is not None) and (
col in self.G.keys()):
print("Column %s already on grid, not reading again" % col)
else:
if self.has_column(col):
self.drop_column(col)
if col not in subfolders:
raise Exception("Column %s is not in file" % str(col))
# read the columns into new grid instance
if mode == "real":
tmp_grid = RealGrid(fname=fname, read_columns=columns)
elif mode == "complex":
tmp_grid = ComplexGrid(fname=fname, read_columns=columns)
else:
raise Exception('Mode must be real or complex')
assert self.Ngrid == tmp_grid.Ngrid
assert self.boxsize == tmp_grid.boxsize
assert type(self) == type(tmp_grid)
self.append_column(col,
tmp_grid.G[col],
column_info=tmp_grid.column_infos.get(
col, None))
del tmp_grid
if self.comm.rank == 0:
self.logger.info("Done reading columns %s" % str(columns))
#self.logger.info("Done reading %s" % fname)
class RealGrid(Grid):
"""
A class for storing and manipulating 3D grids in configuration space.
"""
def __init__(self,
fname=None,
read_columns=None,
meshsource=None,
column=None,
column_info=None,
Ngrid=None,
boxsize=None):
Grid.__init__(self,
fname=fname,
read_columns=read_columns,
meshsource=meshsource,
column=column,
column_info=column_info,
Ngrid=Ngrid,
boxsize=boxsize)
def print_info(self):
pass
# print("")
# if self.G is None:
# print("RealGrid data: None")
# else:
# print("RealGrid data:", self.G.dtype)
# print("RealGrid column_infos:", self.column_infos)
# print("")
def fft_x2k(self, column, drop_column=False):
"""
Compute FFT of a column and return it as FieldMesh object (storing ComplexField).
"""
if self.comm.rank == 0:
self.logger.info('Do FFT x2k')
self.check_column_exists(column)
# Convert meshsource to RealField. What normalization is used here?
#rfield = self.G[column].to_real_field()
#cfield = rfield.r2c()
cfield = self.G[column].compute(mode='complex')
if self.comm.rank == 0:
self.logger.info('Done FFT x2k')
if drop_column:
self.drop_column(column)
print_cstats(cfield,
prefix="%s after fft " % column,
logger=self.logger)
return FieldMesh(cfield)
def apply_smoothing(self,
column,
mode='Gaussian',
R=0.0,
helper_gridk=None,
additional_props=None):
if self.comm.rank == 0:
self.logger.info("Apply smoothing to %s. Mode=%s, R=%s" %
(column, mode, R))
column_info = self.column_infos[column]
# field_k is a FieldMesh object
field_k = self.fft_x2k(column)
if helper_gridk is None:
helper_gridk = ComplexGrid(meshsource=field_k,
column=column,
Ngrid=self.Ngrid,
boxsize=self.boxsize)
else:
helper_gridk.append_column(column, field_k)
del field_k
helper_gridk.apply_smoothing(column,
mode=mode,
R=R,
additional_props=additional_props)
print_cstats(helper_gridk.G[column].compute(mode="complex"),
prefix="gridk after fft result ")
# field_x is a FieldMesh object
field_x = helper_gridk.fft_k2x(column, drop_column=True)
self.append_column(column, field_x, column_info=column_info)
def apply_fx(self, fx):
# todo: implement using nbkit apply function
raise Exception("Not implemented")
def plot_slice(self,
column,
fname,
vmin=None,
vmax=None,
mode=0,
title='AUTO',
title_fs=12):
"""
Mode: 0: Use nbodykit mesh preview.
"""
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
if mode == 0:
plt.imshow(self.G[column].preview(axes=[0, 1]))
# old Marcel plot code
# x_of_slice = (0,self.boxsize)
# y_of_slice = (0,self.boxsize)
# if vmin is None:
# vmin = np.min(image)
# if vmax is None:
# vmax = np.max(image)
# # good: RdBu_r, coolwarm
# myplot = ax.imshow(image, vmin=vmin, vmax=vmax,
# interpolation='gaussian',
# cmap='RdBu_r',
# extent=(x_of_slice[0], x_of_slice[1], y_of_slice[0], y_of_slice[1]))
# colorbar
myfontsize = 14
cbar = plt.colorbar(myplot, ax=ax, shrink=0.8, orientation='vertical')
#pad=0.175, fraction=0.1, aspect=10)
#cbar.set_ticks(np.linspace(vmin, vmax, 3))
# cosmetics
if title == 'AUTO':
ax.set_title(column, y=1.01, fontsize=title_fs)
elif title is not None:
ax.set_title(title, y=1.01, fontsize=title_fs)
#ax.set_xlabel('$x\,[\\mathrm{Mpc}/h]$')
#ax.set_ylabel('$y\,[\\mathrm{Mpc}/h]$')
plt.tight_layout()
plt.savefig(fname)
print("Made %s" % fname)
def store_smoothed_gridx(self,
col,
path,
fname,
helper_gridk=None,
smoothing_mode='Gaussian',
R=None,
plot=False,
replace_nan=False):
"""
Copy column col, FFT to k space, apply smoothing, FFT to x space,
save to disk.
"""
assert helper_gridk is not None
tmpcol = 'tmp4storage'
if fname is None:
fname = col
if R is not None:
if replace_nan is False:
helper_gridk.append_column(tmpcol,
self.fft_x2k(col, drop_column=False))
else:
# replace nan by value of replace_nan
def replace_fcn(x, v):
return np.where(
np.isnan(v),
np.zeros(v.shape, dtype=v.dtype) + replace_nan, v)
outfield = self.G[col].to_real_field()
outfield.apply(replace_fcn, kind='relative', out=outfield)
self.append_column(tmpcol, FieldMesh(outfield))
del outfield
helper_gridk.append_column(
tmpcol, self.fft_x2k(tmpcol, drop_column=True))
helper_gridk.apply_smoothing(tmpcol, mode=smoothing_mode, R=R)
self.append_column(tmpcol,
helper_gridk.fft_k2x(tmpcol, drop_column=True))
else:
if replace_nan is False:
self.append_column(tmpcol, self.G[col])
else:
# replace nan by value of replace_nan
def replace_fcn(x, v):
return np.where(
np.isnan(v),
np.zeros(v.shape, dtype=v.dtype) + replace_nan, v)
outfield = self.G[col].to_real_field()
outfield.apply(replace_fcn, kind='relative', out=outfield)
self.append_column(tmpcol, FieldMesh(outfield))
del outfield
out_fname = os.path.join(path, '%s_R%s.bigfile' % (fname, str(R)))
self.save_to_bigfile(out_fname,
columns=[tmpcol],
new_dataset_for_each_column=True)
if plot:
self.plot_slice(tmpcol, 'liveslice_%s_R%s.png' % (col, str(R)))
self.drop_column(tmpcol)
def convert_to_weighted_uniform_catalog(self,
col=None,
uni_cat_Nptcles_per_dim=None,
fill_value_negative_mass=None,
add_const_to_mass=0.0):
"""
Convert 3D overdensity in gridx.G[col] to a uniform (=regular) catalog of ptcles with mass
gridx.G[col]. Each particle sits at a node of the regular grid.
Note: Our uniform catalog means sth different than nbodykit's UniformCatalog which uses
random positions.
Similar to nbkit03_utils.interpolate_pm_rfield_to_catalog.
fill_value_negative_mass : if not None, set mass ofparticles with negative to mass to this value.
"""
raise Exception(
'TODO: Own Catalog class not needed here, should implement without it.'
)
import Catalog
uniform_cat = Catalog.Catalog()
uniform_cat.sim_Ngrid = None
uniform_cat.sim_boxsize = self.boxsize
grid_infodict = self.column_infos.get(col, {})
uniform_cat.dataset_attrs = {
'Smoothing': np.nan,
'Nmesh': uni_cat_Nptcles_per_dim,
'BoxSize': [self.boxsize, self.boxsize, self.boxsize],
'grid_infodict': json.dumps(grid_infodict)
}
# generate uniform catalog with particles on a regular grid
# see https://nbodykit.readthedocs.io/en/latest/_modules/nbodykit/mockmaker.html#poisson_sample_to_points
# and http://rainwoodman.github.io/pmesh/_modules/pmesh/pm.html#ParticleMesh.generate_uniform_particle_grid
rfield = self.G[col].to_real_field()
comm = rfield.pm.comm
# ranges from 0 to 1?
pos = rfield.pm.generate_uniform_particle_grid(shift=0.0,
dtype='f4',
return_id=False)
if comm.rank == 0:
self.logger.info("uniform regular catalog produced.")
if True:
# Sort, similar to https://nbodykit.readthedocs.io/en/latest/_modules/nbodykit/mockmaker.html#poisson_sample_to_points)
# Not sure if needed.
# generate linear ordering of the positions.
# this should have been a method in pmesh, e.g. argument
# to genereate_uniform_particle_grid(return_id=True);
# grid separation H=Delta x
H = rfield.BoxSize / rfield.Nmesh
# FIXME: after pmesh update, remove this
orderby = np.int64(pos[:, 0] / H[0] + 0.5)
for i in range(1, rfield.ndim):
orderby[...] *= rfield.Nmesh[i]
orderby[...] += np.int64(pos[:, i] / H[i] + 0.5)
# sort by ID to maintain MPI invariance.
import mpsort
pos = mpsort.sort(copy(pos), orderby=orderby, comm=comm)
if comm.rank == 0:
self.logger.info("sorting done")
# normalize so position goes from 0 to 1
pos = pos / rfield.BoxSize
#dtype = np.dtype( [ ('Position', ('f4', 3)),
# ('Mass', 'f4'),
# ] )
#uniform_cat.P = np.empty( (uni_cat_Nptcles_per_dim**3,), dtype=dtype )
from nbodykit.source.catalog.array import ArrayCatalog
# uniform_cat.P is a CatalogSource object
uniform_cat.P = ArrayCatalog(
{'Position': pos},
comm=comm,
**uniform_cat.dataset_attrs # store info in uniform_cat.P.attrs
)
if comm.rank == 0:
self.logger.info(
"position min, max (expect b/w 0 and 1) = %s, %s" %
(uniform_cat.P.compute(uniform_cat.P['Position'].min()),
uniform_cat.P.compute(uniform_cat.P['Position'].max())))
# x components in units such that box ranges from 0 to 1. Note dx=1/Np.
#x_components_1d = np.linspace(0.0, (Ng-1)*(L/float(Ng)), num=Ng, endpoint=True)/L
#x_components_1d = np.linspace(0.0, (Np-1)/float(Np), num=Np, endpoint=True)
#ones_1d = np.ones(x_components_1d.shape)
# Put particles on the regular grid
#uniform_cat.P['Position'][:,0] = np.einsum('a,b,c->abc', x_components_1d, ones_1d, ones_1d).reshape((Np**3,))
#uniform_cat.P['Position'][:,1] = np.einsum('a,b,c->abc', ones_1d, x_components_1d, ones_1d).reshape((Np**3,))
#uniform_cat.P['Position'][:,2] = np.einsum('a,b,c->abc', ones_1d, ones_1d, x_components_1d).reshape((Np**3,))
# assign mass = delta = gridx.G[col]
if uni_cat_Nptcles_per_dim != self.Ngrid:
raise Exception(
"Only implemented uni_cat_Nptcles_per_dim=Ngrid for now; otherwise need to use nbkit0.3 readout."
)
#uniform_cat.P['Mass'][:] = add_const_to_mass + self.G[col].reshape((self.Ngrid**3,))
# get a layout (need window to determine buffer region)
window = 'cic'
layout = rfield.pm.decompose(uniform_cat.P['Position'] * rfield.BoxSize,
smoothing=window)
# interpolate field to particle positions (use pmesh 'readout' function)
# code:https://github.com/rainwoodman/pmesh/blob/54447c8b47085b82c72130074f6ce33cea9e4b21/pmesh/_window.pyx#L156
# https://github.com/rainwoodman/pmesh/blob/54447c8b47085b82c72130074f6ce33cea9e4b21/pmesh/_window_imp.c
# https://github.com/rainwoodman/pmesh/blob/master/pmesh/cic.py#L83
samples_of_delta = rfield.readout(uniform_cat.P['Position'] *
rfield.BoxSize,
resampler=window,
layout=layout)
# save into catalog column
if add_const_to_mass != 0.0:
if self.comm.rank == 0:
self.logger.info('add_const_to_mass: %s' %
str(add_const_to_mass))
uniform_cat.P['Mass'] = add_const_to_mass + samples_of_delta
print_cstats(uniform_cat.P['Mass'].compute(), 'Mass of ptcles ',
self.logger)
# check mass >= 0
minmass = get_cstat(uniform_cat.P['Mass'].compute(), 'min')
if minmass < 0.0:
# check for negative mass particles
mass_rfield = uniform_cat.P['Mass'].compute()
#print('mass rfield:', mass_rfield[:])
ww = np.where(mass_rfield < 0.0)[0]
#print("ww ", ww)
Nneg = self.comm.allreduce(np.array([ww.shape[0]]))
Ntot = self.comm.allreduce(uniform_cat.P['Mass'].compute().size)
if self.comm.rank == 0:
self.logger.info(
"WARNING: %d cells have negative mass (%.3g percent of all cells)"
% (Nneg, 100. * float(Nneg) / float(Ntot)))
if fill_value_negative_mass is not None:
# set negative mass to fill_value_negative_mass (is there something better we can do?)
if self.comm.rank == 0:
self.logger.info("Replace negative mass by %g" %
fill_value_negative_mass)
uniform_cat.P['Mass'] = np.where(
mass_rfield < 0.0,
np.zeros(mass_rfield.shape, dtype=mass_rfield.dtype) +
fill_value_negative_mass, mass_rfield)
else:
print(
"Not doing anything about negative ptcle masses (ok when using sum-CIC painting?)"
)
return uniform_cat
class ComplexGrid(Grid):
"""
A class for storing and manipulating complex 3D grids in Fourier (k-)space.
"""
def __init__(self,
fname=None,
read_columns=None,
meshsource=None,
column=None,
column_info=None,
Ngrid=None,
boxsize=None):
Grid.__init__(self,
fname=fname,
read_columns=read_columns,
meshsource=meshsource,
column=column,
column_info=column_info,
Ngrid=Ngrid,
boxsize=boxsize)
# construct k component in each direction
#self.k_component_1d = fft_ms_v2.get_1d_k_cpts(Ngrid=self.Ngrid, boxsize=self.boxsize)
#assert self.k_component_1d.shape == (self.Ngrid,)
#self._helper_grid_names = ['INV_ABSK', 'ABSK']
def print_info(self):
pass
# print("")
# if self.G is None:
# print("ComplexGrid data: None")
# else:
# print("ComplexGrid data:", self.G.dtype)
# print("")
def compute_helper_grid(self, column_name=None, DCmode=-1.0e-50):
pass
# """
# Return array of shape (Ngrid**3,) containing 1/k at each entry.
# """
# if not column_name in self._helper_grid_names:
# raise Exception("Invalid helper grid column_name %s" % str(column_name))
# if self.has_column(column_name):
# return
# if column_name == 'ABSK':
# # compute k = sqrt(kx**2+ky**2+kz**2)
# Ngrid = self.Ngrid
# ones = np.ones( (Ngrid**3,), dtype='c16')
# ones = ones.reshape( (Ngrid,Ngrid,Ngrid) )
# absk = np.zeros( (Ngrid**3,), dtype='c16')
# absk += (np.einsum('a,a,abc->abc',
# self.k_component_1d, self.k_component_1d, ones)).reshape((Ngrid**3,))
# absk += (np.einsum('b,b,abc->abc',
# self.k_component_1d, self.k_component_1d, ones)).reshape((Ngrid**3,))
# absk += (np.einsum('c,c,abc->abc',
# self.k_component_1d, self.k_component_1d, ones)).reshape((Ngrid**3,))
# #absk = np.sqrt(absk)
# absk = absk**0.5
# absk[0] = 0.0
# #absk2 = absk.reshape( (Ngrid**3,) ).copy()
# #absk = np.ma.filled(absk, fill_value=np.nan)
# #absk2 = np.ma.getdata(absk2)
# #absk2 = np.ascontiguousarray(absk2)
# self.append_column('ABSK', absk)
# elif column_name == 'INV_ABSK':
# if not self.has_column('ABSK'):
# self.compute_helper_grid('ABSK')
# absk = self.G['ABSK']
# self.append_column('INV_ABSK', np.where(absk==0, DCmode*np.ones(absk.shape), 1.0/absk))
def drop_helper_grids(self):
"""
Empty cached helper arrays, like inv_absk.
"""
pass
# for col in self._helper_grid_names:
# if self.has_column(col):
# self.drop_column(col)
def fft_k2x(self, column, drop_column=False):
"""
Compute FFT of a column and return it as FieldMesh object (storing RealField).
"""
self.check_column_exists(column)
if self.comm.rank == 0:
self.logger.info('Do FFT k2x')
rfield = self.G[column].compute(mode='real')
if self.comm.rank == 0:
self.logger.info('Done FFT k2x')
# # todo: check if we got a real field with no imag part
# max_imag = np.max(np.abs(np.imag(field_x)))
# avg_real = np.mean(np.abs(np.real(field_x)))
# print("max_imag, avg_real:", max_imag, avg_real)
# if max_imag > 1e-3 * avg_real:
# raise Exception("Real field has too large imaginary part. Consider smoothing with R>=%g or %g Mpc/h." % (
# 1.5*self.boxsize/float(self.Ngrid), 2.*self.boxsize/float(self.Ngrid)))
if drop_column:
self.drop_column(column)
return FieldMesh(rfield)
def apply_smoothing(self,
column,
mode='Gaussian',
R=0.0,
kmax=None,
additional_props=None,
just_return_window_fcn=False):
"""
mode: 'Gaussian' or 'SharpK' or 'kstep'.
Result overwrites data in grid.G[column].
"""
if just_return_window_fcn:
# just return a fcn computing the smoothing kernel WR
def calc_WR(kvec):
if mode == 'Gaussian':
if R != 0.0:
WR = np.exp(-(R * kvec)**2 / 2.0)
else:
WR = np.ones(kvec.shape)
elif mode == 'InverseGaussian':
raise Exception("todo")
elif mode == 'kstep':
step_kmin = additional_props['step_kmin']
step_kmax = additional_props['step_kmax']
WR = np.where((kvec >= step_kmin) & (kvec < step_kmax),
np.ones(kvec.shape), np.zeros(kvec.shape))
else:
raise Exception(
"just_return_window_fcn not implemented for %s" % mode)
if kmax is not None:
WR = np.where(kvec <= kmax, WR, np.zeros(WR.shape))
return WR
return calc_WR
# actually apply smoothing to the field
if self.comm.rank == 0:
self.logger.info(
"Apply smoothing to %s with mode=%s, R=%g Mpc/h, kmax=%s h/Mpc"
% (column, mode, R, str(kmax)))
column_info = self.column_infos[column]
self.append_column(column,
nbkit03_utils.apply_smoothing(
self.G[column],
mode=mode,
R=R,
kmax=kmax,
additional_props=additional_props),
column_info=column_info)
def calc_all_power_spectra(self,