NavierStokes.py 50.4 KB
Newer Older
Chichi Lalescu's avatar
Chichi Lalescu committed
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
#######################################################################
#                                                                     #
#  Copyright 2015 Max Planck Institute                                #
#                 for Dynamics and Self-Organization                  #
#                                                                     #
#  This file is part of bfps.                                         #
#                                                                     #
#  bfps is free software: you can redistribute it and/or modify       #
#  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.                             #
#                                                                     #
#  bfps is distributed in the hope that it will be useful,            #
#  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  #
#  along with bfps.  If not, see <http://www.gnu.org/licenses/>       #
#                                                                     #
# Contact: Cristian.Lalescu@ds.mpg.de                                 #
#                                                                     #
#######################################################################


Cristian Lalescu's avatar
Cristian Lalescu committed
26

27
28
29
import os
import numpy as np
import h5py
30
import argparse
31

32
import bfps
33
from ._code import _code
34
from ._fluid_base import _fluid_particle_base
Cristian Lalescu's avatar
Cristian Lalescu committed
35

36
class NavierStokes(_fluid_particle_base):
37
38
39
40
41
    """Objects of this class can be used to generate production DNS codes.
    Any functionality that users require should be available through this class,
    in the sense that they can implement whatever they need by simply inheriting
    this class.
    """
Cristian Lalescu's avatar
Cristian Lalescu committed
42
43
    def __init__(
            self,
44
            name = 'NavierStokes-v' + bfps.__version__,
Cristian Lalescu's avatar
Cristian Lalescu committed
45
            work_dir = './',
46
            simname = 'test',
47
            fluid_precision = 'single',
Chichi Lalescu's avatar
Chichi Lalescu committed
48
            fftw_plan_rigor = 'FFTW_MEASURE',
49
            frozen_fields = False,
Cristian Lalescu's avatar
Cristian Lalescu committed
50
51
52
53
54
            use_fftw_wisdom = True,
            QR_stats_on = False):
        self.QR_stats_on = QR_stats_on
        self.frozen_fields = frozen_fields
        self.fftw_plan_rigor = fftw_plan_rigor
55
56
        _fluid_particle_base.__init__(
                self,
57
                name = name + '-' + fluid_precision,
58
                work_dir = work_dir,
59
                simname = simname,
60
61
                dtype = fluid_precision,
                use_fftw_wisdom = use_fftw_wisdom)
62
63
64
        self.parameters['nu'] = 0.1
        self.parameters['fmode'] = 1
        self.parameters['famplitude'] = 0.5
65
66
        self.parameters['fk0'] = 2.0
        self.parameters['fk1'] = 4.0
67
68
69
70
71
72
73
74
        self.parameters['forcing_type'] = 'linear'
        self.parameters['histogram_bins'] = 256
        self.parameters['max_velocity_estimate'] = 1.0
        self.parameters['max_vorticity_estimate'] = 1.0
        self.parameters['QR2D_histogram_bins'] = 64
        self.parameters['max_trS2_estimate'] = 1.0
        self.parameters['max_Q_estimate'] = 1.0
        self.parameters['max_R_estimate'] = 1.0
75
        self.file_datasets_grow = """
76
                //begincpp
77
                std::string temp_string;
78
                hsize_t dims[4];
79
80
                hid_t group;
                hid_t Cspace, Cdset;
81
                int ndims;
82
                // store kspace information
Cristian Lalescu's avatar
Cristian Lalescu committed
83
                Cdset = H5Dopen(stat_file, "/kspace/kshell", H5P_DEFAULT);
Cristian Lalescu's avatar
Cristian Lalescu committed
84
85
                Cspace = H5Dget_space(Cdset);
                H5Sget_simple_extent_dims(Cspace, dims, NULL);
Cristian Lalescu's avatar
Cristian Lalescu committed
86
                H5Sclose(Cspace);
87
88
                if (fs->nshells != dims[0])
                {
89
90
91
                    DEBUG_MSG(
                        "ERROR: computed nshells %d not equal to data file nshells %d\\n",
                        fs->nshells, dims[0]);
92
93
                    file_problems++;
                }
Cristian Lalescu's avatar
Cristian Lalescu committed
94
95
                H5Dwrite(Cdset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, fs->kshell);
                H5Dclose(Cdset);
Cristian Lalescu's avatar
Cristian Lalescu committed
96
                Cdset = H5Dopen(stat_file, "/kspace/nshell", H5P_DEFAULT);
Cristian Lalescu's avatar
Cristian Lalescu committed
97
98
                H5Dwrite(Cdset, H5T_NATIVE_INT64, H5S_ALL, H5S_ALL, H5P_DEFAULT, fs->nshell);
                H5Dclose(Cdset);
Cristian Lalescu's avatar
Cristian Lalescu committed
99
                Cdset = H5Dopen(stat_file, "/kspace/kM", H5P_DEFAULT);
Chichi Lalescu's avatar
Chichi Lalescu committed
100
                H5Dwrite(Cdset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &fs->kMspec);
Cristian Lalescu's avatar
Cristian Lalescu committed
101
                H5Dclose(Cdset);
Cristian Lalescu's avatar
Cristian Lalescu committed
102
                Cdset = H5Dopen(stat_file, "/kspace/dk", H5P_DEFAULT);
Cristian Lalescu's avatar
Cristian Lalescu committed
103
104
                H5Dwrite(Cdset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &fs->dk);
                H5Dclose(Cdset);
105
106
107
                group = H5Gopen(stat_file, "/statistics", H5P_DEFAULT);
                H5Ovisit(group, H5_INDEX_NAME, H5_ITER_NATIVE, grow_statistics_dataset, NULL);
                H5Gclose(group);
108
109
                //endcpp
                """
110
111
        self.style = {}
        self.statistics = {}
Chichi Lalescu's avatar
Chichi Lalescu committed
112
        self.fluid_output = 'fs->write(\'v\', \'c\');\n'
113
        return None
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
    def create_stat_output(
            self,
            dset_name,
            data_buffer,
            data_type = 'H5T_NATIVE_DOUBLE',
            size_setup = None,
            close_spaces = True):
        new_stat_output_txt = 'Cdset = H5Dopen(stat_file, "{0}", H5P_DEFAULT);\n'.format(dset_name)
        if not type(size_setup) == type(None):
            new_stat_output_txt += (
                    size_setup +
                    'wspace = H5Dget_space(Cdset);\n' +
                    'ndims = H5Sget_simple_extent_dims(wspace, dims, NULL);\n' +
                    'mspace = H5Screate_simple(ndims, count, NULL);\n' +
                    'H5Sselect_hyperslab(wspace, H5S_SELECT_SET, offset, NULL, count, NULL);\n')
        new_stat_output_txt += ('H5Dwrite(Cdset, {0}, mspace, wspace, H5P_DEFAULT, {1});\n' +
                                'H5Dclose(Cdset);\n').format(data_type, data_buffer)
        if close_spaces:
            new_stat_output_txt += ('H5Sclose(mspace);\n' +
                                    'H5Sclose(wspace);\n')
        return new_stat_output_txt
135
136
137
    def write_fluid_stats(self):
        self.fluid_includes += '#include <cmath>\n'
        self.fluid_includes += '#include "fftw_tools.hpp"\n'
Cristian Lalescu's avatar
Cristian Lalescu committed
138
139
        self.stat_src += """
                //begincpp
140
141
142
143
144
145
146
147
148
149
                double *velocity_moments  = new double[10*4];
                double *vorticity_moments = new double[10*4];
                ptrdiff_t *hist_velocity  = new ptrdiff_t[histogram_bins*4];
                ptrdiff_t *hist_vorticity = new ptrdiff_t[histogram_bins*4];
                double max_estimates[4];
                fs->compute_velocity(fs->cvorticity);
                double *spec_velocity  = new double[fs->nshells*9];
                double *spec_vorticity = new double[fs->nshells*9];
                fs->cospectrum(fs->cvelocity, fs->cvelocity, spec_velocity);
                fs->cospectrum(fs->cvorticity, fs->cvorticity, spec_vorticity);
Cristian Lalescu's avatar
Cristian Lalescu committed
150
151
                //endcpp
                """
Cristian Lalescu's avatar
Cristian Lalescu committed
152
153
154
        if self.QR_stats_on:
            self.stat_src += """
                //begincpp
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
                double *trS2_Q_R_moments  = new double[10*3];
                double *gradu_moments     = new double[10*9];
                ptrdiff_t *hist_trS2_Q_R  = new ptrdiff_t[histogram_bins*3];
                ptrdiff_t *hist_gradu     = new ptrdiff_t[histogram_bins*9];
                ptrdiff_t *hist_QR2D      = new ptrdiff_t[QR2D_histogram_bins*QR2D_histogram_bins];
                double trS2QR_max_estimates[3];
                double gradu_max_estimates[9];
                trS2QR_max_estimates[0] = max_trS2_estimate;
                trS2QR_max_estimates[1] = max_Q_estimate;
                trS2QR_max_estimates[2] = max_R_estimate;
                std::fill_n(gradu_max_estimates, 9, sqrt(3*max_trS2_estimate));
                fs->compute_gradient_statistics(
                    fs->cvelocity,
                    gradu_moments,
                    trS2_Q_R_moments,
                    hist_gradu,
                    hist_trS2_Q_R,
                    hist_QR2D,
                    trS2QR_max_estimates,
                    gradu_max_estimates,
                    histogram_bins,
                    QR2D_histogram_bins);
                //endcpp
                """
Cristian Lalescu's avatar
Cristian Lalescu committed
179
180
        self.stat_src += """
                //begincpp
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
                fs->ift_velocity();
                max_estimates[0] = max_velocity_estimate/sqrt(3);
                max_estimates[1] = max_estimates[0];
                max_estimates[2] = max_estimates[0];
                max_estimates[3] = max_velocity_estimate;
                fs->compute_rspace_stats4(fs->rvelocity,
                                         velocity_moments,
                                         hist_velocity,
                                         max_estimates,
                                         histogram_bins);
                fs->ift_vorticity();
                max_estimates[0] = max_vorticity_estimate/sqrt(3);
                max_estimates[1] = max_estimates[0];
                max_estimates[2] = max_estimates[0];
                max_estimates[3] = max_vorticity_estimate;
                fs->compute_rspace_stats4(fs->rvorticity,
                                         vorticity_moments,
                                         hist_vorticity,
                                         max_estimates,
                                         histogram_bins);
                if (fs->cd->myrank == 0)
                {{
                    hid_t Cdset, wspace, mspace;
                    int ndims;
                    hsize_t count[4], offset[4], dims[4];
                    offset[0] = fs->iteration/niter_stat;
                    offset[1] = 0;
                    offset[2] = 0;
                    offset[3] = 0;
Cristian Lalescu's avatar
Cristian Lalescu committed
210
                //endcpp
Cristian Lalescu's avatar
Cristian Lalescu committed
211
212
213
214
215
                """.format(self.C_dtype)
        if self.dtype == np.float32:
            field_H5T = 'H5T_NATIVE_FLOAT'
        elif self.dtype == np.float64:
            field_H5T = 'H5T_NATIVE_DOUBLE'
216
        self.stat_src += self.create_stat_output(
217
218
219
220
221
222
223
224
225
                '/statistics/xlines/velocity',
                'fs->rvelocity',
                data_type = field_H5T,
                size_setup = """
                    count[0] = 1;
                    count[1] = nx;
                    count[2] = 3;
                    """,
                close_spaces = False)
226
        self.stat_src += self.create_stat_output(
227
228
229
                '/statistics/xlines/vorticity',
                'fs->rvorticity',
                data_type = field_H5T)
230
        self.stat_src += self.create_stat_output(
231
232
233
234
235
236
237
238
                '/statistics/moments/velocity',
                'velocity_moments',
                size_setup = """
                    count[0] = 1;
                    count[1] = 10;
                    count[2] = 4;
                    """,
                close_spaces = False)
239
        self.stat_src += self.create_stat_output(
240
241
                '/statistics/moments/vorticity',
                'vorticity_moments')
242
        self.stat_src += self.create_stat_output(
243
244
245
246
247
248
249
250
251
                '/statistics/spectra/velocity_velocity',
                'spec_velocity',
                size_setup = """
                    count[0] = 1;
                    count[1] = fs->nshells;
                    count[2] = 3;
                    count[3] = 3;
                    """,
                close_spaces = False)
252
        self.stat_src += self.create_stat_output(
253
254
                '/statistics/spectra/vorticity_vorticity',
                'spec_vorticity')
255
        self.stat_src += self.create_stat_output(
256
257
258
259
260
261
262
263
264
                '/statistics/histograms/velocity',
                'hist_velocity',
                data_type = 'H5T_NATIVE_INT64',
                size_setup = """
                    count[0] = 1;
                    count[1] = histogram_bins;
                    count[2] = 4;
                    """,
                close_spaces = False)
265
        self.stat_src += self.create_stat_output(
266
267
268
                '/statistics/histograms/vorticity',
                'hist_vorticity',
                data_type = 'H5T_NATIVE_INT64')
Cristian Lalescu's avatar
Cristian Lalescu committed
269
270
271
272
273
274
275
276
277
        if self.QR_stats_on:
            self.stat_src += self.create_stat_output(
                    '/statistics/moments/trS2_Q_R',
                    'trS2_Q_R_moments',
                    size_setup ="""
                        count[0] = 1;
                        count[1] = 10;
                        count[2] = 3;
                        """)
278
279
280
281
282
283
284
285
286
            self.stat_src += self.create_stat_output(
                    '/statistics/moments/velocity_gradient',
                    'gradu_moments',
                    size_setup ="""
                        count[0] = 1;
                        count[1] = 10;
                        count[2] = 3;
                        count[3] = 3;
                        """)
Cristian Lalescu's avatar
Cristian Lalescu committed
287
288
289
290
291
292
293
294
295
            self.stat_src += self.create_stat_output(
                    '/statistics/histograms/trS2_Q_R',
                    'hist_trS2_Q_R',
                    data_type = 'H5T_NATIVE_INT64',
                    size_setup = """
                        count[0] = 1;
                        count[1] = histogram_bins;
                        count[2] = 3;
                        """)
296
297
298
299
300
301
302
303
304
305
            self.stat_src += self.create_stat_output(
                    '/statistics/histograms/velocity_gradient',
                    'hist_gradu',
                    data_type = 'H5T_NATIVE_INT64',
                    size_setup = """
                        count[0] = 1;
                        count[1] = histogram_bins;
                        count[2] = 3;
                        count[3] = 3;
                        """)
Cristian Lalescu's avatar
Cristian Lalescu committed
306
307
308
309
310
311
312
313
314
            self.stat_src += self.create_stat_output(
                    '/statistics/histograms/QR2D',
                    'hist_QR2D',
                    data_type = 'H5T_NATIVE_INT64',
                    size_setup = """
                        count[0] = 1;
                        count[1] = QR2D_histogram_bins;
                        count[2] = QR2D_histogram_bins;
                        """)
Cristian Lalescu's avatar
Cristian Lalescu committed
315
316
        self.stat_src += """
                //begincpp
317
318
319
320
321
322
323
                }
                delete[] spec_velocity;
                delete[] spec_vorticity;
                delete[] velocity_moments;
                delete[] vorticity_moments;
                delete[] hist_velocity;
                delete[] hist_vorticity;
Cristian Lalescu's avatar
Cristian Lalescu committed
324
325
326
327
328
                //endcpp
                """
        if self.QR_stats_on:
            self.stat_src += """
                //begincpp
329
330
331
332
333
                delete[] trS2_Q_R_moments;
                delete[] gradu_moments;
                delete[] hist_trS2_Q_R;
                delete[] hist_gradu;
                delete[] hist_QR2D;
Cristian Lalescu's avatar
Cristian Lalescu committed
334
335
                //endcpp
                """
336
337
338
        return None
    def fill_up_fluid_code(self):
        self.fluid_includes += '#include <cstring>\n'
Cristian Lalescu's avatar
Cristian Lalescu committed
339
340
341
        self.fluid_variables += ('fluid_solver<{0}> *fs;\n'.format(self.C_dtype) +
                                 'int *kindices;\n' +
                                 'hid_t H5T_field_complex;\n')
Chichi Lalescu's avatar
Chichi Lalescu committed
342
343
344
345
346
347
        self.fluid_definitions += """
                    typedef struct {{
                        {0} re;
                        {0} im;
                    }} tmp_complex_type;
                    """.format(self.C_dtype)
348
        self.write_fluid_stats()
Cristian Lalescu's avatar
Cristian Lalescu committed
349
350
351
352
        if self.dtype == np.float32:
            field_H5T = 'H5T_NATIVE_FLOAT'
        elif self.dtype == np.float64:
            field_H5T = 'H5T_NATIVE_DOUBLE'
353
        self.fluid_start += """
Cristian Lalescu's avatar
Cristian Lalescu committed
354
355
                //begincpp
                char fname[512];
356
                fs = new fluid_solver<{0}>(
Cristian Lalescu's avatar
Cristian Lalescu committed
357
358
                        simname,
                        nx, ny, nz,
359
                        dkx, dky, dkz,
360
361
                        dealias_type,
                        {1});
Cristian Lalescu's avatar
Cristian Lalescu committed
362
363
364
                fs->nu = nu;
                fs->fmode = fmode;
                fs->famplitude = famplitude;
Cristian Lalescu's avatar
Cristian Lalescu committed
365
366
367
                fs->fk0 = fk0;
                fs->fk1 = fk1;
                strncpy(fs->forcing_type, forcing_type, 128);
Chichi Lalescu's avatar
Chichi Lalescu committed
368
                fs->iteration = iteration;
Cristian Lalescu's avatar
Cristian Lalescu committed
369
                fs->read('v', 'c');
Cristian Lalescu's avatar
Cristian Lalescu committed
370
371
372
373
374
375
                if (fs->cd->myrank == 0)
                {{
                    H5T_field_complex = H5Tcreate(H5T_COMPOUND, sizeof(tmp_complex_type));
                    H5Tinsert(H5T_field_complex, "r", HOFFSET(tmp_complex_type, re), {2});
                    H5Tinsert(H5T_field_complex, "i", HOFFSET(tmp_complex_type, im), {2});
                }}
Cristian Lalescu's avatar
Cristian Lalescu committed
376
                //endcpp
Cristian Lalescu's avatar
Cristian Lalescu committed
377
                """.format(self.C_dtype, self.fftw_plan_rigor, field_H5T)
Chichi Lalescu's avatar
Chichi Lalescu committed
378
379
380
381
382
383
        if not self.frozen_fields:
            self.fluid_loop = 'fs->step(dt);\n'
        else:
            self.fluid_loop = ''
        self.fluid_loop += ('if (fs->iteration % niter_out == 0)\n{\n' +
                            self.fluid_output + '\n}\n')
Cristian Lalescu's avatar
Cristian Lalescu committed
384
385
        self.fluid_end = ('if (fs->iteration % niter_out != 0)\n{\n' +
                          self.fluid_output + '\n}\n' +
Cristian Lalescu's avatar
Cristian Lalescu committed
386
387
388
389
                          'if (fs->cd->myrank == 0)\n' +
                          '{\n' +
                          'delete[] kindices;\n' +
                          'H5Tclose(H5T_field_complex);\n' +
Chichi Lalescu's avatar
Chichi Lalescu committed
390
391
                          '}\n' +
                          'delete fs;\n')
392
        return None
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
    def add_3D_rFFTW_field(
            self,
            name = 'rFFTW_acc'):
        if self.dtype == np.float32:
            FFTW = 'fftwf'
        elif self.dtype == np.float64:
            FFTW = 'fftw'
        self.fluid_variables += '{0} *{1};\n'.format(self.C_dtype, name)
        self.fluid_start += '{0} = {1}_alloc_real(2*fs->cd->local_size);\n'.format(name, FFTW)
        self.fluid_end   += '{0}_free({1});\n'.format(FFTW, name)
        return None
    def add_interpolator(
            self,
            interp_type = 'spline',
            neighbours = 1,
            smoothness = 1,
            name = 'field_interpolator',
            field_name = 'fs->rvelocity'):
        self.fluid_includes += '#include "rFFTW_interpolator.hpp"\n'
412
413
        self.fluid_variables += 'rFFTW_interpolator <{0}, {1}> *{2};\n'.format(
                self.C_dtype, neighbours, name)
414
415
416
417
418
419
420
        self.parameters[name + '_type'] = interp_type
        self.parameters[name + '_neighbours'] = neighbours
        if interp_type == 'spline':
            self.parameters[name + '_smoothness'] = smoothness
            beta_name = 'beta_n{0}_m{1}'.format(neighbours, smoothness)
        elif interp_type == 'Lagrange':
            beta_name = 'beta_Lagrange_n{0}'.format(neighbours)
Cristian Lalescu's avatar
Cristian Lalescu committed
421
        self.fluid_start += '{0} = new rFFTW_interpolator<{1}, {2}>(fs, {3}, {4});\n'.format(
422
423
424
                name,
                self.C_dtype,
                neighbours,
Cristian Lalescu's avatar
Cristian Lalescu committed
425
426
                beta_name,
                field_name)
427
        self.fluid_end += 'delete {0};\n'.format(name)
428
        return None
429
430
    def add_particles(
            self,
431
            integration_steps = 2,
Cristian Lalescu's avatar
Cristian Lalescu committed
432
            kcut = None,
433
            interpolator = 'field_interpolator',
434
            frozen_particles = False,
Cristian Lalescu's avatar
Cristian Lalescu committed
435
            acc_name = None):
436
437
438
439
440
441
442
443
444
        """Adds code for tracking a series of particle species, each
        consisting of `nparticles` particles.

        :type integration_steps: int, list of int
        :type kcut: None (default), str, list of str
        :type interpolator: str, list of str
        :type frozen_particles: bool
        :type acc_name: str

445
446
447
        .. warning:: if not None, kcut must be a list of decreasing
                     wavenumbers, since filtering is done sequentially
                     on the same complex FFTW field.
448
        """
Cristian Lalescu's avatar
Cristian Lalescu committed
449
450
451
452
453
        if self.dtype == np.float32:
            FFTW = 'fftwf'
        elif self.dtype == np.float64:
            FFTW = 'fftw'
        s0 = self.particle_species
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
        if type(integration_steps) == int:
            integration_steps = [integration_steps]
        if type(kcut) == str:
            kcut = [kcut]
        if type(interpolator) == str:
            interpolator = [interpolator]
        nspecies = max(len(integration_steps), len(interpolator))
        if type(kcut) == list:
            nspecies = max(nspecies, len(kcut))
        if len(integration_steps) == 1:
            integration_steps = [integration_steps[0] for s in range(nspecies)]
        if len(interpolator) == 1:
            interpolator = [interpolator[0] for s in range(nspecies)]
        if type(kcut) == list:
            if len(kcut) == 1:
                kcut = [kcut[0] for s in range(nspecies)]
        assert(len(integration_steps) == nspecies)
        assert(len(interpolator) == nspecies)
        if type(kcut) == list:
            assert(len(kcut) == nspecies)
        for s in range(nspecies):
Cristian Lalescu's avatar
Cristian Lalescu committed
475
            neighbours = self.parameters[interpolator[s] + '_neighbours']
476
477
            if type(kcut) == list:
                self.parameters['tracers{0}_kcut'.format(s0 + s)] = kcut[s]
Cristian Lalescu's avatar
Cristian Lalescu committed
478
            self.parameters['tracers{0}_interpolator'.format(s0 + s)] = interpolator[s]
479
            self.parameters['tracers{0}_acc_on'.format(s0 + s)] = int(not type(acc_name) == type(None))
Cristian Lalescu's avatar
Cristian Lalescu committed
480
481
            self.parameters['tracers{0}_integration_steps'.format(s0 + s)] = integration_steps[s]
            self.file_datasets_grow += """
482
483
                        //begincpp
                        temp_string = (std::string("/particles/") +
484
485
486
487
                                       std::string(ps{0}->name));
                        group = H5Gopen(stat_file, temp_string.c_str(), H5P_DEFAULT);
                        grow_particle_datasets(group, temp_string.c_str(), NULL, NULL);
                        H5Gclose(group);
488
                        //endcpp
Cristian Lalescu's avatar
Cristian Lalescu committed
489
490
491
492
493
494
495
496
                        """.format(s0 + s)

        #### code that outputs statistics
        output_vel_acc = '{\n'
        # array for putting sampled velocity in
        # must compute velocity, just in case it was messed up by some
        # other particle species before the stats
        output_vel_acc += ('double *velocity = new double[3*nparticles];\n' +
497
498
499
                           'fs->compute_velocity(fs->cvorticity);\n')
        if not type(kcut) == list:
            output_vel_acc += 'fs->ift_velocity();\n'
Cristian Lalescu's avatar
Cristian Lalescu committed
500
501
502
503
504
        if not type(acc_name) == type(None):
            # array for putting sampled acceleration in
            # must compute acceleration
            output_vel_acc += 'double *acceleration = new double[3*nparticles];\n'
            output_vel_acc += 'fs->compute_Lagrangian_acceleration({0});\n'.format(acc_name)
505
        for s in range(nspecies):
506
507
508
            if type(kcut) == list:
                output_vel_acc += 'fs->low_pass_Fourier(fs->cvelocity, 3, {0});\n'.format(kcut[s])
                output_vel_acc += 'fs->ift_velocity();\n'
Cristian Lalescu's avatar
Cristian Lalescu committed
509
510
511
512
513
514
515
516
517
518
519
            output_vel_acc += """
                {0}->field = fs->rvelocity;
                ps{1}->sample_vec_field({0}, velocity);
                """.format(interpolator[s], s0 + s)
            if not type(acc_name) == type(None):
                output_vel_acc += """
                    {0}->field = {1};
                    ps{2}->sample_vec_field({0}, acceleration);
                    """.format(interpolator[s], acc_name, s0 + s)
            output_vel_acc += """
                if (myrank == 0)
520
                {{
Cristian Lalescu's avatar
Cristian Lalescu committed
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
                //VELOCITY begin
                std::string temp_string = (std::string("/particles/") +
                                           std::string(ps{0}->name) +
                                           std::string("/velocity"));
                hid_t Cdset = H5Dopen(stat_file, temp_string.c_str(), H5P_DEFAULT);
                hid_t mspace, wspace;
                int ndims;
                hsize_t count[3], offset[3];
                wspace = H5Dget_space(Cdset);
                ndims = H5Sget_simple_extent_dims(wspace, count, NULL);
                count[0] = 1;
                offset[0] = ps{0}->iteration / ps{0}->traj_skip;
                offset[1] = 0;
                offset[2] = 0;
                mspace = H5Screate_simple(ndims, count, NULL);
                H5Sselect_hyperslab(wspace, H5S_SELECT_SET, offset, NULL, count, NULL);
                H5Dwrite(Cdset, H5T_NATIVE_DOUBLE, mspace, wspace, H5P_DEFAULT, velocity);
                H5Dclose(Cdset);
539
                //VELOCITY end\n""".format(s0 + s)
Cristian Lalescu's avatar
Cristian Lalescu committed
540
541
542
543
544
545
546
547
548
549
550
            if not type(acc_name) == type(None):
                output_vel_acc += """
                    //ACCELERATION begin
                    temp_string = (std::string("/particles/") +
                                   std::string(ps{0}->name) +
                                   std::string("/acceleration"));
                    Cdset = H5Dopen(stat_file, temp_string.c_str(), H5P_DEFAULT);
                    H5Dwrite(Cdset, H5T_NATIVE_DOUBLE, mspace, wspace, H5P_DEFAULT, acceleration);
                    H5Sclose(mspace);
                    H5Sclose(wspace);
                    H5Dclose(Cdset);
551
                    //ACCELERATION end\n""".format(s0 + s)
Cristian Lalescu's avatar
Cristian Lalescu committed
552
553
554
555
556
557
558
            output_vel_acc += '}\n'
        output_vel_acc += 'delete[] velocity;\n'
        if not type(acc_name) == type(None):
            output_vel_acc += 'delete[] acceleration;\n'
        output_vel_acc += '}\n'

        #### initialize, stepping and finalize code
559
560
561
562
563
564
565
        if not type(kcut) == list:
            update_fields = ('fs->compute_velocity(fs->cvorticity);\n' +
                             'fs->ift_velocity();\n')
            self.particle_start += update_fields
            self.particle_loop  += update_fields
        else:
            self.particle_loop += 'fs->compute_velocity(fs->cvorticity);\n'
Cristian Lalescu's avatar
Cristian Lalescu committed
566
567
568
569
        self.particle_includes += '#include "rFFTW_particles.hpp"\n'
        self.particle_stat_src += (
                'if (ps0->iteration % niter_part == 0)\n' +
                '{\n')
570
        for s in range(nspecies):
571
            neighbours = self.parameters[interpolator[s] + '_neighbours']
Cristian Lalescu's avatar
Cristian Lalescu committed
572
573
574
            self.particle_start += 'sprintf(fname, "tracers{0}");\n'.format(s0 + s)
            self.particle_end += ('ps{0}->write(stat_file);\n' +
                                  'delete ps{0};\n').format(s0 + s)
575
576
577
            self.particle_variables += 'rFFTW_particles<VELOCITY_TRACER, {0}, {1}> *ps{2};\n'.format(
                    self.C_dtype,
                    neighbours,
Cristian Lalescu's avatar
Cristian Lalescu committed
578
                    s0 + s)
579
            self.particle_start += ('ps{0} = new rFFTW_particles<VELOCITY_TRACER, {1}, {2}>(\n' +
Cristian Lalescu's avatar
Cristian Lalescu committed
580
                                    'fname, {3},\n' +
581
582
                                    'nparticles,\n' +
                                    'niter_part, tracers{0}_integration_steps);\n').format(
Cristian Lalescu's avatar
Cristian Lalescu committed
583
                                            s0 + s,
584
585
                                            self.C_dtype,
                                            neighbours,
Cristian Lalescu's avatar
Cristian Lalescu committed
586
587
588
589
590
                                            interpolator[s])
            self.particle_start += ('ps{0}->dt = dt;\n' +
                                    'ps{0}->iteration = iteration;\n' +
                                    'ps{0}->read(stat_file);\n').format(s0 + s)
            if not frozen_particles:
591
592
593
594
                if type(kcut) == list:
                    update_field = ('fs->low_pass_Fourier(fs->cvelocity, 3, {0});\n'.format(kcut[s]) +
                                    'fs->ift_velocity();\n')
                    self.particle_loop += update_field
Cristian Lalescu's avatar
Cristian Lalescu committed
595
596
597
                self.particle_loop += '{0}->field = fs->rvelocity;\n'.format(interpolator[s])
                self.particle_loop += 'ps{0}->step();\n'.format(s0 + s)
            self.particle_stat_src += 'ps{0}->write(stat_file, false);\n'.format(s0 + s)
598
        self.particle_start += output_vel_acc
Cristian Lalescu's avatar
Cristian Lalescu committed
599
600
        self.particle_stat_src += output_vel_acc
        self.particle_stat_src += '}\n'
601
        self.particle_species += nspecies
602
        return None
Cristian Lalescu's avatar
Cristian Lalescu committed
603
604
    def get_data_file_name(self):
        return os.path.join(self.work_dir, self.simname + '.h5')
605
    def get_data_file(self):
Cristian Lalescu's avatar
Cristian Lalescu committed
606
        return h5py.File(self.get_data_file_name(), 'r')
607
608
    def get_postprocess_file_name(self):
        return os.path.join(self.work_dir, self.simname + '_postprocess.h5')
Cristian Lalescu's avatar
Cristian Lalescu committed
609
610
    def get_postprocess_file(self):
        return h5py.File(self.get_postprocess_file_name(), 'r')
Chichi Lalescu's avatar
Chichi Lalescu committed
611
    def compute_statistics(self, iter0 = 0, iter1 = None):
612
613
        if len(list(self.statistics.keys())) > 0:
            return None
Cristian Lalescu's avatar
Cristian Lalescu committed
614
        self.read_parameters()
615
        with self.get_data_file() as data_file:
616
617
            if 'moments' not in data_file['statistics'].keys():
                return None
618
619
            iter0 = min((data_file['statistics/moments/velocity'].shape[0] *
                         self.parameters['niter_stat']-1),
620
                        iter0)
Chichi Lalescu's avatar
Chichi Lalescu committed
621
622
623
624
            if type(iter1) == type(None):
                iter1 = data_file['iteration'].value
            else:
                iter1 = min(data_file['iteration'].value, iter1)
625
626
            ii0 = iter0 // self.parameters['niter_stat']
            ii1 = iter1 // self.parameters['niter_stat']
627
628
            self.statistics['kshell'] = data_file['kspace/kshell'].value
            self.statistics['kM'] = data_file['kspace/kM'].value
Chichi Lalescu's avatar
Chichi Lalescu committed
629
            self.statistics['dk'] = data_file['kspace/dk'].value
630
            if self.particle_species > 0:
631
632
633
                self.trajectories = [data_file['particles/' + key + '/state'][
                                        iter0//self.parameters['niter_part'] :
                                        iter1//self.parameters['niter_part']+1]
634
                                     for key in data_file['particles'].keys()]
635
            computation_needed = True
636
637
638
639
            pp_file = h5py.File(self.get_postprocess_file_name(), 'a')
            if 'ii0' in pp_file.keys():
                computation_needed =  not (ii0 == pp_file['ii0'].value and
                                           ii1 == pp_file['ii1'].value)
640
                if computation_needed:
641
642
                    for k in pp_file.keys():
                        del pp_file[k]
643
            if computation_needed:
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
                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)))
                pp_file['energy(t, k)'] = (
                    data_file['statistics/spectra/velocity_velocity'][ii0:ii1+1, :, 0, 0] +
                    data_file['statistics/spectra/velocity_velocity'][ii0:ii1+1, :, 1, 1] +
                    data_file['statistics/spectra/velocity_velocity'][ii0:ii1+1, :, 2, 2])/2
                pp_file['enstrophy(t, k)'] = (
                    data_file['statistics/spectra/vorticity_vorticity'][ii0:ii1+1, :, 0, 0] +
                    data_file['statistics/spectra/vorticity_vorticity'][ii0:ii1+1, :, 1, 1] +
                    data_file['statistics/spectra/vorticity_vorticity'][ii0:ii1+1, :, 2, 2])/2
                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
661
                if 'trS2_Q_R' in data_file['statistics/moments'].keys():
662
                    pp_file['mean_trS2(t)'] = data_file['statistics/moments/trS2_Q_R'][:, 1, 0]
663
664
665
666
            for k in ['t',
                      'energy(t, k)',
                      'enstrophy(t, k)',
                      'vel_max(t)',
667
668
                      'renergy(t)',
                      'mean_trS2(t)']:
669
670
                if k in pp_file.keys():
                    self.statistics[k] = pp_file[k].value
671
672
673
674
            self.compute_time_averages()
        return None
    def compute_time_averages(self):
        for key in ['energy', 'enstrophy']:
Chichi Lalescu's avatar
Chichi Lalescu committed
675
676
677
            self.statistics[key + '(t)'] = (self.statistics['dk'] *
                                            np.sum(self.statistics[key + '(t, k)'], axis = 1))
        self.statistics['Uint(t)'] = np.sqrt(2*self.statistics['energy(t)'] / 3)
678
679
        self.statistics['Lint(t)'] = ((self.statistics['dk']*np.pi /
                                       (2*self.statistics['Uint(t)']**2)) *
Chichi Lalescu's avatar
Chichi Lalescu committed
680
681
682
683
684
685
686
687
                                      np.nansum(self.statistics['energy(t, k)'] /
                                                self.statistics['kshell'][None, :], axis = 1))
        for key in ['energy',
                    'enstrophy',
                    'vel_max',
                    'mean_trS2',
                    'Uint',
                    'Lint']:
688
689
            if key + '(t)' in self.statistics.keys():
                self.statistics[key] = np.average(self.statistics[key + '(t)'], axis = 0)
690
691
692
693
694
695
696
        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
Chichi Lalescu's avatar
Chichi Lalescu committed
697
698
699
700
701
702
703
704
705
            self.statistics['Re' + suffix] = (self.statistics['Uint' + suffix] *
                                              self.statistics['Lint' + suffix] /
                                              self.parameters['nu'])
            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'])
706
707
            self.statistics['kMeta' + suffix] = (self.statistics['kM'] *
                                                 self.statistics['etaK' + suffix])
Cristian Lalescu's avatar
Cristian Lalescu committed
708
709
            if self.parameters['dealias_type'] == 1:
                self.statistics['kMeta' + suffix] *= 0.8
Chichi Lalescu's avatar
Chichi Lalescu committed
710
711
        self.statistics['Tint'] = self.statistics['Lint'] / self.statistics['Uint']
        self.statistics['Taylor_microscale'] = self.statistics['lambda']
712
        return None
713
714
715
716
717
    def set_plt_style(
            self,
            style = {'dashes' : (None, None)}):
        self.style.update(style)
        return None
Chichi Lalescu's avatar
Chichi Lalescu committed
718
719
720
721
    def read_cfield(
            self,
            field_name = 'vorticity',
            iteration = 0):
Cristian Lalescu's avatar
Cristian Lalescu committed
722
723
724
725
726
727
        """read the Fourier representation of a vector field.

        Read the binary file containing iteration ``iteration`` of the
        field ``field_name``, and return it as a properly shaped
        ``numpy.memmap`` object.
        """
Chichi Lalescu's avatar
Chichi Lalescu committed
728
729
730
731
732
733
734
735
736
        return 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))
737
    def write_par(self, iter0 = 0):
738
        _fluid_particle_base.write_par(self, iter0 = iter0)
739
740
741
        with h5py.File(os.path.join(self.work_dir, self.simname + '.h5'), 'r+') as ofile:
            kspace = self.get_kspace()
            nshells = kspace['nshell'].shape[0]
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
            for k in ['velocity', 'vorticity']:
                time_chunk = 2**20//(8*3*self.parameters['nx'])
                time_chunk = max(time_chunk, 1)
                ofile.create_dataset('statistics/xlines/' + k,
                                     (1, self.parameters['nx'], 3),
                                     chunks = (time_chunk, self.parameters['nx'], 3),
                                     maxshape = (None, self.parameters['nx'], 3),
                                     dtype = self.dtype,
                                     compression = 'gzip')
                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,
                                     compression = 'gzip')
                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,
                                     compression = 'gzip')
                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,
                                     compression = 'gzip')
            for s in range(self.particle_species):
                time_chunk = 2**20 // (8*3*
                                       self.parameters['nparticles']*
                                       self.parameters['tracers{0}_integration_steps'.format(s)])
                time_chunk = max(time_chunk, 1)
                ofile.create_dataset('particles/tracers{0}/rhs'.format(s),
                                     (1,
                                      self.parameters['tracers{0}_integration_steps'.format(s)],
                                      self.parameters['nparticles'],
                                      3),
                                     maxshape = (None,
                                                 self.parameters['tracers{0}_integration_steps'.format(s)],
                                                 self.parameters['nparticles'],
                                                 3),
                                     chunks =  (time_chunk,
                                                self.parameters['tracers{0}_integration_steps'.format(s)],
                                                self.parameters['nparticles'],
                                                3),
                                     dtype = np.float64)
                time_chunk = 2**20 // (8*3*self.parameters['nparticles'])
                time_chunk = max(time_chunk, 1)
                ofile.create_dataset(
                    '/particles/tracers{0}/velocity'.format(s),
                    (1,
                     self.parameters['nparticles'],
                     3),
                    chunks = (time_chunk, self.parameters['nparticles'], 3),
                    maxshape = (None, self.parameters['nparticles'], 3),
                    dtype = np.float64)
                if self.parameters['tracers{0}_acc_on'.format(s)]:
                    ofile.create_dataset(
                        '/particles/tracers{0}/acceleration'.format(s),
                        (1,
                         self.parameters['nparticles'],
                         3),
                        chunks = (time_chunk, self.parameters['nparticles'], 3),
                        maxshape = (None, self.parameters['nparticles'], 3),
                        dtype = np.float64)
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
            if self.QR_stats_on:
                time_chunk = 2**20//(8*3*self.parameters['histogram_bins'])
                time_chunk = max(time_chunk, 1)
                ofile.create_dataset('statistics/histograms/trS2_Q_R',
                                     (1,
                                      self.parameters['histogram_bins'],
                                      3),
                                     chunks = (time_chunk,
                                               self.parameters['histogram_bins'],
                                               3),
                                     maxshape = (None,
                                                 self.parameters['histogram_bins'],
                                                 3),
                                     dtype = np.int64,
                                     compression = 'gzip')
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
                time_chunk = 2**20//(8*9*self.parameters['histogram_bins'])
                time_chunk = max(time_chunk, 1)
                ofile.create_dataset('statistics/histograms/velocity_gradient',
                                     (1,
                                      self.parameters['histogram_bins'],
                                      3,
                                      3),
                                     chunks = (time_chunk,
                                               self.parameters['histogram_bins'],
                                               3,
                                               3),
                                     maxshape = (None,
                                                 self.parameters['histogram_bins'],
                                                 3,
                                                 3),
                                     dtype = np.int64,
                                     compression = 'gzip')
851
852
853
854
855
856
857
858
                time_chunk = 2**20//(8*3*10)
                time_chunk = max(time_chunk, 1)
                a = ofile.create_dataset('statistics/moments/trS2_Q_R',
                                     (1, 10, 3),
                                     chunks = (time_chunk, 10, 3),
                                     maxshape = (None, 10, 3),
                                     dtype = np.float64,
                                     compression = 'gzip')
859
860
861
862
863
864
865
866
                time_chunk = 2**20//(8*9*10)
                time_chunk = max(time_chunk, 1)
                a = ofile.create_dataset('statistics/moments/velocity_gradient',
                                     (1, 10, 3, 3),
                                     chunks = (time_chunk, 10, 3, 3),
                                     maxshape = (None, 10, 3, 3),
                                     dtype = np.float64,
                                     compression = 'gzip')
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
                time_chunk = 2**20//(8*self.parameters['QR2D_histogram_bins']**2)
                time_chunk = max(time_chunk, 1)
                ofile.create_dataset('statistics/histograms/QR2D',
                                     (1,
                                      self.parameters['QR2D_histogram_bins'],
                                      self.parameters['QR2D_histogram_bins']),
                                     chunks = (time_chunk,
                                               self.parameters['QR2D_histogram_bins'],
                                               self.parameters['QR2D_histogram_bins']),
                                     maxshape = (None,
                                                 self.parameters['QR2D_histogram_bins'],
                                                 self.parameters['QR2D_histogram_bins']),
                                     dtype = np.int64,
                                     compression = 'gzip')
        return None
Cristian Lalescu's avatar
Cristian Lalescu committed
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
    def add_particle_fields(
            self,
            interp_type = 'spline',
            kcut = None,
            neighbours = 1,
            smoothness = 1,
            name = 'particle_field',
            field_class = 'rFFTW_interpolator',
            acc_field_name = 'rFFTW_acc'):
        self.fluid_includes += '#include "{0}.hpp"\n'.format(field_class)
        self.fluid_variables += field_class + '<{0}, {1}> *vel_{2}, *acc_{2};\n'.format(
                self.C_dtype, neighbours, name)
        self.parameters[name + '_type'] = interp_type
        self.parameters[name + '_neighbours'] = neighbours
        if interp_type == 'spline':
            self.parameters[name + '_smoothness'] = smoothness
            beta_name = 'beta_n{0}_m{1}'.format(neighbours, smoothness)
        elif interp_type == 'Lagrange':
            beta_name = 'beta_Lagrange_n{0}'.format(neighbours)
        if field_class == 'rFFTW_interpolator':
            self.fluid_start += ('vel_{0} = new {1}<{2}, {3}>(fs, {4}, fs->rvelocity);\n' +
                                 'acc_{0} = new {1}<{2}, {3}>(fs, {4}, {5});\n').format(name,
                                                                                   field_class,
                                                                                   self.C_dtype,
                                                                                   neighbours,
                                                                                   beta_name,
                                                                                   acc_field_name)
        elif field_class == 'interpolator':
            self.fluid_start += ('vel_{0} = new {1}<{2}, {3}>(fs, {4});\n' +
                                 'acc_{0} = new {1}<{2}, {3}>(fs, {4});\n').format(name,
                                                                                   field_class,
                                                                                   self.C_dtype,
                                                                                   neighbours,
                                                                                   beta_name,
                                                                                   acc_field_name)
        self.fluid_end += ('delete vel_{0};\n' +
                           'delete acc_{0};\n').format(name)
        update_fields = 'fs->compute_velocity(fs->cvorticity);\n'
        if not type(kcut) == type(None):
            update_fields += 'fs->low_pass_Fourier(fs->cvelocity, 3, {0});\n'.format(kcut)
        update_fields += ('fs->ift_velocity();\n' +
                          'fs->compute_Lagrangian_acceleration(acc_{0}->field);\n').format(name)
        self.fluid_start += update_fields
        self.fluid_loop += update_fields
        return None
927
    def specific_parser_arguments(
928
929
            self,
            parser):
930
        _fluid_particle_base.specific_parser_arguments(self, parser)
931
932
933
934
        parser.add_argument(
                '--src-wd',
                type = str,
                dest = 'src_work_dir',
935
                default = '')
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
        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(
               '--njobs',
               type = int, dest = 'njobs',
               default = 1)
        parser.add_argument(
               '--QR-stats',
               action = 'store_true',
               dest = 'QR_stats',
               help = 'add this option if you want to compute velocity gradient and QR stats')
        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')
        parser.add_argument(
               '--particle-rand-seed',
               type = int,
               dest = 'particle_rand_seed',
               default = None)
        return None
972
973
974
975
    def launch(
            self,
            args = [],
            **kwargs):
976
        opt = self.prepare_launch(args)
977
978
979
980
981
982
        # with the default Lundgren forcing, I can estimate the dissipation
        # with nondefault forcing, figure out the amplitude for this viscosity
        # yourself
        self.QR_stats_on = opt.QR_stats
        self.parameters['nu'] = (opt.kMeta * 2 / opt.n)**(4./3)
        self.parameters['dt'] = (opt.dtfactor / opt.n)
983
984
985
986
987
        # custom famplitude for 288 and 576
        if opt.n == 288:
            self.parameters['famplitude'] = 0.45
        elif opt.n == 576:
            self.parameters['famplitude'] = 0.47
988
989
990
991
992
993
994
995
996
        if ((self.parameters['niter_todo'] % self.parameters['niter_out']) != 0):
            self.parameters['niter_out'] = self.parameters['niter_todo']
        if self.QR_stats_on:
            # max_Q_estimate and max_R_estimate are just used for the 2D pdf
            # therefore I just want them to be small multiples of mean trS2
            # I'm already estimating the dissipation with kMeta...
            meantrS2 = (opt.n//2 / opt.kMeta)**4 * self.parameters['nu']**2
            self.parameters['max_Q_estimate'] = meantrS2
            self.parameters['max_R_estimate'] = .4*meantrS2**1.5
997
998
999
            # add QR suffix to code name, since we now expect additional
            # datasets in the .h5 file
            self.name += '-QR'
1000
1001
        if len(opt.src_work_dir) == 0:
            opt.src_work_dir = opt.work_dir
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
        self.pars_from_namespace(opt)
        self.fill_up_fluid_code()
        self.finalize_code()
        self.write_src()
        if not os.path.exists(os.path.join(self.work_dir, self.simname + '.h5')):
            self.write_par()
            if self.parameters['nparticles'] > 0:
                data = self.generate_tracer_state(
                        species = 0,
                        rseed = opt.particle_rand_seed)
                for s in range(1, self.particle_species):
                    self.generate_tracer_state(species = s, data = data)
            init_condition_file = os.path.join(
                    self.work_dir,
                    self.simname + '_cvorticity_i{0:0>5x}'.format(0))
            if not os.path.exists(init_condition_file):
                if len(opt.src_simname) > 0:
                    src_file = os.path.join(
1020
                            os.path.realpath(opt.src_work_dir),
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
                            opt.src_simname + '_cvorticity_i{0:0>5x}'.format(opt.src_iteration))
                    os.symlink(src_file, init_condition_file)
                else:
                   self.generate_vector_field(
                           write_to_file = True,
                           spectra_slope = 2.0,
                           amplitude = 0.25)
        self.run(
                ncpu = opt.ncpu,
                njobs = opt.njobs)
        return None
Cristian Lalescu's avatar
Cristian Lalescu committed
1032