Index: NBody.py
===================================================================
--- NBody.py	(revision 131)
+++ NBody.py	(revision 132)
@@ -12,6 +12,11 @@
 import pyopencl.array as cl_array
 from numpy.random import randint as nprnd
 
+def DictionariesAPI():
+    Marsaglia={'CONG':0,'SHR3':1,'MWC':2,'KISS':3}
+    Computing={'FP32':0,'FP64':1}
+    return(Marsaglia,Computing)
+
 BlobOpenCL= """
 #define znew  ((z=36969*(z&65535)+(z>>16))<<16)
 #define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
@@ -25,68 +30,81 @@
 #define SHR3fp SHR3 * 2.328306435454494e-10f
 #define CONGfp CONG * 2.328306435454494e-10f
 
+#define TFP32 0
+#define TFP64 1
+
 #define LENGTH 1.
 
 #define PI 3.14159265359
 
 #define SMALL_NUM 0.000000001
 
-float4 Interaction(float4 m,float4 n)
+#if TYPE == TFP32
+#define MYFLOAT4 float4
+#define MYFLOAT8 float8
+#define MYFLOAT float
+#else
+#define MYFLOAT4 double4
+#define MYFLOAT8 double8
+#define MYFLOAT double
+#endif
+
+MYFLOAT4 Interaction(MYFLOAT4 m,MYFLOAT4 n)
 {
-    return((n-m)/(float)pow(distance(n,m),2));
+    return((n-m)/(MYFLOAT)pow(distance(n,m),2));
 }
 
 // Elements from : http://doswa.com/2009/01/02/fourth-order-runge-kutta-numerical-integration.html
 
-float8 AtomicRungeKutta(__global float8* clDataIn,int gid,float dt)
+MYFLOAT8 AtomicRungeKutta(__global MYFLOAT8* clDataIn,int gid,MYFLOAT dt)
 {
-    float4 x0=clDataIn[gid].lo;
-    float4 v0=clDataIn[gid].hi;
-    float4 a0=(0.,0.,0.,0.);
+    MYFLOAT4 x0=clDataIn[gid].lo;
+    MYFLOAT4 v0=clDataIn[gid].hi;
+    MYFLOAT4 a0=(0.,0.,0.,0.);
     for (int i=0;i<get_global_size(0);i++)
     {
         if (gid != i)
         a0+=Interaction(x0,clDataIn[i].lo);
     }
         
-    float4 x1=x0+v0*(float)0.5*dt;
-    float4 v1=v0+a0*(float)0.5*dt;
-    float4 a1=(0.,0.,0.,0.);
+    MYFLOAT4 x1=x0+v0*(MYFLOAT)0.5*dt;
+    MYFLOAT4 v1=v0+a0*(MYFLOAT)0.5*dt;
+    MYFLOAT4 a1=(0.,0.,0.,0.);
     for (int i=0;i<get_global_size(0);i++)
     {
         if (gid != i)
         a1+=Interaction(x1,clDataIn[i].lo);
     }
 
-    float4 x2=x0+v1*(float)0.5*dt;
-    float4 v2=v0+a1*(float)0.5*dt;
-    float4 a2=(0.,0.,0.,0.);
+    MYFLOAT4 x2=x0+v1*(MYFLOAT)0.5*dt;
+    MYFLOAT4 v2=v0+a1*(MYFLOAT)0.5*dt;
+    MYFLOAT4 a2=(0.,0.,0.,0.);
     for (int i=0;i<get_global_size(0);i++)
     {
         if (gid != i)
         a2+=Interaction(x2,clDataIn[i].lo);
     }
     
-    float4 x3=x0+v2*dt;
-    float4 v3=v0+a2*dt;
-    float4 a3=(0.,0.,0.,0.);
+    MYFLOAT4 x3=x0+v2*dt;
+    MYFLOAT4 v3=v0+a2*dt;
+    MYFLOAT4 a3=(0.,0.,0.,0.);
     for (int i=0;i<get_global_size(0);i++)
     {
         if (gid != i)
         a3+=Interaction(x3,clDataIn[i].lo);
     }
     
-    float4 xf=x0+dt*(v0+(float)2.*(v1+v2)+v3)/(float)6.;
-    float4 vf=v0+dt*(a0+(float)2.*(a1+a2)+a3)/(float)6.;
+    MYFLOAT4 xf=x0+dt*(v0+(MYFLOAT)2.*(v1+v2)+v3)/(MYFLOAT)6.;
+    MYFLOAT4 vf=v0+dt*(a0+(MYFLOAT)2.*(a1+a2)+a3)/(MYFLOAT)6.;
      
-    return((float8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
+    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
 }
 
 // Elements from : http://doswa.com/2009/01/02/fourth-order-runge-kutta-numerical-integration.html
 
-float8 AtomicRungeKutta2(__global float8* clDataIn,int gid,float dt)
+MYFLOAT8 AtomicRungeKutta2(__global MYFLOAT8* clDataIn,int gid,MYFLOAT dt)
 {
-    float4 x[4],v[4],a[4],xf,vf;
+    MYFLOAT4 x[4],v[4],a[4],xf,vf;
 
     x[0]=clDataIn[gid].lo;
     v[0]=clDataIn[gid].hi;
@@ -97,8 +115,8 @@
         a[0]+=Interaction(x[0],clDataIn[i].lo);
     }
         
-    x[1]=x[0]+v[0]*(float)0.5*dt;
-    v[1]=v[0]+a[0]*(float)0.5*dt;
+    x[1]=x[0]+v[0]*(MYFLOAT)0.5*dt;
+    v[1]=v[0]+a[0]*(MYFLOAT)0.5*dt;
     a[1]=(0.,0.,0.,0.);
     for (int i=0;i<get_global_size(0);i++)
     {
@@ -106,8 +124,8 @@
         a[1]+=Interaction(x[1],clDataIn[i].lo);
     }
 
-    x[2]=x[0]+v[1]*(float)0.5*dt;
-    v[2]=v[0]+a[1]*(float)0.5*dt;
+    x[2]=x[0]+v[1]*(MYFLOAT)0.5*dt;
+    v[2]=v[0]+a[1]*(MYFLOAT)0.5*dt;
     a[2]=(0.,0.,0.,0.);
     for (int i=0;i<get_global_size(0);i++)
     {
@@ -124,15 +142,15 @@
         a[3]+=Interaction(x[3],clDataIn[i].lo);
     }
     
-    xf=x[0]+dt*(v[0]+(float)2.*(v[1]+v[2])+v[3])/(float)6.;
-    vf=v[0]+dt*(a[0]+(float)2.*(a[1]+a[2])+a[3])/(float)6.;
+    xf=x[0]+dt*(v[0]+(MYFLOAT)2.*(v[1]+v[2])+v[3])/(MYFLOAT)6.;
+    vf=v[0]+dt*(a[0]+(MYFLOAT)2.*(a[1]+a[2])+a[3])/(MYFLOAT)6.;
      
-    return((float8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
+    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
 }
 
-float8 AtomicEuler(__global float8* clDataIn,int gid,float dt)
+MYFLOAT8 AtomicEuler(__global MYFLOAT8* clDataIn,int gid,MYFLOAT dt)
 {
-    float4 x,v,a,xf,vf;
+    MYFLOAT4 x,v,a,xf,vf;
 
     x=clDataIn[gid].lo;
     v=clDataIn[gid].hi;
@@ -146,38 +164,38 @@
     xf=x+dt*v;
     vf=v+dt*a;
  
-    return((float8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
+    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
 }
 
-__kernel void SplutterPoints(__global float8* clData, float box, float velocity,
+__kernel void SplutterPoints(__global MYFLOAT8* clData, MYFLOAT box, MYFLOAT velocity,
                                uint seed_z,uint seed_w)
 {
     int gid = get_global_id(0);
     uint z=seed_z+(uint)gid;
     uint w=seed_w-(uint)gid;
-    float theta=MWCfp*PI;
-    float phi=MWCfp*PI*2.;
-    float sinTheta=sin(theta);
-    clData[gid].s01234567 = (float8) (box*MWCfp,box*MWCfp,box*MWCfp,0.,0.,0.,0.,0.);
+    MYFLOAT theta=MWCfp*PI;
+    MYFLOAT phi=MWCfp*PI*2.;
+    MYFLOAT sinTheta=sin(theta);
+    clData[gid].s01234567 = (MYFLOAT8) (box*MWCfp,box*MWCfp,box*MWCfp,0.,0.,0.,0.,0.);
     clData[gid].s4=velocity*sinTheta*cos(phi);
     clData[gid].s5=velocity*sinTheta*sin(phi);
     clData[gid].s6=velocity*cos(theta);
 }
 
-__kernel void RungeKutta(__global float8* clData,float h)
+__kernel void RungeKutta(__global MYFLOAT8* clData,MYFLOAT h)
 {
     int gid = get_global_id(0);
     
-    float8 clDataGid=AtomicRungeKutta(clData,gid,h);
+    MYFLOAT8 clDataGid=AtomicRungeKutta(clData,gid,h);
     barrier(CLK_GLOBAL_MEM_FENCE);
     clData[gid]=clDataGid;
 }
 
-__kernel void Euler(__global float8* clData,float h)
+__kernel void Euler(__global MYFLOAT8* clData,MYFLOAT h)
 {
     int gid = get_global_id(0);
     
-    float8 clDataGid=AtomicEuler(clData,gid,h);
+    MYFLOAT8 clDataGid=AtomicEuler(clData,gid,h);
     barrier(CLK_GLOBAL_MEM_FENCE);
     clData[gid]=clDataGid;
 }
@@ -185,6 +203,10 @@
 
 if __name__=='__main__':
     
+    # ValueType
+    ValueType='FP32'
+    class MyFloat(np.float32):pass
+    clType=cl_array.vec.float8
     # Set defaults values
     np.set_printoptions(precision=2)  
     # Id of Device : 1 is for first find !
@@ -192,20 +214,24 @@
     # Iterations is integer
     Number=1024
     # Size of box
-    SizeOfBox=1.
+    SizeOfBox=MyFloat(1.)
     # Initial velocity of particules
-    Velocity=1.
+    Velocity=MyFloat(1.)
     # Redo the last process
     Iterations=1000
     # Step
-    Step=0.1
+    Step=MyFloat(0.1)
     # Method of integration
     Method='RungeKutta'
+    # InitialRandom
+    InitialRandom=False
+    # RNG Marsaglia Method
+    RNG='MWC'
+    
+    HowToUse='%s -h [Help] -r [InitialRandom] -d <DeviceId> -n <NumberOfParticules> -z <SizeOfBox> -v <Velocity> -s <Step> -i <Iterations> -m <RungeKutta|Euler> -t <FP32|FP64>'
 
-    HowToUse='%s -d <DeviceId> -n <NumberOfParticules> -z <SizeOfBox> -v <Velocity> -s <Step> -i <Iterations> -m <RungeKutta|Euler>'
-
     try:
-        opts, args = getopt.getopt(sys.argv[1:],"hd:n:z:v:i:s:m:",["device=","number=","size=","velocity=","iterations=","step=","method="])
+        opts, args = getopt.getopt(sys.argv[1:],"rhd:n:z:v:i:s:m:t:",["random","device=","number=","size=","velocity=","iterations=","step=","method=","valuetype="])
     except getopt.GetoptError:
         print(HowToUse % sys.argv[0])
         sys.exit(2)
@@ -216,7 +242,7 @@
 
             print("\nInformations about devices detected under OpenCL:")
             try:
-                Id=1
+                Id=0
                 for platform in cl.get_platforms():
                     for device in platform.get_devices():
                         deviceType=cl.device_type.to_string(device.type)
@@ -227,6 +253,14 @@
                 print("Your platform does not seem to support OpenCL")
                 sys.exit()
 
+        elif opt in ("-t", "--valuetype"):
+            if arg=='FP64':
+                class MyFloat(np.float64): pass
+                clType=cl_array.vec.double8
+            else:
+                class MyFloat(np.float32):pass
+                clType=cl_array.vec.float8
+            ValueType = arg
         elif opt in ("-d", "--device"):
             Device=int(arg)
         elif opt in ("-m", "--method"):
@@ -234,14 +268,20 @@
         elif opt in ("-n", "--number"):
             Number=int(arg)
         elif opt in ("-z", "--size"):
-            SizeOfBox=np.float32(arg)
+            SizeOfBox=MyFloat(arg)
         elif opt in ("-v", "--velocity"):
-            Velocity=np.float32(arg)
+            Velocity=MyFloat(arg)
         elif opt in ("-s", "--step"):
-            Step=np.float32(arg)
+            Step=MyFloat(arg)
         elif opt in ("-i", "--iterations"):
             Iterations=int(arg)
-            
+        elif opt in ("-r", "--random"):
+            InitialRandom=True
+
+    SizeOfBox=MyFloat(SizeOfBox)
+    Velocity=MyFloat(Velocity)
+    Step=MyFloat(Step)
+                
     print("Device choosed : %s" % Device)
     print("Number of particules : %s" % Number)
     print("Size of Box : %s" % SizeOfBox)
@@ -249,10 +289,16 @@
     print("Number of iterations % s" % Iterations)
     print("Step of iteration % s" % Step)
     print("Method of resolution % s" % Method)
-    
-    MyData = np.zeros(Number, dtype=cl_array.vec.float8)
+    print("Seed for RNG % s" % InitialRandom)
+    print("ValueType is % s" % ValueType)
 
-    Id=1
+    # Create Numpy array of CL vector with 8 FP32    
+    MyData = np.zeros(Number, dtype=clType)
+
+    Marsaglia,Computing=DictionariesAPI()
+
+    # Scan the OpenCL arrays
+    Id=0
     HasXPU=False
     for platform in cl.get_platforms():
         for device in platform.get_devices():
@@ -267,15 +313,16 @@
         print("No XPU #%i found in all of %i devices, sorry..." % (Device,Id-1))
         sys.exit()      
 
-    # Je cree le contexte et la queue pour son execution
+    # Create Context
     try:
         ctx = cl.Context([XPU])
         queue = cl.CommandQueue(ctx,properties=cl.command_queue_properties.PROFILING_ENABLE)
     except:
         print("Crash during context creation")
-   
 
-    MyRoutines = cl.Program(ctx, BlobOpenCL).build()
+    print(Marsaglia[RNG],Computing[ValueType])
+    # Build all routines used for the computing
+    MyRoutines = cl.Program(ctx, BlobOpenCL).build(options = "-cl-mad-enable -cl-fast-relaxed-math -DTRNG=%i -DTYPE=%i" % (Marsaglia[RNG],Computing[ValueType]))
 
 # Initial forced values for exploration
 #    MyData[0][0]=np.float32(-1.)
@@ -289,12 +336,17 @@
     clData = cl.Buffer(ctx, mf.READ_WRITE, MyData.nbytes)
     #clData = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyData)
 
-    print('Tous au meme endroit')
+    print('At this points, all particles are at the same place.')
 
-#    MyRoutines.SplutterPoints(queue,(Number,1),None,clDataIn,np.float32(SizeOfBox),np.float32(Velocity),np.uint32(nprnd(2**32)),np.uint32(nprnd(2**32)))
-    MyRoutines.SplutterPoints(queue,(Number,1),None,clData,np.float32(SizeOfBox),np.float32(Velocity),np.uint32(110271),np.uint32(250173))
+    print(SizeOfBox.dtype)
+    
+    # Set particles to RNG points
+    if InitialRandom:
+        MyRoutines.SplutterPoints(queue,(Number,1),None,clData,SizeOfBox,Velocity,np.uint32(nprnd(2**32)),np.uint32(nprnd(2**32)))
+    else:
+        MyRoutines.SplutterPoints(queue,(Number,1),None,clData,SizeOfBox,Velocity,np.uint32(110271),np.uint32(250173))
 
-    print('Tous distribues')
+    print('All particules distributed')
  
     cl.enqueue_copy(queue, MyData, clData)
     t0=np.array([[MyData[0][0],MyData[0][1],MyData[0][2]]])
@@ -303,10 +355,10 @@
 
     time_start=time.time()
     for i in range(Iterations):
-        if Method=="RungeKutta":
-            CLLaunch=MyRoutines.RungeKutta(queue,(Number,1),None,clData,np.float32(Step))
+        if Method=="RungeKutta":            
+            CLLaunch=MyRoutines.RungeKutta(queue,(Number,1),None,clData,Step)
         else:
-            CLLaunch=MyRoutines.Euler(queue,(Number,1),None,clData,np.float32(Step))
+            CLLaunch=MyRoutines.Euler(queue,(Number,1),None,clData,Step)
         CLLaunch.wait()
         cl.enqueue_copy(queue, MyData, clData)
         t0=np.append(t0,[MyData[0][0],MyData[0][1],MyData[0][2]])
@@ -314,23 +366,23 @@
         tL=np.append(tL,[MyData[-1][0],MyData[-1][1],MyData[-1][2]])
     print("\nDuration on %s for each %s" % (Device,(time.time()-time_start)/Iterations))
     
-    t0=np.transpose(np.reshape(t0,(Iterations+1,3)))
-    t1=np.transpose(np.reshape(t1,(Iterations+1,3)))
-    tL=np.transpose(np.reshape(tL,(Iterations+1,3)))
+    # t0=np.transpose(np.reshape(t0,(Iterations+1,3)))
+    # t1=np.transpose(np.reshape(t1,(Iterations+1,3)))
+    # tL=np.transpose(np.reshape(tL,(Iterations+1,3)))
     
-    import matplotlib.pyplot as plt
-    from mpl_toolkits.mplot3d import Axes3D
+    # import matplotlib.pyplot as plt
+    # from mpl_toolkits.mplot3d import Axes3D
     
-    fig = plt.figure()
-    ax = fig.gca(projection='3d')
-    ax.scatter(t0[0],t0[1],t0[2], marker='^',color='blue')
-    ax.scatter(t1[0],t1[1],t1[2], marker='o',color='red')
-    ax.scatter(tL[0],tL[1],tL[2], marker='D',color='green')
+    # fig = plt.figure()
+    # ax = fig.gca(projection='3d')
+    # ax.scatter(t0[0],t0[1],t0[2], marker='^',color='blue')
+    # ax.scatter(t1[0],t1[1],t1[2], marker='o',color='red')
+    # ax.scatter(tL[0],tL[1],tL[2], marker='D',color='green')
     
-    ax.set_xlabel('X Label')
-    ax.set_ylabel('Y Label')
-    ax.set_zlabel('Z Label')
+    # ax.set_xlabel('X Label')
+    # ax.set_ylabel('Y Label')
+    # ax.set_zlabel('Z Label')
 
-    plt.show()
+    # plt.show()
     
     clData.release()
