Révision 132 NBody/NBody.py

NBody.py (revision 132)
12 12
import pyopencl.array as cl_array
13 13
from numpy.random import randint as nprnd
14 14

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

  
15 20
BlobOpenCL= """
16 21
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
17 22
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
......
25 30
#define SHR3fp SHR3 * 2.328306435454494e-10f
26 31
#define CONGfp CONG * 2.328306435454494e-10f
27 32

  
33
#define TFP32 0
34
#define TFP64 1
35

  
28 36
#define LENGTH 1.
29 37

  
30 38
#define PI 3.14159265359
31 39

  
32 40
#define SMALL_NUM 0.000000001
33 41

  
34
float4 Interaction(float4 m,float4 n)
42
#if TYPE == TFP32
43
#define MYFLOAT4 float4
44
#define MYFLOAT8 float8
45
#define MYFLOAT float
46
#else
47
#define MYFLOAT4 double4
48
#define MYFLOAT8 double8
49
#define MYFLOAT double
50
#endif
51

  
52
MYFLOAT4 Interaction(MYFLOAT4 m,MYFLOAT4 n)
35 53
{
36
    return((n-m)/(float)pow(distance(n,m),2));
54
    return((n-m)/(MYFLOAT)pow(distance(n,m),2));
37 55
}
38 56

  
39 57
// Elements from : http://doswa.com/2009/01/02/fourth-order-runge-kutta-numerical-integration.html
40 58

  
41
float8 AtomicRungeKutta(__global float8* clDataIn,int gid,float dt)
59
MYFLOAT8 AtomicRungeKutta(__global MYFLOAT8* clDataIn,int gid,MYFLOAT dt)
42 60
{
43
    float4 x0=clDataIn[gid].lo;
44
    float4 v0=clDataIn[gid].hi;
45
    float4 a0=(0.,0.,0.,0.);
61
    MYFLOAT4 x0=clDataIn[gid].lo;
62
    MYFLOAT4 v0=clDataIn[gid].hi;
63
    MYFLOAT4 a0=(0.,0.,0.,0.);
46 64
    for (int i=0;i<get_global_size(0);i++)
47 65
    {
48 66
        if (gid != i)
49 67
        a0+=Interaction(x0,clDataIn[i].lo);
50 68
    }
51 69
        
52
    float4 x1=x0+v0*(float)0.5*dt;
53
    float4 v1=v0+a0*(float)0.5*dt;
54
    float4 a1=(0.,0.,0.,0.);
70
    MYFLOAT4 x1=x0+v0*(MYFLOAT)0.5*dt;
71
    MYFLOAT4 v1=v0+a0*(MYFLOAT)0.5*dt;
72
    MYFLOAT4 a1=(0.,0.,0.,0.);
55 73
    for (int i=0;i<get_global_size(0);i++)
56 74
    {
57 75
        if (gid != i)
58 76
        a1+=Interaction(x1,clDataIn[i].lo);
59 77
    }
60 78

  
61
    float4 x2=x0+v1*(float)0.5*dt;
62
    float4 v2=v0+a1*(float)0.5*dt;
63
    float4 a2=(0.,0.,0.,0.);
79
    MYFLOAT4 x2=x0+v1*(MYFLOAT)0.5*dt;
80
    MYFLOAT4 v2=v0+a1*(MYFLOAT)0.5*dt;
81
    MYFLOAT4 a2=(0.,0.,0.,0.);
64 82
    for (int i=0;i<get_global_size(0);i++)
65 83
    {
66 84
        if (gid != i)
67 85
        a2+=Interaction(x2,clDataIn[i].lo);
68 86
    }
69 87
    
70
    float4 x3=x0+v2*dt;
71
    float4 v3=v0+a2*dt;
72
    float4 a3=(0.,0.,0.,0.);
88
    MYFLOAT4 x3=x0+v2*dt;
89
    MYFLOAT4 v3=v0+a2*dt;
90
    MYFLOAT4 a3=(0.,0.,0.,0.);
73 91
    for (int i=0;i<get_global_size(0);i++)
74 92
    {
75 93
        if (gid != i)
76 94
        a3+=Interaction(x3,clDataIn[i].lo);
77 95
    }
78 96
    
79
    float4 xf=x0+dt*(v0+(float)2.*(v1+v2)+v3)/(float)6.;
80
    float4 vf=v0+dt*(a0+(float)2.*(a1+a2)+a3)/(float)6.;
97
    MYFLOAT4 xf=x0+dt*(v0+(MYFLOAT)2.*(v1+v2)+v3)/(MYFLOAT)6.;
98
    MYFLOAT4 vf=v0+dt*(a0+(MYFLOAT)2.*(a1+a2)+a3)/(MYFLOAT)6.;
81 99
     
82
    return((float8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
100
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
83 101
}
84 102

  
85 103
// Elements from : http://doswa.com/2009/01/02/fourth-order-runge-kutta-numerical-integration.html
86 104

  
87
float8 AtomicRungeKutta2(__global float8* clDataIn,int gid,float dt)
105
MYFLOAT8 AtomicRungeKutta2(__global MYFLOAT8* clDataIn,int gid,MYFLOAT dt)
88 106
{
89
    float4 x[4],v[4],a[4],xf,vf;
107
    MYFLOAT4 x[4],v[4],a[4],xf,vf;
90 108

  
91 109
    x[0]=clDataIn[gid].lo;
92 110
    v[0]=clDataIn[gid].hi;
......
97 115
        a[0]+=Interaction(x[0],clDataIn[i].lo);
98 116
    }
99 117
        
100
    x[1]=x[0]+v[0]*(float)0.5*dt;
101
    v[1]=v[0]+a[0]*(float)0.5*dt;
118
    x[1]=x[0]+v[0]*(MYFLOAT)0.5*dt;
119
    v[1]=v[0]+a[0]*(MYFLOAT)0.5*dt;
102 120
    a[1]=(0.,0.,0.,0.);
103 121
    for (int i=0;i<get_global_size(0);i++)
104 122
    {
......
106 124
        a[1]+=Interaction(x[1],clDataIn[i].lo);
107 125
    }
108 126

  
109
    x[2]=x[0]+v[1]*(float)0.5*dt;
110
    v[2]=v[0]+a[1]*(float)0.5*dt;
127
    x[2]=x[0]+v[1]*(MYFLOAT)0.5*dt;
128
    v[2]=v[0]+a[1]*(MYFLOAT)0.5*dt;
111 129
    a[2]=(0.,0.,0.,0.);
112 130
    for (int i=0;i<get_global_size(0);i++)
113 131
    {
......
124 142
        a[3]+=Interaction(x[3],clDataIn[i].lo);
125 143
    }
126 144
    
127
    xf=x[0]+dt*(v[0]+(float)2.*(v[1]+v[2])+v[3])/(float)6.;
128
    vf=v[0]+dt*(a[0]+(float)2.*(a[1]+a[2])+a[3])/(float)6.;
145
    xf=x[0]+dt*(v[0]+(MYFLOAT)2.*(v[1]+v[2])+v[3])/(MYFLOAT)6.;
146
    vf=v[0]+dt*(a[0]+(MYFLOAT)2.*(a[1]+a[2])+a[3])/(MYFLOAT)6.;
129 147
     
130
    return((float8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
148
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
131 149
}
132 150

  
133
float8 AtomicEuler(__global float8* clDataIn,int gid,float dt)
151
MYFLOAT8 AtomicEuler(__global MYFLOAT8* clDataIn,int gid,MYFLOAT dt)
134 152
{
135
    float4 x,v,a,xf,vf;
153
    MYFLOAT4 x,v,a,xf,vf;
136 154

  
137 155
    x=clDataIn[gid].lo;
138 156
    v=clDataIn[gid].hi;
......
146 164
    xf=x+dt*v;
147 165
    vf=v+dt*a;
148 166
 
149
    return((float8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
167
    return((MYFLOAT8)(xf.s0,xf.s1,xf.s2,xf.s3,vf.s0,vf.s1,vf.s2,vf.s3));
150 168
}
151 169

  
152
__kernel void SplutterPoints(__global float8* clData, float box, float velocity,
170
__kernel void SplutterPoints(__global MYFLOAT8* clData, MYFLOAT box, MYFLOAT velocity,
153 171
                               uint seed_z,uint seed_w)
154 172
{
155 173
    int gid = get_global_id(0);
156 174
    uint z=seed_z+(uint)gid;
157 175
    uint w=seed_w-(uint)gid;
158
    float theta=MWCfp*PI;
159
    float phi=MWCfp*PI*2.;
160
    float sinTheta=sin(theta);
161
    clData[gid].s01234567 = (float8) (box*MWCfp,box*MWCfp,box*MWCfp,0.,0.,0.,0.,0.);
176
    MYFLOAT theta=MWCfp*PI;
177
    MYFLOAT phi=MWCfp*PI*2.;
178
    MYFLOAT sinTheta=sin(theta);
179
    clData[gid].s01234567 = (MYFLOAT8) (box*MWCfp,box*MWCfp,box*MWCfp,0.,0.,0.,0.,0.);
162 180
    clData[gid].s4=velocity*sinTheta*cos(phi);
163 181
    clData[gid].s5=velocity*sinTheta*sin(phi);
164 182
    clData[gid].s6=velocity*cos(theta);
165 183
}
166 184

  
167
__kernel void RungeKutta(__global float8* clData,float h)
185
__kernel void RungeKutta(__global MYFLOAT8* clData,MYFLOAT h)
168 186
{
169 187
    int gid = get_global_id(0);
170 188
    
171
    float8 clDataGid=AtomicRungeKutta(clData,gid,h);
189
    MYFLOAT8 clDataGid=AtomicRungeKutta(clData,gid,h);
172 190
    barrier(CLK_GLOBAL_MEM_FENCE);
173 191
    clData[gid]=clDataGid;
174 192
}
175 193

  
176
__kernel void Euler(__global float8* clData,float h)
194
__kernel void Euler(__global MYFLOAT8* clData,MYFLOAT h)
177 195
{
178 196
    int gid = get_global_id(0);
179 197
    
180
    float8 clDataGid=AtomicEuler(clData,gid,h);
198
    MYFLOAT8 clDataGid=AtomicEuler(clData,gid,h);
181 199
    barrier(CLK_GLOBAL_MEM_FENCE);
182 200
    clData[gid]=clDataGid;
183 201
}
......
185 203

  
186 204
if __name__=='__main__':
187 205
    
206
    # ValueType
207
    ValueType='FP32'
208
    class MyFloat(np.float32):pass
209
    clType=cl_array.vec.float8
188 210
    # Set defaults values
189 211
    np.set_printoptions(precision=2)  
190 212
    # Id of Device : 1 is for first find !
......
192 214
    # Iterations is integer
193 215
    Number=1024
194 216
    # Size of box
195
    SizeOfBox=1.
217
    SizeOfBox=MyFloat(1.)
196 218
    # Initial velocity of particules
197
    Velocity=1.
219
    Velocity=MyFloat(1.)
198 220
    # Redo the last process
199 221
    Iterations=1000
200 222
    # Step
201
    Step=0.1
223
    Step=MyFloat(0.1)
202 224
    # Method of integration
203 225
    Method='RungeKutta'
226
    # InitialRandom
227
    InitialRandom=False
228
    # RNG Marsaglia Method
229
    RNG='MWC'
230
    
231
    HowToUse='%s -h [Help] -r [InitialRandom] -d <DeviceId> -n <NumberOfParticules> -z <SizeOfBox> -v <Velocity> -s <Step> -i <Iterations> -m <RungeKutta|Euler> -t <FP32|FP64>'
204 232

  
205
    HowToUse='%s -d <DeviceId> -n <NumberOfParticules> -z <SizeOfBox> -v <Velocity> -s <Step> -i <Iterations> -m <RungeKutta|Euler>'
206

  
207 233
    try:
208
        opts, args = getopt.getopt(sys.argv[1:],"hd:n:z:v:i:s:m:",["device=","number=","size=","velocity=","iterations=","step=","method="])
234
        opts, args = getopt.getopt(sys.argv[1:],"rhd:n:z:v:i:s:m:t:",["random","device=","number=","size=","velocity=","iterations=","step=","method=","valuetype="])
209 235
    except getopt.GetoptError:
210 236
        print(HowToUse % sys.argv[0])
211 237
        sys.exit(2)
......
216 242

  
217 243
            print("\nInformations about devices detected under OpenCL:")
218 244
            try:
219
                Id=1
245
                Id=0
220 246
                for platform in cl.get_platforms():
221 247
                    for device in platform.get_devices():
222 248
                        deviceType=cl.device_type.to_string(device.type)
......
227 253
                print("Your platform does not seem to support OpenCL")
228 254
                sys.exit()
229 255

  
256
        elif opt in ("-t", "--valuetype"):
257
            if arg=='FP64':
258
                class MyFloat(np.float64): pass
259
                clType=cl_array.vec.double8
260
            else:
261
                class MyFloat(np.float32):pass
262
                clType=cl_array.vec.float8
263
            ValueType = arg
230 264
        elif opt in ("-d", "--device"):
231 265
            Device=int(arg)
232 266
        elif opt in ("-m", "--method"):
......
234 268
        elif opt in ("-n", "--number"):
235 269
            Number=int(arg)
236 270
        elif opt in ("-z", "--size"):
237
            SizeOfBox=np.float32(arg)
271
            SizeOfBox=MyFloat(arg)
238 272
        elif opt in ("-v", "--velocity"):
239
            Velocity=np.float32(arg)
273
            Velocity=MyFloat(arg)
240 274
        elif opt in ("-s", "--step"):
241
            Step=np.float32(arg)
275
            Step=MyFloat(arg)
242 276
        elif opt in ("-i", "--iterations"):
243 277
            Iterations=int(arg)
244
            
278
        elif opt in ("-r", "--random"):
279
            InitialRandom=True
280

  
281
    SizeOfBox=MyFloat(SizeOfBox)
282
    Velocity=MyFloat(Velocity)
283
    Step=MyFloat(Step)
284
                
245 285
    print("Device choosed : %s" % Device)
246 286
    print("Number of particules : %s" % Number)
247 287
    print("Size of Box : %s" % SizeOfBox)
......
249 289
    print("Number of iterations % s" % Iterations)
250 290
    print("Step of iteration % s" % Step)
251 291
    print("Method of resolution % s" % Method)
252
    
253
    MyData = np.zeros(Number, dtype=cl_array.vec.float8)
292
    print("Seed for RNG % s" % InitialRandom)
293
    print("ValueType is % s" % ValueType)
254 294

  
255
    Id=1
295
    # Create Numpy array of CL vector with 8 FP32    
296
    MyData = np.zeros(Number, dtype=clType)
297

  
298
    Marsaglia,Computing=DictionariesAPI()
299

  
300
    # Scan the OpenCL arrays
301
    Id=0
256 302
    HasXPU=False
257 303
    for platform in cl.get_platforms():
258 304
        for device in platform.get_devices():
......
267 313
        print("No XPU #%i found in all of %i devices, sorry..." % (Device,Id-1))
268 314
        sys.exit()      
269 315

  
270
    # Je cree le contexte et la queue pour son execution
316
    # Create Context
271 317
    try:
272 318
        ctx = cl.Context([XPU])
273 319
        queue = cl.CommandQueue(ctx,properties=cl.command_queue_properties.PROFILING_ENABLE)
274 320
    except:
275 321
        print("Crash during context creation")
276
   
277 322

  
278
    MyRoutines = cl.Program(ctx, BlobOpenCL).build()
323
    print(Marsaglia[RNG],Computing[ValueType])
324
    # Build all routines used for the computing
325
    MyRoutines = cl.Program(ctx, BlobOpenCL).build(options = "-cl-mad-enable -cl-fast-relaxed-math -DTRNG=%i -DTYPE=%i" % (Marsaglia[RNG],Computing[ValueType]))
279 326

  
280 327
# Initial forced values for exploration
281 328
#    MyData[0][0]=np.float32(-1.)
......
289 336
    clData = cl.Buffer(ctx, mf.READ_WRITE, MyData.nbytes)
290 337
    #clData = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=MyData)
291 338

  
292
    print('Tous au meme endroit')
339
    print('At this points, all particles are at the same place.')
293 340

  
294
#    MyRoutines.SplutterPoints(queue,(Number,1),None,clDataIn,np.float32(SizeOfBox),np.float32(Velocity),np.uint32(nprnd(2**32)),np.uint32(nprnd(2**32)))
295
    MyRoutines.SplutterPoints(queue,(Number,1),None,clData,np.float32(SizeOfBox),np.float32(Velocity),np.uint32(110271),np.uint32(250173))
341
    print(SizeOfBox.dtype)
342
    
343
    # Set particles to RNG points
344
    if InitialRandom:
345
        MyRoutines.SplutterPoints(queue,(Number,1),None,clData,SizeOfBox,Velocity,np.uint32(nprnd(2**32)),np.uint32(nprnd(2**32)))
346
    else:
347
        MyRoutines.SplutterPoints(queue,(Number,1),None,clData,SizeOfBox,Velocity,np.uint32(110271),np.uint32(250173))
296 348

  
297
    print('Tous distribues')
349
    print('All particules distributed')
298 350
 
299 351
    cl.enqueue_copy(queue, MyData, clData)
300 352
    t0=np.array([[MyData[0][0],MyData[0][1],MyData[0][2]]])
......
303 355

  
304 356
    time_start=time.time()
305 357
    for i in range(Iterations):
306
        if Method=="RungeKutta":
307
            CLLaunch=MyRoutines.RungeKutta(queue,(Number,1),None,clData,np.float32(Step))
358
        if Method=="RungeKutta":            
359
            CLLaunch=MyRoutines.RungeKutta(queue,(Number,1),None,clData,Step)
308 360
        else:
309
            CLLaunch=MyRoutines.Euler(queue,(Number,1),None,clData,np.float32(Step))
361
            CLLaunch=MyRoutines.Euler(queue,(Number,1),None,clData,Step)
310 362
        CLLaunch.wait()
311 363
        cl.enqueue_copy(queue, MyData, clData)
312 364
        t0=np.append(t0,[MyData[0][0],MyData[0][1],MyData[0][2]])
......
314 366
        tL=np.append(tL,[MyData[-1][0],MyData[-1][1],MyData[-1][2]])
315 367
    print("\nDuration on %s for each %s" % (Device,(time.time()-time_start)/Iterations))
316 368
    
317
    t0=np.transpose(np.reshape(t0,(Iterations+1,3)))
318
    t1=np.transpose(np.reshape(t1,(Iterations+1,3)))
319
    tL=np.transpose(np.reshape(tL,(Iterations+1,3)))
369
    # t0=np.transpose(np.reshape(t0,(Iterations+1,3)))
370
    # t1=np.transpose(np.reshape(t1,(Iterations+1,3)))
371
    # tL=np.transpose(np.reshape(tL,(Iterations+1,3)))
320 372
    
321
    import matplotlib.pyplot as plt
322
    from mpl_toolkits.mplot3d import Axes3D
373
    # import matplotlib.pyplot as plt
374
    # from mpl_toolkits.mplot3d import Axes3D
323 375
    
324
    fig = plt.figure()
325
    ax = fig.gca(projection='3d')
326
    ax.scatter(t0[0],t0[1],t0[2], marker='^',color='blue')
327
    ax.scatter(t1[0],t1[1],t1[2], marker='o',color='red')
328
    ax.scatter(tL[0],tL[1],tL[2], marker='D',color='green')
376
    # fig = plt.figure()
377
    # ax = fig.gca(projection='3d')
378
    # ax.scatter(t0[0],t0[1],t0[2], marker='^',color='blue')
379
    # ax.scatter(t1[0],t1[1],t1[2], marker='o',color='red')
380
    # ax.scatter(tL[0],tL[1],tL[2], marker='D',color='green')
329 381
    
330
    ax.set_xlabel('X Label')
331
    ax.set_ylabel('Y Label')
332
    ax.set_zlabel('Z Label')
382
    # ax.set_xlabel('X Label')
383
    # ax.set_ylabel('Y Label')
384
    # ax.set_zlabel('Z Label')
333 385

  
334
    plt.show()
386
    # plt.show()
335 387
    
336 388
    clData.release()

Formats disponibles : Unified diff