DNS.py 54.4 KB
Newer Older
1
2
3
4
################################################################################
#                                                                              #
#  Copyright 2015-2019 Max Planck Institute for Dynamics and Self-Organization #
#                                                                              #
5
#  This file is part of TurTLE.                                                #
6
#                                                                              #
7
#  TurTLE is free software: you can redistribute it and/or modify              #
8
9
10
11
#  it under the terms of the GNU General Public License as published           #
#  by the Free Software Foundation, either version 3 of the License,           #
#  or (at your option) any later version.                                      #
#                                                                              #
12
#  TurTLE is distributed in the hope that it will be useful,                   #
13
14
15
16
17
#  but WITHOUT ANY WARRANTY; without even the implied warranty of              #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               #
#  GNU General Public License for more details.                                #
#                                                                              #
#  You should have received a copy of the GNU General Public License           #
18
#  along with TurTLE.  If not, see <http://www.gnu.org/licenses/>              #
19
20
21
22
#                                                                              #
# Contact: Cristian.Lalescu@ds.mpg.de                                          #
#                                                                              #
################################################################################
Cristian Lalescu's avatar
Cristian Lalescu committed
23
24
25
26
27
28
29
30
31
32
33
34



import os
import sys
import shutil
import subprocess
import h5py
import math
import numpy as np
import warnings

35
import TurTLE
Cristian Lalescu's avatar
Cristian Lalescu committed
36
from ._code import _code
37
from TurTLE import tools
Cristian Lalescu's avatar
Cristian Lalescu committed
38
39
40
41
42
43
44
45

class DNS(_code):
    """This class is meant to stitch together the C++ code into a final source file,
    compile it, and handle all job launching.
    """
    def __init__(
            self,
            work_dir = './',
46
47
48
49
50
51
            simname = 'test'):
        _code.__init__(
                self,
                work_dir = work_dir,
                simname = simname)
        self.generate_default_parameters()
Cristian Lalescu's avatar
Cristian Lalescu committed
52
        self.statistics = {}
53
54
55
56
        return None
    def set_precision(
            self,
            fluid_dtype):
Cristian Lalescu's avatar
Cristian Lalescu committed
57
58
59
60
61
62
63
64
65
66
        if fluid_dtype in [np.float32, np.float64]:
            self.fluid_dtype = fluid_dtype
        elif fluid_dtype in ['single', 'double']:
            if fluid_dtype == 'single':
                self.fluid_dtype = np.dtype(np.float32)
            elif fluid_dtype == 'double':
                self.fluid_dtype = np.dtype(np.float64)
        self.rtype = self.fluid_dtype
        if self.rtype == np.float32:
            self.ctype = np.dtype(np.complex64)
67
            self.C_field_dtype = 'float'
68
            self.fluid_precision = 'single'
Cristian Lalescu's avatar
Cristian Lalescu committed
69
70
        elif self.rtype == np.float64:
            self.ctype = np.dtype(np.complex128)
71
            self.C_field_dtype = 'double'
72
73
            self.fluid_precision = 'double'
        return None
74
75
    def write_src(
            self):
Cristian Lalescu's avatar
Cristian Lalescu committed
76
77
        self.version_message = (
                '/***********************************************************************\n' +
78
79
                '* this code automatically generated by TurTLE\n' +
                '* version {0}\n'.format(TurTLE.__version__) +
Cristian Lalescu's avatar
Cristian Lalescu committed
80
                '***********************************************************************/\n\n\n')
81
82
83
84
85
        self.include_list = [
                '"base.hpp"',
                '"scope_timer.hpp"',
                '"fftw_interface.hpp"',
                '"full_code/main_code.hpp"',
86
                '<cmath>',
87
88
89
90
91
92
93
94
95
                '<iostream>',
                '<hdf5.h>',
                '<string>',
                '<cstring>',
                '<fftw3-mpi.h>',
                '<omp.h>',
                '<cfenv>',
                '<cstdlib>',
                '"full_code/{0}.hpp"\n'.format(self.dns_type)]
Cristian Lalescu's avatar
Cristian Lalescu committed
96
        self.main = """
97
98
99
            int main(int argc, char *argv[])
            {{
                bool fpe = (
Cristian Lalescu's avatar
Cristian Lalescu committed
100
101
                    (getenv("TURTLE_FPE_OFF") == nullptr) ||
                    (getenv("TURTLE_FPE_OFF") != std::string("TRUE")));
102
103
104
                return main_code< {0} >(argc, argv, fpe);
            }}
            """.format(self.dns_type + '<{0}>'.format(self.C_field_dtype))
105
106
107
108
109
110
111
        self.includes = '\n'.join(
                ['#include ' + hh
                 for hh in self.include_list])
        with open(self.name + '.cpp', 'w') as outfile:
            outfile.write(self.version_message + '\n\n')
            outfile.write(self.includes + '\n\n')
            outfile.write(self.main + '\n')
112
113
114
        return None
    def generate_default_parameters(self):
        # these parameters are relevant for all DNS classes
Cristian Lalescu's avatar
Cristian Lalescu committed
115
        self.parameters['fftw_plan_rigor'] = 'FFTW_ESTIMATE'
116
117
118
119
120
121
122
        self.parameters['dealias_type'] = int(1)
        self.parameters['dkx'] = float(1.0)
        self.parameters['dky'] = float(1.0)
        self.parameters['dkz'] = float(1.0)
        self.parameters['niter_todo'] = int(8)
        self.parameters['niter_stat'] = int(1)
        self.parameters['niter_out'] = int(8)
123
        self.parameters['checkpoints_per_file'] = int(1)
124
        self.parameters['dt'] = float(0.01)
125
        self.parameters['nu'] = float(0.1)
126
        self.parameters['fmode'] = int(1)
127
        self.parameters['famplitude'] = float(0.5)
Cristian Lalescu's avatar
Cristian Lalescu committed
128
        self.parameters['friction_coefficient'] = float(0.5)
Cristian Lalescu's avatar
Cristian Lalescu committed
129
130
        self.parameters['energy'] = float(0.5)
        self.parameters['injection_rate'] = float(0.4)
131
132
        self.parameters['fk0'] = float(2.0)
        self.parameters['fk1'] = float(4.0)
Cristian Lalescu's avatar
Cristian Lalescu committed
133
        self.parameters['forcing_type'] = 'fixed_energy_injection_rate'
134
135
136
137
        self.parameters['histogram_bins'] = int(256)
        self.parameters['max_velocity_estimate'] = float(1)
        self.parameters['max_vorticity_estimate'] = float(1)
        # parameters specific to particle version
138
139
        self.NSVEp_extra_parameters = {}
        self.NSVEp_extra_parameters['niter_part'] = int(1)
140
141
        self.NSVEp_extra_parameters['niter_part_fine_period'] = int(10)
        self.NSVEp_extra_parameters['niter_part_fine_duration'] = int(0)
142
        self.NSVEp_extra_parameters['nparticles'] = int(10)
143
        self.NSVEp_extra_parameters['cpp_random_particles'] = int(0)
144
145
146
        self.NSVEp_extra_parameters['tracers0_integration_steps'] = int(4)
        self.NSVEp_extra_parameters['tracers0_neighbours'] = int(1)
        self.NSVEp_extra_parameters['tracers0_smoothness'] = int(1)
147
148
149
150
151
        self.NSVEp_extra_parameters['tracers0_enable_p2p'] = int(0)
        self.NSVEp_extra_parameters['tracers0_enable_inner'] = int(0)
        self.NSVEp_extra_parameters['tracers0_enable_vorticity_omega'] = int(0)
        self.NSVEp_extra_parameters['tracers0_cutoff'] = float(1)
        self.NSVEp_extra_parameters['tracers0_inner_v0'] = float(1)
Cristian Lalescu's avatar
Cristian Lalescu committed
152
        self.NSVEp_extra_parameters['tracers0_lambda'] = float(1)
Cristian Lalescu's avatar
Cristian Lalescu committed
153
        #self.extra_parameters = {}
154
        #for key in ['NSVE', 'NSVE_no_output', 'NSVEparticles', 'NSVEparticles_no_output', 'NSVEcomplex_particles']:
Cristian Lalescu's avatar
Cristian Lalescu committed
155
        #    self.extra_parameters[key] = {}
156
        #for key in ['NSVEparticles', 'NSVEparticles_no_output', 'NSVEcomplex_particles']:
Cristian Lalescu's avatar
Cristian Lalescu committed
157
        #    self.extra_parameters[key].update(self.NSVEp_extra_parameters)
Cristian Lalescu's avatar
Cristian Lalescu committed
158
        return None
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
    def get_kspace(self):
        kspace = {}
        if self.parameters['dealias_type'] == 1:
            kMx = self.parameters['dkx']*(self.parameters['nx']//2 - 1)
            kMy = self.parameters['dky']*(self.parameters['ny']//2 - 1)
            kMz = self.parameters['dkz']*(self.parameters['nz']//2 - 1)
        else:
            kMx = self.parameters['dkx']*(self.parameters['nx']//3 - 1)
            kMy = self.parameters['dky']*(self.parameters['ny']//3 - 1)
            kMz = self.parameters['dkz']*(self.parameters['nz']//3 - 1)
        kspace['kM'] = max(kMx, kMy, kMz)
        kspace['dk'] = min(self.parameters['dkx'],
                           self.parameters['dky'],
                           self.parameters['dkz'])
        nshells = int(kspace['kM'] / kspace['dk']) + 2
        kspace['nshell'] = np.zeros(nshells, dtype = np.int64)
        kspace['kshell'] = np.zeros(nshells, dtype = np.float64)
        kspace['kx'] = np.arange( 0,
                                  self.parameters['nx']//2 + 1).astype(np.float64)*self.parameters['dkx']
        kspace['ky'] = np.arange(-self.parameters['ny']//2 + 1,
                                  self.parameters['ny']//2 + 1).astype(np.float64)*self.parameters['dky']
        kspace['ky'] = np.roll(kspace['ky'], self.parameters['ny']//2+1)
        kspace['kz'] = np.arange(-self.parameters['nz']//2 + 1,
                                  self.parameters['nz']//2 + 1).astype(np.float64)*self.parameters['dkz']
        kspace['kz'] = np.roll(kspace['kz'], self.parameters['nz']//2+1)
        return kspace
    def get_data_file_name(self):
        return os.path.join(self.work_dir, self.simname + '.h5')
    def get_data_file(self):
        return h5py.File(self.get_data_file_name(), 'r')
    def get_particle_file_name(self):
        return os.path.join(self.work_dir, self.simname + '_particles.h5')
    def get_particle_file(self):
        return h5py.File(self.get_particle_file_name(), 'r')
193
194
195
196
    def get_cache_file_name(self):
        return os.path.join(self.work_dir, self.simname + '_cache.h5')
    def get_cache_file(self):
        return h5py.File(self.get_cache_file_name(), 'r')
197
    def get_postprocess_file_name(self):
198
        return self.get_cache_file_name()
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    def get_postprocess_file(self):
        return h5py.File(self.get_postprocess_file_name(), 'r')
    def compute_statistics(self, iter0 = 0, iter1 = None):
        """Run basic postprocessing on raw data.
        The energy spectrum :math:`E(t, k)` and the enstrophy spectrum
        :math:`\\frac{1}{2}\omega^2(t, k)` are computed from the

        .. math::

            \sum_{k \\leq \\|\\mathbf{k}\\| \\leq k+dk}\\hat{u_i} \\hat{u_j}^*, \\hskip .5cm
            \sum_{k \\leq \\|\\mathbf{k}\\| \\leq k+dk}\\hat{\omega_i} \\hat{\\omega_j}^*

        tensors, and the enstrophy spectrum is also used to
        compute the dissipation :math:`\\varepsilon(t)`.
        These basic quantities are stored in a newly created HDF5 file,
214
        ``simname_cache.h5``.
215
216
217
        """
        if len(list(self.statistics.keys())) > 0:
            return None
Cristian Lalescu's avatar
Cristian Lalescu committed
218
219
220
        if not os.path.exists(self.get_data_file_name()):
            if os.path.exists(self.get_cache_file_name()):
                self.read_parameters(fname = self.get_cache_file_name())
Cristian Lalescu's avatar
Cristian Lalescu committed
221
222
223
224
225
226
227
228
                pp_file = self.get_cache_file()
                for k in ['t',
                          'energy(t)',
                          'energy(k)',
                          'enstrophy(t)',
                          'enstrophy(k)',
                          'R_ij(t)',
                          'vel_max(t)',
229
230
                          'renergy(t)',
                          'renstrophy(t)']:
Cristian Lalescu's avatar
Cristian Lalescu committed
231
232
233
234
235
236
                    if k in pp_file.keys():
                        self.statistics[k] = pp_file[k][...]
                self.statistics['kM'] = pp_file['kspace/kM'][...]
                self.statistics['dk'] = pp_file['kspace/dk'][...]
                self.statistics['kshell'] = pp_file['kspace/kshell'][...]
                self.statistics['nshell'] = pp_file['kspace/nshell'][...]
Cristian Lalescu's avatar
Cristian Lalescu committed
237
238
239
240
241
242
243
244
245
        else:
            self.read_parameters()
            with self.get_data_file() as data_file:
                if 'moments' not in data_file['statistics'].keys():
                    return None
                iter0 = min((data_file['statistics/moments/velocity'].shape[0] *
                             self.parameters['niter_stat']-1),
                            iter0)
                if type(iter1) == type(None):
246
                    iter1 = data_file['iteration'][...]
Cristian Lalescu's avatar
Cristian Lalescu committed
247
                else:
248
                    iter1 = min(data_file['iteration'][...], iter1)
Cristian Lalescu's avatar
Cristian Lalescu committed
249
250
                ii0 = iter0 // self.parameters['niter_stat']
                ii1 = iter1 // self.parameters['niter_stat']
251
252
                self.statistics['kshell'] = data_file['kspace/kshell'][...]
                self.statistics['nshell'] = data_file['kspace/nshell'][...]
Cristian Lalescu's avatar
Cristian Lalescu committed
253
254
255
                for kk in [-1, -2]:
                    if (self.statistics['kshell'][kk] == 0):
                        self.statistics['kshell'][kk] = np.nan
256
257
                self.statistics['kM'] = data_file['kspace/kM'][...]
                self.statistics['dk'] = data_file['kspace/dk'][...]
Cristian Lalescu's avatar
Cristian Lalescu committed
258
259
260
261
262
263
                computation_needed = True
                pp_file = h5py.File(self.get_postprocess_file_name(), 'a')
                if not ('parameters' in pp_file.keys()):
                    data_file.copy('parameters', pp_file)
                    data_file.copy('kspace', pp_file)
                if 'ii0' in pp_file.keys():
264
265
                    computation_needed =  not (ii0 == pp_file['ii0'][...] and
                                               ii1 == pp_file['ii1'][...])
Cristian Lalescu's avatar
Cristian Lalescu committed
266
                    if computation_needed:
267
268
269
                        for k in ['t', 'vel_max(t)',
                                  'renergy(t)',
                                  'renstrophy(t)',
Cristian Lalescu's avatar
Cristian Lalescu committed
270
271
272
273
274
275
276
277
278
                                  'energy(t)', 'enstrophy(t)',
                                  'energy(k)', 'enstrophy(k)',
                                  'energy(t, k)',
                                  'enstrophy(t, k)',
                                  'R_ij(t)',
                                  'ii0', 'ii1', 'iter0', 'iter1']:
                            if k in pp_file.keys():
                                del pp_file[k]
                if computation_needed:
Cristian Lalescu's avatar
Cristian Lalescu committed
279
                    #TODO figure out whether normalization is sane or not
Cristian Lalescu's avatar
Cristian Lalescu committed
280
281
282
283
284
285
286
                    pp_file['iter0'] = iter0
                    pp_file['iter1'] = iter1
                    pp_file['ii0'] = ii0
                    pp_file['ii1'] = ii1
                    pp_file['t'] = (self.parameters['dt']*
                                    self.parameters['niter_stat']*
                                    (np.arange(ii0, ii1+1).astype(np.float)))
Cristian Lalescu's avatar
Cristian Lalescu committed
287
288
289
                    # we have an extra division by shell_width because of the Dirac delta restricting integration to the shell
                    phi_ij = data_file['statistics/spectra/velocity_velocity'][ii0:ii1+1] / self.statistics['dk']
                    pp_file['R_ij(t)'] = np.sum(phi_ij*self.statistics['dk'], axis = 1)
Cristian Lalescu's avatar
Cristian Lalescu committed
290
291
292
293
                    energy_tk = (
                        phi_ij[:, :, 0, 0] +
                        phi_ij[:, :, 1, 1] +
                        phi_ij[:, :, 2, 2])/2
Cristian Lalescu's avatar
Cristian Lalescu committed
294
295
296
297
298
                    pp_file['energy(t)'] = np.sum(energy_tk*self.statistics['dk'], axis = 1)
                    # normalization factor is (4 pi * shell_width * kshell^2) / (nmodes in shell * dkx*dky*dkz)
                    norm_factor = (4*np.pi*self.statistics['dk']*self.statistics['kshell']**2) / (self.parameters['dkx']*self.parameters['dky']*self.parameters['dkz']*self.statistics['nshell'])
                    pp_file['energy(k)'] = np.mean(energy_tk, axis = 0)*norm_factor
                    phi_vorticity_ij = data_file['statistics/spectra/vorticity_vorticity'][ii0:ii1+1] / self.statistics['dk']
Cristian Lalescu's avatar
Cristian Lalescu committed
299
                    enstrophy_tk = (
300
301
302
                        phi_vorticity_ij[:, :, 0, 0] +
                        phi_vorticity_ij[:, :, 1, 1] +
                        phi_vorticity_ij[:, :, 2, 2])/2
Cristian Lalescu's avatar
Cristian Lalescu committed
303
304
                    pp_file['enstrophy(t)'] = np.sum(enstrophy_tk*self.statistics['dk'], axis = 1)
                    pp_file['enstrophy(k)'] = np.mean(enstrophy_tk, axis = 0)*norm_factor
Cristian Lalescu's avatar
Cristian Lalescu committed
305
306
                    pp_file['vel_max(t)'] = data_file['statistics/moments/velocity'][ii0:ii1+1, 9, 3]
                    pp_file['renergy(t)'] = data_file['statistics/moments/velocity'][ii0:ii1+1, 2, 3]/2
307
                    pp_file['renstrophy(t)'] = data_file['statistics/moments/vorticity'][ii0:ii1+1, 2, 3]/2
Cristian Lalescu's avatar
Cristian Lalescu committed
308
309
310
311
312
313
314
        for k in ['t',
                  'energy(t)',
                  'energy(k)',
                  'enstrophy(t)',
                  'enstrophy(k)',
                  'R_ij(t)',
                  'vel_max(t)',
315
316
                  'renergy(t)',
                  'renstrophy(t)']:
Cristian Lalescu's avatar
Cristian Lalescu committed
317
            if k in pp_file.keys():
318
                self.statistics[k] = pp_file[k][...]
Cristian Lalescu's avatar
Cristian Lalescu committed
319
320
321
322
        # sanity check --- Parseval theorem check
        assert(np.max(np.abs(
                self.statistics['renergy(t)'] -
                self.statistics['energy(t)']) / self.statistics['energy(t)']) < 1e-5)
323
324
325
        assert(np.max(np.abs(
                self.statistics['renstrophy(t)'] -
                self.statistics['enstrophy(t)']) / self.statistics['enstrophy(t)']) < 1e-5)
Cristian Lalescu's avatar
Cristian Lalescu committed
326
        self.compute_time_averages()
327
        return None
328
329
    def compute_Reynolds_stress_invariants(
            self):
Cristian Lalescu's avatar
Cristian Lalescu committed
330
331
332
        """
        see Choi and Lumley, JFM v436 p59 (2001)
        """
333
334
335
336
337
338
339
340
        Rij = self.statistics['R_ij(t)']
        Rij /= (2*self.statistics['energy(t)'][:, None, None])
        Rij[:, 0, 0] -= 1./3
        Rij[:, 1, 1] -= 1./3
        Rij[:, 2, 2] -= 1./3
        self.statistics['I2(t)'] = np.sqrt(np.einsum('...ij,...ij', Rij, Rij, optimize = True) / 6)
        self.statistics['I3(t)'] = np.cbrt(np.einsum('...ij,...jk,...ki', Rij, Rij, Rij, optimize = True) / 6)
        return None
341
342
343
344
    def compute_time_averages(self):
        """Compute easy stats.

        Further computation of statistics based on the contents of
345
        ``simname_cache.h5``.
346
347
348
349
350
351
        Standard quantities are as follows
        (consistent with [Ishihara]_):

        .. math::

            U_{\\textrm{int}}(t) = \\sqrt{\\frac{2E(t)}{3}}, \\hskip .5cm
352
353
354
            L_{\\textrm{int}} = \\frac{\pi}{2U_{int}^2} \\int \\frac{dk}{k} E(k), \\hskip .5cm
            T_{\\textrm{int}} =
            \\frac{L_{\\textrm{int}}}{U_{\\textrm{int}}}
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373

            \\eta_K = \\left(\\frac{\\nu^3}{\\varepsilon}\\right)^{1/4}, \\hskip .5cm
            \\tau_K = \\left(\\frac{\\nu}{\\varepsilon}\\right)^{1/2}, \\hskip .5cm
            \\lambda = \\sqrt{\\frac{15 \\nu U_{\\textrm{int}}^2}{\\varepsilon}}

            Re = \\frac{U_{\\textrm{int}} L_{\\textrm{int}}}{\\nu}, \\hskip
            .5cm
            R_{\\lambda} = \\frac{U_{\\textrm{int}} \\lambda}{\\nu}

        .. [Ishihara] T. Ishihara et al,
                      *Small-scale statistics in high-resolution direct numerical
                      simulation of turbulence: Reynolds number dependence of
                      one-point velocity gradient statistics*.
                      J. Fluid Mech.,
                      **592**, 335-366, 2007
        """
        self.statistics['Uint(t)'] = np.sqrt(2*self.statistics['energy(t)'] / 3)
        for key in ['energy',
                    'enstrophy',
374
375
                    'mean_trS2',
                    'Uint']:
376
377
            if key + '(t)' in self.statistics.keys():
                self.statistics[key] = np.average(self.statistics[key + '(t)'], axis = 0)
378
        self.statistics['vel_max'] = np.max(self.statistics['vel_max(t)'])
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
        for suffix in ['', '(t)']:
            self.statistics['diss'    + suffix] = (self.parameters['nu'] *
                                                   self.statistics['enstrophy' + suffix]*2)
            self.statistics['etaK'    + suffix] = (self.parameters['nu']**3 /
                                                   self.statistics['diss' + suffix])**.25
            self.statistics['tauK'    + suffix] =  (self.parameters['nu'] /
                                                    self.statistics['diss' + suffix])**.5
            self.statistics['lambda' + suffix] = (15 * self.parameters['nu'] *
                                                  self.statistics['Uint' + suffix]**2 /
                                                  self.statistics['diss' + suffix])**.5
            self.statistics['Rlambda' + suffix] = (self.statistics['Uint' + suffix] *
                                                   self.statistics['lambda' + suffix] /
                                                   self.parameters['nu'])
            self.statistics['kMeta' + suffix] = (self.statistics['kM'] *
                                                 self.statistics['etaK' + suffix])
            if self.parameters['dealias_type'] == 1:
                self.statistics['kMeta' + suffix] *= 0.8
Cristian Lalescu's avatar
Cristian Lalescu committed
396
        self.statistics['Lint'] = ((np.pi /
397
                                    (2*self.statistics['Uint']**2)) *
398
399
                                   np.sum(self.statistics['energy(k)'][1:-2] /
                                          self.statistics['kshell'][1:-2]))
400
401
402
        self.statistics['Re'] = (self.statistics['Uint'] *
                                 self.statistics['Lint'] /
                                 self.parameters['nu'])
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
        self.statistics['Tint'] = self.statistics['Lint'] / self.statistics['Uint']
        self.statistics['Taylor_microscale'] = self.statistics['lambda']
        return None
    def set_plt_style(
            self,
            style = {'dashes' : (None, None)}):
        self.style.update(style)
        return None
    def convert_complex_from_binary(
            self,
            field_name = 'vorticity',
            iteration = 0,
            file_name = None):
        """read the Fourier representation of a vector field.

        Read the binary file containing iteration ``iteration`` of the
        field ``field_name``, and write it in a ``.h5`` file.
        """
        data = np.memmap(
                os.path.join(self.work_dir,
                             self.simname + '_{0}_i{1:0>5x}'.format('c' + field_name, iteration)),
                dtype = self.ctype,
                mode = 'r',
                shape = (self.parameters['ny'],
                         self.parameters['nz'],
                         self.parameters['nx']//2+1,
                         3))
        if type(file_name) == type(None):
            file_name = self.simname + '_{0}_i{1:0>5x}.h5'.format('c' + field_name, iteration)
            file_name = os.path.join(self.work_dir, file_name)
        f = h5py.File(file_name, 'a')
        f[field_name + '/complex/{0}'.format(iteration)] = data
        f.close()
        return None
    def write_par(
            self,
Cristian Lalescu's avatar
Cristian Lalescu committed
439
            iter0 = 0):
440
441
442
        assert (self.parameters['niter_todo'] % self.parameters['niter_stat'] == 0)
        assert (self.parameters['niter_todo'] % self.parameters['niter_out']  == 0)
        assert (self.parameters['niter_out']  % self.parameters['niter_stat'] == 0)
443
444
445
446
447
448
        if self.dns_type in [
                'NSVEparticles_no_output',
                'NSVEcomplex_particles',
                'NSVE_Stokes_particles',
                'NSVEparticles',
                'static_field',
449
                'static_field_with_ghost_collisions',
450
                'kraichnan_field']:
451
452
            assert (self.parameters['niter_todo'] % self.parameters['niter_part'] == 0)
            assert (self.parameters['niter_out']  % self.parameters['niter_part'] == 0)
453
454
        _code.write_par(self, iter0 = iter0)
        with h5py.File(self.get_data_file_name(), 'r+') as ofile:
455
            ofile['code_info/exec_name'] = self.name
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
            kspace = self.get_kspace()
            for k in kspace.keys():
                ofile['kspace/' + k] = kspace[k]
            nshells = kspace['nshell'].shape[0]
            kspace = self.get_kspace()
            nshells = kspace['nshell'].shape[0]
            vec_stat_datasets = ['velocity', 'vorticity']
            scal_stat_datasets = []
            for k in vec_stat_datasets:
                time_chunk = 2**20//(8*3*3*nshells)
                time_chunk = max(time_chunk, 1)
                ofile.create_dataset('statistics/spectra/' + k + '_' + k,
                                     (1, nshells, 3, 3),
                                     chunks = (time_chunk, nshells, 3, 3),
                                     maxshape = (None, nshells, 3, 3),
                                     dtype = np.float64)
                time_chunk = 2**20//(8*4*10)
                time_chunk = max(time_chunk, 1)
                a = ofile.create_dataset('statistics/moments/' + k,
                                     (1, 10, 4),
                                     chunks = (time_chunk, 10, 4),
                                     maxshape = (None, 10, 4),
                                     dtype = np.float64)
                time_chunk = 2**20//(8*4*self.parameters['histogram_bins'])
                time_chunk = max(time_chunk, 1)
                ofile.create_dataset('statistics/histograms/' + k,
                                     (1,
                                      self.parameters['histogram_bins'],
                                      4),
                                     chunks = (time_chunk,
                                               self.parameters['histogram_bins'],
                                               4),
                                     maxshape = (None,
                                                 self.parameters['histogram_bins'],
                                                 4),
                                     dtype = np.int64)
            ofile['checkpoint'] = int(0)
493
494
            if self.dns_type in ['static_field_with_ghost_collisions']:
                ofile.create_group('statistics/collisions')
Cristian Lalescu's avatar
Cristian Lalescu committed
495
        if (self.dns_type in ['NSVE', 'NSVE_no_output']):
496
497
            return None
        return None
498
    def job_parser_arguments(
499
500
            self,
            parser):
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
        parser.add_argument(
                '--ncpu',
                type = int,
                dest = 'ncpu',
                default = -1)
        parser.add_argument(
                '--np', '--nprocesses',
                metavar = 'NPROCESSES',
                help = 'number of mpi processes to use',
                type = int,
                dest = 'nb_processes',
                default = 4)
        parser.add_argument(
                '--ntpp', '--nthreads-per-process',
                type = int,
                dest = 'nb_threads_per_process',
                metavar = 'NTHREADS_PER_PROCESS',
                help = 'number of threads to use per MPI process',
                default = 1)
520
521
522
523
        parser.add_argument(
                '--no-debug',
                action = 'store_true',
                dest = 'no_debug')
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
        parser.add_argument(
                '--no-submit',
                action = 'store_true',
                dest = 'no_submit')
        parser.add_argument(
                '--environment',
                type = str,
                dest = 'environment',
                default = None)
        parser.add_argument(
                '--minutes',
                type = int,
                dest = 'minutes',
                default = 5,
                help = 'If environment supports it, this is the requested wall-clock-limit.')
        parser.add_argument(
               '--njobs',
               type = int, dest = 'njobs',
               default = 1)
        return None
    def simulation_parser_arguments(
            self,
            parser):
        parser.add_argument(
                '--simname',
                type = str, dest = 'simname',
                default = 'test')
        parser.add_argument(
552
               '-n', '--grid-size',
553
554
555
556
557
               type = int,
               dest = 'n',
               default = 32,
               metavar = 'N',
               help = 'code is run by default in a grid of NxNxN')
558
559
560
561
562
563
564
565
        for coord in ['x', 'y', 'z']:
            parser.add_argument(
                   '--L{0}'.format(coord), '--box-length-{0}'.format(coord),
                   type = float,
                   dest = 'L{0}'.format(coord),
                   default = 2.0,
                   metavar = 'length{0}'.format(coord),
                   help = 'length of the box in the {0} direction will be `length{0} x pi`'.format(coord))
566
567
568
569
570
571
572
573
574
        parser.add_argument(
                '--wd',
                type = str, dest = 'work_dir',
                default = './')
        parser.add_argument(
                '--precision',
                choices = ['single', 'double'],
                type = str,
                default = 'single')
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
        parser.add_argument(
                '--src-wd',
                type = str,
                dest = 'src_work_dir',
                default = '')
        parser.add_argument(
                '--src-simname',
                type = str,
                dest = 'src_simname',
                default = '')
        parser.add_argument(
                '--src-iteration',
                type = int,
                dest = 'src_iteration',
                default = 0)
        parser.add_argument(
               '--kMeta',
               type = float,
               dest = 'kMeta',
               default = 2.0)
        parser.add_argument(
               '--dtfactor',
               type = float,
               dest = 'dtfactor',
               default = 0.5,
               help = 'dt is computed as DTFACTOR / N')
601
602
603
604
        return None
    def particle_parser_arguments(
            self,
            parser):
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
        parser.add_argument(
               '--particle-rand-seed',
               type = int,
               dest = 'particle_rand_seed',
               default = None)
        parser.add_argument(
               '--pclouds',
               type = int,
               dest = 'pclouds',
               default = 1,
               help = ('number of particle clouds. Particle "clouds" '
                       'consist of particles distributed according to '
                       'pcloud-type.'))
        parser.add_argument(
                '--pcloud-type',
                choices = ['random-cube',
                           'regular-cube'],
                dest = 'pcloud_type',
                default = 'random-cube')
        parser.add_argument(
               '--particle-cloud-size',
               type = float,
               dest = 'particle_cloud_size',
               default = 2*np.pi)
        return None
630
631
632
633
634
635
636
637
638
639
640
    def add_parser_arguments(
            self,
            parser):
        subparsers = parser.add_subparsers(
                dest = 'DNS_class',
                help = 'type of simulation to run')
        subparsers.required = True
        parser_NSVE = subparsers.add_parser(
                'NSVE',
                help = 'plain Navier-Stokes vorticity formulation')

641
642
643
644
645
646
647
        parser_NSVE_no_output = subparsers.add_parser(
                'NSVE_no_output',
                help = 'plain Navier-Stokes vorticity formulation, checkpoints are NOT SAVED')

        parser_NSVEparticles_no_output = subparsers.add_parser(
                'NSVEparticles_no_output',
                help = 'plain Navier-Stokes vorticity formulation, with basic fluid tracers, checkpoints are NOT SAVED')
648

649
650
651
652
        parser_static_field = subparsers.add_parser(
                'static_field',
                help = 'static field with basic fluid tracers')

653
654
655
656
        parser_static_field_with_ghost_collisions = subparsers.add_parser(
                'static_field_with_ghost_collisions',
                help = 'static field with basic fluid tracers and ghost collisions')

Lukas Bentkamp's avatar
Lukas Bentkamp committed
657
658
659
660
        parser_kraichnan_field = subparsers.add_parser(
                'kraichnan_field',
                help = 'Kraichnan field with basic fluid tracers')

661
662
663
        parser_NSVEp2 = subparsers.add_parser(
                'NSVEparticles',
                help = 'plain Navier-Stokes vorticity formulation, with basic fluid tracers')
664

665
666
667
668
        parser_NSVE_Stokes_particles = subparsers.add_parser(
                'NSVE_Stokes_particles',
                help = 'plain Navier-Stokes vorticity formulation, with passive Stokes drag particles')

669
        parser_NSVEp2p = subparsers.add_parser(
670
671
                'NSVEcomplex_particles',
                help = 'plain Navier-Stokes vorticity formulation, with oriented active particles')
672
673
674
        parser_NSVEp_extra = subparsers.add_parser(
                'NSVEp_extra_sampling',
                help = 'plain Navier-Stokes vorticity formulation, with basic fluid tracers, that sample velocity gradient, as well as pressure and its derivatives.')
Cristian Lalescu's avatar
Cristian Lalescu committed
675
        for pp in [
676
677
678
679
680
                'NSVE',
                'NSVE_no_output',
                'NSVEparticles_no_output',
                'NSVEp2',
                'NSVEp2p',
681
                'NSVE_Stokes_particles',
682
683
                'NSVEp_extra',
                'static_field',
684
                'static_field_with_ghost_collisions',
685
                'kraichnan_field']:
Cristian Lalescu's avatar
Cristian Lalescu committed
686
687
688
            eval('self.simulation_parser_arguments({0})'.format('parser_' + pp))
            eval('self.job_parser_arguments({0})'.format('parser_' + pp))
            eval('self.parameters_to_parser_arguments({0})'.format('parser_' + pp))
Cristian Lalescu's avatar
Cristian Lalescu committed
689
690
            eval('self.parameters_to_parser_arguments('
                    'parser_{0},'
Cristian Lalescu's avatar
Cristian Lalescu committed
691
692
                    'self.generate_extra_parameters(\'{0}\'))'.format(pp))
        for pp in [
693
694
695
                'NSVEparticles_no_output',
                'NSVEp2',
                'NSVEp2p',
696
                'NSVE_Stokes_particles',
697
698
699
                'NSVEp_extra',
                'static_field',
                'kraichnan_field']:
Cristian Lalescu's avatar
Cristian Lalescu committed
700
            eval('self.particle_parser_arguments({0})'.format('parser_' + pp))
Cristian Lalescu's avatar
Cristian Lalescu committed
701
702
            eval('self.parameters_to_parser_arguments('
                    'parser_{0},'
Cristian Lalescu's avatar
Cristian Lalescu committed
703
                    'self.NSVEp_extra_parameters)'.format(pp))
704
        return None
705
706
707
708
709
    def generate_extra_parameters(
            self,
            dns_type):
        pars = {}
        if dns_type == 'kraichnan_field':
710
            pars['output_velocity'] = int(1)
711
712
713
            pars['field_random_seed'] = int(1)
            pars['spectrum_slope'] = float(-5./3)
            pars['spectrum_k_cutoff'] = float(16)
714
            pars['spectrum_coefficient'] = float(0.1)
715
        if dns_type == 'NSVE_Stokes_particles':
716
            pars['initial_field_amplitude'] = float(0.0)
717
            pars['initial_particle_vel'] = float(0.05)
718
            pars['drag_coefficient'] = float(0.1)
719
        return pars
720
721
    def prepare_launch(
            self,
722
723
            args = [],
            extra_parameters = None):
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
        """Set up reasonable parameters.

        With the default Lundgren forcing applied in the band [2, 4],
        we can estimate the dissipation, therefore we can estimate
        :math:`k_M \\eta_K` and constrain the viscosity.

        In brief, the command line parameter :math:`k_M \\eta_K` is
        used in the following formula for :math:`\\nu` (:math:`N` is the
        number of real space grid points per coordinate):

        .. math::

            \\nu = \\left(\\frac{2 k_M \\eta_K}{N} \\right)^{4/3}

        With this choice, the average dissipation :math:`\\varepsilon`
        will be close to 0.4, and the integral scale velocity will be
        close to 0.77, yielding the approximate value for the Taylor
        microscale and corresponding Reynolds number:

        .. math::

            \\lambda \\approx 4.75\\left(\\frac{2 k_M \\eta_K}{N} \\right)^{4/6}, \\hskip .5in
            R_\\lambda \\approx 3.7 \\left(\\frac{N}{2 k_M \\eta_K} \\right)^{4/6}

        """
        opt = _code.prepare_launch(self, args = args)
750
751
        self.set_precision(opt.precision)
        self.dns_type = opt.DNS_class
752
        self.name = self.dns_type + '-' + self.fluid_precision + '-v' + TurTLE.__version__
753
        # merge parameters if needed
754
755
756
        if self.dns_type in [
                'NSVEparticles',
                'NSVEcomplex_particles',
757
                'NSVE_Stokes_particles',
758
759
760
761
762
                'NSVEparticles_no_output',
                'NSVEp_extra_sampling',
                'static_field',
                'static_field_with_ghost_collisions',
                'kraichnan_field']:
763
764
            for k in self.NSVEp_extra_parameters.keys():
                self.parameters[k] = self.NSVEp_extra_parameters[k]
765
766
767
768
        if type(extra_parameters) != type(None):
            if self.dns_type in extra_parameters.keys():
                for k in extra_parameters[self.dns_type].keys():
                    self.parameters[k] = extra_parameters[self.dns_type][k]
769
770
771
        additional_parameters = self.generate_extra_parameters(self.dns_type)
        for k in additional_parameters.keys():
            self.parameters[k] = additional_parameters[k]
772
773
774
775
        if ((self.parameters['niter_todo'] % self.parameters['niter_out']) != 0):
            self.parameters['niter_out'] = self.parameters['niter_todo']
        if len(opt.src_work_dir) == 0:
            opt.src_work_dir = os.path.realpath(opt.work_dir)
776
777
778
779
        if type(opt.dkx) == type(None):
            opt.dkx = 2. / opt.Lx
        if type(opt.dky) == type(None):
            opt.dky = 2. / opt.Ly
Cristian Lalescu's avatar
Cristian Lalescu committed
780
        if type(opt.dkz) == type(None):
781
            opt.dkz = 2. / opt.Lz
782
783
784
785
786
787
        if type(opt.nx) == type(None):
            opt.nx = opt.n
        if type(opt.ny) == type(None):
            opt.ny = opt.n
        if type(opt.nz) == type(None):
            opt.nz = opt.n
788
789
790
791
792
793
        if type(opt.fk0) == type(None):
            opt.fk0 = self.parameters['fk0']
        if type(opt.fk1) == type(None):
            opt.fk1 = self.parameters['fk1']
        if type(opt.injection_rate) == type(None):
            opt.injection_rate = self.parameters['injection_rate']
Cristian Lalescu's avatar
Cristian Lalescu committed
794
        if type(opt.dealias_type) == type(None):
795
            opt.dealias_type = self.parameters['dealias_type']
796
797
798
799
800
        if (opt.nx > opt.n or
            opt.ny > opt.n or
            opt.nz > opt.n):
            opt.n = min(opt.nx, opt.ny, opt.nz)
            print("Warning: '-n' parameter changed to minimum of nx, ny, nz. This affects the computation of nu.")
Lukas Bentkamp's avatar
Lukas Bentkamp committed
801
802
803
804
        if self.dns_type in ['kraichnan_field']:
            self.parameters['dt'] = opt.dtfactor * 0.5 / opt.n**2
        else:
            self.parameters['dt'] = (opt.dtfactor / opt.n)
805
        self.parameters['nu'] = (opt.kMeta * 2 / opt.n)**(4./3)
Cristian Lalescu's avatar
Cristian Lalescu committed
806
807
808
809
810
        # check value of kMax
        kM = opt.n * 0.5
        if opt.dealias_type == 1:
            kM *= 0.8
        # tweak forcing/viscosity based on forcint type
Cristian Lalescu's avatar
Cristian Lalescu committed
811
        if opt.forcing_type == 'linear':
812
813
814
815
816
            # custom famplitude for 288 and 576
            if opt.n == 288:
                self.parameters['famplitude'] = 0.45
            elif opt.n == 576:
                self.parameters['famplitude'] = 0.47
Cristian Lalescu's avatar
Cristian Lalescu committed
817
        elif opt.forcing_type == 'fixed_energy_injection_rate':
818
819
            # use the fact that mean dissipation rate is equal to injection rate
            self.parameters['nu'] = (
Cristian Lalescu's avatar
Cristian Lalescu committed
820
                    opt.injection_rate *
821
                    (opt.kMeta / kM)**4)**(1./3)
822
        elif opt.forcing_type == 'fixed_energy':
Cristian Lalescu's avatar
Cristian Lalescu committed
823
824
            kf = 1. / (1./opt.fk0 +
                       1./opt.fk1)
825
826
827
828
            self.parameters['nu'] = (
                    (opt.kMeta / kM)**(4./3) *
                    (np.pi / kf)**(1./3) *
                    (2*self.parameters['energy'] / 3)**0.5)
829
830
831
832
        if type(opt.checkpoints_per_file) == type(None):
            # hardcoded FFTW complex representation size
            field_size = 3*(opt.nx+2)*opt.ny*opt.nz*self.fluid_dtype.itemsize
            checkpoint_size = field_size
833
834
835
            if self.dns_type in [
                    'kraichnan_field',
                    'static_field',
836
                    'static_field_with_ghost_collisions',
837
838
839
840
841
                    'NSVEparticles',
                    'NSVEcomplex_particles',
                    'NSVE_Stokes_particles',
                    'NSVEparticles_no_output',
                    'NSVEp_extra_sampling']:
842
843
844
                rhs_size = self.parameters['tracers0_integration_steps']
                if type(opt.tracers0_integration_steps) != type(None):
                    rhs_size = opt.tracers0_integration_steps
845
846
847
848
                nparticles = opt.nparticles
                if type(nparticles) == type(None):
                    nparticles = self.NSVEp_extra_parameters['nparticles']
                particle_size = (1+rhs_size)*3*nparticles*8
849
850
851
                checkpoint_size += particle_size
            if checkpoint_size < 1e9:
                opt.checkpoints_per_file = int(1e9 / checkpoint_size)
852
853
854
855
856
857
858
859
860
861
862
863
864
        self.pars_from_namespace(opt)
        return opt
    def launch(
            self,
            args = [],
            **kwargs):
        opt = self.prepare_launch(args = args)
        self.launch_jobs(opt = opt, **kwargs)
        return None
    def get_checkpoint_0_fname(self):
        return os.path.join(
                    self.work_dir,
                    self.simname + '_checkpoint_0.h5')
865
    def get_checkpoint_fname(self, iteration = 0):
866
        checkpoint = (iteration // self.parameters['niter_out']) // self.parameters['checkpoints_per_file']
867
868
869
        return os.path.join(
                    self.work_dir,
                    self.simname + '_checkpoint_{0}.h5'.format(checkpoint))
870
871
872
    def generate_tracer_state(
            self,
            rseed = None,
873
874
875
            species = 0,
            integration_steps = None,
            ncomponents = 3):
876
        try:
877
878
879
880
            if type(integration_steps) == type(None):
                integration_steps = self.NSVEp_extra_parameters['tracers0_integration_steps']
            if 'tracers{0}_integration_steps'.format(species) in self.parameters.keys():
                integration_steps = self.parameters['tracers{0}_integration_steps'.format(species)]
881
882
883
            if self.dns_type in [
                    'NSVEcomplex_particles',
                    'NSVE_Stokes_particles'] and species == 0:
884
885
886
                ncomponents = 6
            with h5py.File(self.get_checkpoint_0_fname(), 'a') as data_file:
                nn = self.parameters['nparticles']
887
888
889
890
                if not 'tracers{0}'.format(species) in data_file.keys():
                    data_file.create_group('tracers{0}'.format(species))
                    data_file.create_group('tracers{0}/rhs'.format(species))
                    data_file.create_group('tracers{0}/state'.format(species))
891
892
                data_file['tracers{0}/rhs'.format(species)].create_dataset(
                        '0',
893
                        shape = (integration_steps, nn, ncomponents,),
894
                        dtype = np.float)
895
                dset = data_file['tracers{0}/state'.format(species)].create_dataset(
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
                        '0',
                        shape = (nn, ncomponents,),
                        dtype = np.float)
                if not type(rseed) == type(None):
                    np.random.seed(rseed)
                cc = int(0)
                batch_size = int(1e6)
                def get_random_phases(npoints):
                    return np.random.random(
                                (npoints, 3))*2*np.pi
                def get_random_versors(npoints):
                    bla = np.random.normal(
                            size = (npoints, 3))
                    bla  /= np.sum(bla**2, axis = 1)[:, None]**.5
                    return bla
                while nn > 0:
                    if nn > batch_size:
                        dset[cc*batch_size:(cc+1)*batch_size, :3] = get_random_phases(batch_size)
                        if dset.shape[1] == 6:
915
916
917
                            if self.dns_type == 'NSVE_Stokes_particles':
                                dset[cc*batch_size:(cc+1)*batch_size, 3:] = self.parameters['initial_particle_vel']*get_random_versors(batch_size)
                            else:
918
                                dset[cc*batch_size:(cc+1)*batch_size, 3:] = get_random_versors(batch_size)
919
920
921
922
                        nn -= batch_size
                    else:
                        dset[cc*batch_size:cc*batch_size+nn, :3] = get_random_phases(nn)
                        if dset.shape[1] == 6:
923
                            if self.dns_type == 'NSVE_Stokes_particles':
Tobias Baetge's avatar
Tobias Baetge committed
924
                                dset[cc*batch_size:cc*batch_size+nn, 3:] = self.parameters['initial_particle_vel']*get_random_versors(nn)
925
926
                            else:
                                dset[cc*batch_size:cc*batch_size+nn, 3:] = get_random_versors(nn)
927
928
929
930
                        nn = 0
                    cc += 1
        except Exception as e:
            print(e)
931
        return None
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
    def generate_vector_field(
            self,
            rseed = 7547,
            spectra_slope = 1.,
            amplitude = 1.,
            iteration = 0,
            field_name = 'vorticity',
            write_to_file = False,
            # to switch to constant field, use generate_data_3D_uniform
            # for scalar_generator
            scalar_generator = tools.generate_data_3D):
        """generate vector field.

        The generated field is not divergence free, but it has the proper
        shape.

        :param rseed: seed for random number generator
        :param spectra_slope: spectrum of field will look like k^(-p)
        :param amplitude: all amplitudes are multiplied with this value
        :param iteration: the field is written at this iteration
        :param field_name: the name of the field being generated
        :param write_to_file: should we write the field to file?
        :param scalar_generator: which function to use for generating the
            individual components.
956
957
            Possible values: TurTLE.tools.generate_data_3D,
            TurTLE.tools.generate_data_3D_uniform
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
        :type rseed: int
        :type spectra_slope: float
        :type amplitude: float
        :type iteration: int
        :type field_name: str
        :type write_to_file: bool
        :type scalar_generator: function

        :returns: ``Kdata``, a complex valued 4D ``numpy.array`` that uses the
            transposed FFTW layout.
            Kdata[ky, kz, kx, i] is the amplitude of mode (kx, ky, kz) for
            the i-th component of the field.
            (i.e. x is the fastest index and z the slowest index in the
            real-space representation).
        """
        np.random.seed(rseed)
        Kdata00 = scalar_generator(
975
976
977
                self.parameters['nz'],
                self.parameters['ny'],
                self.parameters['nx'],
978
979
980
                p = spectra_slope,
                amplitude = amplitude).astype(self.ctype)
        Kdata01 = scalar_generator(
981
982
983
                self.parameters['nz'],
                self.parameters['ny'],
                self.parameters['nx'],
984
985
986
                p = spectra_slope,
                amplitude = amplitude).astype(self.ctype)
        Kdata02 = scalar_generator(
987
988
989
                self.parameters['nz'],
                self.parameters['ny'],
                self.parameters['nx'],
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
                p = spectra_slope,
                amplitude = amplitude).astype(self.ctype)
        Kdata0 = np.zeros(
                Kdata00.shape + (3,),
                Kdata00.dtype)
        Kdata0[..., 0] = Kdata00
        Kdata0[..., 1] = Kdata01
        Kdata0[..., 2] = Kdata02
        Kdata1 = tools.padd_with_zeros(
                Kdata0,
                self.parameters['nz'],
                self.parameters['ny'],
                self.parameters['nx'])
        if write_to_file:
            Kdata1.tofile(
                    os.path.join(self.work_dir,
                                 self.simname + "_c{0}_i{1:0>5x}".format(field_name, iteration)))
        return Kdata1
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
    def copy_complex_field(
            self,
            src_file_name,
            src_dset_name,
            dst_file,
            dst_dset_name,
            make_link = True):
        # I define a min_shape thingie, but for now I only trust this method for
        # the case of increasing/decreasing by the same factor in all directions.
        # in principle we could write something more generic, but i'm not sure
        # how complicated that would be
1019
1020
        dst_shape = (self.parameters['ny'],
                     self.parameters['nz'],
1021
1022
1023
1024
                     (self.parameters['nx']+2) // 2,
                     3)
        src_file = h5py.File(src_file_name, 'r')
        if (src_file[src_dset_name].shape == dst_shape):
1025
1026
1027
            dst_file[dst_dset_name] = h5py.ExternalLink(
                    src_file_name,
                    src_dset_name)
1028
1029
1030
1031
1032
        else:
            min_shape = (min(dst_shape[0], src_file[src_dset_name].shape[0]),
                         min(dst_shape[1], src_file[src_dset_name].shape[1]),
                         min(dst_shape[2], src_file[src_dset_name].shape[2]),
                         3)
1033
            src_shape = src_file[src_dset_name].shape
1034
1035
1036
            dst_file.create_dataset(
                    dst_dset_name,
                    shape = dst_shape,
1037
1038
                    dtype = np.dtype(self.ctype),
                    fillvalue = complex(0))
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
            for kz in range(min_shape[0]//2):
                dst_file[dst_dset_name][kz,:min_shape[1]//2, :min_shape[2]] = \
                        src_file[src_dset_name][kz, :min_shape[1]//2, :min_shape[2]]
                dst_file[dst_dset_name][kz,
                                        dst_shape[1] - min_shape[1]//2+1:,
                                        :min_shape[2]] = \
                        src_file[src_dset_name][kz,
                                                src_shape[1] - min_shape[1]//2+1,
                                                :min_shape[2]]
                if kz > 0:
                    dst_file[dst_dset_name][-kz,:min_shape[1]//2, :min_shape[2]] = \
                            src_file[src_dset_name][-kz, :min_shape[1]//2, :min_shape[2]]
                    dst_file[dst_dset_name][-kz,
                                            dst_shape[1] - min_shape[1]//2+1:,
                                            :min_shape[2]] = \
                            src_file[src_dset_name][-kz,
                                                    src_shape[1] - min_shape[1]//2+1,
                                                    :min_shape[2]]
1057
        return None
1058
1059
1060
    def generate_particle_data(
            self,
            opt = None):
1061
1062
1063
1064
1065
        if (self.parameters['nparticles'] > 0):
            if (self.parameters['cpp_random_particles'] == 0):
                self.generate_tracer_state(
                        species = 0,
                        rseed = opt.particle_rand_seed)
1066
1067
            if not os.path.exists(self.get_particle_file_name()):
                with h5py.File(self.get_particle_file_name(), 'w') as particle_file:
Cristian Lalescu's avatar
Cristian Lalescu committed
1068
                    particle_file.create_group('tracers0/position')
1069
1070
                    particle_file.create_group('tracers0/velocity')
                    particle_file.create_group('tracers0/acceleration')
1071
                    if self.dns_type in ['NSVEcomplex_particles']:
1072
                        particle_file.create_group('tracers0/orientation')
1073
                        particle_file.create_group('tracers0/velocity_gradient')
1074
1075
                    if self.dns_type in ['NSVE_Stokes_particles']:
                        particle_file.create_group('tracers0/momentum')
1076
1077
1078
1079
1080
                    if self.dns_type in ['NSVEp_extra_sampling']:
                        particle_file.create_group('tracers0/velocity_gradient')
                        particle_file.create_group('tracers0/pressure')
                        particle_file.create_group('tracers0/pressure_gradient')
                        particle_file.create_group('tracers0/pressure_Hessian')
1081
        return None
Cristian Lalescu's avatar
Cristian Lalescu committed
1082
    def generate_initial_condition(
1083
            self,
Cristian Lalescu's avatar
Cristian Lalescu committed
1084
1085
1086
1087
            opt = None):
        # take care of fields' initial condition
        # first, check if initial field exists
        need_field = False
1088
        if self.check_current_vorticity_exists:
Cristian Lalescu's avatar
Cristian Lalescu committed
1089
            need_field = True
1090
        if self.dns_type in [
1091
1092
                'NSVE',
                'NSVE_no_output',
1093
1094
1095
                'static_field',
                'NSVEparticles',
                'NSVEcomplex_particles',
1096
                'NSVE_Stokes_particles',
1097
1098
1099
                'NSVEparticles_no_output',
                'NSVEp_extra_sampling']:
            if not os.path.exists(self.get_checkpoint_0_fname()):
1100
                need_field = True
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
            else:
                f = h5py.File(self.get_checkpoint_0_fname(), 'r')
                try:
                    dset = f['vorticity/complex/0']
                    need_field = (dset.shape == (self.parameters['ny'],
                                                 self.parameters['nz'],
                                                 self.parameters['nx']//2+1,
                                                 3))
                except:
                    need_field = True
                f.close()
Cristian Lalescu's avatar
Cristian Lalescu committed
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
        if need_field:
            f = h5py.File(self.get_checkpoint_0_fname(), 'a')
            if len(opt.src_simname) > 0:
                source_cp = 0
                src_file = 'not_a_file'
                while True:
                    src_file = os.path.join(
                        os.path.realpath(opt.src_work_dir),
                        opt.src_simname + '_checkpoint_{0}.h5'.format(source_cp))
                    f0 = h5py.File(src_file, 'r')
                    if '{0}'.format(opt.src_iteration) in f0['vorticity/complex'].keys():
                        f0.close()
                        break
                    source_cp += 1
                self.copy_complex_field(
                        src_file,
                        'vorticity/complex/{0}'.format(opt.src_iteration),
                        f,
                        'vorticity/complex/{0}'.format(0))
1131
            else:
1132
1133
                if self.dns_type == 'NSVE_Stokes_particles':
                  data = self.generate_vector_field(
Cristian Lalescu's avatar
Cristian Lalescu committed
1134
1135
                       write_to_file = False,
                       spectra_slope = 2.0,
1136
1137
1138
                       amplitude = self.parameters['initial_field_amplitude'])
                else:
                    data = self.generate_vector_field(
Cristian Lalescu's avatar
Cristian Lalescu committed
1139
1140
                       write_to_file = False,
                       spectra_slope = 2.0,
1141
                       amplitude = 0.05)
Cristian Lalescu's avatar
Cristian Lalescu committed
1142
1143
                f['vorticity/complex/{0}'.format(0)] = data
            f.close()
1144
1145
1146
1147
1148
        if self.dns_type == 'kraichnan_field':
            if not os.path.exists(self.get_checkpoint_0_fname()):
                f = h5py.File(self.get_checkpoint_0_fname(), 'a')
                f.create_group('velocity/real')
                f.close()
Cristian Lalescu's avatar
Cristian Lalescu committed
1149
        # now take care of particles' initial condition
1150
1151
1152
        if self.dns_type in [
                'kraichnan_field',
                'static_field',
1153
                'static_field_with_ghost_collisions',
1154
1155
                'NSVEparticles',
                'NSVEcomplex_particles',
1156
                'NSVE_Stokes_particles',
1157
1158
                'NSVEparticles_no_output',
                'NSVEp_extra_sampling']:
Cristian Lalescu's avatar
Cristian Lalescu committed
1159
1160
1161
1162
1163
1164
            self.generate_particle_data(opt = opt)
        return None
    def launch_jobs(
            self,
            opt = None):
        if not os.path.exists(self.get_data_file_name()):
1165
            self.generate_initial_condition(opt = opt)
Cristian Lalescu's avatar
Cristian Lalescu committed
1166
            self.write_par()
1167
1168
1169
        if (('test' in self.dns_type) or
            (self.dns_type in ['kraichnan_field'])):
            self.check_current_vorticity_exists = False
1170
1171
1172
1173
1174
1175
        self.run(
                nb_processes = opt.nb_processes,
                nb_threads_per_process = opt.nb_threads_per_process,
                njobs = opt.njobs,
                hours = opt.minutes // 60,
                minutes = opt.minutes % 60,
1176
1177
                no_submit = opt.no_submit,
                no_debug = opt.no_debug)
1178
        return None