Statistiques
| Révision :

root / NBody / NBodyGL.py @ 169

Historique | Voir | Annoter | Télécharger (24,71 ko)

1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
"""
4
Demonstrateur OpenCL d'interaction NCorps
5

6
Emmanuel QUEMENER <emmanuel.quemener@ens-lyon.fr> CeCILLv2
7
"""
8
import getopt
9
import sys
10
import time
11
import numpy as np
12
import pyopencl as cl
13
import pyopencl.array as cl_array
14
from numpy.random import randint as nprnd
15
import string, sys
16
from OpenGL.GL import *
17
from OpenGL.GLUT import *
18

    
19
def DictionariesAPI():
20
    Marsaglia={'CONG':0,'SHR3':1,'MWC':2,'KISS':3}
21
    Computing={'FP32':0,'FP64':1}
22
    return(Marsaglia,Computing)
23

    
24

    
25

    
26

    
27

    
28

    
29

    
30

    
31

    
32

    
33

    
34

    
35

    
36

    
37

    
38

    
39

    
40

    
41

    
42

    
43

    
44

    
45

    
46

    
47

    
48

    
49

    
50

    
51

    
52

    
53

    
54

    
55

    
56

    
57

    
58

    
59

    
60

    
61

    
62

    
63

    
64

    
65

    
66

    
67

    
68

    
69

    
70

    
71

    
72

    
73

    
74

    
75

    
76

    
77

    
78

    
79

    
80

    
81

    
82

    
83

    
84

    
85

    
86

    
87
BlobOpenCL= """
88
#define TFP32 0
89
#define TFP64 1
90

91
#if TYPE == TFP32
92
#define MYFLOAT4 float4
93
#define MYFLOAT8 float8
94
#define MYFLOAT float
95
#define DISTANCE fast_distance
96
#else
97
#define MYFLOAT4 double4
98
#define MYFLOAT8 double8
99
#define MYFLOAT double
100
#define DISTANCE distance
101
#if defined(cl_khr_fp64)  // Khronos extension available?
102
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
103
#endif
104
#endif
105

106

107
#define znew  ((zmwc=36969*(zmwc&65535)+(zmwc>>16))<<16)
108
#define wnew  ((wmwc=18000*(wmwc&65535)+(wmwc>>16))&65535)
109
#define MWC   (znew+wnew)
110
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
111
#define CONG  (jcong=69069*jcong+1234567)
112
#define KISS  ((MWC^CONG)+SHR3)
113

114

115
#define MWCfp (MYFLOAT)(MWC * 2.3283064365386963e-10f)
116
#define KISSfp (MYFLOAT)(KISS * 2.3283064365386963e-10f)
117
#define SHR3fp (MYFLOAT)(SHR3 * 2.3283064365386963e-10f)
118
#define CONGfp (MYFLOAT)(CONG * 2.3283064365386963e-10f)
119

120
#define PI (MYFLOAT)3.141592653589793238462643197169399375105820974944592307816406286e0f
121

122
#define SMALL_NUM (MYFLOAT)1.e-9f
123

124
#define LENGTH 1.e0f
125

126
// Create my own Distance implementation: distance buggy on Oland AMD chipset
127

128
MYFLOAT MyDistance(MYFLOAT4 n,MYFLOAT4 m)
129
{
130
    private MYFLOAT x2,y2,z2;
131
    x2=n.s0-m.s0;
132
    x2*=x2;
133
    y2=n.s1-m.s1;
134
    y2*=y2;
135
    z2=n.s2-m.s2;
136
    z2*=z2;
137
    return(sqrt(x2+y2+z2));
138
}
139

140
MYFLOAT4 Interaction(MYFLOAT4 m,MYFLOAT4 n)
141
{
142
    private MYFLOAT r=MyDistance((MYFLOAT4)n,(MYFLOAT4)m);
143

144
    return(((MYFLOAT4)n-(MYFLOAT4)m)/(MYFLOAT)(r*r*r));
145
}
146

147
MYFLOAT PairPotential(MYFLOAT4 m,MYFLOAT4 n)
148
{
149
    return((MYFLOAT)(-1.e0f)/(DISTANCE(n,m)));
150

151
//    return((MYFLOAT)(-1.e0f)/(MyDistance(n,m)));
152
}
153

154
MYFLOAT AtomicPotential(__global MYFLOAT4* clDataX,int gid)
155
{
156
    private MYFLOAT potential=(MYFLOAT)0.e0f;
157
    private MYFLOAT4 x=clDataX[gid]; 
158
    
159
    for (int i=0;i<get_global_size(0);i++)
160
    {
161
        if (gid != i)
162
        potential+=PairPotential(x,clDataX[i]);
163
    }
164

165
    barrier(CLK_GLOBAL_MEM_FENCE);
166
    return(potential);
167
}
168

169
MYFLOAT AtomicPotentialCoM(__global MYFLOAT4* clDataX,__global MYFLOAT4* clCoM,int gid)
170
{
171
    return(PairPotential(clDataX[gid],clCoM[0]));
172
}
173

174
// Elements from : http://doswa.com/2009/01/02/fourth-order-runge-kutta-numerical-integration.html
175

176
MYFLOAT8 AtomicRungeKutta(__global MYFLOAT4* clDataInX,__global MYFLOAT4* clDataInV,int gid,MYFLOAT dt)
177
{
178
    private MYFLOAT4 a0,v0,x0,a1,v1,x1,a2,v2,x2,a3,v3,x3,a4,v4,x4,xf,vf;
179
    MYFLOAT4 DT=dt*(MYFLOAT4)(1.e0f,1.e0f,1.e0f,1.e0f);
180

181
    a0=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
182
    v0=(MYFLOAT4)clDataInV[gid];
183
    x0=(MYFLOAT4)clDataInX[gid];
184
    int N = get_global_size(0);    
185
    
186
    for (private int i=0;i<N;i++)
187
    {
188
        if (gid != i)
189
        a0+=Interaction(x0,clDataInX[i]);
190
    }
191
        
192
    a1=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
193
    v1=a0*dt+v0;
194
    x1=v0*dt+x0;
195
    for (private int j=0;j<N;j++)
196
    {
197
        if (gid != j)
198
        a1+=Interaction(x1,clDataInX[j]);
199
    }
200

201
    a2=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
202
    v2=a1*(MYFLOAT)(dt/2.e0f)+v0;
203
    x2=v1*(MYFLOAT)(dt/2.e0f)+x0;
204
    for (private int k=0;k<N;k++)
205
    {
206
        if (gid != k)
207
        a2+=Interaction(x2,clDataInX[k]);
208
    }
209
    
210
    a3=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
211
    v3=a2*(MYFLOAT)(dt/2.e0f)+v0;
212
    x3=v2*(MYFLOAT)(dt/2.e0f)+x0;
213
    for (private int l=0;l<N;l++)
214
    {
215
        if (gid != l)
216
        a3+=Interaction(x3,clDataInX[l]);
217
    }
218
    
219
    a4=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
220
    v4=a3*dt+v0;
221
    x4=v3*dt+x0;
222
    for (private int m=0;m<N;m++)
223
    {
224
        if (gid != m)
225
        a4+=Interaction(x4,clDataInX[m]);
226
    }
227
    
228
    xf=x0+dt*(v1+(MYFLOAT)2.e0f*(v2+v3)+v4)/(MYFLOAT)6.e0f;
229
    vf=v0+dt*(a1+(MYFLOAT)2.e0f*(a2+a3)+a4)/(MYFLOAT)6.e0f;
230
     
231
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
232
}
233

234
MYFLOAT8 AtomicHeun(__global MYFLOAT4* clDataInX,__global MYFLOAT4* clDataInV,int gid,MYFLOAT dt)
235
{
236
    private MYFLOAT4 x0,v0,a0,x1,v1,a1,xf,vf;
237
    MYFLOAT4 Dt=dt*(MYFLOAT4)(1.e0f,1.e0f,1.e0f,1.e0f);
238

239
    x0=(MYFLOAT4)clDataInX[gid];
240
    v0=(MYFLOAT4)clDataInV[gid];
241
    a0=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
242

243
    for (private int i=0;i<get_global_size(0);i++)
244
    {
245
        if (gid != i)
246
        a0+=Interaction(x0,clDataInX[i]);
247
    }
248

249
    a1=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
250
    //v1=v0+dt*a0;
251
    //x1=x0+dt*v0;
252
    v1=dt*a0+v0;
253
    x1=dt*v0+x0;
254

255
    for (private int j=0;j<get_global_size(0);j++)
256
    {
257
        if (gid != j)
258
        a1+=Interaction(x1,clDataInX[j]);
259
    }
260

261
    vf=v0+dt*(a0+a1)/(MYFLOAT)2.e0f;
262
    xf=x0+dt*(v0+v1)/(MYFLOAT)2.e0f;
263

264
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
265
}
266

267
MYFLOAT8 AtomicImplicitEuler(__global MYFLOAT4* clDataInX,__global MYFLOAT4* clDataInV,int gid,MYFLOAT dt)
268
{
269
    MYFLOAT4 x0,v0,a,xf,vf;
270

271
    x0=(MYFLOAT4)clDataInX[gid];
272
    v0=(MYFLOAT4)clDataInV[gid];
273
    a=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
274

275
    for (private int i=0;i<get_global_size(0);i++)
276
    {
277
        if (gid != i)
278
          a+=Interaction(x0,clDataInX[i]);
279
    }
280
       
281
    vf=v0+dt*a;
282
    xf=x0+dt*vf;
283

284
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
285
}
286

287
MYFLOAT8 AtomicExplicitEuler(__global MYFLOAT4* clDataInX,__global MYFLOAT4* clDataInV,int gid,MYFLOAT dt)
288
{
289
    MYFLOAT4 x0,v0,a,xf,vf;
290

291
    x0=(MYFLOAT4)clDataInX[gid];
292
    v0=(MYFLOAT4)clDataInV[gid];
293
    a=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
294

295
    for (private int i=0;i<get_global_size(0);i++)
296
    {
297
        if (gid != i)
298
        a+=Interaction(x0,clDataInX[i]);
299
    }
300
       
301
    vf=v0+dt*a;
302
    xf=x0+dt*v0;
303
 
304
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
305
}
306

307
__kernel void InBallSplutterPoints(__global MYFLOAT4* clDataX, MYFLOAT radius, 
308
                             uint seed_z,uint seed_w)
309
{
310
    private int gid=get_global_id(0);
311
    private uint zmwc=seed_z+gid;
312
    private uint wmwc=seed_w+(gid+1)%2;
313
    private MYFLOAT Heat,Radius,Theta,Phi,PosX,PosY,PosZ,SinTheta;
314
 
315
    for (int i=0;i<gid;i++)
316
    {
317
        Heat=MWCfp;
318
    }
319

320
// More accurate distribution based on spherical coordonates
321
// Disactivated because of AMD Oland GPU crash on launch
322
//     Radius=MWCfp*radius;
323
//     Theta=(MYFLOAT)acos((float)(-2.e0f*MWCfp+1.0e0f));
324
//     Phi=(MYFLOAT)(2.e0f*PI*MWCfp);
325
//     SinTheta=sin((float)Theta);
326
//     PosX=cos((float)Phi)*Radius*SinTheta;
327
//     PosY=sin((float)Phi)*Radius*SinTheta;
328
//     PosZ=cos((float)Theta)*Radius;
329
//     clDataX[gid]=(MYFLOAT4)(PosX,PosY,PosZ,0.e0f);
330

331
    MYFLOAT4 Position=(MYFLOAT4)((MWCfp-0.5e0f)*radius,(MWCfp-0.5e0f)*radius,(MWCfp-0.5e0f)*radius,0.e0f);
332
    MYFLOAT Length=(MYFLOAT)length((MYFLOAT4)Position);
333
    clDataX[gid]=Position/Length*fmod(radius,Length);    
334

335
    barrier(CLK_GLOBAL_MEM_FENCE);
336
}
337

338
__kernel void InBoxSplutterPoints(__global MYFLOAT4* clDataX, MYFLOAT box, 
339
                             uint seed_z,uint seed_w)
340
{
341
    int gid=get_global_id(0);
342
    uint zmwc=seed_z+gid;
343
    uint wmwc=seed_w-gid;
344
    private MYFLOAT Heat;
345
 
346
    for (int i=0;i<gid;i++)
347
    {
348
        Heat=MWCfp;
349
    }
350

351
    clDataX[gid]=(MYFLOAT4)((MWCfp-0.5e0f)*box,(MWCfp-0.5e0f)*box,(MWCfp-0.5e0f)*box,0.e0f);
352

353
    barrier(CLK_GLOBAL_MEM_FENCE);
354
}
355

356
__kernel void SplutterStress(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,__global MYFLOAT4* clCoM, MYFLOAT velocity,uint seed_z,uint seed_w)
357
{
358
    int gid = get_global_id(0);
359
    MYFLOAT N = (MYFLOAT)get_global_size(0);
360
    uint zmwc=seed_z+(uint)gid;
361
    uint wmwc=seed_w-(uint)gid;
362
    MYFLOAT4 SpeedVector;
363

364
    if (velocity<SMALL_NUM) {
365
       SpeedVector=(MYFLOAT4)normalize(cross(clDataX[gid],clCoM[0]))*sqrt((-AtomicPotential(clDataX,gid)/(MYFLOAT)2.e0f));
366
    }
367
    else
368
    {    
369
       // cast to float for sin,cos are NEEDED by Mesa FP64 implementation!
370
       // Implemention on AMD Oland are probably broken in float
371

372
       MYFLOAT theta=acos((float)(1.0e0f-2.e0f*MWCfp));
373
       MYFLOAT phi=MWCfp*PI*(MYFLOAT)2.e0f;
374
       MYFLOAT sinTheta=sin((float)theta);
375
       MYFLOAT sinPhi=sin((float)phi);
376

377
       SpeedVector=(MYFLOAT4)((MWCfp-0.5e0f)*velocity,(MWCfp-0.5e0f)*velocity,
378
                              (MWCfp-0.5e0f)*velocity,0.e0f);
379
    }
380
    clDataV[gid]=SpeedVector;
381
    barrier(CLK_GLOBAL_MEM_FENCE);
382
}
383

384
__kernel void RungeKutta(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,MYFLOAT h)
385
{
386
    private int gid = get_global_id(0);
387
    private MYFLOAT8 clDataGid;
388
    
389
    clDataGid=AtomicRungeKutta(clDataX,clDataV,gid,h);
390
    barrier(CLK_GLOBAL_MEM_FENCE);
391
    clDataX[gid]=clDataGid.s0123;
392
    clDataV[gid]=clDataGid.s4567;
393
}
394

395
__kernel void Heun(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,MYFLOAT h)
396
{
397
    private int gid = get_global_id(0);
398
    private MYFLOAT8 clDataGid;
399
    
400
    clDataGid=AtomicHeun(clDataX,clDataV,gid,h);
401
    barrier(CLK_GLOBAL_MEM_FENCE);
402
    clDataX[gid]=clDataGid.s0123;
403
    clDataV[gid]=clDataGid.s4567;
404
}
405

406
__kernel void ImplicitEuler(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,MYFLOAT h)
407
{
408
    private int gid = get_global_id(0);
409
    private MYFLOAT8 clDataGid;
410
    
411
    clDataGid=AtomicImplicitEuler(clDataX,clDataV,gid,h);
412
    barrier(CLK_GLOBAL_MEM_FENCE);
413
    clDataX[gid]=clDataGid.s0123;
414
    clDataV[gid]=clDataGid.s4567;
415
}
416

417
__kernel void ExplicitEuler(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,MYFLOAT h)
418
{
419
    private int gid = get_global_id(0);
420
    private MYFLOAT8 clDataGid;    
421

422
    clDataGid=AtomicExplicitEuler(clDataX,clDataV,gid,h);
423
    barrier(CLK_GLOBAL_MEM_FENCE);
424
    clDataX[gid]=clDataGid.s0123;
425
    clDataV[gid]=clDataGid.s4567;
426
}
427

428
__kernel void CoMPotential(__global MYFLOAT4* clDataX,__global MYFLOAT4* clCoM,__global MYFLOAT* clPotential)
429
{
430
    int gid = get_global_id(0);
431

432
    clPotential[gid]=PairPotential(clDataX[gid],clCoM[0]);
433
}
434

435
__kernel void Potential(__global MYFLOAT4* clDataX,__global MYFLOAT* clPotential)
436
{
437
    int gid = get_global_id(0);
438

439
    MYFLOAT potential=(MYFLOAT)0.e0f;
440
    MYFLOAT4 x=clDataX[gid]; 
441
    
442
    for (int i=0;i<get_global_size(0);i++)
443
    {
444
        if (gid != i)
445
        potential+=PairPotential(x,clDataX[i]);
446
    }
447
                 
448
    barrier(CLK_GLOBAL_MEM_FENCE);
449
    clPotential[gid]=potential*(MYFLOAT)5.e-1f;
450
}
451

452
__kernel void CenterOfMass(__global MYFLOAT4* clDataX,__global MYFLOAT4* clCoM,int Size)
453
{
454
    MYFLOAT4 CoM=clDataX[0]; 
455

456
    for (int i=1;i<Size;i++)
457
    {
458
        CoM+=clDataX[i];
459
    }
460

461
    barrier(CLK_GLOBAL_MEM_FENCE);
462
    clCoM[0]=(MYFLOAT4)(CoM.s0,CoM.s1,CoM.s2,0.e0f)/(MYFLOAT)Size;
463
}
464

465
__kernel void Kinetic(__global MYFLOAT4* clDataV,__global MYFLOAT* clKinetic)
466
{
467
    int gid = get_global_id(0);
468
    
469
    barrier(CLK_GLOBAL_MEM_FENCE);
470
    MYFLOAT d=(MYFLOAT)length(clDataV[gid]);
471
    clKinetic[gid]=(MYFLOAT)5.e-1f*(MYFLOAT)(d*d);
472
}
473

474
"""
475

    
476
def MainOpenCL(clDataX,clDataV,Step,Method):
477
    time_start=time.time()
478
    if Method=="RungeKutta":
479
        CLLaunch=MyRoutines.RungeKutta(queue,(Number,1),None,clDataX,clDataV,Step)
480
    elif Method=="ExplicitEuler":
481
        CLLaunch=MyRoutines.ExplicitEuler(queue,(Number,1),None,clDataX,clDataV,Step)
482
    elif Method=="Heun":
483
        CLLaunch=MyRoutines.Heun(queue,(Number,1),None,clDataX,clDataV,Step)
484
    else:
485
        CLLaunch=MyRoutines.ImplicitEuler(queue,(Number,1),None,clDataX,clDataV,Step)
486
    CLLaunch.wait()
487
    Elapsed=time.time()-time_start
488
    return(Elapsed)
489
    
490
def display(*args):
491

    
492
    global MyDataX,MyDataV,clDataX,clDataV,Step,Method,Number,Iterations,Durations,Verbose,SpeedRendering
493
    
494
    glClearColor(0.0, 0.0, 0.0, 0.0)
495
    glClear(GL_COLOR_BUFFER_BIT)
496
    glColor3f(1.0,1.0,1.0)
497
    
498
    Elapsed=MainOpenCL(clDataX,clDataV,Step,Method)
499
    if SpeedRendering:
500
        cl.enqueue_copy(queue, MyDataV, clDataV)
501
        MyDataV.reshape(Number,4)[:,3]=1
502
        glVertexPointerf(MyDataV.reshape(Number,4))
503
    else:
504
        cl.enqueue_copy(queue, MyDataX, clDataX)
505
        MyDataX.reshape(Number,4)[:,3]=1
506
        glVertexPointerf(MyDataX.reshape(Number,4))
507

    
508
    if Verbose:
509
        print("Duration of #%s iteration: %s" % (Iterations,Elapsed))
510
    else:
511
        sys.stdout.write('.')
512
        sys.stdout.flush()
513
    Durations=np.append(Durations,MainOpenCL(clDataX,clDataV,Step,Method))    
514
    glEnableClientState(GL_VERTEX_ARRAY)
515
    glDrawArrays(GL_POINTS, 0, Number)
516
    glDisableClientState(GL_VERTEX_ARRAY)
517
    glFlush()
518
    Iterations+=1
519
    glutSwapBuffers()
520

    
521
def halt():
522
    pass
523

    
524
def keyboard(k,x,y):
525
    global ViewRZ,SizeOfBox,SpeedRendering
526
    LC_Z = as_8_bit( 'z' )
527
    UC_Z = as_8_bit( 'Z' )
528
    Plus = as_8_bit( '+' )
529
    Minus = as_8_bit( '-' )
530
    Switch = as_8_bit( 's' )
531

    
532
    Zoom=1
533
    if k == LC_Z:
534
        ViewRZ += 1.0
535
    elif k == UC_Z:
536
        ViewRZ -= 1.0
537
    elif k == Plus:
538
        Zoom *= 2.0
539
    elif k == Minus:
540
        Zoom /= 2.0
541
    elif k == Switch:
542
        if SpeedRendering:
543
            SpeedRendering=False
544
        else:
545
            SpeedRendering=True
546
    elif ord(k) == 27: # Escape
547
        glutLeaveMainLoop()
548
        return(False)
549
    else:
550
        return
551
    glRotatef(ViewRZ, 0.0, 0.0, 1.0)
552
    glScalef(Zoom,Zoom,Zoom)
553
    glutPostRedisplay()
554

    
555
def special(k,x,y):
556
    global ViewRX, ViewRY, ViewRZ
557

    
558
    if k == GLUT_KEY_UP:
559
        ViewRX += 1.0
560
    elif k == GLUT_KEY_DOWN:
561
        ViewRX -= 1.0
562
    elif k == GLUT_KEY_LEFT:
563
        ViewRY += 1.0
564
    elif k == GLUT_KEY_RIGHT:
565
        ViewRY -= 1.0
566
    else:
567
        return
568
    glRotatef(ViewRX, 1.0, 0.0, 0.0)
569
    glRotatef(ViewRY, 0.0, 1.0, 0.0)
570
    glutPostRedisplay()
571

    
572
def setup_viewport():
573
    global SizeOfBox
574
    glMatrixMode(GL_PROJECTION)
575
    glLoadIdentity()
576
    glOrtho(-SizeOfBox, SizeOfBox, -SizeOfBox, SizeOfBox, -SizeOfBox, SizeOfBox)
577
    glutPostRedisplay()
578
    
579
def reshape(w, h):
580
    glViewport(0, 0, w, h)
581
    setup_viewport()
582

    
583
if __name__=='__main__':
584

    
585
    global Number,Step,clDataX,clDataV,MyDataX,MyDataV,Method,SizeOfBox,Iterations,Verbose,Durations
586
    
587
    # ValueType
588
    ValueType='FP32'
589
    class MyFloat(np.float32):pass
590
    #    clType8=cl_array.vec.float8
591
    # Set defaults values
592
    np.set_printoptions(precision=2)  
593
    # Id of Device : 1 is for first find !
594
    Device=0
595
    # Number of bodies is integer
596
    Number=2
597
    # Number of iterations (for standalone execution)
598
    Iterations=100
599
    # Size of shape
600
    SizeOfShape=MyFloat(1.)
601
    # Initial velocity of particules
602
    Velocity=MyFloat(1.)
603
    # Step
604
    Step=MyFloat(1./32)
605
    # Method of integration
606
    Method='ImplicitEuler'
607
    # InitialRandom
608
    InitialRandom=False
609
    # RNG Marsaglia Method
610
    RNG='MWC'
611
    # Viriel Distribution of stress
612
    VirielStress=True
613
    # Verbose
614
    Verbose=False
615
    # OpenGL real time rendering
616
    OpenGL=False
617
    # Speed rendering
618
    SpeedRendering=False
619
    # Shape to distribute
620
    Shape='Box'
621
    
622
    HowToUse='%s -h [Help] -r [InitialRandom] -g [OpenGL] -e [VirielStress] -d <DeviceId> -p [SpeedRendering] -n <NumberOfParticules> -i <Iterations> -z <SizeOfBoxOrBall> -v <Velocity> -s <Step> -b <Ball|Box> -m <ImplicitEuler|RungeKutta|ExplicitEuler|Heun> -t <FP32|FP64>'
623

    
624
    try:
625
        opts, args = getopt.getopt(sys.argv[1:],"rpgehd:n:i:z:v:s:m:t:b:",["random","rendering","opengl","viriel","device=","number=","iterations=","size=","velocity=","step=","method=","valuetype=","shape="])
626
    except getopt.GetoptError:
627
        print(HowToUse % sys.argv[0])
628
        sys.exit(2)
629

    
630
    for opt, arg in opts:
631
        if opt == '-h':
632
            print(HowToUse % sys.argv[0])
633

    
634
            print("\nInformations about devices detected under OpenCL:")
635
            try:
636
                Id=0
637
                for platform in cl.get_platforms():
638
                    for device in platform.get_devices():
639
                        # Failed now because of POCL implementation
640
                        #deviceType=cl.device_type.to_string(device.type)
641
                        deviceType="xPU"
642
                        print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip(),deviceType,device.name.lstrip()))
643
                        Id=Id+1
644
                sys.exit()
645
            except ImportError:
646
                print("Your platform does not seem to support OpenCL")
647
                sys.exit()
648

    
649
        elif opt in ("-t", "--valuetype"):
650
            if arg=='FP64':
651
                class MyFloat(np.float64): pass
652
            else:
653
                class MyFloat(np.float32):pass
654
            ValueType = arg
655
        elif opt in ("-d", "--device"):
656
            Device=int(arg)
657
        elif opt in ("-m", "--method"):
658
            Method=arg
659
        elif opt in ("-b", "--shape"):
660
            Shape=arg
661
        elif opt in ("-n", "--number"):
662
            Number=int(arg)
663
        elif opt in ("-i", "--iterations"):
664
            Iterations=int(arg)
665
        elif opt in ("-z", "--size"):
666
            SizeOfShape=MyFloat(arg)
667
        elif opt in ("-v", "--velocity"):
668
            Velocity=MyFloat(arg)
669
            VirielStress=False
670
        elif opt in ("-s", "--step"):
671
            Step=MyFloat(arg)
672
        elif opt in ("-r", "--random"):
673
            InitialRandom=True
674
        elif opt in ("-c", "--check"):
675
            CheckEnergies=True
676
        elif opt in ("-e", "--viriel"):
677
            VirielStress=True
678
        elif opt in ("-g", "--opengl"):
679
            OpenGL=True
680
        elif opt in ("-p", "--rendering"):
681
            SpeedRendering=True
682
                        
683
    SizeOfShape=MyFloat(SizeOfShape*Number)
684
    Velocity=MyFloat(Velocity)
685
    Step=MyFloat(Step)
686
                
687
    print("Device choosed : %s" % Device)
688
    print("Number of particules : %s" % Number)
689
    print("Size of Shape : %s" % SizeOfShape)
690
    print("Initial velocity : %s" % Velocity)
691
    print("Step of iteration : %s" % Step)
692
    print("Number of iterations : %s" % Iterations)
693
    print("Method of resolution : %s" % Method)
694
    print("Initial Random for RNG Seed : %s" % InitialRandom)
695
    print("ValueType is : %s" % ValueType)
696
    print("Viriel distribution of stress : %s" % VirielStress)
697
    print("OpenGL real time rendering : %s" % OpenGL)
698
    print("Speed rendering : %s" % SpeedRendering)
699

    
700
    # Create Numpy array of CL vector with 8 FP32    
701
    MyCoM = np.zeros(4,dtype=MyFloat)
702
    MyDataX = np.zeros(Number*4, dtype=MyFloat)
703
    MyDataV = np.zeros(Number*4, dtype=MyFloat)
704
    MyPotential = np.zeros(Number, dtype=MyFloat)
705
    MyKinetic = np.zeros(Number, dtype=MyFloat)
706

    
707
    Marsaglia,Computing=DictionariesAPI()
708

    
709
    # Scan the OpenCL arrays
710
    Id=0
711
    HasXPU=False
712
    for platform in cl.get_platforms():
713
        for device in platform.get_devices():
714
            if Id==Device:
715
                PlatForm=platform
716
                XPU=device
717
                print("CPU/GPU selected: ",device.name.lstrip())
718
                print("Platform selected: ",platform.name)
719
                HasXPU=True
720
            Id+=1
721

    
722
    if HasXPU==False:
723
        print("No XPU #%i found in all of %i devices, sorry..." % (Device,Id-1))
724
        sys.exit()      
725

    
726
    # Create Context
727
    try:
728
        ctx = cl.Context([XPU])
729
        queue = cl.CommandQueue(ctx,properties=cl.command_queue_properties.PROFILING_ENABLE)
730
    except:
731
        print("Crash during context creation")
732

    
733
    # Build all routines used for the computing
734

    
735
    #BuildOptions="-cl-mad-enable -cl-kernel-arg-info -cl-fast-relaxed-math -cl-std=CL1.2 -DTRNG=%i -DTYPE=%i" % (Marsaglia[RNG],Computing[ValueType])
736
    BuildOptions="-cl-mad-enable -cl-fast-relaxed-math -DTRNG=%i -DTYPE=%i" % (Marsaglia[RNG],Computing[ValueType])
737

    
738
    if 'Intel' in PlatForm.name or 'Experimental' in PlatForm.name or 'Clover' in PlatForm.name or 'Portable' in PlatForm.name :
739
        MyRoutines = cl.Program(ctx, BlobOpenCL).build(options = BuildOptions)
740
    else:
741
        MyRoutines = cl.Program(ctx, BlobOpenCL).build(options = BuildOptions+" -cl-strict-aliasing")
742
        
743
    mf = cl.mem_flags
744
    # Read/Write approach for buffering
745
    clDataX = cl.Buffer(ctx, mf.READ_WRITE, MyDataX.nbytes)
746
    clDataV = cl.Buffer(ctx, mf.READ_WRITE, MyDataV.nbytes)
747
    clPotential = cl.Buffer(ctx, mf.READ_WRITE, MyPotential.nbytes)
748
    clKinetic = cl.Buffer(ctx, mf.READ_WRITE, MyKinetic.nbytes)
749
    clCoM = cl.Buffer(ctx, mf.READ_WRITE, MyCoM.nbytes)
750
    
751
    # Write/HostPointer approach for buffering
752
    # clDataX = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyDataX)
753
    # clDataV = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyDataV)
754
    # clPotential = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyPotential)
755
    # clKinetic = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyKinetic)
756
    # clCoM = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyCoM)
757

    
758
    print('All particles superimposed.')
759

    
760
    # Set particles to RNG points
761
    if InitialRandom:
762
        seed_w=np.uint32(nprnd(2**32))
763
        seed_z=np.uint32(nprnd(2**32))
764
    else:
765
        seed_w=np.uint32(19710211)
766
        seed_z=np.uint32(20081010)
767
            
768
    if Shape=='Ball':
769
        MyRoutines.InBallSplutterPoints(queue,(Number,1),None,clDataX,SizeOfShape,seed_w,seed_z)
770
    else:
771
        MyRoutines.InBoxSplutterPoints(queue,(Number,1),None,clDataX,SizeOfShape,seed_w,seed_z)
772

    
773
    print('All particules distributed')
774

    
775
    CLLaunch=MyRoutines.CenterOfMass(queue,(1,1),None,clDataX,clCoM,np.int32(Number))
776
    CLLaunch.wait()
777
    cl.enqueue_copy(queue,MyCoM,clCoM)
778
    print('Center Of Mass estimated: (%s,%s,%s)' % (MyCoM[0],MyCoM[1],MyCoM[2]))
779
    
780
    if VirielStress:
781
        CLLaunch=MyRoutines.SplutterStress(queue,(Number,1),None,clDataX,clDataV,clCoM,MyFloat(0.),np.uint32(110271),np.uint32(250173))
782
    else:
783
        CLLaunch=MyRoutines.SplutterStress(queue,(Number,1),None,clDataX,clDataV,clCoM,Velocity,np.uint32(110271),np.uint32(250173))
784
    CLLaunch.wait()
785

    
786
    print('All particules stressed')
787

    
788
    CLLaunch=MyRoutines.Potential(queue,(Number,1),None,clDataX,clPotential)
789
    CLLaunch=MyRoutines.Kinetic(queue,(Number,1),None,clDataV,clKinetic)
790
    CLLaunch.wait()
791
    cl.enqueue_copy(queue,MyPotential,clPotential)
792
    cl.enqueue_copy(queue,MyKinetic,clKinetic)
793
    print('Energy estimated: Viriel=%s Potential=%s Kinetic=%s\n'% (np.sum(MyPotential)+2*np.sum(MyKinetic),np.sum(MyPotential),np.sum(MyKinetic)))
794

    
795
    if SpeedRendering:
796
        SizeOfBox=max(2*MyKinetic)
797
    else:
798
        SizeOfBox=SizeOfShape        
799
    
800
    wall_time_start=time.time()
801

    
802
    Durations=np.array([],dtype=MyFloat)
803
    print('Starting!')
804
    if OpenGL:
805
        global SizeOfBox,ViewRX,ViewRY,ViewRZ
806
        Iterations=0
807
        ViewRX,ViewRY,ViewRZ = 0.,0.,0.
808
        # Launch OpenGL Loop
809
        glutInit(sys.argv)
810
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
811
        glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,GLUT_ACTION_CONTINUE_EXECUTION)
812
        glutInitWindowSize(512,512)
813
        glutCreateWindow(b'NBodyGL')
814
        setup_viewport()
815
        glutReshapeFunc(reshape)
816
        glutDisplayFunc(display)
817
        glutIdleFunc(display)
818
        #   glutMouseFunc(mouse)
819
        glutSpecialFunc(special)
820
        glutKeyboardFunc(keyboard)
821
        glutMainLoop()
822
    else:
823
        for iteration in range(Iterations):
824
            Elapsed=MainOpenCL(clDataX,clDataV,Step,Method)
825
            if Verbose:
826
                print("Duration of #%s iteration: %s" % (Iterations,Elapsed))
827
            else:
828
                sys.stdout.write('.')
829
                sys.stdout.flush()
830
            Durations=np.append(Durations,Elapsed)
831

    
832
    print('\nEnding!')
833
            
834
    MyRoutines.CenterOfMass(queue,(1,1),None,clDataX,clCoM,np.int32(Number))
835
    CLLaunch=MyRoutines.Potential(queue,(Number,1),None,clDataX,clPotential)
836
    CLLaunch=MyRoutines.Kinetic(queue,(Number,1),None,clDataV,clKinetic)
837
    CLLaunch.wait()
838
    cl.enqueue_copy(queue,MyCoM,clCoM)
839
    cl.enqueue_copy(queue,MyPotential,clPotential)
840
    cl.enqueue_copy(queue,MyKinetic,clKinetic)
841
    print('\nCenter Of Mass estimated: (%s,%s,%s)' % (MyCoM[0],MyCoM[1],MyCoM[2]))
842
    print('Energy estimated: Viriel=%s Potential=%s Kinetic=%s\n'% (np.sum(MyPotential)+2.*np.sum(MyKinetic),np.sum(MyPotential),np.sum(MyKinetic)))
843

    
844
    print("Duration stats on device %s with %s iterations :\n\tMean:\t%s\n\tMedian:\t%s\n\tStddev:\t%s\n\tMin:\t%s\n\tMax:\t%s\n\n\tVariability:\t%s\n" % (Device,Iterations,np.mean(Durations),np.median(Durations),np.std(Durations),np.min(Durations),np.max(Durations),np.std(Durations)/np.median(Durations)))
845

    
846
    # Contraction of Square*Size*Hertz: Size*Size/Elapsed
847
    Squertz=np.ones(len(Durations))
848
    Squertz*=Number*Number
849
    Squertz/=Durations
850

    
851
    print("Squertz in log10 stats on device %s with %s iterations :\n\tMean:\t%s\n\tMedian:\t%s\n\tStddev:\t%s\n\tMin:\t%s\n\tMax:\t%s\n" % (Device,Iterations,np.log10(np.mean(Squertz)),np.log10(np.median(Squertz)),np.log10(np.std(Squertz)),np.log10(np.min(Squertz)),np.log10(np.max(Squertz))))
852
        
853
    clDataX.release()
854
    clDataV.release()
855
    clKinetic.release()
856
    clPotential.release()
857