runner.c 27.1 KB
Newer Older
1
/*******************************************************************************
2
 * This file is part of SWIFT.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 * Coypright (c) 2012 Pedro Gonnet (pedro.gonnet@durham.ac.uk)
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program 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 Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 ******************************************************************************/
Pedro Gonnet's avatar
Pedro Gonnet committed
19

Pedro Gonnet's avatar
Pedro Gonnet committed
20
21
/* Config parameters. */
#include "../config.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
22
23
24
25
26
27
28
29
30
31

/* Some standard headers. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <omp.h>
Pedro Gonnet's avatar
Pedro Gonnet committed
32
#include <sched.h>
Pedro Gonnet's avatar
Pedro Gonnet committed
33
34
35

/* Local headers. */
#include "cycle.h"
36
#include "atomic.h"
37
#include "timers.h"
38
#include "const.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
39
#include "lock.h"
40
41
42
#include "task.h"
#include "part.h"
#include "cell.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
43
#include "space.h"
44
#include "queue.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
45
#include "engine.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
46
#include "runner.h"
47
#include "runner_iact.h"
48
#include "error.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

/* Convert cell location to ID. */
#define cell_getid( cdim , i , j , k ) ( (int)(k) + (cdim)[2]*( (int)(j) + (cdim)[1]*(int)(i) ) )

/* The counters. */
int runner_counter[ runner_counter_count ];

        

const float runner_shift[13*3] = {
     5.773502691896258e-01 ,  5.773502691896258e-01 ,  5.773502691896258e-01 ,
     7.071067811865475e-01 ,  7.071067811865475e-01 ,  0.0                   ,
     5.773502691896258e-01 ,  5.773502691896258e-01 , -5.773502691896258e-01 ,
     7.071067811865475e-01 ,  0.0                   ,  7.071067811865475e-01 ,
     1.0                   ,  0.0                   ,  0.0                   ,
     7.071067811865475e-01 ,  0.0                   , -7.071067811865475e-01 ,
     5.773502691896258e-01 , -5.773502691896258e-01 ,  5.773502691896258e-01 ,
     7.071067811865475e-01 , -7.071067811865475e-01 ,  0.0                   ,
     5.773502691896258e-01 , -5.773502691896258e-01 , -5.773502691896258e-01 ,
     0.0                   ,  7.071067811865475e-01 ,  7.071067811865475e-01 ,
     0.0                   ,  1.0                   ,  0.0                   ,
     0.0                   ,  7.071067811865475e-01 , -7.071067811865475e-01 ,
     0.0                   ,  0.0                   ,  1.0                   ,
    };
const char runner_flip[27] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 ,
                               0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }; 


77
78
79
80
81
82
83
84
85
/* Import the density functions. */
#define FUNCTION density
#include "runner_doiact.h"

#undef FUNCTION
#define FUNCTION force
#include "runner_doiact.h"


Pedro Gonnet's avatar
Pedro Gonnet committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/**
 * @brief Sort the entries in ascending order using QuickSort.
 *
 * @param sort The entries
 * @param N The number of entries.
 */
 
void runner_dosort_ascending ( struct entry *sort , int N ) {

    struct {
        short int lo, hi;
        } qstack[10];
    int qpos, i, j, lo, hi, imin;
    struct entry temp;
    float pivot;
        
    /* Sort parts in cell_i in decreasing order with quicksort */
    qstack[0].lo = 0; qstack[0].hi = N - 1; qpos = 0;
    while ( qpos >= 0 ) {
        lo = qstack[qpos].lo; hi = qstack[qpos].hi;
        qpos -= 1;
        if ( hi - lo < 15 ) {
            for ( i = lo ; i < hi ; i++ ) {
                imin = i;
                for ( j = i+1 ; j <= hi ; j++ )
                    if ( sort[j].d < sort[imin].d )
                        imin = j;
                if ( imin != i ) {
                    temp = sort[imin]; sort[imin] = sort[i]; sort[i] = temp;
                    }
                }
            }
        else {
            pivot = sort[ ( lo + hi ) / 2 ].d;
            i = lo; j = hi;
            while ( i <= j ) {
                while ( sort[i].d < pivot ) i++;
                while ( sort[j].d > pivot ) j--;
                if ( i <= j ) {
                    if ( i < j ) {
                        temp = sort[i]; sort[i] = sort[j]; sort[j] = temp;
                        }
                    i += 1; j -= 1;
                    }
                }
            if ( j > ( lo + hi ) / 2 ) {
                if ( lo < j ) {
                    qpos += 1;
                    qstack[qpos].lo = lo;
                    qstack[qpos].hi = j;
                    }
                if ( i < hi ) {
                    qpos += 1;
                    qstack[qpos].lo = i;
                    qstack[qpos].hi = hi;
                    }
                }
            else {
                if ( i < hi ) {
                    qpos += 1;
                    qstack[qpos].lo = i;
                    qstack[qpos].hi = hi;
                    }
                if ( lo < j ) {
                    qpos += 1;
                    qstack[qpos].lo = lo;
                    qstack[qpos].hi = j;
                    }
                }
            }
        }
                
    }
    
    
/**
 * @brief Sort the particles in the given cell along all cardinal directions.
 *
 * @param r The #runner.
 * @param c The #cell.
166
 * @param flags Cell flag.
167
168
 * @param clock Flag indicating whether to record the timing or not, needed
 *      for recursive calls.
Pedro Gonnet's avatar
Pedro Gonnet committed
169
170
 */
 
171
void runner_dosort ( struct runner *r , struct cell *c , int flags , int clock ) {
Pedro Gonnet's avatar
Pedro Gonnet committed
172
173
174

    struct entry *finger;
    struct entry *fingers[8];
175
    struct cpart *cparts = c->cparts;
Pedro Gonnet's avatar
Pedro Gonnet committed
176
    int j, k, count = c->count;
Pedro Gonnet's avatar
Pedro Gonnet committed
177
    int i, ind, off[8], inds[8], temp_i, missing;
178
    // float shift[3];
Pedro Gonnet's avatar
Pedro Gonnet committed
179
    float buff[8], px[3];
180
    
Pedro Gonnet's avatar
Pedro Gonnet committed
181
182
    TIMER_TIC
    
183
184
185
186
187
    /* Clean-up the flags, i.e. filter out what's already been sorted. */
    flags &= ~c->sorted;
    if ( flags == 0 )
        return;
    
Pedro Gonnet's avatar
Pedro Gonnet committed
188
    /* start by allocating the entry arrays. */
189
190
191
192
193
    if ( c->sort == NULL || c->sortsize < c->count ) {
        if ( c->sort != NULL )
            free( c->sort );
        c->sortsize = c->count * 1.1;
        if ( ( c->sort = (struct entry *)malloc( sizeof(struct entry) * (c->sortsize + 1) * 13 ) ) == NULL )
Pedro Gonnet's avatar
Pedro Gonnet committed
194
            error( "Failed to allocate sort memory." );
195
        }
Pedro Gonnet's avatar
Pedro Gonnet committed
196
197
198
199
        
    /* Does this cell have any progeny? */
    if ( c->split ) {
    
Pedro Gonnet's avatar
Pedro Gonnet committed
200
201
202
203
        /* Fill in the gaps within the progeny. */
        for ( k = 0 ; k < 8 ; k++ ) {
            if ( c->progeny[k] == NULL )
                continue;
204
            missing = flags & ~c->progeny[k]->sorted;
Pedro Gonnet's avatar
Pedro Gonnet committed
205
            if ( missing )
206
                runner_dosort( r , c->progeny[k] , missing , 0 );
Pedro Gonnet's avatar
Pedro Gonnet committed
207
208
209
210
            }
    
        /* Loop over the 13 different sort arrays. */
        for ( j = 0 ; j < 13 ; j++ ) {
Pedro Gonnet's avatar
Pedro Gonnet committed
211
212
213
214
215
        
            /* Has this sort array been flagged? */
            if ( !( flags & (1 << j) ) )
                continue;
                
216
217
218
219
220
221
222
223
224
225
226
227
228
229
            /* Init the particle index offsets. */
            for ( off[0] = 0 , k = 1 ; k < 8 ; k++ )
                if ( c->progeny[k-1] != NULL )
                    off[k] = off[k-1] + c->progeny[k-1]->count;
                else
                    off[k] = off[k-1];

            /* Init the entries and indices. */
            for ( k = 0 ; k < 8 ; k++ ) {
                inds[k] = k;
                if ( c->progeny[k] != NULL && c->progeny[k]->count > 0 ) {
                    fingers[k] = &c->progeny[k]->sort[ j*(c->progeny[k]->count + 1) ];
                    buff[k] = fingers[k]->d;
                    off[k] = off[k];
Pedro Gonnet's avatar
Pedro Gonnet committed
230
                    }
231
232
                else
                    buff[k] = FLT_MAX;
Pedro Gonnet's avatar
Pedro Gonnet committed
233
234
                }

235
236
237
238
239
240
            /* Sort the buffer. */
            for ( i = 0 ; i < 7 ; i++ )
                for ( k = i+1 ; k < 8 ; k++ )
                    if ( buff[ inds[k] ] < buff[ inds[i] ] ) {
                        temp_i = inds[i]; inds[i] = inds[k]; inds[k] = temp_i;
                        }
Pedro Gonnet's avatar
Pedro Gonnet committed
241

242
243
244
            /* For each entry in the new sort list. */
            finger = &c->sort[ j*(count + 1) ];
            for ( ind = 0 ; ind < count ; ind++ ) {
Pedro Gonnet's avatar
Pedro Gonnet committed
245

246
247
248
                /* Copy the minimum into the new sort array. */
                finger[ind].d = buff[inds[0]];
                finger[ind].i = fingers[inds[0]]->i + off[inds[0]];
Pedro Gonnet's avatar
Pedro Gonnet committed
249

250
251
252
                /* Update the buffer. */
                fingers[inds[0]] += 1;
                buff[inds[0]] = fingers[inds[0]]->d;
Pedro Gonnet's avatar
Pedro Gonnet committed
253

254
255
256
257
                /* Find the smallest entry. */
                for ( k = 1 ; k < 8 && buff[inds[k]] < buff[inds[k-1]] ; k++ ) {
                    temp_i = inds[k-1]; inds[k-1] = inds[k]; inds[k] = temp_i;
                    }
Pedro Gonnet's avatar
Pedro Gonnet committed
258

259
                } /* Merge. */
Pedro Gonnet's avatar
Pedro Gonnet committed
260
261
262
263
264
            
            /* Add a sentinel. */
            c->sort[ j*(c->count + 1) + c->count ].d = FLT_MAX;
            c->sort[ j*(c->count + 1) + c->count ].i = 0;
            
265
266
267
            /* Mark as sorted. */
            c->sorted |= ( 1 << j );
            
Pedro Gonnet's avatar
Pedro Gonnet committed
268
269
270
271
272
273
274
            } /* loop over sort arrays. */
    
        } /* progeny? */
        
    /* Otherwise, just sort. */
    else {
    
275
        /* Fill the sort array. */
Pedro Gonnet's avatar
Pedro Gonnet committed
276
        for ( k = 0 ; k < count ; k++ ) {
277
278
279
            px[0] = cparts[k].x[0];
            px[1] = cparts[k].x[1];
            px[2] = cparts[k].x[2];
280
281
282
            for ( j = 0 ; j < 13 ; j++ )
                if ( flags & (1 << j) ) {
                    c->sort[ j*(count + 1) + k].i = k;
Pedro Gonnet's avatar
Pedro Gonnet committed
283
                    c->sort[ j*(count + 1) + k].d = px[0]*runner_shift[ 3*j + 0 ] + px[1]*runner_shift[ 3*j + 1 ] + px[2]*runner_shift[ 3*j + 2 ];
284
                    }
Pedro Gonnet's avatar
Pedro Gonnet committed
285
            }
286
287

        /* Add the sentinel and sort. */
Pedro Gonnet's avatar
Pedro Gonnet committed
288
        for ( j = 0 ; j < 13 ; j++ )
289
290
291
292
            if ( flags & (1 << j) ) {
                c->sort[ j*(count + 1) + c->count ].d = FLT_MAX;
                c->sort[ j*(count + 1) + c->count ].i = 0;
                runner_dosort_ascending( &c->sort[ j*(count + 1) ] , c->count );
293
                c->sorted |= ( 1 << j );
Pedro Gonnet's avatar
Pedro Gonnet committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
                }
            
        }
        
    /* Verify the sorting. */
    /* for ( j = 0 ; j < 13 ; j++ ) {
        if ( !( flags & (1 << j) ) )
            continue;
        finger = &c->sort[ j*(c->count + 1) ];
        for ( k = 1 ; k < c->count ; k++ ) {
            if ( finger[k].d < finger[k-1].d )
                error( "Sorting failed, ascending array." );
            if ( finger[k].i >= c->count )
                error( "Sorting failed, indices borked." );
            }
        } */
310
        
Pedro Gonnet's avatar
Pedro Gonnet committed
311
312
    #ifdef TIMER_VERBOSE
        printf( "runner_dosort[%02i]: %i parts at depth %i (flags = %i%i%i%i%i%i%i%i%i%i%i%i%i) took %.3f ms.\n" ,
Pedro Gonnet's avatar
Pedro Gonnet committed
313
            r->id , c->count , c->depth ,
Pedro Gonnet's avatar
Pedro Gonnet committed
314
            (flags & 0x1000) >> 12 , (flags & 0x800) >> 11 , (flags & 0x400) >> 10 , (flags & 0x200) >> 9 , (flags & 0x100) >> 8 , (flags & 0x80) >> 7 , (flags & 0x40) >> 6 , (flags & 0x20) >> 5 , (flags & 0x10) >> 4 , (flags & 0x8) >> 3 , (flags & 0x4) >> 2 , (flags & 0x2) >> 1 , (flags & 0x1) >> 0 , 
315
            ((double)TIMER_TOC(timer_dosort)) / CPU_TPS * 1000 ); fflush(stdout);
Pedro Gonnet's avatar
Pedro Gonnet committed
316
    #else
317
318
        if ( clock )
            TIMER_TOC(timer_dosort);
Pedro Gonnet's avatar
Pedro Gonnet committed
319
320
321
    #endif

    }
322
323
324
325
326
    
    
/**
 * @brief Intermediate task between density and force
 *
Pedro Gonnet's avatar
Pedro Gonnet committed
327
 * @param r The runner thread.
328
 * @param c The cell.
329
330
 */
 
Pedro Gonnet's avatar
Pedro Gonnet committed
331
void runner_doghost ( struct runner *r , struct cell *c ) {
332
333

    struct part *p;
334
    struct cpart *cp;
335
    struct cell *finger;
Pedro Gonnet's avatar
Pedro Gonnet committed
336
337
    int i, k, redo, count = c->count;
    int *pid;
Pedro Gonnet's avatar
Pedro Gonnet committed
338
    float h, hg, ihg, ihg2, ihg4, h_corr;
339
    float normDiv_v, normCurl_v;
340
    float dt_step = r->e->dt_step;
341
342
    TIMER_TIC
    
Pedro Gonnet's avatar
Pedro Gonnet committed
343
344
345
346
347
348
349
    /* Recurse? */
    if ( c->split ) {
        for ( k = 0 ; k < 8 ; k++ )
            if ( c->progeny[k] != NULL )
                runner_doghost( r , c->progeny[k] );
        return;
        }
350
        
Pedro Gonnet's avatar
Pedro Gonnet committed
351
352
353
354
355
356
357
358
    /* Init the IDs that have to be updated. */
    if ( ( pid = (int *)alloca( sizeof(int) * count ) ) == NULL )
        error( "Call to alloca failed." );
    for ( k = 0 ; k < count ; k++ )
        pid[k] = k;
        
    /* While there are particles that need to be updated... */
    while ( count > 0 ) {
359
    
Pedro Gonnet's avatar
Pedro Gonnet committed
360
361
        /* Reset the redo-count. */
        redo = 0;
362
    
Pedro Gonnet's avatar
Pedro Gonnet committed
363
364
365
366
367
        /* Loop over the parts in this cell. */
        for ( i = 0 ; i < count ; i++ ) {

            /* Get a direct pointer on the part. */
            p = &c->parts[ pid[i] ];
368
            cp = &c->cparts[ pid[i] ];
369
            
370
            /* Is this part within the timestep? */
371
            if ( cp->dt <= dt_step ) {
Pedro Gonnet's avatar
Pedro Gonnet committed
372
            
373
  	            /* Some smoothing length multiples. */
Pedro Gonnet's avatar
Pedro Gonnet committed
374
375
376
	            h = p->h;
                hg = kernel_gamma * h;
                ihg = 1.0f / hg;
377
                ihg2 = ihg * ihg;
378
                ihg4 = ihg2 * ihg2;
379
380

                /* Adjust the computed weighted number of neighbours. */
381
                p->density.wcount += kernel_wroot;
382

Pedro Gonnet's avatar
Pedro Gonnet committed
383
384
385
386
		        /* Final operation on the density. */
                p->rho = ihg * ihg2 * ( p->rho + p->mass*kernel_root );
                p->rho_dh *= ihg4;
                    
387
                /* Compute the smoothing length update (Newton step). */
388
389
390
391
392
393
394
395
396
                if ( p->density.wcount_dh == 0.0f )
                    h_corr = p->h;
                else {
                    h_corr = ( const_nwneigh - p->density.wcount ) / p->density.wcount_dh;

                    /* Truncate to the range [ -p->h/2 , p->h ]. */
                    h_corr = fminf( h_corr , h );
                    h_corr = fmaxf( h_corr , -h/2 );
                    }
397
398
399
                
                /* Apply the correction to p->h. */
                p->h += h_corr;
400
                cp->h = p->h;
401
402

                /* Did we get the right number density? */
403
404
405
406
                if ( p->density.wcount > const_nwneigh + const_delta_nwneigh ||
                     p->density.wcount < const_nwneigh - const_delta_nwneigh ) {
                    // printf( "runner_doghost: particle %lli (h=%e,depth=%i) has bad wcount=%.3f.\n" , p->id , p->h , c->depth , p->density.wcount ); fflush(stdout);
                    // p->h += ( p->density.wcount + kernel_root - const_nwneigh ) / p->density.wcount_dh;
407
408
                    pid[redo] = pid[i];
                    redo += 1;
409
                    p->density.wcount = 0.0;
410
                    p->density.wcount_dh = 0.0;
411
412
                    p->rho = 0.0;
                    p->rho_dh = 0.0;
413
		            p->density.div_v = 0.0;
414
		            for ( k=0 ; k < 3 ; k++)
415
		                p->density.curl_v[k] = 0.0;
416
417
                    continue;
                    }
418

419
420
421
422
                /* Pre-compute some stuff for the balsara switch. */
		        normDiv_v = fabs( p->density.div_v / p->rho * ihg4 );
		        normCurl_v = sqrtf( p->density.curl_v[0] * p->density.curl_v[0] + p->density.curl_v[1] * p->density.curl_v[1] + p->density.curl_v[2] * p->density.curl_v[2] ) / p->rho * ihg4;
                
Pedro Gonnet's avatar
Pedro Gonnet committed
423
424
425
                /* As of here, particle force variables will be set. Do _NOT_
                   try to read any particle density variables! */
                
426
                /* Compute this particle's sound speed. */
427
                p->force.c = sqrtf( const_gamma * ( const_gamma - 1.0f ) * p->u );
428
429

                /* Compute the P/Omega/rho2. */
Pedro Gonnet's avatar
Pedro Gonnet committed
430
                p->force.POrho2 = p->u * ( const_gamma - 1.0f ) / ( p->rho + hg * p->rho_dh / 3.0f );
431

432
		        /* Balsara switch */
Pedro Gonnet's avatar
Pedro Gonnet committed
433
		        p->force.balsara = normCurl_v / ( normDiv_v + normCurl_v + 0.0001f * p->force.c * ihg );
434

435
436
437
                /* Reset the acceleration. */
                for ( k = 0 ; k < 3 ; k++ )
                    p->a[k] = 0.0f;
Pedro Gonnet's avatar
Pedro Gonnet committed
438

439
                /* Reset the time derivatives. */
440
441
442
                p->force.u_dt = 0.0f;
                p->force.h_dt = 0.0f;
                p->force.v_sig = 0.0f;
Pedro Gonnet's avatar
Pedro Gonnet committed
443

444
                }
Pedro Gonnet's avatar
Pedro Gonnet committed
445
446

            }
447
            
Pedro Gonnet's avatar
Pedro Gonnet committed
448
449
        /* Re-set the counter for the next loop (potentially). */
        count = redo;
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
        if ( count > 0 ) {
        
            // error( "Bad smoothing length, fixing this isn't implemented yet." );
            
            /* Climb up the cell hierarchy. */
            for ( finger = c ; finger != NULL ; finger = finger->parent ) {
            
                /* Run through this cell's density interactions. */
                for ( k = 0 ; k < finger->nr_density ; k++ ) {
                
                    /* Self-interaction? */
                    if ( finger->density[k]->type == task_type_self )
                        runner_doself_subset_density( r , finger , c->parts , pid , count );
                        
                    /* Otherwise, pair interaction? */
                    else if ( finger->density[k]->type == task_type_pair ) {
                    
                        /* Left or right? */
                        if ( finger->density[k]->ci == finger )
                            runner_dopair_subset_density( r , finger , c->parts , pid , count , finger->density[k]->cj );
                        else
                            runner_dopair_subset_density( r , finger , c->parts , pid , count , finger->density[k]->ci );
                        
                        }
                
                    /* Otherwise, sub interaction? */
476
477
478
479
480
481
482
483
484
                    else if ( finger->density[k]->type == task_type_sub ) {
                    
                        /* Left or right? */
                        if ( finger->density[k]->ci == finger )
                            runner_dosub_subset_density( r , finger , c->parts , pid , count , finger->density[k]->cj , -1 );
                        else
                            runner_dosub_subset_density( r , finger , c->parts , pid , count , finger->density[k]->ci , -1 );
                        
                        }
485
486
                
                    }
Pedro Gonnet's avatar
Pedro Gonnet committed
487
                    
488
489
490
                }
        
            }
491
492
493
494
495
            
        }

    #ifdef TIMER_VERBOSE
        printf( "runner_doghost[%02i]: %i parts at depth %i took %.3f ms.\n" ,
Pedro Gonnet's avatar
Pedro Gonnet committed
496
            r->id , c->count , c->depth ,
497
            ((double)TIMER_TOC(timer_doghost)) / CPU_TPS * 1000 ); fflush(stdout);
498
    #else
499
        TIMER_TOC(timer_doghost);
500
501
502
    #endif
    
    }
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    
    
/**
 * @brief Compute the second kick of the given cell.
 *
 * @param r The runner thread.
 * @param c The cell.
 */
 
void runner_dokick2 ( struct runner *r , struct cell *c ) {

    int k, count = 0, nr_parts = c->count;
    float dt_min = FLT_MAX, dt_max = 0.0f, ekin = 0.0f, epot = 0.0f;
    float mom[3] = { 0.0f , 0.0f , 0.0f }, ang[3] = { 0.0f , 0.0f , 0.0f };
    float x[3], v[3], u, h, pdt, m;
    float dt_step = r->e->dt_step, dt = r->e->dt, hdt = 0.5f*dt;
    struct part *p, *parts = c->parts;
    struct xpart *xp;
    
    TIMER_TIC
    
    /* Loop over the particles and kick them. */
    for ( k = 0 ; k < nr_parts ; k++ ) {

        /* Get a handle on the part. */
        p = &parts[k];
        xp = p->xtras;

        /* Get local copies of particle data. */
        pdt = p->dt;
        h = p->h;
        m = p->mass;
        x[0] = p->x[0]; x[1] = p->x[1]; x[2] = p->x[2];

        /* Scale the derivatives if they're freshly computed. */
        if ( pdt <= dt_step ) {
            p->force.h_dt *= h * 0.333333333f;
            count += 1;
            }

        /* Update the particle's time step. */
        p->dt = pdt = const_cfl * h / ( p->force.v_sig );

        /* Update positions and energies at the half-step. */
        p->v[0] = v[0] = xp->v_old[0] + hdt * p->a[0];
        p->v[1] = v[1] = xp->v_old[1] + hdt * p->a[1];
        p->v[2] = v[2] = xp->v_old[2] + hdt * p->a[2];
        p->u = u = xp->u_old + hdt * p->force.u_dt;

        /* Get the smallest/largest dt. */
        dt_min = fminf( dt_min , pdt );
        dt_max = fmaxf( dt_max , pdt );

        /* Collect total energy. */
        ekin += 0.5 * m * ( v[0]*v[0] + v[1]*v[1] + v[2]*v[2] );
        epot += m * u;

        /* Collect momentum */
        mom[0] += m * p->v[0];
        mom[1] += m * p->v[1];
        mom[2] += m * p->v[2];

	    /* Collect angular momentum */
	    ang[0] += m * ( x[1]*v[2] - v[2]*x[1] );
	    ang[1] += m * ( x[2]*v[0] - v[0]*x[2] );
	    ang[2] += m * ( x[0]*v[1] - v[1]*x[0] );

	    /* Collect entropic function */
	    // lent += u * pow( p->rho, 1.f-const_gamma );

        }

    #ifdef TIMER_VERBOSE
        printf( "runner_dokick2[%02i]: %i parts at depth %i took %.3f ms.\n" ,
            r->id , c->count , c->depth ,
            ((double)TIMER_TOC(timer_kick2)) / CPU_TPS * 1000 ); fflush(stdout);
    #else
        TIMER_TOC(timer_kick2);
    #endif
        
    /* Store the computed values in the cell. */
    c->dt_min = dt_min;
    c->dt_max = dt_max;
    c->updated = count;
    c->ekin = ekin;
    c->epot = epot;
    c->mom[0] = mom[0]; c->mom[1] = mom[1]; c->mom[2] = mom[2];
    c->ang[0] = ang[0]; c->ang[1] = ang[1]; c->ang[2] = ang[2];
        
    }
Pedro Gonnet's avatar
Pedro Gonnet committed
593
594
595
596
597
598
599
600
601
602


/**
 * @brief The #runner main thread routine.
 *
 * @param data A pointer to this thread's data.
 */
 
void *runner_main ( void *data ) {

Pedro Gonnet's avatar
Pedro Gonnet committed
603
604
605
    struct runner *r = (struct runner *)data;
    struct engine *e = r->e;
    int threadID = r->id;
Pedro Gonnet's avatar
Pedro Gonnet committed
606
    int k, qid, naq, keep, tpq;
Pedro Gonnet's avatar
Pedro Gonnet committed
607
    struct queue *queues[ e->nr_queues ], *myq;
Pedro Gonnet's avatar
Pedro Gonnet committed
608
609
    struct task *t;
    struct cell *ci, *cj;
Pedro Gonnet's avatar
Pedro Gonnet committed
610
    unsigned int myseed = rand() + r->id;
Pedro Gonnet's avatar
Pedro Gonnet committed
611
612
613
614
615
616
617
618
    #ifdef TIMER
        ticks stalled;
    #endif
    
    /* Main loop. */
    while ( 1 ) {
    
        /* Wait at the barrier. */
Pedro Gonnet's avatar
Pedro Gonnet committed
619
        engine_barrier( e );
Pedro Gonnet's avatar
Pedro Gonnet committed
620
621
        
        /* Set some convenient local data. */
Pedro Gonnet's avatar
Pedro Gonnet committed
622
        keep = e->policy & engine_policy_keep;
Pedro Gonnet's avatar
Pedro Gonnet committed
623
        myq = &e->queues[ threadID * e->nr_queues / e->nr_threads ];
Pedro Gonnet's avatar
Pedro Gonnet committed
624
        tpq = ceil( ((double)e->nr_threads) / e->nr_queues );
625
626
627
        #ifdef TIMER
            stalled = 0;
        #endif
Pedro Gonnet's avatar
Pedro Gonnet committed
628
629
        
        /* Set up the local list of active queues. */
Pedro Gonnet's avatar
Pedro Gonnet committed
630
        naq = e->nr_queues;
Pedro Gonnet's avatar
Pedro Gonnet committed
631
        for ( k = 0 ; k < naq ; k++ )
Pedro Gonnet's avatar
Pedro Gonnet committed
632
            queues[k] = &e->queues[k];
Pedro Gonnet's avatar
Pedro Gonnet committed
633
634
    
        /* Set up the local list of active queues. */
Pedro Gonnet's avatar
Pedro Gonnet committed
635
        naq = e->nr_queues;
Pedro Gonnet's avatar
Pedro Gonnet committed
636
        for ( k = 0 ; k < naq ; k++ )
Pedro Gonnet's avatar
Pedro Gonnet committed
637
            queues[k] = &e->queues[k];
Pedro Gonnet's avatar
Pedro Gonnet committed
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    
        /* Loop while there are tasks... */
        while ( 1 ) {
        
            /* Remove any inactive queues. */
            for ( k = 0 ; k < naq ; k++ )
                if ( queues[k]->next == queues[k]->count ) {
                    naq -= 1;
                    queues[k] = queues[naq];
                    k -= 1;
                    }
            if ( naq == 0 )
                break;
        
            /* Get a task, how and from where depends on the policy. */
            TIMER_TIC
            t = NULL;
Pedro Gonnet's avatar
Pedro Gonnet committed
655
            if ( e->nr_queues == 1 ) {
656
                t = queue_gettask_old( &e->queues[0] , 1 , 0 );
Pedro Gonnet's avatar
Pedro Gonnet committed
657
                }
Pedro Gonnet's avatar
Pedro Gonnet committed
658
            else if ( e->policy & engine_policy_steal ) {
Pedro Gonnet's avatar
Pedro Gonnet committed
659
                if ( ( myq->next == myq->count ) ||
660
                     ( t = queue_gettask( myq , r->id , 0 , 0 ) ) == NULL ) {
Pedro Gonnet's avatar
Pedro Gonnet committed
661
                    TIMER_TIC2
662
                    qid = rand_r( &myseed ) % naq;
Pedro Gonnet's avatar
Pedro Gonnet committed
663
                    keep = ( e->policy & engine_policy_keep ) &&
Pedro Gonnet's avatar
Pedro Gonnet committed
664
665
666
667
668
                           ( myq->count <= myq->size-tpq );
                    if ( myq->next == myq->count )
                        COUNT(runner_counter_steal_empty);
                    else
                        COUNT(runner_counter_steal_stall);
669
                    t = queue_gettask( queues[qid] , r->id , 0 , keep );
Pedro Gonnet's avatar
Pedro Gonnet committed
670
671
                    if ( t != NULL && keep )
                        queue_insert( myq , t );
672
                    TIMER_TOC2(timer_steal);
Pedro Gonnet's avatar
Pedro Gonnet committed
673
674
                    }
                }
Pedro Gonnet's avatar
Pedro Gonnet committed
675
            else if ( e->policy & engine_policy_rand ) {
676
                qid = rand_r( &myseed ) % naq;
677
                t = queue_gettask( queues[qid] , r->id , e->policy & engine_policy_block , 0 );
Pedro Gonnet's avatar
Pedro Gonnet committed
678
679
                }
            else {
680
                t = queue_gettask( &e->queues[threadID] , r->id , e->policy & engine_policy_block , 0 );
Pedro Gonnet's avatar
Pedro Gonnet committed
681
                }
682
            TIMER_TOC(timer_getpair);
Pedro Gonnet's avatar
Pedro Gonnet committed
683
684
685
686
            
            /* Did I get anything? */
            if ( t == NULL ) {
                COUNT(runner_counter_stall);
687
688
689
690
                #ifdef TIMER
                    if ( !stalled )
                        stalled = getticks();
                #endif
Pedro Gonnet's avatar
Pedro Gonnet committed
691
692
693
694
                continue;
                }
            #ifdef TIMER
            else if ( stalled ) {
695
                timers_toc( timer_stalled , stalled );
Pedro Gonnet's avatar
Pedro Gonnet committed
696
                #ifdef TIMER_VERBOSE
Pedro Gonnet's avatar
Pedro Gonnet committed
697
                    printf( "runner_main[%02i]: stalled %.3f ms\n" , r->id , ((double)stalled) / CPU_TPS * 1000 );
Pedro Gonnet's avatar
Pedro Gonnet committed
698
699
700
701
702
703
704
705
706
707
708
709
                    fflush(stdout);
                #endif
                stalled = 0;
                }
            #endif
        
            /* Get the cells. */
            ci = t->ci;
            cj = t->cj;
            
            /* Different types of tasks... */
            switch ( t->type ) {
710
711
                case task_type_self:
                    if ( t->subtype == task_subtype_density )
712
                        runner_doself1_density( r , ci );
713
                    else if ( t->subtype == task_subtype_force )
714
                        runner_doself2_force( r , ci );
715
716
                    else
                        error( "Unknown task subtype." );
Pedro Gonnet's avatar
Pedro Gonnet committed
717
718
                    cell_unlocktree( ci );
                    break;
719
720
                case task_type_pair:
                    if ( t->subtype == task_subtype_density )
721
                        runner_dopair1_density( r , ci , cj );
722
                    else if ( t->subtype == task_subtype_force )
723
                        runner_dopair2_force( r , ci , cj );
724
725
                    else
                        error( "Unknown task subtype." );
Pedro Gonnet's avatar
Pedro Gonnet committed
726
727
728
                    cell_unlocktree( ci );
                    cell_unlocktree( cj );
                    break;
729
                case task_type_sort:
730
                    runner_dosort( r , ci , t->flags , 1 );
731
                    cell_unlocktree( ci );
Pedro Gonnet's avatar
Pedro Gonnet committed
732
                    break;
733
734
                case task_type_sub:
                    if ( t->subtype == task_subtype_density )
735
                        runner_dosub1_density( r , ci , cj , t->flags );
736
                    else if ( t->subtype == task_subtype_force )
737
                        runner_dosub2_force( r , ci , cj , t->flags );
738
739
                    else
                        error( "Unknown task subtype." );
Pedro Gonnet's avatar
Pedro Gonnet committed
740
741
742
743
                    cell_unlocktree( ci );
                    if ( cj != NULL )
                        cell_unlocktree( cj );
                    break;
744
                case task_type_ghost:
Pedro Gonnet's avatar
Pedro Gonnet committed
745
                    if ( ci->super == ci )
Pedro Gonnet's avatar
Pedro Gonnet committed
746
                        runner_doghost( r , ci );
747
                    break;
748
749
750
                case task_type_kick2:
                    runner_dokick2( r , ci );
                    break;
Pedro Gonnet's avatar
Pedro Gonnet committed
751
752
753
754
755
756
                default:
                    error( "Unknown task type." );
                }
                
            /* Resolve any dependencies. */
            for ( k = 0 ; k < t->nr_unlock_tasks ; k++ )
757
758
                if ( atomic_dec( &t->unlock_tasks[k]->wait ) == 0 )
                    error( "Task negative wait." );
Pedro Gonnet's avatar
Pedro Gonnet committed
759
760
761
762
763
764
        
            } /* main loop. */
            
    	/* Any leftover stalls? */    
        #ifdef TIMER
        if ( stalled ) {
765
            timers_toc( timer_stalled , stalled );
Pedro Gonnet's avatar
Pedro Gonnet committed
766
            #ifdef TIMER_VERBOSE
Pedro Gonnet's avatar
Pedro Gonnet committed
767
                printf( "runner_main[%02i]: stalled %.3f ms\n" , r->id , ((double)stalled) / CPU_TPS * 1000 );
Pedro Gonnet's avatar
Pedro Gonnet committed
768
769
770
771
772
773
774
775
776
777
778
779
780
781
                fflush(stdout);
            #endif
            stalled = 0;
            }
        #endif
            
        }
        
    /* Be kind, rewind. */
    return NULL;

    }