Révision 170

NBody/NBody.py (revision 170)
12 12
import pyopencl as cl
13 13
import pyopencl.array as cl_array
14 14
from numpy.random import randint as nprnd
15
import string, sys
16
from OpenGL.GL import *
17
from OpenGL.GLUT import *
15 18

  
16 19
def DictionariesAPI():
17 20
    Marsaglia={'CONG':0,'SHR3':1,'MWC':2,'KISS':3}
18 21
    Computing={'FP32':0,'FP64':1}
19
    return(Marsaglia,Computing)
22
    Interaction={'Force':0,'Potential':1}
23
    return(Marsaglia,Computing,Interaction)
20 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

  
21 88
BlobOpenCL= """
22
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
23
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
24
#define MWC   (znew+wnew)
25
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
26
#define CONG  (jcong=69069*jcong+1234567)
27
#define KISS  ((MWC^CONG)+SHR3)
28

  
29 89
#define TFP32 0
30 90
#define TFP64 1
31 91

  
32
#define LENGTH 1.e0f
92
#define TFORCE 0
93
#define TPOTENTIAL 1
33 94

  
34 95
#if TYPE == TFP32
35 96
#define MYFLOAT4 float4
......
37 98
#define MYFLOAT float
38 99
#define DISTANCE fast_distance
39 100
#else
40
#if defined(cl_khr_fp64)  // Khronos extension available?
41
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
42
#define DOUBLE_SUPPORT_AVAILABLE
43
#elif defined(cl_amd_fp64)  // AMD extension available?
44
#pragma OPENCL EXTENSION cl_amd_fp64 : enable
45
#define DOUBLE_SUPPORT_AVAILABLE
46
#endif
47 101
#define MYFLOAT4 double4
48 102
#define MYFLOAT8 double8
49 103
#define MYFLOAT double
50 104
#define DISTANCE distance
105
#if defined(cl_khr_fp64)  // Khronos extension available?
106
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
51 107
#endif
108
#endif
52 109

  
110

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

  
118

  
53 119
#define MWCfp (MYFLOAT)(MWC * 2.3283064365386963e-10f)
54 120
#define KISSfp (MYFLOAT)(KISS * 2.3283064365386963e-10f)
55 121
#define SHR3fp (MYFLOAT)(SHR3 * 2.3283064365386963e-10f)
......
57 123

  
58 124
#define PI (MYFLOAT)3.141592653589793238462643197169399375105820974944592307816406286e0f
59 125

  
60
#define SMALL_NUM 1.e-9f
126
#define SMALL_NUM (MYFLOAT)1.e-9f
61 127

  
62
MYFLOAT4 Interaction(MYFLOAT4 m,MYFLOAT4 n)
63
{
64
    private MYFLOAT r=DISTANCE(n,m);
128
#define LENGTH 1.e0f
65 129

  
66
    return((n-m)/(MYFLOAT)(r*r*r));
67
}
130
// Create my own Distance implementation: distance buggy on Oland AMD chipset
68 131

  
69
MYFLOAT4 InteractionCore(MYFLOAT4 m,MYFLOAT4 n)
132
MYFLOAT MyDistance(MYFLOAT4 n,MYFLOAT4 m)
70 133
{
71
    private MYFLOAT core=(MYFLOAT)1.e5f;
72
    private MYFLOAT r=DISTANCE(n,m);
73
    private MYFLOAT d=r*r+core*core;
74

  
75
    return(core*(n-m)/(MYFLOAT)(d*d));
134
    private MYFLOAT x2,y2,z2;
135
    x2=n.s0-m.s0;
136
    x2*=x2;
137
    y2=n.s1-m.s1;
138
    y2*=y2;
139
    z2=n.s2-m.s2;
140
    z2*=z2;
141
    return(sqrt(x2+y2+z2));
76 142
}
77 143

  
144
// Interaction to avoid artevasion of bodies : 1-e^-x*x is x*x near 0
145

  
146
//MYFLOAT4 InteractionCore(MYFLOAT4 m,MYFLOAT4 n)
147
//{
148
//    private MYFLOAT r=MyDistance((MYFLOAT4)n,(MYFLOAT4)m);
149
//    private MYFLOAT r2=r*r;
150
//    private MYFLOAT c=1.e0f/(MYFLOAT)get_global_size(0);
151

  
152
//    private MYFLOAT4 unity=normalize(n,m);
153

  
154
//    return(((MYFLOAT4)n-(MYFLOAT4)m)*(MYFLOAT)(1.e0f-exp(-c*r2))/(MYFLOAT)(r*r2));
155
//}
156

  
78 157
MYFLOAT PairPotential(MYFLOAT4 m,MYFLOAT4 n)
79 158
{
159

  
160
//    return((MYFLOAT)(-1.e0f)/(MyDistance(m,n)));
161

  
162
//    MYFLOAT r=DISTANCE(n,m);
163
//    return((-1.e0f+exp(-r))/r);
164

  
165

  
80 166
    return((MYFLOAT)(-1.e0f)/(DISTANCE(n,m)));
81 167
}
82 168

  
169
MYFLOAT4 Interaction(MYFLOAT4 m,MYFLOAT4 n)
170
#if INTERACTION == TFORCE
171
// Simplest implementation of force (equals to acceleration)
172
// seems to bo bad (numerous artevasions)
173
// MYFLOAT4 InteractionForce(MYFLOAT4 m,MYFLOAT4 n)
174
{
175
    private MYFLOAT r=MyDistance(n,m);
176
    return((n-m)/(MYFLOAT)(r*r*r));
177
}
178
#else
179
// Force definited as gradient of potential
180
// Estimate potential and proximate potential to estimate force
181
// MYFLOAT4 InteractionPotential(MYFLOAT4 m,MYFLOAT4 n)
182
{
183
    private MYFLOAT epsilon=(MYFLOAT)(1.e0f/1048576);
184
    private MYFLOAT4 er=normalize(n-m);
185
    private MYFLOAT4 dr=er*(MYFLOAT)epsilon;
186

  
187
    return(er*(PairPotential(m,n)-PairPotential(m+dr,n))/epsilon);
188
}
189
#endif
190

  
83 191
MYFLOAT AtomicPotential(__global MYFLOAT4* clDataX,int gid)
84 192
{
85 193
    private MYFLOAT potential=(MYFLOAT)0.e0f;
......
100 208
    return(PairPotential(clDataX[gid],clCoM[0]));
101 209
}
102 210

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

  
103 213
MYFLOAT8 AtomicRungeKutta(__global MYFLOAT4* clDataInX,__global MYFLOAT4* clDataInV,int gid,MYFLOAT dt)
104 214
{
105 215
    private MYFLOAT4 a0,v0,x0,a1,v1,x1,a2,v2,x2,a3,v3,x3,a4,v4,x4,xf,vf;
216
    MYFLOAT4 DT=dt*(MYFLOAT4)(1.e0f,1.e0f,1.e0f,1.e0f);
106 217

  
107 218
    a0=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
108 219
    v0=(MYFLOAT4)clDataInV[gid];
109 220
    x0=(MYFLOAT4)clDataInX[gid];
110 221
    int N = get_global_size(0);    
111 222
    
112
    for (int i=0;i<N;i++)
223
    for (private int i=0;i<N;i++)
113 224
    {
114 225
        if (gid != i)
115 226
        a0+=Interaction(x0,clDataInX[i]);
116 227
    }
117 228
        
118 229
    a1=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
119
    v1=v0+a0*dt;
120
    x1=x0+v0*dt;
121
    for (int i=0;i<N;i++)
230
    v1=a0*dt+v0;
231
    x1=v0*dt+x0;
232
    for (private int j=0;j<N;j++)
122 233
    {
123
        if (gid != i)
124
        a1+=Interaction(x1,clDataInX[i]);
234
        if (gid != j)
235
        a1+=Interaction(x1,clDataInX[j]);
125 236
    }
126 237

  
127 238
    a2=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
128
    v2=v0+a1*dt*(MYFLOAT)5.e-1f;
129
    x2=x0+v1*dt*(MYFLOAT)5.e-1f;
130
    for (int i=0;i<N;i++)
239
    v2=a1*(MYFLOAT)(dt/2.e0f)+v0;
240
    x2=v1*(MYFLOAT)(dt/2.e0f)+x0;
241
    for (private int k=0;k<N;k++)
131 242
    {
132
        if (gid != i)
133
        a2+=Interaction(x2,clDataInX[i]);
243
        if (gid != k)
244
        a2+=Interaction(x2,clDataInX[k]);
134 245
    }
135 246
    
136 247
    a3=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
137
    v3=v0+a2*dt*(MYFLOAT)5.e-1f;
138
    x3=x0+v2*dt*(MYFLOAT)5.e-1f;
139
    for (int i=0;i<N;i++)
248
    v3=a2*(MYFLOAT)(dt/2.e0f)+v0;
249
    x3=v2*(MYFLOAT)(dt/2.e0f)+x0;
250
    for (private int l=0;l<N;l++)
140 251
    {
141
        if (gid != i)
142
        a3+=Interaction(x3,clDataInX[i]);
252
        if (gid != l)
253
        a3+=Interaction(x3,clDataInX[l]);
143 254
    }
144 255
    
145 256
    a4=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
146
    v4=v0+a3*dt;
147
    x4=x0+v3*dt;
148
    for (int i=0;i<N;i++)
257
    v4=a3*dt+v0;
258
    x4=v3*dt+x0;
259
    for (private int m=0;m<N;m++)
149 260
    {
150
        if (gid != i)
151
        a4+=Interaction(x4,clDataInX[i]);
261
        if (gid != m)
262
        a4+=Interaction(x4,clDataInX[m]);
152 263
    }
153 264
    
154 265
    xf=x0+dt*(v1+(MYFLOAT)2.e0f*(v2+v3)+v4)/(MYFLOAT)6.e0f;
155 266
    vf=v0+dt*(a1+(MYFLOAT)2.e0f*(a2+a3)+a4)/(MYFLOAT)6.e0f;
156 267
     
157
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,1.e0f,vf.s0,vf.s1,vf.s2,1.e0f));
268
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
158 269
}
159 270

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

  
162 271
MYFLOAT8 AtomicHeun(__global MYFLOAT4* clDataInX,__global MYFLOAT4* clDataInV,int gid,MYFLOAT dt)
163 272
{
164
    private MYFLOAT4 x,v,a,xi,vi,ai,xf,vf;
273
    private MYFLOAT4 x0,v0,a0,x1,v1,a1,xf,vf;
274
    MYFLOAT4 Dt=dt*(MYFLOAT4)(1.e0f,1.e0f,1.e0f,1.e0f);
165 275

  
166
    x=(MYFLOAT4)clDataInX[gid];
167
    v=(MYFLOAT4)clDataInV[gid];
168
    a=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
276
    x0=(MYFLOAT4)clDataInX[gid];
277
    v0=(MYFLOAT4)clDataInV[gid];
278
    a0=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
169 279

  
170
    for (int i=0;i<get_global_size(0);i++)
280
    for (private int i=0;i<get_global_size(0);i++)
171 281
    {
172 282
        if (gid != i)
173
        a+=Interaction(x,clDataInX[i]);
283
        a0+=Interaction(x0,clDataInX[i]);
174 284
    }
175 285

  
176
    vi=v+dt*a;
177
    xi=x+dt*vi;
178
    ai=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
286
    a1=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
287
    //v1=v0+dt*a0;
288
    //x1=x0+dt*v0;
289
    v1=dt*a0+v0;
290
    x1=dt*v0+x0;
179 291

  
180
    for (int i=0;i<get_global_size(0);i++)
292
    for (private int j=0;j<get_global_size(0);j++)
181 293
    {
182
        if (gid != i)
183
        ai+=Interaction(xi,clDataInX[i]);
294
        if (gid != j)
295
        a1+=Interaction(x1,clDataInX[j]);
184 296
    }
185
       
186
    vf=v+dt*(a+ai)/(MYFLOAT)2.e0f;
187
    xf=x+dt*(v+vi)/(MYFLOAT)2.e0f;
188 297

  
189
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,1.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
298
    vf=v0+dt*(a0+a1)/(MYFLOAT)2.e0f;
299
    xf=x0+dt*(v0+v1)/(MYFLOAT)2.e0f;
300

  
301
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
190 302
}
191 303

  
192 304
MYFLOAT8 AtomicImplicitEuler(__global MYFLOAT4* clDataInX,__global MYFLOAT4* clDataInV,int gid,MYFLOAT dt)
193 305
{
194
    private MYFLOAT4 x,v,a,xf,vf;
306
    MYFLOAT4 x0,v0,a,xf,vf;
195 307

  
196
    x=(MYFLOAT4)clDataInX[gid];
197
    v=(MYFLOAT4)clDataInV[gid];
308
    x0=(MYFLOAT4)clDataInX[gid];
309
    v0=(MYFLOAT4)clDataInV[gid];
198 310
    a=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
199 311

  
200
    for (int i=0;i<get_global_size(0);i++)
312
    for (private int i=0;i<get_global_size(0);i++)
201 313
    {
202 314
        if (gid != i)
203
        a+=Interaction(x,clDataInX[i]);
315
          a+=Interaction(x0,clDataInX[i]);
204 316
    }
205 317
       
206
    vf=v+dt*a;
207
    xf=x+dt*vf;
208
 
209
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,1.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
318
    vf=v0+dt*a;
319
    xf=x0+dt*vf;
320

  
321
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
210 322
}
211 323

  
212 324
MYFLOAT8 AtomicExplicitEuler(__global MYFLOAT4* clDataInX,__global MYFLOAT4* clDataInV,int gid,MYFLOAT dt)
213 325
{
214
    MYFLOAT4 x,v,a,xf,vf;
326
    MYFLOAT4 x0,v0,a,xf,vf;
215 327

  
216
    x=(MYFLOAT4)clDataInX[gid];
217
    v=(MYFLOAT4)clDataInV[gid];
328
    x0=(MYFLOAT4)clDataInX[gid];
329
    v0=(MYFLOAT4)clDataInV[gid];
218 330
    a=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
219 331

  
220
    for (int i=0;i<get_global_size(0);i++)
332
    for (private int i=0;i<get_global_size(0);i++)
221 333
    {
222 334
        if (gid != i)
223
        a+=Interaction(x,clDataInX[i]);
335
        a+=Interaction(x0,clDataInX[i]);
224 336
    }
225 337
       
226
    vf=v+dt*a;
227
    xf=x+dt*v;
338
    vf=v0+dt*a;
339
    xf=x0+dt*v0;
228 340
 
229
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,1.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
341
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
230 342
}
231 343

  
232
__kernel void SplutterPoints(__global MYFLOAT4* clDataX, MYFLOAT box, 
344
__kernel void InBallSplutterPoints(__global MYFLOAT4* clDataX, 
345
                                   MYFLOAT diameter,uint seed_z,uint seed_w)
346
{
347
    private int gid=get_global_id(0);
348
    private uint zmwc=seed_z+gid;
349
    private uint wmwc=seed_w+(gid+1)%2;
350
    private MYFLOAT Heat;
351
 
352
    for (int i=0;i<gid;i++)
353
    {
354
        Heat=MWCfp;
355
    }
356

  
357
// More accurate distribution based on spherical coordonates
358
// Disactivated because of AMD Oland GPU crash on launch
359
//     private MYFLOAT Radius,Theta,Phi,PosX,PosY,PosZ,SinTheta;
360
//     Radius=MWCfp*diameter/2.e0f;
361
//     Theta=(MYFLOAT)acos((float)(-2.e0f*MWCfp+1.0e0f));
362
//     Phi=(MYFLOAT)(2.e0f*PI*MWCfp);
363
//     SinTheta=sin((float)Theta);
364
//     PosX=cos((float)Phi)*Radius*SinTheta;
365
//     PosY=sin((float)Phi)*Radius*SinTheta;
366
//     PosZ=cos((float)Theta)*Radius;
367
//     clDataX[gid]=(MYFLOAT4)(PosX,PosY,PosZ,0.e0f);
368

  
369
    private MYFLOAT Radius=diameter/2.e0f;
370
    private MYFLOAT Length=diameter;
371
    private MYFLOAT4 Position;
372
    while (Length>Radius) {
373
       Position=(MYFLOAT4)((MWCfp-0.5e0f)*diameter,(MWCfp-0.5e0f)*diameter,(MWCfp-0.5e0f)*diameter,0.e0f);
374
       Length=(MYFLOAT)length((MYFLOAT4)Position);
375
    }
376

  
377
    clDataX[gid]=Position;    
378

  
379
    barrier(CLK_GLOBAL_MEM_FENCE);
380
}
381

  
382
__kernel void InBoxSplutterPoints(__global MYFLOAT4* clDataX, MYFLOAT box, 
233 383
                             uint seed_z,uint seed_w)
234 384
{
235
    int gid = get_global_id(0);
236
    uint z=seed_z+(uint)gid;
237
    uint w=seed_w-(uint)gid;
238
    
239
    MYFLOAT x0=box*(MYFLOAT)(MWCfp-(MYFLOAT)5.e-1f);
240
    MYFLOAT y0=box*(MYFLOAT)(MWCfp-(MYFLOAT)5.e-1f);
241
    MYFLOAT z0=box*(MYFLOAT)(MWCfp-(MYFLOAT)5.e-1f);
385
    int gid=get_global_id(0);
386
    uint zmwc=seed_z+gid;
387
    uint wmwc=seed_w-gid;
388
    private MYFLOAT Heat;
389
 
390
    for (int i=0;i<gid;i++)
391
    {
392
        Heat=MWCfp;
393
    }
242 394

  
243
    clDataX[gid].s0123 = (MYFLOAT4) (x0,y0,z0,1.e0f);
395
    clDataX[gid]=(MYFLOAT4)((MWCfp-0.5e0f)*box,(MWCfp-0.5e0f)*box,(MWCfp-0.5e0f)*box,0.e0f);
396

  
397
    barrier(CLK_GLOBAL_MEM_FENCE);
244 398
}
245 399

  
246 400
__kernel void SplutterStress(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,__global MYFLOAT4* clCoM, MYFLOAT velocity,uint seed_z,uint seed_w)
247 401
{
248 402
    int gid = get_global_id(0);
249 403
    MYFLOAT N = (MYFLOAT)get_global_size(0);
250
    uint z=seed_z+(uint)gid;
251
    uint w=seed_w-(uint)gid;
404
    uint zmwc=seed_z+(uint)gid;
405
    uint wmwc=seed_w-(uint)gid;
406
    MYFLOAT4 SpeedVector;
252 407

  
253 408
    if (velocity<SMALL_NUM) {
254
       MYFLOAT4 SpeedVector=(MYFLOAT4)normalize(cross(clDataX[gid],clCoM[0]))*sqrt(-AtomicPotential(clDataX,gid)/(MYFLOAT)2.e0f);
255
       clDataV[gid]=SpeedVector;
409
       SpeedVector=(MYFLOAT4)normalize(cross(clDataX[gid],clCoM[0]))*sqrt((-AtomicPotential(clDataX,gid)/(MYFLOAT)2.e0f));
256 410
    }
257 411
    else
258 412
    {    
259 413
       // cast to float for sin,cos are NEEDED by Mesa FP64 implementation!
260
       MYFLOAT theta=MWCfp*PI;
414
       // Implemention on AMD Oland are probably broken in float
415

  
416
       MYFLOAT theta=acos((float)(1.0e0f-2.e0f*MWCfp));
261 417
       MYFLOAT phi=MWCfp*PI*(MYFLOAT)2.e0f;
262 418
       MYFLOAT sinTheta=sin((float)theta);
419
       MYFLOAT sinPhi=sin((float)phi);
263 420

  
264
       clDataV[gid].s0=velocity*sinTheta*cos((float)phi);
265
       clDataV[gid].s1=velocity*sinTheta*sin((float)phi);
266
       clDataV[gid].s2=velocity*cos((float)theta);
267
       clDataV[gid].s3=(MYFLOAT)1.e0f;
421
       SpeedVector=(MYFLOAT4)((MWCfp-0.5e0f)*velocity,(MWCfp-0.5e0f)*velocity,
422
                              (MWCfp-0.5e0f)*velocity,0.e0f);
268 423
    }
424
    clDataV[gid]=SpeedVector;
425
    barrier(CLK_GLOBAL_MEM_FENCE);
269 426
}
270 427

  
271 428
__kernel void RungeKutta(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,MYFLOAT h)
272 429
{
273
    int gid = get_global_id(0);
430
    private int gid = get_global_id(0);
431
    private MYFLOAT8 clDataGid;
274 432
    
275
    MYFLOAT8 clDataGid=AtomicRungeKutta(clDataX,clDataV,gid,h);
433
    clDataGid=AtomicRungeKutta(clDataX,clDataV,gid,h);
276 434
    barrier(CLK_GLOBAL_MEM_FENCE);
277
    clDataX[gid]=clDataGid.lo;
278
    clDataV[gid]=clDataGid.hi;
435
    clDataX[gid]=clDataGid.s0123;
436
    clDataV[gid]=clDataGid.s4567;
279 437
}
280 438

  
281
__kernel void ImplicitEuler(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,MYFLOAT h)
439
__kernel void Heun(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,MYFLOAT h)
282 440
{
283
    int gid = get_global_id(0);
441
    private int gid = get_global_id(0);
442
    private MYFLOAT8 clDataGid;
284 443
    
285
    MYFLOAT8 clDataGid=AtomicImplicitEuler(clDataX,clDataV,gid,h);
444
    clDataGid=AtomicHeun(clDataX,clDataV,gid,h);
286 445
    barrier(CLK_GLOBAL_MEM_FENCE);
287
    clDataX[gid]=clDataGid.lo;
288
    clDataV[gid]=clDataGid.hi;
446
    clDataX[gid]=clDataGid.s0123;
447
    clDataV[gid]=clDataGid.s4567;
289 448
}
290 449

  
291
__kernel void Heun(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,MYFLOAT h)
450
__kernel void ImplicitEuler(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,MYFLOAT h)
292 451
{
293
    int gid = get_global_id(0);
452
    private int gid = get_global_id(0);
453
    private MYFLOAT8 clDataGid;
294 454
    
295
    MYFLOAT8 clDataGid=AtomicHeun(clDataX,clDataV,gid,h);
455
    clDataGid=AtomicImplicitEuler(clDataX,clDataV,gid,h);
296 456
    barrier(CLK_GLOBAL_MEM_FENCE);
297
    clDataX[gid]=clDataGid.lo;
298
    clDataV[gid]=clDataGid.hi;
457
    clDataX[gid]=clDataGid.s0123;
458
    clDataV[gid]=clDataGid.s4567;
299 459
}
300 460

  
301 461
__kernel void ExplicitEuler(__global MYFLOAT4* clDataX,__global MYFLOAT4* clDataV,MYFLOAT h)
302 462
{
303
    int gid = get_global_id(0);
304
    
305
    MYFLOAT8 clDataGid=AtomicExplicitEuler(clDataX,clDataV,gid,h);
463
    private int gid = get_global_id(0);
464
    private MYFLOAT8 clDataGid;    
465

  
466
    clDataGid=AtomicExplicitEuler(clDataX,clDataV,gid,h);
306 467
    barrier(CLK_GLOBAL_MEM_FENCE);
307
    clDataX[gid]=clDataGid.lo;
308
    clDataV[gid]=clDataGid.hi;
468
    clDataX[gid]=clDataGid.s0123;
469
    clDataV[gid]=clDataGid.s4567;
309 470
}
310 471

  
311 472
__kernel void CoMPotential(__global MYFLOAT4* clDataX,__global MYFLOAT4* clCoM,__global MYFLOAT* clPotential)
......
342 503
    }
343 504

  
344 505
    barrier(CLK_GLOBAL_MEM_FENCE);
345
    clCoM[0]=(MYFLOAT4)(CoM.s0,CoM.s1,CoM.s2,1.e0f)/(MYFLOAT)Size;
506
    clCoM[0]=(MYFLOAT4)(CoM.s0,CoM.s1,CoM.s2,0.e0f)/(MYFLOAT)Size;
346 507
}
347 508

  
348 509
__kernel void Kinetic(__global MYFLOAT4* clDataV,__global MYFLOAT* clKinetic)
......
353 514
    MYFLOAT d=(MYFLOAT)length(clDataV[gid]);
354 515
    clKinetic[gid]=(MYFLOAT)5.e-1f*(MYFLOAT)(d*d);
355 516
}
517

  
356 518
"""
357 519

  
358
def Energy(MyData):
359
    return(sum(MyData*MyData))
520
def MainOpenCL(clDataX,clDataV,Step,Method):
521
    time_start=time.time()
522
    if Method=="RungeKutta":
523
        CLLaunch=MyRoutines.RungeKutta(queue,(Number,1),None,clDataX,clDataV,Step)
524
    elif Method=="ExplicitEuler":
525
        CLLaunch=MyRoutines.ExplicitEuler(queue,(Number,1),None,clDataX,clDataV,Step)
526
    elif Method=="Heun":
527
        CLLaunch=MyRoutines.Heun(queue,(Number,1),None,clDataX,clDataV,Step)
528
    else:
529
        CLLaunch=MyRoutines.ImplicitEuler(queue,(Number,1),None,clDataX,clDataV,Step)
530
    CLLaunch.wait()
531
    Elapsed=time.time()-time_start
532
    return(Elapsed)
533
    
534
def display(*args):
360 535

  
536
    global MyDataX,MyDataV,clDataX,clDataV,Step,Method,Number,Iterations,Durations,Verbose,SpeedRendering
537
    
538
    glClearColor(0.0, 0.0, 0.0, 0.0)
539
    glClear(GL_COLOR_BUFFER_BIT)
540
    glColor3f(1.0,1.0,1.0)
541
    
542
    Elapsed=MainOpenCL(clDataX,clDataV,Step,Method)
543
    if SpeedRendering:
544
        cl.enqueue_copy(queue, MyDataV, clDataV)
545
        MyDataV.reshape(Number,4)[:,3]=1
546
        glVertexPointerf(MyDataV.reshape(Number,4))
547
    else:
548
        cl.enqueue_copy(queue, MyDataX, clDataX)
549
        MyDataX.reshape(Number,4)[:,3]=1
550
        glVertexPointerf(MyDataX.reshape(Number,4))
551

  
552
    if Verbose:
553
        print("Positions for #%s iteration: %s" % (Iterations,MyDataX))
554
    else:
555
        sys.stdout.write('.')
556
        sys.stdout.flush()
557
    Durations=np.append(Durations,MainOpenCL(clDataX,clDataV,Step,Method))    
558
    glEnableClientState(GL_VERTEX_ARRAY)
559
    glDrawArrays(GL_POINTS, 0, Number)
560
    glDisableClientState(GL_VERTEX_ARRAY)
561
    glFlush()
562
    Iterations+=1
563
    glutSwapBuffers()
564

  
565
def halt():
566
    pass
567

  
568
def keyboard(k,x,y):
569
    global ViewRZ,SizeOfBox,SpeedRendering
570
    LC_Z = as_8_bit( 'z' )
571
    UC_Z = as_8_bit( 'Z' )
572
    Plus = as_8_bit( '+' )
573
    Minus = as_8_bit( '-' )
574
    Switch = as_8_bit( 's' )
575

  
576
    Zoom=1
577
    if k == LC_Z:
578
        ViewRZ += 1.0
579
    elif k == UC_Z:
580
        ViewRZ -= 1.0
581
    elif k == Plus:
582
        Zoom *= 2.0
583
    elif k == Minus:
584
        Zoom /= 2.0
585
    elif k == Switch:
586
        if SpeedRendering:
587
            SpeedRendering=False
588
        else:
589
            SpeedRendering=True
590
    elif ord(k) == 27: # Escape
591
        glutLeaveMainLoop()
592
        return(False)
593
    else:
594
        return
595
    glRotatef(ViewRZ, 0.0, 0.0, 1.0)
596
    glScalef(Zoom,Zoom,Zoom)
597
    glutPostRedisplay()
598

  
599
def special(k,x,y):
600
    global ViewRX, ViewRY, ViewRZ
601

  
602
    if k == GLUT_KEY_UP:
603
        ViewRX += 1.0
604
    elif k == GLUT_KEY_DOWN:
605
        ViewRX -= 1.0
606
    elif k == GLUT_KEY_LEFT:
607
        ViewRY += 1.0
608
    elif k == GLUT_KEY_RIGHT:
609
        ViewRY -= 1.0
610
    else:
611
        return
612
    glRotatef(ViewRX, 1.0, 0.0, 0.0)
613
    glRotatef(ViewRY, 0.0, 1.0, 0.0)
614
    glutPostRedisplay()
615

  
616
def setup_viewport():
617
    global SizeOfBox
618
    glMatrixMode(GL_PROJECTION)
619
    glLoadIdentity()
620
    glOrtho(-SizeOfBox, SizeOfBox, -SizeOfBox, SizeOfBox, -SizeOfBox, SizeOfBox)
621
    glutPostRedisplay()
622
    
623
def reshape(w, h):
624
    glViewport(0, 0, w, h)
625
    setup_viewport()
626

  
361 627
if __name__=='__main__':
628

  
629
    global Number,Step,clDataX,clDataV,MyDataX,MyDataV,Method,SizeOfBox,Iterations,Verbose,Durations
362 630
    
363 631
    # ValueType
364 632
    ValueType='FP32'
365 633
    class MyFloat(np.float32):pass
366 634
    #    clType8=cl_array.vec.float8
367
    clType4=cl_array.vec.float4
368 635
    # Set defaults values
369 636
    np.set_printoptions(precision=2)  
370 637
    # Id of Device : 1 is for first find !
371 638
    Device=0
372
    # Iterations is integer
639
    # Number of bodies is integer
373 640
    Number=2
374
    # Size of box
375
    SizeOfBox=MyFloat(1.)
641
    # Number of iterations (for standalone execution)
642
    Iterations=10
643
    # Size of shape
644
    SizeOfShape=MyFloat(1.)
376 645
    # Initial velocity of particules
377 646
    Velocity=MyFloat(1.)
378
    # Redo the last process
379
    Iterations=int(np.pi*1024)
380 647
    # Step
381
    Step=MyFloat(1./1024)
648
    Step=MyFloat(1./32)
382 649
    # Method of integration
383 650
    Method='ImplicitEuler'
384 651
    # InitialRandom
385 652
    InitialRandom=False
386 653
    # RNG Marsaglia Method
387 654
    RNG='MWC'
388
    # CheckEnergies
389
    CheckEnergies=False
390
    # Display samples in 3D
391
    GraphSamples=False
392 655
    # Viriel Distribution of stress
393 656
    VirielStress=True
657
    # Verbose
658
    Verbose=False
659
    # OpenGL real time rendering
660
    OpenGL=False
661
    # Speed rendering
662
    SpeedRendering=False
663
    # Shape to distribute
664
    Shape='Ball'
665
    # Type of Interaction
666
    InterType='Potential'
394 667
    
395
    HowToUse='%s -h [Help] -r [InitialRandom] -e [VirielStress] -g [GraphSamples] -c [CheckEnergies] -d <DeviceId> -n <NumberOfParticules> -z <SizeOfBox> -v <Velocity> -s <Step> -i <Iterations> -m <ImplicitEuler|RungeKutta|ExplicitEuler|Heun> -t <FP32|FP64>'
668
    HowToUse='%s -h [Help] -r [InitialRandom] -g [OpenGL] -e [VirielStress] -o [Verbose] -p [SpeedRendering] -f [Force] -d <DeviceId> -n <NumberOfParticules> -i <Iterations> -z <SizeOfBoxOrBall> -v <Velocity> -s <Step> -b <Ball|Box> -m <ImplicitEuler|RungeKutta|ExplicitEuler|Heun> -t <FP32|FP64>'
396 669

  
397 670
    try:
398
        opts, args = getopt.getopt(sys.argv[1:],"rehgcd:n:z:v:i:s:m:t:",["random","viriel","graph","check","device=","number=","size=","velocity=","iterations=","step=","method=","valuetype="])
671
        opts, args = getopt.getopt(sys.argv[1:],"rpfgehod:n:i:z:v:s:m:t:b:",["random","rendering","force","opengl","viriel","verbose","device=","number=","iterations=","size=","velocity=","step=","method=","valuetype=","shape="])
399 672
    except getopt.GetoptError:
400 673
        print(HowToUse % sys.argv[0])
401 674
        sys.exit(2)
......
409 682
                Id=0
410 683
                for platform in cl.get_platforms():
411 684
                    for device in platform.get_devices():
685
                        # Failed now because of POCL implementation
412 686
                        #deviceType=cl.device_type.to_string(device.type)
413 687
                        deviceType="xPU"
414 688
                        print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip(),deviceType,device.name.lstrip()))
......
421 695
        elif opt in ("-t", "--valuetype"):
422 696
            if arg=='FP64':
423 697
                class MyFloat(np.float64): pass
424
                clType4=cl_array.vec.double4
425 698
            else:
426 699
                class MyFloat(np.float32):pass
427
                clType4=cl_array.vec.float4
428 700
            ValueType = arg
429 701
        elif opt in ("-d", "--device"):
430 702
            Device=int(arg)
431 703
        elif opt in ("-m", "--method"):
432 704
            Method=arg
705
        elif opt in ("-b", "--shape"):
706
            Shape=arg
433 707
        elif opt in ("-n", "--number"):
434 708
            Number=int(arg)
709
        elif opt in ("-i", "--iterations"):
710
            Iterations=int(arg)
435 711
        elif opt in ("-z", "--size"):
436
            SizeOfBox=MyFloat(arg)
712
            SizeOfShape=MyFloat(arg)
437 713
        elif opt in ("-v", "--velocity"):
438 714
            Velocity=MyFloat(arg)
439 715
            VirielStress=False
440 716
        elif opt in ("-s", "--step"):
441 717
            Step=MyFloat(arg)
442
        elif opt in ("-i", "--iterations"):
443
            Iterations=int(arg)
444 718
        elif opt in ("-r", "--random"):
445 719
            InitialRandom=True
446 720
        elif opt in ("-c", "--check"):
447 721
            CheckEnergies=True
448
        elif opt in ("-g", "--graph"):
449
            GraphSamples=True
450 722
        elif opt in ("-e", "--viriel"):
451 723
            VirielStress=True
452
                        
453
    SizeOfBox=MyFloat(Number*SizeOfBox)
724
        elif opt in ("-g", "--opengl"):
725
            OpenGL=True
726
        elif opt in ("-p", "--rendering"):
727
            SpeedRendering=True
728
        elif opt in ("-o", "--verbose"):
729
            Verbose=True
730
        elif opt in ("-f", "--force"):
731
            InterType='Force'
732

  
733
    SizeOfShape=MyFloat(SizeOfShape*Number)
454 734
    Velocity=MyFloat(Velocity)
455 735
    Step=MyFloat(Step)
456 736
                
457 737
    print("Device choosed : %s" % Device)
458 738
    print("Number of particules : %s" % Number)
459
    print("Size of Box : %s" % SizeOfBox)
739
    print("Size of Shape : %s" % SizeOfShape)
460 740
    print("Initial velocity : %s" % Velocity)
741
    print("Step of iteration : %s" % Step)
461 742
    print("Number of iterations : %s" % Iterations)
462
    print("Step of iteration : %s" % Step)
463 743
    print("Method of resolution : %s" % Method)
464 744
    print("Initial Random for RNG Seed : %s" % InitialRandom)
465
    print("Check for Energies : %s" % CheckEnergies)
466
    print("Graph for Samples : %s" % GraphSamples)
467 745
    print("ValueType is : %s" % ValueType)
468
    print("Viriel distribution of stress %s" % VirielStress)
746
    print("Viriel distribution of stress : %s" % VirielStress)
747
    print("OpenGL real time rendering : %s" % OpenGL)
748
    print("Speed rendering : %s" % SpeedRendering)
749
    print("Interaction type : %s" % InterType)
469 750

  
470 751
    # Create Numpy array of CL vector with 8 FP32    
471
    MyCoM = np.zeros(1,dtype=clType4)
472
    MyDataX = np.zeros(Number, dtype=clType4)
473
    MyDataV = np.zeros(Number, dtype=clType4)
752
    MyCoM = np.zeros(4,dtype=MyFloat)
753
    MyDataX = np.zeros(Number*4, dtype=MyFloat)
754
    MyDataV = np.zeros(Number*4, dtype=MyFloat)
474 755
    MyPotential = np.zeros(Number, dtype=MyFloat)
475 756
    MyKinetic = np.zeros(Number, dtype=MyFloat)
476 757

  
477
    Marsaglia,Computing=DictionariesAPI()
758
    Marsaglia,Computing,Interaction=DictionariesAPI()
478 759

  
479 760
    # Scan the OpenCL arrays
480 761
    Id=0
......
500 781
    except:
501 782
        print("Crash during context creation")
502 783

  
503
    print(Marsaglia[RNG],Computing[ValueType])
504 784
    # Build all routines used for the computing
505
    #BuildOptions="-DTRNG=%i -DTYPE=%i" % (Marsaglia[RNG],Computing[ValueType])
506
    #BuildOptions="-cl-mad-enable -cl-fast-relaxed-math -DTRNG=%i -DTYPE=%i" % (Marsaglia[RNG],Computing[ValueType])
507
    BuildOptions="-cl-mad-enable -cl-kernel-arg-info -cl-fast-relaxed-math -cl-std=CL1.2 -DTRNG=%i -DTYPE=%i" % (Marsaglia[RNG],Computing[ValueType])
508
    
509
    if 'Intel' in PlatForm.name or 'Clover' in PlatForm.name or 'Portable' in PlatForm.name :
785

  
786
    #BuildOptions="-cl-mad-enable -cl-kernel-arg-info -cl-fast-relaxed-math -cl-std=CL1.2 -DTRNG=%i -DTYPE=%i" % (Marsaglia[RNG],Computing[ValueType])
787
    BuildOptions="-cl-mad-enable -cl-fast-relaxed-math -DTRNG=%i -DTYPE=%i -DINTERACTION=%i" % (Marsaglia[RNG],Computing[ValueType],Interaction[InterType])
788

  
789
    if 'Intel' in PlatForm.name or 'Experimental' in PlatForm.name or 'Clover' in PlatForm.name or 'Portable' in PlatForm.name :
510 790
        MyRoutines = cl.Program(ctx, BlobOpenCL).build(options = BuildOptions)
511 791
    else:
512 792
        MyRoutines = cl.Program(ctx, BlobOpenCL).build(options = BuildOptions+" -cl-strict-aliasing")
793
        
794
    mf = cl.mem_flags
795
    # Read/Write approach for buffering
796
    clDataX = cl.Buffer(ctx, mf.READ_WRITE, MyDataX.nbytes)
797
    clDataV = cl.Buffer(ctx, mf.READ_WRITE, MyDataV.nbytes)
798
    clPotential = cl.Buffer(ctx, mf.READ_WRITE, MyPotential.nbytes)
799
    clKinetic = cl.Buffer(ctx, mf.READ_WRITE, MyKinetic.nbytes)
800
    clCoM = cl.Buffer(ctx, mf.READ_WRITE, MyCoM.nbytes)
513 801
    
514
    mf = cl.mem_flags
515
    # clDataX = cl.Buffer(ctx, mf.READ_WRITE, MyDataX.nbytes)
516
    # clDataV = cl.Buffer(ctx, mf.READ_WRITE, MyDataV.nbytes)
517
    # clPotential = cl.Buffer(ctx, mf.READ_WRITE, MyPotential.nbytes)
518
    # clKinetic = cl.Buffer(ctx, mf.READ_WRITE, MyKinetic.nbytes)
519
    # clCoM = cl.Buffer(ctx, mf.READ_WRITE, MyCoM.nbytes)
802
    # Write/HostPointer approach for buffering
803
    # clDataX = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyDataX)
804
    # clDataV = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyDataV)
805
    # clPotential = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyPotential)
806
    # clKinetic = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyKinetic)
807
    # clCoM = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyCoM)
520 808

  
521
    clDataX = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyDataX)
522
    clDataV = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyDataV)
523
    clPotential = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyPotential)
524
    clKinetic = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyKinetic)
525
    clCoM = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyCoM)
526

  
527 809
    print('All particles superimposed.')
528 810

  
529
    print(SizeOfBox.dtype)
530
    
531 811
    # Set particles to RNG points
532 812
    if InitialRandom:
533
        MyRoutines.SplutterPoints(queue,(Number,1),None,clDataX,SizeOfBox,np.uint32(nprnd(2**32)),np.uint32(nprnd(2**32)))
813
        seed_w=np.uint32(nprnd(2**32))
814
        seed_z=np.uint32(nprnd(2**32))
534 815
    else:
535
        MyRoutines.SplutterPoints(queue,(Number,1),None,clDataX,SizeOfBox,np.uint32(110271),np.uint32(250173))
816
        seed_w=np.uint32(19710211)
817
        seed_z=np.uint32(20081010)
818
            
819
    if Shape=='Ball':
820
        MyRoutines.InBallSplutterPoints(queue,(Number,1),None,clDataX,SizeOfShape,seed_w,seed_z)
821
    else:
822
        MyRoutines.InBoxSplutterPoints(queue,(Number,1),None,clDataX,SizeOfShape,seed_w,seed_z)
536 823

  
537 824
    print('All particules distributed')
538 825

  
539 826
    CLLaunch=MyRoutines.CenterOfMass(queue,(1,1),None,clDataX,clCoM,np.int32(Number))
540 827
    CLLaunch.wait()
541 828
    cl.enqueue_copy(queue,MyCoM,clCoM)
542
    print('Center Of Mass: (%s,%s,%s)' % (MyCoM[0][0],MyCoM[0][1],MyCoM[0][2]))
829
    print('Center Of Mass estimated: (%s,%s,%s)' % (MyCoM[0],MyCoM[1],MyCoM[2]))
543 830
    
544 831
    if VirielStress:
545 832
        CLLaunch=MyRoutines.SplutterStress(queue,(Number,1),None,clDataX,clDataV,clCoM,MyFloat(0.),np.uint32(110271),np.uint32(250173))
546 833
    else:
547 834
        CLLaunch=MyRoutines.SplutterStress(queue,(Number,1),None,clDataX,clDataV,clCoM,Velocity,np.uint32(110271),np.uint32(250173))
548 835
    CLLaunch.wait()
549
        
550
    if GraphSamples:
551
        cl.enqueue_copy(queue, MyDataX, clDataX)
552
        t0=np.array([[MyDataX[0][0],MyDataX[0][1],MyDataX[0][2]]])
553
        t1=np.array([[MyDataX[1][0],MyDataX[1][1],MyDataX[1][2]]])
554
        tL=np.array([[MyDataX[-1][0],MyDataX[-1][1],MyDataX[-1][2]]])
555 836

  
837
    print('All particules stressed')
838

  
556 839
    CLLaunch=MyRoutines.Potential(queue,(Number,1),None,clDataX,clPotential)
557 840
    CLLaunch=MyRoutines.Kinetic(queue,(Number,1),None,clDataV,clKinetic)
558 841
    CLLaunch.wait()
559 842
    cl.enqueue_copy(queue,MyPotential,clPotential)
560 843
    cl.enqueue_copy(queue,MyKinetic,clKinetic)
561
    print('Viriel=%s Potential=%s Kinetic=%s'% (np.sum(MyPotential)+2*np.sum(MyKinetic),np.sum(MyPotential),np.sum(MyKinetic)))
562
 
563
    if GraphSamples:
564
        cl.enqueue_copy(queue, MyDataX, clDataX)
565
        t0=np.array([[MyDataX[0][0],MyDataX[0][1],MyDataX[0][2]]])
566
        t1=np.array([[MyDataX[1][0],MyDataX[1][1],MyDataX[1][2]]])
567
        tL=np.array([[MyDataX[-1][0],MyDataX[-1][1],MyDataX[-1][2]]])
844
    print('Energy estimated: Viriel=%s Potential=%s Kinetic=%s\n'% (np.sum(MyPotential)+2*np.sum(MyKinetic),np.sum(MyPotential),np.sum(MyKinetic)))
568 845

  
569
    time_start=time.time()
570
    for i in range(Iterations):
571
        if Method=="RungeKutta":            
572
            CLLaunch=MyRoutines.RungeKutta(queue,(Number,1),None,clDataX,clDataV,Step)
573
        elif Method=="ExplicitEuler":
574
            CLLaunch=MyRoutines.ExplicitEuler(queue,(Number,1),None,clDataX,clDataV,Step)
575
        elif Method=="Heun":
576
            CLLaunch=MyRoutines.Heun(queue,(Number,1),None,clDataX,clDataV,Step)
577
        else:
578
            CLLaunch=MyRoutines.ImplicitEuler(queue,(Number,1),None,clDataX,clDataV,Step)
579
        CLLaunch.wait()
846
    if SpeedRendering:
847
        SizeOfBox=max(2*MyKinetic)
848
    else:
849
        SizeOfBox=SizeOfShape        
850
    
851
    wall_time_start=time.time()
580 852

  
581
        if CheckEnergies:
582
            CLLaunch=MyRoutines.Potential(queue,(Number,1),None,clDataX,clPotential)
583
            CLLaunch=MyRoutines.Kinetic(queue,(Number,1),None,clDataV,clKinetic)
584
            CLLaunch.wait()
585
            cl.enqueue_copy(queue,MyPotential,clPotential)
586
            cl.enqueue_copy(queue,MyKinetic,clKinetic)
587
            print(np.sum(MyPotential)+2.*np.sum(MyKinetic),np.sum(MyPotential),np.sum(MyKinetic))
853
    Durations=np.array([],dtype=MyFloat)
854
    print('Starting!')
855
    if OpenGL:
856
        global ViewRX,ViewRY,ViewRZ
857
        Iterations=0
858
        ViewRX,ViewRY,ViewRZ = 0.,0.,0.
859
        # Launch OpenGL Loop
860
        glutInit(sys.argv)
861
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
862
        glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,GLUT_ACTION_CONTINUE_EXECUTION)
863
        glutInitWindowSize(512,512)
864
        glutCreateWindow(b'NBodyGL')
865
        setup_viewport()
866
        glutReshapeFunc(reshape)
867
        glutDisplayFunc(display)
868
        glutIdleFunc(display)
869
        #   glutMouseFunc(mouse)
870
        glutSpecialFunc(special)
871
        glutKeyboardFunc(keyboard)
872
        glutMainLoop()
873
    else:
874
        for iteration in range(Iterations):
875
            Elapsed=MainOpenCL(clDataX,clDataV,Step,Method)
876
            if Verbose:
877
                # print("Duration of #%s iteration: %s" % (iteration,Elapsed))
878
                cl.enqueue_copy(queue, MyDataX, clDataX)
879
                print("Positions for #%s iteration: %s" % (iteration,MyDataX))
880
            else:
881
                sys.stdout.write('.')
882
                sys.stdout.flush()
883
            Durations=np.append(Durations,Elapsed)
588 884

  
589
            print(MyPotential,MyKinetic)
885
    print('\nEnding!')
590 886
            
591
        if GraphSamples:
592
            cl.enqueue_copy(queue, MyDataX, clDataX)
593
            t0=np.append(t0,[MyDataX[0][0],MyDataX[0][1],MyDataX[0][2]])
594
            t1=np.append(t1,[MyDataX[1][0],MyDataX[1][1],MyDataX[1][2]])
595
            tL=np.append(tL,[MyDataX[-1][0],MyDataX[-1][1],MyDataX[-1][2]])
596
    print("\nDuration on %s for each %s\n" % (Device,(time.time()-time_start)/Iterations))
597

  
598 887
    MyRoutines.CenterOfMass(queue,(1,1),None,clDataX,clCoM,np.int32(Number))
599 888
    CLLaunch=MyRoutines.Potential(queue,(Number,1),None,clDataX,clPotential)
600 889
    CLLaunch=MyRoutines.Kinetic(queue,(Number,1),None,clDataV,clKinetic)
......
602 891
    cl.enqueue_copy(queue,MyCoM,clCoM)
603 892
    cl.enqueue_copy(queue,MyPotential,clPotential)
604 893
    cl.enqueue_copy(queue,MyKinetic,clKinetic)
605
    print('Center Of Mass: (%s,%s,%s)' % (MyCoM[0][0],MyCoM[0][1],MyCoM[0][2]))
606
    print('Viriel=%s Potential=%s Kinetic=%s'% (np.sum(MyPotential)+2.*np.sum(MyKinetic),np.sum(MyPotential),np.sum(MyKinetic)))
607
    
608
    if GraphSamples:    
609
        t0=np.transpose(np.reshape(t0,(Iterations+1,3)))
610
        t1=np.transpose(np.reshape(t1,(Iterations+1,3)))
611
        tL=np.transpose(np.reshape(tL,(Iterations+1,3)))
612
    
613
        import matplotlib.pyplot as plt
614
        from mpl_toolkits.mplot3d import Axes3D
615
    
616
        fig = plt.figure()
617
        ax = fig.gca(projection='3d')
618
        ax.scatter(t0[0],t0[1],t0[2], marker='^',color='blue')
619
        ax.scatter(t1[0],t1[1],t1[2], marker='o',color='red')
620
        ax.scatter(tL[0],tL[1],tL[2], marker='D',color='green')
621
   
622
        ax.set_xlabel('X Label')
623
        ax.set_ylabel('Y Label')
624
        ax.set_zlabel('Z Label')
894
    print('\nCenter Of Mass estimated: (%s,%s,%s)' % (MyCoM[0],MyCoM[1],MyCoM[2]))
895
    print('Energy estimated: Viriel=%s Potential=%s Kinetic=%s\n'% (np.sum(MyPotential)+2.*np.sum(MyKinetic),np.sum(MyPotential),np.sum(MyKinetic)))
625 896

  
626
        plt.show()
627
    
897
    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)))
898

  
899
    # Contraction of Square*Size*Hertz: Size*Size/Elapsed
900
    Squertz=np.ones(len(Durations))
901
    Squertz*=Number*Number
902
    Squertz/=Durations
903

  
904
    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))))
905
        
628 906
    clDataX.release()
629 907
    clDataV.release()
630 908
    clKinetic.release()
631 909
    clPotential.release()
910

  
NBody/NBodyGL.py (revision 170)
137 137
    return(sqrt(x2+y2+z2));
138 138
}
139 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

  
140 147
MYFLOAT4 Interaction(MYFLOAT4 m,MYFLOAT4 n)
141 148
{
142 149
    private MYFLOAT r=MyDistance((MYFLOAT4)n,(MYFLOAT4)m);
150
    private MYFLOAT r2=r*r;
151
    private MYFLOAT c=1.e0f/(MYFLOAT)get_global_size(0);
143 152

  
144
    return(((MYFLOAT4)n-(MYFLOAT4)m)/(MYFLOAT)(r*r*r));
153
    return(((MYFLOAT4)n-(MYFLOAT4)m)*(MYFLOAT)(1.e0f-exp(-c*r2))/(MYFLOAT)(r*r2));
145 154
}
146 155

  
147 156
MYFLOAT PairPotential(MYFLOAT4 m,MYFLOAT4 n)
......
802 811
    Durations=np.array([],dtype=MyFloat)
803 812
    print('Starting!')
804 813
    if OpenGL:
805
        global SizeOfBox,ViewRX,ViewRY,ViewRZ
814
        global ViewRX,ViewRY,ViewRZ
806 815
        Iterations=0
807 816
        ViewRX,ViewRY,ViewRZ = 0.,0.,0.
808 817
        # Launch OpenGL Loop

Formats disponibles : Unified diff