Statistiques
| Révision :

root / NBody / NBody.py @ 155

Historique | Voir | Annoter | Télécharger (19,55 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

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

    
21
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
#define MWCfp MWC * 2.3283064365386963e-10f
30
#define KISSfp KISS * 2.3283064365386963e-10f
31
#define SHR3fp SHR3 * 2.3283064365386963e-10f
32
#define CONGfp CONG * 2.3283064365386963e-10f
33

34
#define TFP32 0
35
#define TFP64 1
36

37
#define LENGTH 1.e0f
38

39
#define PI 3.141592653589793238462643197169399375105820974944592307816406286e0f
40
// #define PI M_PI
41

42
#define SMALL_NUM 1.e-9f
43

44
#if TYPE == TFP32
45
#define MYFLOAT4 float4
46
#define MYFLOAT8 float8
47
#define MYFLOAT float
48
#define DISTANCE fast_distance
49
#else
50
#if defined(cl_khr_fp64)  // Khronos extension available?
51
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
52
#define DOUBLE_SUPPORT_AVAILABLE
53
#elif defined(cl_amd_fp64)  // AMD extension available?
54
#pragma OPENCL EXTENSION cl_amd_fp64 : enable
55
#define DOUBLE_SUPPORT_AVAILABLE
56
#endif
57
#define MYFLOAT4 double4
58
#define MYFLOAT8 double8
59
#define MYFLOAT double
60
#define DISTANCE distance
61
#endif
62

63
MYFLOAT4 Interaction(MYFLOAT4 m,MYFLOAT4 n)
64
{
65
    MYFLOAT r=DISTANCE(n,m);
66

67
    return((n-m)/(r*r*r));
68
}
69

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

76
    return(core*(n-m)/(MYFLOAT)(d*d));
77
}
78

79
MYFLOAT PairPotential(MYFLOAT4 m,MYFLOAT4 n)
80
{
81
    return((MYFLOAT)(-1.e0f)/(DISTANCE(n,m)));
82
}
83

84
MYFLOAT AtomicPotential(__global MYFLOAT8* clData,int gid)
85
{
86
    MYFLOAT potential=(MYFLOAT)0.e0f;
87
    MYFLOAT4 x=clData[gid].lo; 
88
    
89
    for (int i=0;i<get_global_size(0);i++)
90
    {
91
        if (gid != i)
92
        potential+=PairPotential(x,clData[i].lo);
93
    }
94

95
    barrier(CLK_GLOBAL_MEM_FENCE);
96
    return(potential);
97
}
98

99
MYFLOAT AtomicPotentialCoM(__global MYFLOAT8* clData,__global MYFLOAT4* clCoM,int gid)
100
{
101
    return(PairPotential(clData[gid].lo,clCoM[0]));
102
}
103

104
MYFLOAT8 AtomicRungeKutta(__global MYFLOAT8* clDataIn,int gid,MYFLOAT dt)
105
{
106
    MYFLOAT4 a0=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
107
    MYFLOAT4 v0=(MYFLOAT4)clDataIn[gid].hi;
108
    MYFLOAT4 x0=(MYFLOAT4)clDataIn[gid].lo;
109
    int N = get_global_size(0);    
110
    
111
    for (int i=0;i<N;i++)
112
    {
113
        if (gid != i)
114
        a0+=Interaction(x0,clDataIn[i].lo);
115
    }
116
        
117
    MYFLOAT4 a1=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
118
    MYFLOAT4 v1=v0+a0*dt;
119
    MYFLOAT4 x1=x0+v0*dt;
120
    for (int i=0;i<N;i++)
121
    {
122
        if (gid != i)
123
        a1+=Interaction(x1,clDataIn[i].lo);
124
    }
125

126
    MYFLOAT4 a2=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
127
    MYFLOAT4 v2=v0+a1*dt*(MYFLOAT)5.e-1f;
128
    MYFLOAT4 x2=x0+v1*dt*(MYFLOAT)5.e-1f;
129
    for (int i=0;i<N;i++)
130
    {
131
        if (gid != i)
132
        a2+=Interaction(x2,clDataIn[i].lo);
133
    }
134
    
135
    MYFLOAT4 a3=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
136
    MYFLOAT4 v3=v0+a2*dt*(MYFLOAT)5.e-1f;
137
    MYFLOAT4 x3=x0+v2*dt*(MYFLOAT)5.e-1f;
138
    for (int i=0;i<N;i++)
139
    {
140
        if (gid != i)
141
        a3+=Interaction(x3,clDataIn[i].lo);
142
    }
143
    
144
    MYFLOAT4 a4=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
145
    MYFLOAT4 v4=v0+a3*dt;
146
    MYFLOAT4 x4=x0+v3*dt;
147
    for (int i=0;i<N;i++)
148
    {
149
        if (gid != i)
150
        a4+=Interaction(x4,clDataIn[i].lo);
151
    }
152
    
153
    MYFLOAT4 xf=x0+dt*(v1+(MYFLOAT)2.e0f*(v2+v3)+v4)/(MYFLOAT)6.e0f;
154
    MYFLOAT4 vf=v0+dt*(a1+(MYFLOAT)2.e0f*(a2+a3)+a4)/(MYFLOAT)6.e0f;
155
     
156
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
157
}
158

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

161
MYFLOAT8 AtomicHeun(__global MYFLOAT8* clDataIn,int gid,MYFLOAT dt)
162
{
163
    MYFLOAT4 x,v,a,xi,vi,ai,xf,vf;
164

165
    x=(MYFLOAT4)clDataIn[gid].lo;
166
    v=(MYFLOAT4)clDataIn[gid].hi;
167
    a=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
168

169
    for (int i=0;i<get_global_size(0);i++)
170
    {
171
        if (gid != i)
172
        a+=Interaction(x,clDataIn[i].lo);
173
    }
174

175
    vi=v+dt*a;
176
    xi=x+dt*vi;
177
    ai=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
178

179
    for (int i=0;i<get_global_size(0);i++)
180
    {
181
        if (gid != i)
182
        ai+=Interaction(xi,clDataIn[i].lo);
183
    }
184
       
185
    vf=v+dt*(a+ai)*(MYFLOAT)5.e-1f;
186
    xf=x+dt*(v+vi)*(MYFLOAT)5.e-1f;
187

188
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
189
}
190

191
MYFLOAT8 AtomicImplicitEuler(__global MYFLOAT8* clDataIn,int gid,MYFLOAT dt)
192
{
193
    MYFLOAT4 x,v,a,xf,vf;
194

195
    x=(MYFLOAT4)clDataIn[gid].lo;
196
    v=(MYFLOAT4)clDataIn[gid].hi;
197
    a=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
198
    for (int i=0;i<get_global_size(0);i++)
199
    {
200
        if (gid != i)
201
        a+=Interaction(x,clDataIn[i].lo);
202
    }
203
       
204
    vf=v+dt*a;
205
    xf=x+dt*vf;
206
 
207
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
208
}
209

210
MYFLOAT8 AtomicExplicitEuler(__global MYFLOAT8* clDataIn,int gid,MYFLOAT dt)
211
{
212
    MYFLOAT4 x,v,a,xf,vf;
213

214
    x=(MYFLOAT4)clDataIn[gid].lo;
215
    v=(MYFLOAT4)clDataIn[gid].hi;
216
    a=(MYFLOAT4)(0.e0f,0.e0f,0.e0f,0.e0f);
217
    for (int i=0;i<get_global_size(0);i++)
218
    {
219
        if (gid != i)
220
        a+=Interaction(x,clDataIn[i].lo);
221
    }
222
       
223
    vf=v+dt*a;
224
    xf=x+dt*v;
225
 
226
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,0.e0f,vf.s0,vf.s1,vf.s2,0.e0f));
227
}
228

229
__kernel void SplutterPoints(__global MYFLOAT8* clData, MYFLOAT box, 
230
                             uint seed_z,uint seed_w)
231
{
232
    int gid = get_global_id(0);
233
    uint z=seed_z+(uint)gid;
234
    uint w=seed_w-(uint)gid;
235
    
236
    MYFLOAT x0=box*(MYFLOAT)(MWCfp-(MYFLOAT)5.e-1f);
237
    MYFLOAT y0=box*(MYFLOAT)(MWCfp-(MYFLOAT)5.e-1f);
238
    MYFLOAT z0=box*(MYFLOAT)(MWCfp-(MYFLOAT)5.e-1f);
239

240
    clData[gid].s01234567 = (MYFLOAT8) (x0,y0,z0,0.e0f,0.e0f,0.e0f,0.e0f,0.e0f);
241
}
242

243
__kernel void SplutterStress(__global MYFLOAT8* clData,__global MYFLOAT4* clCoM, MYFLOAT velocity,uint seed_z,uint seed_w)
244
{
245
    int gid = get_global_id(0);
246
    MYFLOAT N = (MYFLOAT)get_global_size(0);
247
    uint z=seed_z+(uint)gid;
248
    uint w=seed_w-(uint)gid;
249

250
    if (velocity<SMALL_NUM) {
251
       MYFLOAT4 SpeedVector=(MYFLOAT4)normalize(cross(clData[gid].lo,clCoM[0]))*sqrt(-AtomicPotential(clData,gid)*(MYFLOAT)5.e-1f);
252
       clData[gid].hi=SpeedVector;
253
    }
254
    else
255
    {    
256
       // cast to float for sin,cos are NEEDED by Mesa FP64 implementation!
257
       MYFLOAT theta=MWCfp*PI;
258
       MYFLOAT phi=MWCfp*PI*(MYFLOAT)2.e0f;
259
       MYFLOAT sinTheta=sin((float)theta);
260

261
       clData[gid].s4=velocity*sinTheta*cos((float)phi);
262
       clData[gid].s5=velocity*sinTheta*sin((float)phi);
263
       clData[gid].s6=velocity*cos((float)theta);
264
    }
265
}
266

267
__kernel void RungeKutta(__global MYFLOAT8* clData,MYFLOAT h)
268
{
269
    int gid = get_global_id(0);
270
    
271
    MYFLOAT8 clDataGid=AtomicRungeKutta(clData,gid,h);
272
    barrier(CLK_GLOBAL_MEM_FENCE);
273
    clData[gid]=clDataGid;
274
}
275

276
__kernel void ImplicitEuler(__global MYFLOAT8* clData,MYFLOAT h)
277
{
278
    int gid = get_global_id(0);
279
    
280
    MYFLOAT8 clDataGid=AtomicImplicitEuler(clData,gid,h);
281
    barrier(CLK_GLOBAL_MEM_FENCE);
282
    clData[gid]=clDataGid;
283
}
284

285
__kernel void Heun(__global MYFLOAT8* clData,MYFLOAT h)
286
{
287
    int gid = get_global_id(0);
288
    
289
    MYFLOAT8 clDataGid=AtomicHeun(clData,gid,h);
290
    barrier(CLK_GLOBAL_MEM_FENCE);
291
    clData[gid]=clDataGid;
292
}
293

294
__kernel void ExplicitEuler(__global MYFLOAT8* clData,MYFLOAT h)
295
{
296
    int gid = get_global_id(0);
297
    
298
    MYFLOAT8 clDataGid=AtomicExplicitEuler(clData,gid,h);
299
    barrier(CLK_GLOBAL_MEM_FENCE);
300
    clData[gid]=clDataGid;
301
}
302

303
__kernel void CoMPotential(__global MYFLOAT8* clData,__global MYFLOAT4* clCoM,__global MYFLOAT* clPotential)
304
{
305
    int gid = get_global_id(0);
306

307
    clPotential[gid]=PairPotential(clData[gid].lo,clCoM[0]);
308
}
309

310
__kernel void Potential(__global MYFLOAT8* clData,__global MYFLOAT* clPotential)
311
{
312
    int gid = get_global_id(0);
313

314
    MYFLOAT potential=(MYFLOAT)0.e0f;
315
    MYFLOAT4 x=clData[gid].lo; 
316
    
317
    for (int i=0;i<get_global_size(0);i++)
318
    {
319
        if (gid != i)
320
        potential+=PairPotential(x,clData[i].lo);
321
    }
322
                 
323
    barrier(CLK_GLOBAL_MEM_FENCE);
324
    clPotential[gid]=potential*(MYFLOAT)5.e-1f;
325
}
326

327
__kernel void CenterOfMass(__global MYFLOAT8* clData,__global MYFLOAT4* clCoM,int Size)
328
{
329
    MYFLOAT4 CoM=clData[0].lo; 
330

331
    for (int i=1;i<Size;i++)
332
    {
333
        CoM+=clData[i].lo;
334
    }
335

336
    barrier(CLK_GLOBAL_MEM_FENCE);
337
    clCoM[0]=(MYFLOAT4)(CoM.s0,CoM.s1,CoM.s2,0.e0f)/(MYFLOAT)Size;
338
}
339

340
__kernel void Kinetic(__global MYFLOAT8* clData,__global MYFLOAT* clKinetic)
341
{
342
    int gid = get_global_id(0);
343
    
344
    barrier(CLK_GLOBAL_MEM_FENCE);
345
    MYFLOAT d=(MYFLOAT)length(clData[gid].hi);
346
    clKinetic[gid]=(MYFLOAT)5.e-1f*(MYFLOAT)(d*d);
347
}
348
"""
349

    
350
def Energy(MyData):
351
    return(sum(MyData*MyData))
352

    
353
if __name__=='__main__':
354
    
355
    # ValueType
356
    ValueType='FP32'
357
    class MyFloat(np.float32):pass
358
    clType8=cl_array.vec.float8
359
    clType4=cl_array.vec.float4
360
    # Set defaults values
361
    np.set_printoptions(precision=2)  
362
    # Id of Device : 1 is for first find !
363
    Device=1
364
    # Iterations is integer
365
    Number=4
366
    # Size of box
367
    SizeOfBox=MyFloat(1.)
368
    # Initial velocity of particules
369
    Velocity=MyFloat(1.)
370
    # Redo the last process
371
    Iterations=100
372
    # Step
373
    Step=MyFloat(0.01)
374
    # Method of integration
375
    Method='ImplicitEuler'
376
    # InitialRandom
377
    InitialRandom=False
378
    # RNG Marsaglia Method
379
    RNG='MWC'
380
    # CheckEnergies
381
    CheckEnergies=False
382
    # Display samples in 3D
383
    GraphSamples=False
384
    # Viriel Distribution of stress
385
    VirielStress=True
386
    
387
    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 <RungeKutta|ImplicitEuler|ExplicitEuler|Heun> -t <FP32|FP64>'
388

    
389
    try:
390
        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="])
391
    except getopt.GetoptError:
392
        print(HowToUse % sys.argv[0])
393
        sys.exit(2)
394

    
395
    for opt, arg in opts:
396
        if opt == '-h':
397
            print(HowToUse % sys.argv[0])
398

    
399
            print("\nInformations about devices detected under OpenCL:")
400
            try:
401
                Id=0
402
                for platform in cl.get_platforms():
403
                    for device in platform.get_devices():
404
                        #deviceType=cl.device_type.to_string(device.type)
405
                        deviceType="xPU"
406
                        print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip(),deviceType,device.name.lstrip()))
407
                        Id=Id+1
408
                sys.exit()
409
            except ImportError:
410
                print("Your platform does not seem to support OpenCL")
411
                sys.exit()
412

    
413
        elif opt in ("-t", "--valuetype"):
414
            if arg=='FP64':
415
                class MyFloat(np.float64): pass
416
                clType8=cl_array.vec.double8
417
                clType4=cl_array.vec.double4
418
            else:
419
                class MyFloat(np.float32):pass
420
                clType8=cl_array.vec.float8
421
                clType4=cl_array.vec.float4
422
            ValueType = arg
423
        elif opt in ("-d", "--device"):
424
            Device=int(arg)
425
        elif opt in ("-m", "--method"):
426
            Method=arg
427
        elif opt in ("-n", "--number"):
428
            Number=int(arg)
429
        elif opt in ("-z", "--size"):
430
            SizeOfBox=MyFloat(arg)
431
        elif opt in ("-v", "--velocity"):
432
            Velocity=MyFloat(arg)
433
            VirielStress=False
434
        elif opt in ("-s", "--step"):
435
            Step=MyFloat(arg)
436
        elif opt in ("-i", "--iterations"):
437
            Iterations=int(arg)
438
        elif opt in ("-r", "--random"):
439
            InitialRandom=True
440
        elif opt in ("-c", "--check"):
441
            CheckEnergies=True
442
        elif opt in ("-g", "--graph"):
443
            GraphSamples=True
444
        elif opt in ("-e", "--viriel"):
445
            VirielStress=True
446
                        
447
    SizeOfBox=MyFloat(np.power(Number,1./3.)*SizeOfBox)
448
    Velocity=MyFloat(Velocity)
449
    Step=MyFloat(Step)
450
                
451
    print("Device choosed : %s" % Device)
452
    print("Number of particules : %s" % Number)
453
    print("Size of Box : %s" % SizeOfBox)
454
    print("Initial velocity %s" % Velocity)
455
    print("Number of iterations %s" % Iterations)
456
    print("Step of iteration %s" % Step)
457
    print("Method of resolution %s" % Method)
458
    print("Initial Random for RNG Seed %s" % InitialRandom)
459
    print("Check for Energies %s" % CheckEnergies)
460
    print("Graph for Samples %s" % GraphSamples)
461
    print("ValueType is %s" % ValueType)
462
    print("Viriel distribution of stress %s" % VirielStress)
463

    
464
    # Create Numpy array of CL vector with 8 FP32    
465
    MyCoM = np.zeros(1,dtype=clType4)
466
    MyData = np.zeros(Number, dtype=clType8)
467
    MyPotential = np.zeros(Number, dtype=MyFloat)
468
    MyKinetic = np.zeros(Number, dtype=MyFloat)
469

    
470
    Marsaglia,Computing=DictionariesAPI()
471

    
472
    # Scan the OpenCL arrays
473
    Id=0
474
    HasXPU=False
475
    for platform in cl.get_platforms():
476
        for device in platform.get_devices():
477
            if Id==Device:
478
                PlatForm=platform
479
                XPU=device
480
                print("CPU/GPU selected: ",device.name.lstrip())
481
                print("Platform selected: ",platform.name)
482
                HasXPU=True
483
            Id+=1
484

    
485
    if HasXPU==False:
486
        print("No XPU #%i found in all of %i devices, sorry..." % (Device,Id-1))
487
        sys.exit()      
488

    
489
    # Create Context
490
    try:
491
        ctx = cl.Context([XPU])
492
        queue = cl.CommandQueue(ctx,properties=cl.command_queue_properties.PROFILING_ENABLE)
493
    except:
494
        print("Crash during context creation")
495

    
496
    print(Marsaglia[RNG],Computing[ValueType])
497
    # Build all routines used for the computing
498
    #BuildOptions="-DTRNG=%i -DTYPE=%i" % (Marsaglia[RNG],Computing[ValueType])
499
    BuildOptions="-cl-mad-enable -cl-fast-relaxed-math -DTRNG=%i -DTYPE=%i" % (Marsaglia[RNG],Computing[ValueType])
500
    #BuildOptions="-cl-mad-enable -cl-kernel-arg-info -cl-std=CL1.2 -DTRNG=%i -DTYPE=%i" % (Marsaglia[RNG],Computing[ValueType])
501
    if 'Intel' in PlatForm.name or 'Clover' in PlatForm.name :
502
        MyRoutines = cl.Program(ctx, BlobOpenCL).build(options = BuildOptions)
503
    else:
504
        MyRoutines = cl.Program(ctx, BlobOpenCL).build(options = BuildOptions+" -cl-strict-aliasing")
505

    
506
    mf = cl.mem_flags
507
    clData = cl.Buffer(ctx, mf.READ_WRITE, MyData.nbytes)
508
    clPotential = cl.Buffer(ctx, mf.READ_WRITE, MyPotential.nbytes)
509
    clKinetic = cl.Buffer(ctx, mf.READ_WRITE, MyKinetic.nbytes)
510
    clCoM = cl.Buffer(ctx, mf.READ_WRITE, MyCoM.nbytes)
511
    #clData = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyData)
512

    
513
    print('All particles superimposed.')
514

    
515
    print(SizeOfBox.dtype)
516
    
517
    # Set particles to RNG points
518
    if InitialRandom:
519
        MyRoutines.SplutterPoints(queue,(Number,1),None,clData,SizeOfBox,np.uint32(nprnd(2**32)),np.uint32(nprnd(2**32)))
520
    else:
521
        MyRoutines.SplutterPoints(queue,(Number,1),None,clData,SizeOfBox,np.uint32(110271),np.uint32(250173))
522

    
523
    print('All particules distributed')
524

    
525
    MyRoutines.CenterOfMass(queue,(1,1),None,clData,clCoM,np.int32(Number))
526
    cl.enqueue_copy(queue,MyCoM,clCoM)
527
    print('Center Of Mass: (%s,%s,%s)' % (MyCoM[0][0],MyCoM[0][1],MyCoM[0][2]))
528
    
529
    if VirielStress:
530
        MyRoutines.SplutterStress(queue,(Number,1),None,clData,clCoM,MyFloat(0.),np.uint32(110271),np.uint32(250173))
531
    else:
532
        MyRoutines.SplutterStress(queue,(Number,1),None,clData,clCoM,Velocity,np.uint32(110271),np.uint32(250173))
533
        
534
    if GraphSamples:
535
        cl.enqueue_copy(queue, MyData, clData)
536
        t0=np.array([[MyData[0][0],MyData[0][1],MyData[0][2]]])
537
        t1=np.array([[MyData[1][0],MyData[1][1],MyData[1][2]]])
538
        tL=np.array([[MyData[-1][0],MyData[-1][1],MyData[-1][2]]])
539
        s0=np.array([[MyData[0][4],MyData[0][5],MyData[0][6],MyData[0][7]]])
540
        s1=np.array([[MyData[1][4],MyData[1][5],MyData[1][6],MyData[1][7]]])
541
        sL=np.array([[MyData[-1][4],MyData[-1][5],MyData[-1][6],MyData[-1][7]]])
542

    
543
        #print(t0,t1,tL)
544
        #print(s0,s1,sL)
545
        
546
    CLLaunch=MyRoutines.Potential(queue,(Number,1),None,clData,clPotential)
547
    CLLaunch=MyRoutines.Kinetic(queue,(Number,1),None,clData,clKinetic)
548
    CLLaunch.wait()
549
    cl.enqueue_copy(queue,MyPotential,clPotential)
550
    cl.enqueue_copy(queue,MyKinetic,clKinetic)
551
    print('Viriel=%s Potential=%s Kinetic=%s'% (np.sum(MyPotential)+2*np.sum(MyKinetic),np.sum(MyPotential),np.sum(MyKinetic)))
552
 
553
    if GraphSamples:
554
        cl.enqueue_copy(queue, MyData, clData)
555
        t0=np.array([[MyData[0][0],MyData[0][1],MyData[0][2]]])
556
        t1=np.array([[MyData[1][0],MyData[1][1],MyData[1][2]]])
557
        tL=np.array([[MyData[-1][0],MyData[-1][1],MyData[-1][2]]])
558

    
559
    time_start=time.time()
560
    for i in range(Iterations):
561
        if Method=="ImplicitEuler":            
562
            CLLaunch=MyRoutines.ImplicitEuler(queue,(Number,1),None,clData,Step)
563
        elif Method=="ExplicitEuler":
564
            CLLaunch=MyRoutines.ExplicitEuler(queue,(Number,1),None,clData,Step)
565
        elif Method=="Heun":
566
            CLLaunch=MyRoutines.Heun(queue,(Number,1),None,clData,Step)
567
        else:
568
            CLLaunch=MyRoutines.RungeKutta(queue,(Number,1),None,clData,Step)
569
        CLLaunch.wait()
570
        if CheckEnergies:
571
            CLLaunch=MyRoutines.Potential(queue,(Number,1),None,clData,clPotential)
572
            CLLaunch=MyRoutines.Kinetic(queue,(Number,1),None,clData,clKinetic)
573
            CLLaunch.wait()
574
            cl.enqueue_copy(queue,MyPotential,clPotential)
575
            cl.enqueue_copy(queue,MyKinetic,clKinetic)
576
            print(np.sum(MyPotential)+2.*np.sum(MyKinetic),np.sum(MyPotential),np.sum(MyKinetic))
577

    
578
            print(MyPotential,MyKinetic)
579
            
580
        if GraphSamples:
581
            cl.enqueue_copy(queue, MyData, clData)
582
            t0=np.append(t0,[MyData[0][0],MyData[0][1],MyData[0][2]])
583
            t1=np.append(t1,[MyData[1][0],MyData[1][1],MyData[1][2]])
584
            tL=np.append(tL,[MyData[-1][0],MyData[-1][1],MyData[-1][2]])
585
    print("\nDuration on %s for each %s" % (Device,(time.time()-time_start)/Iterations))
586

    
587
    CLLaunch=MyRoutines.Potential(queue,(Number,1),None,clData,clPotential)
588
    CLLaunch=MyRoutines.Kinetic(queue,(Number,1),None,clData,clKinetic)
589
    CLLaunch.wait()
590
    cl.enqueue_copy(queue,MyPotential,clPotential)
591
    cl.enqueue_copy(queue,MyKinetic,clKinetic)
592
    print('Viriel=%s Potential=%s Kinetic=%s'% (np.sum(MyPotential)+2.*np.sum(MyKinetic),np.sum(MyPotential),np.sum(MyKinetic)))
593
    MyRoutines.CenterOfMass(queue,(1,1),None,clData,clCoM,np.int32(Number))
594
    cl.enqueue_copy(queue,MyCoM,clCoM)
595
    print('Center Of Mass: (%s,%s,%s)' % (MyCoM[0][0],MyCoM[0][1],MyCoM[0][2]))
596
    
597
    if GraphSamples:    
598
        t0=np.transpose(np.reshape(t0,(Iterations+1,3)))
599
        t1=np.transpose(np.reshape(t1,(Iterations+1,3)))
600
        tL=np.transpose(np.reshape(tL,(Iterations+1,3)))
601
    
602
        import matplotlib.pyplot as plt
603
        from mpl_toolkits.mplot3d import Axes3D
604
    
605
        fig = plt.figure()
606
        ax = fig.gca(projection='3d')
607
        ax.scatter(t0[0],t0[1],t0[2], marker='^',color='blue')
608
        ax.scatter(t1[0],t1[1],t1[2], marker='o',color='red')
609
        ax.scatter(tL[0],tL[1],tL[2], marker='D',color='green')
610
   
611
        ax.set_xlabel('X Label')
612
        ax.set_ylabel('Y Label')
613
        ax.set_zlabel('Z Label')
614

    
615
        plt.show()
616
    
617
    clData.release()
618
    clKinetic.release()
619
    clPotential.release()