NavierStokes.py 50.3 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 ._fluid_base import _fluid_particle_base
Cristian Lalescu's avatar
Cristian Lalescu committed
34

35
class NavierStokes(_fluid_particle_base):
36
37
38
39
40
    """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
41
42
    def __init__(
            self,
43
            name = 'NavierStokes',
Cristian Lalescu's avatar
Cristian Lalescu committed
44
            work_dir = './',
45
            simname = 'test',
46
            fluid_precision = 'single',
Chichi Lalescu's avatar
Chichi Lalescu committed
47
            fftw_plan_rigor = 'FFTW_MEASURE',
48
            frozen_fields = False,
Cristian Lalescu's avatar
Cristian Lalescu committed
49
50
51
52
53
            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
54
55
        _fluid_particle_base.__init__(
                self,
56
57
                name = name,
                work_dir = work_dir,
58
                simname = simname,
59
60
                dtype = fluid_precision,
                use_fftw_wisdom = use_fftw_wisdom)
61
62
63
64
65
66
67
68
69
70
71
72
73
        self.parameters['nu'] = 0.1
        self.parameters['fmode'] = 1
        self.parameters['famplitude'] = 0.5
        self.parameters['fk0'] = 1.5
        self.parameters['fk1'] = 3.0
        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
74
        self.file_datasets_grow = """
75
                //begincpp
76
                std::string temp_string;
77
                hsize_t dims[4];
78
79
                hid_t group;
                hid_t Cspace, Cdset;
80
                int ndims;
81
                // store kspace information
Cristian Lalescu's avatar
Cristian Lalescu committed
82
                Cdset = H5Dopen(stat_file, "/kspace/kshell", H5P_DEFAULT);
Cristian Lalescu's avatar
Cristian Lalescu committed
83
84
                Cspace = H5Dget_space(Cdset);
                H5Sget_simple_extent_dims(Cspace, dims, NULL);
Cristian Lalescu's avatar
Cristian Lalescu committed
85
                H5Sclose(Cspace);
86
87
                if (fs->nshells != dims[0])
                {
88
89
90
                    DEBUG_MSG(
                        "ERROR: computed nshells %d not equal to data file nshells %d\\n",
                        fs->nshells, dims[0]);
91
92
                    file_problems++;
                }
Cristian Lalescu's avatar
Cristian Lalescu committed
93
94
                H5Dwrite(Cdset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, fs->kshell);
                H5Dclose(Cdset);
Cristian Lalescu's avatar
Cristian Lalescu committed
95
                Cdset = H5Dopen(stat_file, "/kspace/nshell", H5P_DEFAULT);
Cristian Lalescu's avatar
Cristian Lalescu committed
96
97
                H5Dwrite(Cdset, H5T_NATIVE_INT64, H5S_ALL, H5S_ALL, H5P_DEFAULT, fs->nshell);
                H5Dclose(Cdset);
Cristian Lalescu's avatar
Cristian Lalescu committed
98
                Cdset = H5Dopen(stat_file, "/kspace/kM", H5P_DEFAULT);
Chichi Lalescu's avatar
Chichi Lalescu committed
99
                H5Dwrite(Cdset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &fs->kMspec);
Cristian Lalescu's avatar
Cristian Lalescu committed
100
                H5Dclose(Cdset);
Cristian Lalescu's avatar
Cristian Lalescu committed
101
                Cdset = H5Dopen(stat_file, "/kspace/dk", H5P_DEFAULT);
Cristian Lalescu's avatar
Cristian Lalescu committed
102
103
                H5Dwrite(Cdset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &fs->dk);
                H5Dclose(Cdset);
104
105
106
                group = H5Gopen(stat_file, "/statistics", H5P_DEFAULT);
                H5Ovisit(group, H5_INDEX_NAME, H5_ITER_NATIVE, grow_statistics_dataset, NULL);
                H5Gclose(group);
107
108
                //endcpp
                """
109
110
        self.style = {}
        self.statistics = {}
Chichi Lalescu's avatar
Chichi Lalescu committed
111
        self.fluid_output = 'fs->write(\'v\', \'c\');\n'
112
        return None
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
    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
134
135
136
    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
137
138
        self.stat_src += """
                //begincpp
139
140
141
142
143
144
145
146
147
148
                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
149
150
                //endcpp
                """
Cristian Lalescu's avatar
Cristian Lalescu committed
151
152
153
        if self.QR_stats_on:
            self.stat_src += """
                //begincpp
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
                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
178
179
        self.stat_src += """
                //begincpp
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
                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
209
                //endcpp
Cristian Lalescu's avatar
Cristian Lalescu committed
210
211
212
213
214
                """.format(self.C_dtype)
        if self.dtype == np.float32:
            field_H5T = 'H5T_NATIVE_FLOAT'
        elif self.dtype == np.float64:
            field_H5T = 'H5T_NATIVE_DOUBLE'
215
        self.stat_src += self.create_stat_output(
216
217
218
219
220
221
222
223
224
                '/statistics/xlines/velocity',
                'fs->rvelocity',
                data_type = field_H5T,
                size_setup = """
                    count[0] = 1;
                    count[1] = nx;
                    count[2] = 3;
                    """,
                close_spaces = False)
225
        self.stat_src += self.create_stat_output(
226
227
228
                '/statistics/xlines/vorticity',
                'fs->rvorticity',
                data_type = field_H5T)
229
        self.stat_src += self.create_stat_output(
230
231
232
233
234
235
236
237
                '/statistics/moments/velocity',
                'velocity_moments',
                size_setup = """
                    count[0] = 1;
                    count[1] = 10;
                    count[2] = 4;
                    """,
                close_spaces = False)
238
        self.stat_src += self.create_stat_output(
239
240
                '/statistics/moments/vorticity',
                'vorticity_moments')
241
        self.stat_src += self.create_stat_output(
242
243
244
245
246
247
248
249
250
                '/statistics/spectra/velocity_velocity',
                'spec_velocity',
                size_setup = """
                    count[0] = 1;
                    count[1] = fs->nshells;
                    count[2] = 3;
                    count[3] = 3;
                    """,
                close_spaces = False)
251
        self.stat_src += self.create_stat_output(
252
253
                '/statistics/spectra/vorticity_vorticity',
                'spec_vorticity')
254
        self.stat_src += self.create_stat_output(
255
256
257
258
259
260
261
262
263
                '/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)
264
        self.stat_src += self.create_stat_output(
265
266
267
                '/statistics/histograms/vorticity',
                'hist_vorticity',
                data_type = 'H5T_NATIVE_INT64')
Cristian Lalescu's avatar
Cristian Lalescu committed
268
269
270
271
272
273
274
275
276
        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;
                        """)
277
278
279
280
281
282
283
284
285
            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
286
287
288
289
290
291
292
293
294
            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;
                        """)
295
296
297
298
299
300
301
302
303
304
            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
305
306
307
308
309
310
311
312
313
            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
314
315
        self.stat_src += """
                //begincpp
316
317
318
319
320
321
322
                }
                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
323
324
325
326
327
                //endcpp
                """
        if self.QR_stats_on:
            self.stat_src += """
                //begincpp
328
329
330
331
332
                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
333
334
                //endcpp
                """
335
336
337
        return None
    def fill_up_fluid_code(self):
        self.fluid_includes += '#include <cstring>\n'
Cristian Lalescu's avatar
Cristian Lalescu committed
338
339
340
        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
341
342
343
344
345
346
        self.fluid_definitions += """
                    typedef struct {{
                        {0} re;
                        {0} im;
                    }} tmp_complex_type;
                    """.format(self.C_dtype)
347
        self.write_fluid_stats()
Cristian Lalescu's avatar
Cristian Lalescu committed
348
349
350
351
        if self.dtype == np.float32:
            field_H5T = 'H5T_NATIVE_FLOAT'
        elif self.dtype == np.float64:
            field_H5T = 'H5T_NATIVE_DOUBLE'
352
        self.fluid_start += """
Cristian Lalescu's avatar
Cristian Lalescu committed
353
354
                //begincpp
                char fname[512];
355
                fs = new fluid_solver<{0}>(
Cristian Lalescu's avatar
Cristian Lalescu committed
356
357
                        simname,
                        nx, ny, nz,
358
                        dkx, dky, dkz,
359
360
                        dealias_type,
                        {1});
Cristian Lalescu's avatar
Cristian Lalescu committed
361
362
363
                fs->nu = nu;
                fs->fmode = fmode;
                fs->famplitude = famplitude;
Cristian Lalescu's avatar
Cristian Lalescu committed
364
365
366
                fs->fk0 = fk0;
                fs->fk1 = fk1;
                strncpy(fs->forcing_type, forcing_type, 128);
Chichi Lalescu's avatar
Chichi Lalescu committed
367
                fs->iteration = iteration;
Cristian Lalescu's avatar
Cristian Lalescu committed
368
                fs->read('v', 'c');
Cristian Lalescu's avatar
Cristian Lalescu committed
369
370
371
372
373
374
                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
375
                //endcpp
Cristian Lalescu's avatar
Cristian Lalescu committed
376
                """.format(self.C_dtype, self.fftw_plan_rigor, field_H5T)
Chichi Lalescu's avatar
Chichi Lalescu committed
377
378
379
380
381
382
        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
383
384
        self.fluid_end = ('if (fs->iteration % niter_out != 0)\n{\n' +
                          self.fluid_output + '\n}\n' +
Cristian Lalescu's avatar
Cristian Lalescu committed
385
386
387
388
                          'if (fs->cd->myrank == 0)\n' +
                          '{\n' +
                          'delete[] kindices;\n' +
                          'H5Tclose(H5T_field_complex);\n' +
Chichi Lalescu's avatar
Chichi Lalescu committed
389
390
                          '}\n' +
                          'delete fs;\n')
391
        return None
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
    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'
411
412
        self.fluid_variables += 'rFFTW_interpolator <{0}, {1}> *{2};\n'.format(
                self.C_dtype, neighbours, name)
413
414
415
416
417
418
419
        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
420
        self.fluid_start += '{0} = new rFFTW_interpolator<{1}, {2}>(fs, {3}, {4});\n'.format(
421
422
423
                name,
                self.C_dtype,
                neighbours,
Cristian Lalescu's avatar
Cristian Lalescu committed
424
425
                beta_name,
                field_name)
426
        self.fluid_end += 'delete {0};\n'.format(name)
427
        return None
428
429
    def add_particles(
            self,
430
            integration_steps = 2,
Cristian Lalescu's avatar
Cristian Lalescu committed
431
            kcut = None,
432
            interpolator = 'field_interpolator',
433
            frozen_particles = False,
Cristian Lalescu's avatar
Cristian Lalescu committed
434
            acc_name = None):
435
436
437
438
439
440
441
442
443
        """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

444
445
446
        .. warning:: if not None, kcut must be a list of decreasing
                     wavenumbers, since filtering is done sequentially
                     on the same complex FFTW field.
447
        """
Cristian Lalescu's avatar
Cristian Lalescu committed
448
449
450
451
452
        if self.dtype == np.float32:
            FFTW = 'fftwf'
        elif self.dtype == np.float64:
            FFTW = 'fftw'
        s0 = self.particle_species
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
        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
474
            neighbours = self.parameters[interpolator[s] + '_neighbours']
475
476
            if type(kcut) == list:
                self.parameters['tracers{0}_kcut'.format(s0 + s)] = kcut[s]
Cristian Lalescu's avatar
Cristian Lalescu committed
477
            self.parameters['tracers{0}_interpolator'.format(s0 + s)] = interpolator[s]
478
            self.parameters['tracers{0}_acc_on'.format(s0 + s)] = int(not type(acc_name) == type(None))
Cristian Lalescu's avatar
Cristian Lalescu committed
479
480
            self.parameters['tracers{0}_integration_steps'.format(s0 + s)] = integration_steps[s]
            self.file_datasets_grow += """
481
482
                        //begincpp
                        temp_string = (std::string("/particles/") +
483
484
485
486
                                       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);
487
                        //endcpp
Cristian Lalescu's avatar
Cristian Lalescu committed
488
489
490
491
492
493
494
495
                        """.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' +
496
497
498
                           '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
499
500
501
502
503
        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)
504
        for s in range(nspecies):
505
506
507
            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
508
509
510
511
512
513
514
515
516
517
518
            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)
519
                {{
Cristian Lalescu's avatar
Cristian Lalescu committed
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
                //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);
538
                //VELOCITY end\n""".format(s0 + s)
Cristian Lalescu's avatar
Cristian Lalescu committed
539
540
541
542
543
544
545
546
547
548
549
            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);
550
                    //ACCELERATION end\n""".format(s0 + s)
Cristian Lalescu's avatar
Cristian Lalescu committed
551
552
553
554
555
556
557
            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
558
559
560
561
562
563
564
        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
565
566
567
568
        self.particle_includes += '#include "rFFTW_particles.hpp"\n'
        self.particle_stat_src += (
                'if (ps0->iteration % niter_part == 0)\n' +
                '{\n')
569
        for s in range(nspecies):
570
            neighbours = self.parameters[interpolator[s] + '_neighbours']
Cristian Lalescu's avatar
Cristian Lalescu committed
571
572
573
            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)
574
575
576
            self.particle_variables += 'rFFTW_particles<VELOCITY_TRACER, {0}, {1}> *ps{2};\n'.format(
                    self.C_dtype,
                    neighbours,
Cristian Lalescu's avatar
Cristian Lalescu committed
577
                    s0 + s)
578
            self.particle_start += ('ps{0} = new rFFTW_particles<VELOCITY_TRACER, {1}, {2}>(\n' +
Cristian Lalescu's avatar
Cristian Lalescu committed
579
                                    'fname, {3},\n' +
580
581
                                    'nparticles,\n' +
                                    'niter_part, tracers{0}_integration_steps);\n').format(
Cristian Lalescu's avatar
Cristian Lalescu committed
582
                                            s0 + s,
583
584
                                            self.C_dtype,
                                            neighbours,
Cristian Lalescu's avatar
Cristian Lalescu committed
585
586
587
588
589
                                            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:
590
591
592
593
                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
594
595
596
                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)
597
        self.particle_start += output_vel_acc
Cristian Lalescu's avatar
Cristian Lalescu committed
598
599
        self.particle_stat_src += output_vel_acc
        self.particle_stat_src += '}\n'
600
        self.particle_species += nspecies
601
        return None
Cristian Lalescu's avatar
Cristian Lalescu committed
602
603
    def get_data_file_name(self):
        return os.path.join(self.work_dir, self.simname + '.h5')
604
    def get_data_file(self):
Cristian Lalescu's avatar
Cristian Lalescu committed
605
        return h5py.File(self.get_data_file_name(), 'r')
606
607
    def get_postprocess_file_name(self):
        return os.path.join(self.work_dir, self.simname + '_postprocess.h5')
Cristian Lalescu's avatar
Cristian Lalescu committed
608
609
    def get_postprocess_file(self):
        return h5py.File(self.get_postprocess_file_name(), 'r')
Chichi Lalescu's avatar
Chichi Lalescu committed
610
    def compute_statistics(self, iter0 = 0, iter1 = None):
611
612
        if len(list(self.statistics.keys())) > 0:
            return None
Cristian Lalescu's avatar
Cristian Lalescu committed
613
        self.read_parameters()
614
        with self.get_data_file() as data_file:
615
616
            if 'moments' not in data_file['statistics'].keys():
                return None
617
618
            iter0 = min((data_file['statistics/moments/velocity'].shape[0] *
                         self.parameters['niter_stat']-1),
619
                        iter0)
Chichi Lalescu's avatar
Chichi Lalescu committed
620
621
622
623
            if type(iter1) == type(None):
                iter1 = data_file['iteration'].value
            else:
                iter1 = min(data_file['iteration'].value, iter1)
624
625
            ii0 = iter0 // self.parameters['niter_stat']
            ii1 = iter1 // self.parameters['niter_stat']
626
627
            self.statistics['kshell'] = data_file['kspace/kshell'].value
            self.statistics['kM'] = data_file['kspace/kM'].value
Chichi Lalescu's avatar
Chichi Lalescu committed
628
            self.statistics['dk'] = data_file['kspace/dk'].value
629
            if self.particle_species > 0:
630
631
632
                self.trajectories = [data_file['particles/' + key + '/state'][
                                        iter0//self.parameters['niter_part'] :
                                        iter1//self.parameters['niter_part']+1]
633
                                     for key in data_file['particles'].keys()]
634
            computation_needed = True
635
636
637
638
            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)
639
                if computation_needed:
640
641
                    for k in pp_file.keys():
                        del pp_file[k]
642
            if computation_needed:
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
                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
660
                if 'trS2_Q_R' in data_file['statistics/moments'].keys():
661
                    pp_file['mean_trS2(t)'] = data_file['statistics/moments/trS2_Q_R'][:, 1, 0]
662
663
664
665
            for k in ['t',
                      'energy(t, k)',
                      'enstrophy(t, k)',
                      'vel_max(t)',
666
667
                      'renergy(t)',
                      'mean_trS2(t)']:
668
669
                if k in pp_file.keys():
                    self.statistics[k] = pp_file[k].value
670
671
672
673
            self.compute_time_averages()
        return None
    def compute_time_averages(self):
        for key in ['energy', 'enstrophy']:
Chichi Lalescu's avatar
Chichi Lalescu committed
674
675
676
            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)
677
678
        self.statistics['Lint(t)'] = ((self.statistics['dk']*np.pi /
                                       (2*self.statistics['Uint(t)']**2)) *
Chichi Lalescu's avatar
Chichi Lalescu committed
679
680
681
682
683
684
685
686
                                      np.nansum(self.statistics['energy(t, k)'] /
                                                self.statistics['kshell'][None, :], axis = 1))
        for key in ['energy',
                    'enstrophy',
                    'vel_max',
                    'mean_trS2',
                    'Uint',
                    'Lint']:
687
688
            if key + '(t)' in self.statistics.keys():
                self.statistics[key] = np.average(self.statistics[key + '(t)'], axis = 0)
689
690
691
692
693
694
695
        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
696
697
698
699
700
701
702
703
704
            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'])
705
706
            self.statistics['kMeta' + suffix] = (self.statistics['kM'] *
                                                 self.statistics['etaK' + suffix])
Cristian Lalescu's avatar
Cristian Lalescu committed
707
708
            if self.parameters['dealias_type'] == 1:
                self.statistics['kMeta' + suffix] *= 0.8
Chichi Lalescu's avatar
Chichi Lalescu committed
709
710
        self.statistics['Tint'] = self.statistics['Lint'] / self.statistics['Uint']
        self.statistics['Taylor_microscale'] = self.statistics['lambda']
711
        return None
712
713
714
715
716
    def set_plt_style(
            self,
            style = {'dashes' : (None, None)}):
        self.style.update(style)
        return None
Chichi Lalescu's avatar
Chichi Lalescu committed
717
718
719
720
    def read_cfield(
            self,
            field_name = 'vorticity',
            iteration = 0):
Cristian Lalescu's avatar
Cristian Lalescu committed
721
722
723
724
725
726
        """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
727
728
729
730
731
732
733
734
735
        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))
736
    def write_par(self, iter0 = 0):
737
        _fluid_particle_base.write_par(self, iter0 = iter0)
738
739
740
        with h5py.File(os.path.join(self.work_dir, self.simname + '.h5'), 'r+') as ofile:
            kspace = self.get_kspace()
            nshells = kspace['nshell'].shape[0]
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
            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)
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
            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')
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
                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')
850
851
852
853
854
855
856
857
                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')
858
859
860
861
862
863
864
865
                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')
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
                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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
    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
926
    def specific_parser_arguments(
927
928
            self,
            parser):
929
        _fluid_particle_base.specific_parser_arguments(self, parser)
930
931
932
933
        parser.add_argument(
                '--src-wd',
                type = str,
                dest = 'src_work_dir',
934
                default = '')
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
        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(
               '--precision',
               type = str, dest = 'precision',
               default = 'single')
        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
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
    def launch(
            self,
            args = [],
            **kwargs):
        # with the default Lundgren forcing, I can estimate the dissipation
        # with nondefault forcing, figure out the amplitude for this viscosity
        # yourself
        parser = argparse.ArgumentParser('bfps ' + type(self).__name__)
        self.add_parser_arguments(parser)
        opt = parser.parse_args(args)
        self.QR_stats_on = opt.QR_stats
        self.parameters['nu'] = (opt.kMeta * 2 / opt.n)**(4./3)
        self.parameters['dt'] = (opt.dtfactor / opt.n)
        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

998
999
        if len(opt.src_work_dir) == 0:
            opt.src_work_dir = opt.work_dir
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
        self.pars_from_namespace(opt)
        self.fill_up_fluid_code()
        self.finalize_code()
        self.write_src()
        self.set_host_info(bfps.host_info)
        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(
1019
                            os.path.realpath(opt.src_work_dir),
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
                            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
1031