Révision 7

Pi/MP/PiMP-unprotected.py (revision 7)
1
#!/usr/bin/env python
2

  
3
# Version using Multiprocessing module
4
#
5
# Pi-by-MC
6
#
7
# CC BY-NC-SA 2013 : <emmanuel.quemener@ens-lyon.fr> 
8
#
9

  
10
import getopt
11
import numpy
12

  
13
from random import random
14
# Multithread library call
15
from multiprocessing import Pool
16

  
17
# Common tools
18
import sys
19
import getopt
20
import time
21
import matplotlib.pyplot as plt
22
import math
23
from scipy.optimize import curve_fit
24
from socket import gethostname
25

  
26
# Predicted Amdahl Law (Reduced with s=1-p)  
27
def AmdahlR(N, T1, p):
28
    return (T1*(1-p+p/N))
29

  
30
# Predicted Amdahl Law
31
def Amdahl(N, T1, s, p):
32
    return (T1*(s+p/N))
33

  
34
# Predicted Mylq Law with first order
35
def Mylq(N, T1,s,c,p):
36
    return (T1*(s+c*N+p/N))
37

  
38
# Predicted Mylq Law with second order
39
def Mylq2(N, T1,s,c1,c2,p):
40
    return (T1*(s+c1*N+c2*N*N+p/N))
41

  
42
def MainLoop(iterations):
43
    
44
    total=0
45
    # Absulute necessary to use xrange instead of range to avoid out of memory !
46
    for i in xrange(iterations):
47
        # Random access coordonate
48
        x,y=random(),random()
49
        
50
        if ((x*x+y*y) < 1.0):
51
            total+=1
52
            
53
    return(total)
54
        
55
def MetropolisMP(circle,iterations,steps,jobs):
56

  
57
    MyPi=numpy.zeros(steps)
58
    MyDuration=numpy.array([])
59
    
60
    # Define iterations to send to each node
61
    if iterations%jobs==0:
62
        iterationsMP=iterations/jobs
63
    else:
64
        iterationsMP=iterations/jobs+1
65
    print "%i iterations will be send to each core" % iterationsMP
66
    
67
    WorkItems=[]
68
    for i in xrange(0,jobs):
69
        WorkItems.append(iterationsMP)
70

  
71
    for i in xrange(steps):
72
        start=time.time()
73
        pool=Pool(processes=jobs)
74
        # Define the number of processes to be launched at a time
75
        # pool=Pool(processes=CORES)
76
        print "Start on %i processors..." % jobs
77
        # MAP: distribution of usecases T to be applied to MetropolisStrip 
78
        # WorkLaunches=[ pool.apply_async(MainLoop,(wi,)) for wi in WorkItems ]
79
        # circle=[wl.get() for wl in WorkLaunches]
80
        circle=pool.map(MainLoop,WorkItems)
81
        MyDuration=numpy.append(MyDuration,time.time()-start)
82
        MyPi[i]=4.*float(numpy.sum(circle))/float(iterationsMP)/float(jobs)
83

  
84
    return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration))
85

  
86
def FitAndPrint(N,D,Curves):
87

  
88
    try:
89
      coeffs_Amdahl, matcov_Amdahl = curve_fit(Amdahl, N, D)
90

  
91
      D_Amdahl=Amdahl(N,coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
92
      coeffs_Amdahl[1]=coeffs_Amdahl[1]*coeffs_Amdahl[0]/D[0]
93
      coeffs_Amdahl[2]=coeffs_Amdahl[2]*coeffs_Amdahl[0]/D[0]
94
      coeffs_Amdahl[0]=D[0]
95
      print "Amdahl Normalized: T=%.2f(%.6f+%.6f/N)" % \
96
            (coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
97
    except:
98
        print "Impossible to fit for Amdahl law : only %i elements" % len(D) 
99

  
100
    try:
101
        coeffs_AmdahlR, matcov_AmdahlR = curve_fit(AmdahlR, N, D)
102

  
103
        D_AmdahlR=AmdahlR(N,coeffs_AmdahlR[0],coeffs_AmdahlR[1])
104
        coeffs_AmdahlR[1]=coeffs_AmdahlR[1]*coeffs_AmdahlR[0]/D[0]
105
        coeffs_AmdahlR[0]=D[0]
106
        print "Amdahl Reduced Normalized: T=%.2f(%.6f+%.6f/N)" % \
107
              (coeffs_AmdahlR[0],1-coeffs_AmdahlR[1],coeffs_AmdahlR[1])
108
    except:
109
        print "Impossible to fit for Reduced Amdahl law : only %i elements" % len(D) 
110

  
111
    try:
112
        coeffs_Mylq, matcov_Mylq = curve_fit(Mylq, N, D)
113

  
114
        coeffs_Mylq[1]=coeffs_Mylq[1]*coeffs_Mylq[0]/D[0]
115
        coeffs_Mylq[2]=coeffs_Mylq[2]*coeffs_Mylq[0]/D[0]
116
        coeffs_Mylq[3]=coeffs_Mylq[3]*coeffs_Mylq[0]/D[0]
117
        coeffs_Mylq[0]=D[0]
118
        print "Mylq Normalized : T=%.2f(%.6f+%.6f*N+%.6f/N)" % (coeffs_Mylq[0],
119
                                                                coeffs_Mylq[1],
120
                                                                coeffs_Mylq[2],
121
                                                                coeffs_Mylq[3])
122
        D_Mylq=Mylq(N,coeffs_Mylq[0],coeffs_Mylq[1],coeffs_Mylq[2],
123
                    coeffs_Mylq[3])
124
    except:
125
        print "Impossible to fit for Mylq law : only %i elements" % len(D) 
126

  
127
    if Curves:
128
        plt.xlabel("Number of Threads/work Items")
129
        plt.ylabel("Total Elapsed Time")
130

  
131
        Experience,=plt.plot(N,D,'ro') 
132
        try:
133
            pAmdahl,=plt.plot(N,D_Amdahl,label="Loi de Amdahl")    
134
            pMylq,=plt.plot(N,D_Mylq,label="Loi de Mylq")
135
        except:
136
            print "Fit curves seem not to be available"
137

  
138
        plt.legend()
139
        plt.show()
140

  
141
if __name__=='__main__':
142

  
143
    # Set defaults values
144
    # Iterations is integer
145
    Iterations=1000000
146
    # JobStart in first number of Jobs to explore
147
    JobStart=1
148
    # JobEnd is last number of Jobs to explore
149
    JobEnd=1
150
    # Redo is the times to redo the test to improve metrology
151
    Redo=1
152
    # OutMetrology is method for duration estimation : False is GPU inside
153
    OutMetrology=False
154
    # Curves is True to print the curves
155
    Curves=False
156

  
157
    try:
158
        opts, args = getopt.getopt(sys.argv[1:],"hoci:s:e:r:",["alu=","gpustyle=","parastyle=","iterations=","jobstart=","jobend=","redo=","device="])
159
    except getopt.GetoptError:
160
        print '%s -o (Out of Core Metrology) -c (Print Curves) -i <Iterations> -s <JobStart> -e <JobEnd> -r <RedoToImproveStats>' % sys.argv[0]
161
        sys.exit(2)
162
    
163
    for opt, arg in opts:
164
        if opt == '-h':
165
            print '%s -o (Out of Core Metrology) -c (Print Curves) -i <Iterations> -s <JobStart> -e <JobEnd> -r <RedoToImproveStats>' % sys.argv[0]
166
            sys.exit()
167
        elif opt == '-o':
168
            OutMetrology=True
169
        elif opt == '-c':
170
            Curves=True
171
        elif opt in ("-i", "--iterations"):
172
            Iterations = numpy.uint32(arg)
173
        elif opt in ("-s", "--jobstart"):
174
            JobStart = int(arg)
175
        elif opt in ("-e", "--jobend"):
176
            JobEnd = int(arg)
177
        elif opt in ("-r", "--redo"):
178
            Redo = int(arg)
179

  
180
    print "Iterations : %s" % Iterations
181
    print "Number of threads on start : %s" % JobStart
182
    print "Number of threads on end : %s" % JobEnd
183
    print "Number of redo : %s" % Redo
184
    print "Metrology done out : %r" % OutMetrology
185

  
186
    average=numpy.array([]).astype(numpy.float32)
187
    median=numpy.array([]).astype(numpy.float32)
188
    stddev=numpy.array([]).astype(numpy.float32)
189

  
190
    ExploredJobs=numpy.array([]).astype(numpy.uint32)
191

  
192
    Jobs=JobStart
193

  
194
    while Jobs <= JobEnd:
195
        avg,med,std=0,0,0
196
        ExploredJobs=numpy.append(ExploredJobs,Jobs)
197
        circle=numpy.zeros(Jobs).astype(numpy.uint32)
198
        
199
        if OutMetrology:
200
            duration=numpy.array([]).astype(numpy.float32)
201
            for i in range(Redo):
202
                start=time.time()
203
                MetropolisMP(circle,Iterations,Redo,Jobs)
204
                duration=numpy.append(duration,time.time()-start)
205
            avg=numpy.mean(duration)
206
            med=numpy.median(duration)
207
            std=numpy.std(duration)
208
        else:
209
            avg,med,std=MetropolisMP(circle,Iterations,Redo,Jobs)
210

  
211
        if (avg,med,std) != (0,0,0):
212
            print "avg,med,std",avg,med,std
213
            average=numpy.append(average,avg)
214
            median=numpy.append(median,med)
215
            stddev=numpy.append(stddev,std)
216
        else:
217
            print "Values seem to be wrong..."
218
        # THREADS*=2
219
        numpy.savez("Pi_%s_%i_%.8i_%s" % (JobStart,JobEnd,Iterations,gethostname()),(ExploredJobs,average,median,stddev))
220
        Jobs+=1
221

  
222
    FitAndPrint(ExploredJobs,median,Curves)
0 223

  
Pi/MP/PiMP.py.orig (revision 7)
1
#!/usr/bin/env python
2

  
3
# If numpy is loaded without being used, it does not work !
4
from math import exp
5
from random import random
6
# Multithread library call
7
#import multiprocessing
8
from multiprocessing import Pool
9
import numpy
10
from numpy.random import rand
11

  
12

  
13
def MainLoop(iterations):
14

  
15
    total=numpy.int(0)
16
    for i in range(0,iterations):
17
        # Random access coordonate
18
        #x,y=random(),random()
19
        x,y=rand(),rand()
20

  
21
        if ((x*x+y*y) < 1.0):
22
                total+=1
23

  
24
    return(total)
25

  
26
if __name__=='__main__':
27

  
28
    # Machine
29
    CORES=4
30
    
31
    # A=numpy.zeros(10)
32
    
33
    # Au dessus de 4 10^7, le MPI ne veut plus se lancer...
34
    Iterations=100000000
35

  
36
    total=0
37
    
38
    # Define iterations to send to each node
39
    if Iterations%CORES==0:
40
        iterations=Iterations/CORES
41
    else:
42
        iterations=Iterations/CORES+1
43
        print "%i iterations will be send to each core" % iterations
44
        
45
    IT=[]
46
    for i in range(0,CORES):
47
        IT.append(iterations)
48
        
49
    print IT
50

  
51
    # Define the number of processes to be launched at a time
52
    # POOL: resources to be used ( 
53
    # pool=Pool(processes=CORES)
54
    pool=Pool(processes=CORES)
55
    print "Start on %i processors..." % CORES
56

  
57
    # MAP: distribution of usecases T to be applied to MetropolisStrip 
58
    Results=pool.map(MainLoop,IT)
59
    
60
    # print sum(Results.get())
61
    print Results
0 62

  
Pi/MP/PostProcess.py (revision 7)
1
import numpy
2
npzfile=numpy.load("Ising2D_MP_256_16777216.npz")
3
npzfile['arr_0']
4
T=npzfile['arr_0'].transpose()[0]
5
E=npzfile['arr_0'].transpose()[1]
6
M=npzfile['arr_0'].transpose()[2]
7
print T
8
print E
9
print M
10
import matplotlib.pyplot 
11
matplotlib.pyplot.plot(T,E)
12
matplotlib.pyplot.show()
Pi/MP/PiMP.py (revision 7)
1
#!/usr/bin/env python
2

  
3
# Version using Multiprocessing module
4
#
5
# Pi-by-MC
6
#
7
# CC BY-NC-SA 2013 : <emmanuel.quemener@ens-lyon.fr> 
8
#
9

  
10
import getopt
11
import numpy
12

  
13
from random import random
14
# Multithread library call
15
from multiprocessing import Pool
16

  
17
# Common tools
18
import sys
19
import getopt
20
import time
21
import matplotlib.pyplot as plt
22
import math
23
from scipy.optimize import curve_fit
24
from socket import gethostname
25

  
26
# Predicted Amdahl Law (Reduced with s=1-p)  
27
def AmdahlR(N, T1, p):
28
    return (T1*(1-p+p/N))
29

  
30
# Predicted Amdahl Law
31
def Amdahl(N, T1, s, p):
32
    return (T1*(s+p/N))
33

  
34
# Predicted Mylq Law with first order
35
def Mylq(N, T1,s,c,p):
36
    return (T1*(s+c*N+p/N))
37

  
38
# Predicted Mylq Law with second order
39
def Mylq2(N, T1,s,c1,c2,p):
40
    return (T1*(s+c1*N+c2*N*N+p/N))
41

  
42
def MainLoop(iterations):
43
    
44
    total=0
45
    # Absulute necessary to use xrange instead of range to avoid out of memory !
46
    for i in xrange(iterations):
47
        # Random access coordonate
48
        x,y=random(),random()
49
        
50
        if ((x*x+y*y) < 1.0):
51
            total+=1
52
            
53
    return(total)
54
        
55
def MetropolisMP(circle,iterations,steps,jobs):
56

  
57
    MyPi=numpy.zeros(steps)
58
    MyDuration=numpy.array([])
59
    
60
    # Define iterations to send to each node
61
    if iterations%jobs==0:
62
        iterationsMP=iterations/jobs
63
    else:
64
        iterationsMP=iterations/jobs+1
65
    print "%i iterations will be send to each core" % iterationsMP
66
    
67
    WorkItems=[]
68
    for i in xrange(0,jobs):
69
        WorkItems.append(iterationsMP)
70

  
71
    for i in xrange(steps):
72
        start=time.time()
73
        pool=Pool(processes=jobs)
74
        # Define the number of processes to be launched at a time
75
        # pool=Pool(processes=CORES)
76
        print "Start on %i processors..." % jobs
77
        # MAP: distribution of usecases T to be applied to MetropolisStrip 
78
        # WorkLaunches=[ pool.apply_async(MainLoop,(wi,)) for wi in WorkItems ]
79
        # circle=[wl.get() for wl in WorkLaunches]
80
        circle=pool.map(MainLoop,WorkItems)
81
        MyDuration=numpy.append(MyDuration,time.time()-start)
82
        MyPi[i]=4.*float(numpy.sum(circle))/float(iterationsMP)/float(jobs)
83

  
84
    return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration))
85

  
86
def FitAndPrint(N,D,Curves):
87

  
88
    try:
89
      coeffs_Amdahl, matcov_Amdahl = curve_fit(Amdahl, N, D)
90

  
91
      D_Amdahl=Amdahl(N,coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
92
      coeffs_Amdahl[1]=coeffs_Amdahl[1]*coeffs_Amdahl[0]/D[0]
93
      coeffs_Amdahl[2]=coeffs_Amdahl[2]*coeffs_Amdahl[0]/D[0]
94
      coeffs_Amdahl[0]=D[0]
95
      print "Amdahl Normalized: T=%.2f(%.6f+%.6f/N)" % \
96
            (coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
97
    except:
98
        print "Impossible to fit for Amdahl law : only %i elements" % len(D) 
99

  
100
    try:
101
        coeffs_AmdahlR, matcov_AmdahlR = curve_fit(AmdahlR, N, D)
102

  
103
        D_AmdahlR=AmdahlR(N,coeffs_AmdahlR[0],coeffs_AmdahlR[1])
104
        coeffs_AmdahlR[1]=coeffs_AmdahlR[1]*coeffs_AmdahlR[0]/D[0]
105
        coeffs_AmdahlR[0]=D[0]
106
        print "Amdahl Reduced Normalized: T=%.2f(%.6f+%.6f/N)" % \
107
              (coeffs_AmdahlR[0],1-coeffs_AmdahlR[1],coeffs_AmdahlR[1])
108
    except:
109
        print "Impossible to fit for Reduced Amdahl law : only %i elements" % len(D) 
110

  
111
    try:
112
        coeffs_Mylq, matcov_Mylq = curve_fit(Mylq, N, D)
113

  
114
        coeffs_Mylq[1]=coeffs_Mylq[1]*coeffs_Mylq[0]/D[0]
115
        coeffs_Mylq[2]=coeffs_Mylq[2]*coeffs_Mylq[0]/D[0]
116
        coeffs_Mylq[3]=coeffs_Mylq[3]*coeffs_Mylq[0]/D[0]
117
        coeffs_Mylq[0]=D[0]
118
        print "Mylq Normalized : T=%.2f(%.6f+%.6f*N+%.6f/N)" % (coeffs_Mylq[0],
119
                                                                coeffs_Mylq[1],
120
                                                                coeffs_Mylq[2],
121
                                                                coeffs_Mylq[3])
122
        D_Mylq=Mylq(N,coeffs_Mylq[0],coeffs_Mylq[1],coeffs_Mylq[2],
123
                    coeffs_Mylq[3])
124
    except:
125
        print "Impossible to fit for Mylq law : only %i elements" % len(D) 
126

  
127
    if Curves:
128
        plt.xlabel("Number of Threads/work Items")
129
        plt.ylabel("Total Elapsed Time")
130

  
131
        Experience,=plt.plot(N,D,'ro') 
132
        try:
133
            pAmdahl,=plt.plot(N,D_Amdahl,label="Loi de Amdahl")    
134
            pMylq,=plt.plot(N,D_Mylq,label="Loi de Mylq")
135
        except:
136
            print "Fit curves seem not to be available"
137

  
138
        plt.legend()
139
        plt.show()
140

  
141
if __name__=='__main__':
142

  
143
    # Set defaults values
144
    # Iterations is integer
145
    Iterations=1000000
146
    # JobStart in first number of Jobs to explore
147
    JobStart=1
148
    # JobEnd is last number of Jobs to explore
149
    JobEnd=1
150
    # Redo is the times to redo the test to improve metrology
151
    Redo=1
152
    # OutMetrology is method for duration estimation : False is GPU inside
153
    OutMetrology=False
154
    # Curves is True to print the curves
155
    Curves=False
156

  
157
    try:
158
        opts, args = getopt.getopt(sys.argv[1:],"hoci:s:e:r:",["alu=","gpustyle=","parastyle=","iterations=","jobstart=","jobend=","redo=","device="])
159
    except getopt.GetoptError:
160
        print '%s -o (Out of Core Metrology) -c (Print Curves) -i <Iterations> -s <JobStart> -e <JobEnd> -r <RedoToImproveStats>' % sys.argv[0]
161
        sys.exit(2)
162
    
163
    for opt, arg in opts:
164
        if opt == '-h':
165
            print '%s -o (Out of Core Metrology) -c (Print Curves) -i <Iterations> -s <JobStart> -e <JobEnd> -r <RedoToImproveStats>' % sys.argv[0]
166
            sys.exit()
167
        elif opt == '-o':
168
            OutMetrology=True
169
        elif opt == '-c':
170
            Curves=True
171
        elif opt in ("-i", "--iterations"):
172
            Iterations = numpy.uint32(arg)
173
        elif opt in ("-s", "--jobstart"):
174
            JobStart = int(arg)
175
        elif opt in ("-e", "--jobend"):
176
            JobEnd = int(arg)
177
        elif opt in ("-r", "--redo"):
178
            Redo = int(arg)
179

  
180
    print "Iterations : %s" % Iterations
181
    print "Number of threads on start : %s" % JobStart
182
    print "Number of threads on end : %s" % JobEnd
183
    print "Number of redo : %s" % Redo
184
    print "Metrology done out : %r" % OutMetrology
185

  
186
    average=numpy.array([]).astype(numpy.float32)
187
    median=numpy.array([]).astype(numpy.float32)
188
    stddev=numpy.array([]).astype(numpy.float32)
189

  
190
    ExploredJobs=numpy.array([]).astype(numpy.uint32)
191

  
192
    Jobs=JobStart
193

  
194
    while Jobs <= JobEnd:
195
        avg,med,std=0,0,0
196
        ExploredJobs=numpy.append(ExploredJobs,Jobs)
197
        circle=numpy.zeros(Jobs).astype(numpy.uint32)
198
        
199
        if OutMetrology:
200
            duration=numpy.array([]).astype(numpy.float32)
201
            for i in range(Redo):
202
                start=time.time()
203
                try:
204
                    MetropolisMP(circle,Iterations,Redo,Jobs)
205
                except:
206
                    print "Problem with %i // computations" % Jobs
207
                duration=numpy.append(duration,time.time()-start)
208
            avg=numpy.mean(duration)
209
            med=numpy.median(duration)
210
            std=numpy.std(duration)
211
        else:
212
            try:
213
                avg,med,std=MetropolisMP(circle,Iterations,Redo,Jobs)
214
            except:
215
                print "Problem with %i // computations" % Jobs
216

  
217
        if (avg,med,std) != (0,0,0):
218
            print "avg,med,std",avg,med,std
219
            average=numpy.append(average,avg)
220
            median=numpy.append(median,med)
221
            stddev=numpy.append(stddev,std)
222
        else:
223
            print "Values seem to be wrong..."
224
        # THREADS*=2
225
        numpy.savez("Pi_%s_%i_%.8i_%s" % (JobStart,JobEnd,Iterations,gethostname()),(ExploredJobs,average,median,stddev))
226
        Jobs+=1
227

  
228
    FitAndPrint(ExploredJobs,median,Curves)
0 229

  
Pi/MP/PiMP.py.orig2 (revision 7)
1
#!/usr/bin/env python
2

  
3
# If numpy is loaded without being used, it does not work !
4
from math import exp
5
from random import random
6
# Multithread library call
7
from multiprocessing import Pool
8

  
9
def MainLoop(iterations):
10

  
11
    total=0
12
    for i in xrange(iterations):
13
        # Random access coordonate
14
        x,y=random(),random()
15

  
16
        if ((x*x+y*y) < 1.0):
17
                total+=1
18

  
19
    return(total)
20

  
21
if __name__=='__main__':
22

  
23
   # Machine
24
   CORES=4
25

  
26
   # Au dessus de 4 10^7, le MPI ne veut plus se lancer...
27
   Iterations=1000000000
28

  
29
   total=0
30

  
31
   # Define iterations to send to each node
32
   if Iterations%CORES==0:
33
	   iterations=Iterations/CORES
34
   else:
35
	   iterations=Iterations/CORES+1
36
   print "%i iterations will be send to each core" % iterations
37

  
38
   IT=[]
39
   for i in range(0,CORES):
40
	   IT.append(iterations)
41

  
42
   print IT
43

  
44
   # Define the number of processes to be launched at a time
45
   # POOL: resources to be used ( 
46
   #pool=Pool(processes=CORES)
47
   pool=Pool(CORES)
48
   print "Start on %i processors..." % CORES
49

  
50
   # MAP: distribution of usecases T to be applied to MetropolisStrip 
51
   Results=[ pool.apply_async(MainLoop,(i,)) for i in IT]
52

  
53
   results=[r.get() for r in Results]
54
   print results,sum(results)
0 55

  
Pi/Serial/PostProcess.py (revision 7)
1
import numpy
2
import sys
3
npzfile=numpy.load(sys.argv[1])
4
T=npzfile['arr_0'][0]
5
E=npzfile['arr_0'][1]
6
ED=npzfile['arr_0'][2]
7
import matplotlib.pyplot
8
matplotlib.pyplot.plot(T,E)
9
#matplotlib.pyplot.plot(T,E,T,ED)
10
matplotlib.pyplot.show()
Pi/Results/PostProcessGPU.py (revision 7)
1
import numpy
2
import sys
3

  
4
npzSerial=numpy.load("Ising2D_Serial_256_16777216.npz")
5
npzOCLG=numpy.load("Ising2D_OCLG_256_16777216.npz")
6
npzOCLL=numpy.load("Ising2D_OCLL_256_16777216.npz")
7
npzCUDAG=numpy.load("Ising2D_CUDAG_256_16777216.npz")
8
npzCUDAL=numpy.load("Ising2D_CUDAL_256_16777216.npz")
9

  
10
T=npzSerial['arr_0'][0]
11
ES=npzSerial['arr_0'][1]
12
EOCLG=npzOCLG['arr_0'][1]
13
EOCLL=npzOCLL['arr_0'][1]
14
ECUDAG=npzCUDAG['arr_0'][1]
15
ECUDAL=npzCUDAL['arr_0'][1]
16

  
17
import matplotlib.pyplot
18
matplotlib.pyplot.plot(T,ES,T,EOCLG,T,EOCLL,T,ECUDAG,T,ECUDAL)
19
matplotlib.pyplot.show()
20

  
Pi/Results/PostProcessMP.py (revision 7)
1
import numpy
2
import sys
3

  
4
npzSerial=numpy.load("Ising2D_Serial_256_16777216.npz")
5
npzMP=numpy.load("Ising2D_MP_256_16777216.npz")
6
npzMPI=numpy.load("Ising2D_MPI_256_16777216.npz")
7

  
8
T=npzSerial['arr_0'][0]
9
ES=npzSerial['arr_0'][1]
10
EMP=npzMP['arr_0'].transpose()[1]
11
EMPI=npzMPI['arr_0'].transpose()[1]
12

  
13
import matplotlib.pyplot
14
matplotlib.pyplot.plot(T,ES,T,EMP,T,EMPI)
15
matplotlib.pyplot.show()
16

  
Pi/Results/PostProcessCGPU.py (revision 7)
1
import numpy
2
import sys
3

  
4
npzOCLLG=numpy.load("Ising2D_OCLL_256_16777216_GPU_atlas.npz")
5
npzOCLLC=numpy.load("Ising2D_OCLL_256_16777216_CPU_atlas.npz")
6
npzCUDAL=numpy.load("Ising2D_CUDAL_256_16777216_GPU_atlas.npz")
7

  
8
npzOCLLG2=numpy.load("Ising2D_OCLL_256_16777216_GPU_o745-2.npz")
9
npzCUDAL2=numpy.load("Ising2D_CUDAL_256_16777216_GPU_o745-2.npz")
10

  
11

  
12
T=npzOCLLG['arr_0'][0]
13
EOCLLG=npzOCLLG['arr_0'][1]
14
POCLLG=npzOCLLG['arr_0'][2]
15
EOCLLC=npzOCLLC['arr_0'][1]
16
POCLLC=npzOCLLC['arr_0'][2]
17
ECUDAL=npzCUDAL['arr_0'][1]
18
PCUDAL=npzCUDAL['arr_0'][2]
19

  
20
EOCLLG2=npzOCLLG2['arr_0'][1]
21
POCLLG2=npzOCLLG2['arr_0'][2]
22
ECUDAL2=npzCUDAL2['arr_0'][1]
23
PCUDAL2=npzCUDAL2['arr_0'][2]
24

  
25
dPOCLLG=numpy.diff(POCLLG)
26
dPOCLLC=numpy.diff(POCLLC)
27
dPCUDAL=numpy.diff(PCUDAL)
28

  
29
dPOCLLG2=numpy.diff(POCLLG2)
30
dPCUDAL2=numpy.diff(PCUDAL2)
31

  
32
dPOCLLG=numpy.insert(dPOCLLG,0,0)
33
dPOCLLC=numpy.insert(dPOCLLC,0,0)
34
dPCUDAL=numpy.insert(dPCUDAL,0,0)
35

  
36
dPOCLLG2=numpy.insert(dPOCLLG2,0,0)
37
dPCUDAL2=numpy.insert(dPCUDAL2,0,0)
38

  
39
from matplotlib.pyplot import *
40

  
41
plot(T,EOCLLG,T,EOCLLC,T,ECUDAL,T,dPOCLLG,T,dPOCLLC,T,dPCUDAL,
42
     T,EOCLLG2,T,ECUDAL2,T,dPOCLLG2,T,dPCUDAL2)
43
legend((r'OCL GPU GTX560',r'OCL CPU Xeon4c',r'Cuda GTX560',
44
        r'OCL GPU GT8400',r'Cuda GT8400'))
45
xlabel('Temperature',{'fontsize':20})
46
ylabel('Energy',{'fontsize':20})
47

  
48
matplotlib.pyplot.show()
49

  
Pi/Results/PostProcess.py (revision 7)
1
import numpy
2
import sys
3

  
4
npzSerial=numpy.load("Ising2D_Serial_256_16777216.npz")
5
npzMP=numpy.load("Ising2D_MP_256_16777216.npz")
6
npzMPI=numpy.load("Ising2D_MPI_256_16777216.npz")
7
npzOCLG=numpy.load("Ising2D_OCLG_256_16777216.npz")
8
npzOCLL=numpy.load("Ising2D_OCLL_256_16777216.npz")
9
npzCUDAG=numpy.load("Ising2D_CUDAG_256_16777216.npz")
10
npzCUDAL=numpy.load("Ising2D_CUDAL_256_16777216.npz")
11

  
12
T=npzSerial['arr_0'][0]
13
ES=npzSerial['arr_0'][1]
14
EMP=npzMP['arr_0'].transpose()[1]
15
EMPI=npzMPI['arr_0'].transpose()[1]
16
EOCLG=npzOCLG['arr_0'][1]
17
EOCLL=npzOCLL['arr_0'][1]
18
ECUDAG=npzCUDAG['arr_0'][1]
19
ECUDAL=npzCUDAL['arr_0'][1]
20

  
21
import matplotlib.pyplot
22
matplotlib.pyplot.plot(T,ES,T,EMP,T,EMPI,T,EOCLG,T,EOCLL,T,ECUDAG,T,ECUDAL)
23
matplotlib.pyplot.show()
24

  
Pi/C/CAPI/pimodule.c (revision 7)
1
#include <Python.h>
2
#include <math.h>
3

  
4
// Marsaglia RNG very simple implementation
5
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
6
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
7
#define MWC   (znew+wnew)
8
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
9
#define CONG  (jcong=69069*jcong+1234567)
10
#define KISS  ((MWC^CONG)+SHR3)
11

  
12
#define MWCfp MWC * 2.328306435454494e-10f
13
#define KISSfp KISS * 2.328306435454494e-10f
14

  
15
int _InsideCircle(unsigned int iterations,
16
		  unsigned int seed_w,unsigned int seed_z)
17
{
18
   unsigned int z=seed_z;
19
   unsigned int w=seed_w;
20
   unsigned int i;
21

  
22
   int total=0;
23

  
24
   for (i=0;i<iterations;i++) {
25

  
26
      float x=MWCfp ;
27
      float y=MWCfp ;
28

  
29
      // Matching test
30
      int inside=((x*x+y*y) < 1.0f) ? 1:0;
31
      total+=inside;
32
   }
33

  
34
   return(total);
35
}
36

  
37
static PyObject* InsideCircle(PyObject* self, PyObject* args)
38
{
39
  int i,z,w;
40
 
41
  if (!PyArg_ParseTuple(args, "iii", &i,&z,&w))
42
    return NULL;
43
 
44
  return Py_BuildValue("i", _InsideCircle(i,z,w));
45
}
46
 
47
static PyMethodDef MonteCarloMethods[] = {
48
  {"InsideCircle", InsideCircle, METH_VARARGS, "Inside Circle Randomly Check"},
49
  {NULL, NULL, 0, NULL}
50
};
51
 
52
PyMODINIT_FUNC
53
initMonteCarlo(void)
54
{
55
  (void) Py_InitModule("MonteCarlo", MonteCarloMethods);
56
}
Pi/C/CAPI/MC.py (revision 7)
1
#!/usr/bin/env python
2

  
3
import MonteCarlo
4

  
5
print MonteCarlo.InsideCircle(1000000000,1,2)
Pi/C/CAPI/setup.py (revision 7)
1
from distutils.core import setup, Extension
2

  
3
module1 = Extension('MonteCarlo', sources = ['pimodule.c'])
4

  
5
setup (name = 'PackageName',
6
       version = '1.0',
7
       description = 'This is a demo package',
8
       ext_modules = [module1])
Pi/C/CAPI/Build.sh (revision 7)
1
rm -r build MonteCarlo.so 
2
python setup.py build
3
cp build/lib.linux-x86_64-2.7/MonteCarlo.so .
4
python MC.py
0 5

  
Pi/C/examples/swig/hello.i (revision 7)
1
/*hello.i*/
2
 
3
%module hello
4
extern void say_hello(const char* name);
Pi/C/examples/swig/hello.py (revision 7)
1
# This file was automatically generated by SWIG (http://www.swig.org).
2
# Version 2.0.7
3
#
4
# Do not make changes to this file unless you know what you are doing--modify
5
# the SWIG interface file instead.
6

  
7

  
8

  
9
from sys import version_info
10
if version_info >= (2,6,0):
11
    def swig_import_helper():
12
        from os.path import dirname
13
        import imp
14
        fp = None
15
        try:
16
            fp, pathname, description = imp.find_module('_hello', [dirname(__file__)])
17
        except ImportError:
18
            import _hello
19
            return _hello
20
        if fp is not None:
21
            try:
22
                _mod = imp.load_module('_hello', fp, pathname, description)
23
            finally:
24
                fp.close()
25
            return _mod
26
    _hello = swig_import_helper()
27
    del swig_import_helper
28
else:
29
    import _hello
30
del version_info
31
try:
32
    _swig_property = property
33
except NameError:
34
    pass # Python < 2.2 doesn't have 'property'.
35
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
36
    if (name == "thisown"): return self.this.own(value)
37
    if (name == "this"):
38
        if type(value).__name__ == 'SwigPyObject':
39
            self.__dict__[name] = value
40
            return
41
    method = class_type.__swig_setmethods__.get(name,None)
42
    if method: return method(self,value)
43
    if (not static):
44
        self.__dict__[name] = value
45
    else:
46
        raise AttributeError("You cannot add attributes to %s" % self)
47

  
48
def _swig_setattr(self,class_type,name,value):
49
    return _swig_setattr_nondynamic(self,class_type,name,value,0)
50

  
51
def _swig_getattr(self,class_type,name):
52
    if (name == "thisown"): return self.this.own()
53
    method = class_type.__swig_getmethods__.get(name,None)
54
    if method: return method(self)
55
    raise AttributeError(name)
56

  
57
def _swig_repr(self):
58
    try: strthis = "proxy of " + self.this.__repr__()
59
    except: strthis = ""
60
    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
61

  
62
try:
63
    _object = object
64
    _newclass = 1
65
except AttributeError:
66
    class _object : pass
67
    _newclass = 0
68

  
69

  
70

  
71
def say_hello(*args):
72
  return _hello.say_hello(*args)
73
say_hello = _hello.say_hello
74
# This file is compatible with both classic and new-style classes.
75

  
76

  
Pi/C/examples/swig/hellomodule.c (revision 7)
1
/*hellomodule.c*/
2
 
3
#include <stdio.h>
4
 
5
void say_hello(const char* name) {
6
    printf("Hello %s!\n", name);
7
}
Pi/C/examples/swig/hello_wrap.c (revision 7)
1
/* ----------------------------------------------------------------------------
2
 * This file was automatically generated by SWIG (http://www.swig.org).
3
 * Version 2.0.7
4
 * 
5
 * This file is not intended to be easily readable and contains a number of 
6
 * coding conventions designed to improve portability and efficiency. Do not make
7
 * changes to this file unless you know what you are doing--modify the SWIG 
8
 * interface file instead. 
9
 * ----------------------------------------------------------------------------- */
10

  
11
#define SWIGPYTHON
12
#define SWIG_PYTHON_DIRECTOR_NO_VTABLE
13

  
14
/* -----------------------------------------------------------------------------
15
 *  This section contains generic SWIG labels for method/variable
16
 *  declarations/attributes, and other compiler dependent labels.
17
 * ----------------------------------------------------------------------------- */
18

  
19
/* template workaround for compilers that cannot correctly implement the C++ standard */
20
#ifndef SWIGTEMPLATEDISAMBIGUATOR
21
# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
22
#  define SWIGTEMPLATEDISAMBIGUATOR template
23
# elif defined(__HP_aCC)
24
/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
25
/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
26
#  define SWIGTEMPLATEDISAMBIGUATOR template
27
# else
28
#  define SWIGTEMPLATEDISAMBIGUATOR
29
# endif
30
#endif
31

  
32
/* inline attribute */
33
#ifndef SWIGINLINE
34
# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
35
#   define SWIGINLINE inline
36
# else
37
#   define SWIGINLINE
38
# endif
39
#endif
40

  
41
/* attribute recognised by some compilers to avoid 'unused' warnings */
42
#ifndef SWIGUNUSED
43
# if defined(__GNUC__)
44
#   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
45
#     define SWIGUNUSED __attribute__ ((__unused__)) 
46
#   else
47
#     define SWIGUNUSED
48
#   endif
49
# elif defined(__ICC)
50
#   define SWIGUNUSED __attribute__ ((__unused__)) 
51
# else
52
#   define SWIGUNUSED 
53
# endif
54
#endif
55

  
56
#ifndef SWIG_MSC_UNSUPPRESS_4505
57
# if defined(_MSC_VER)
58
#   pragma warning(disable : 4505) /* unreferenced local function has been removed */
59
# endif 
60
#endif
61

  
62
#ifndef SWIGUNUSEDPARM
63
# ifdef __cplusplus
64
#   define SWIGUNUSEDPARM(p)
65
# else
66
#   define SWIGUNUSEDPARM(p) p SWIGUNUSED 
67
# endif
68
#endif
69

  
70
/* internal SWIG method */
71
#ifndef SWIGINTERN
72
# define SWIGINTERN static SWIGUNUSED
73
#endif
74

  
75
/* internal inline SWIG method */
76
#ifndef SWIGINTERNINLINE
77
# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
78
#endif
79

  
80
/* exporting methods */
81
#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
82
#  ifndef GCC_HASCLASSVISIBILITY
83
#    define GCC_HASCLASSVISIBILITY
84
#  endif
85
#endif
86

  
87
#ifndef SWIGEXPORT
88
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
89
#   if defined(STATIC_LINKED)
90
#     define SWIGEXPORT
91
#   else
92
#     define SWIGEXPORT __declspec(dllexport)
93
#   endif
94
# else
95
#   if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
96
#     define SWIGEXPORT __attribute__ ((visibility("default")))
97
#   else
98
#     define SWIGEXPORT
99
#   endif
100
# endif
101
#endif
102

  
103
/* calling conventions for Windows */
104
#ifndef SWIGSTDCALL
105
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
106
#   define SWIGSTDCALL __stdcall
107
# else
108
#   define SWIGSTDCALL
109
# endif 
110
#endif
111

  
112
/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
113
#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
114
# define _CRT_SECURE_NO_DEPRECATE
115
#endif
116

  
117
/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
118
#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
119
# define _SCL_SECURE_NO_DEPRECATE
120
#endif
121

  
122

  
123

  
124
/* Python.h has to appear first */
125
#include <Python.h>
126

  
127
/* -----------------------------------------------------------------------------
128
 * swigrun.swg
129
 *
130
 * This file contains generic C API SWIG runtime support for pointer
131
 * type checking.
132
 * ----------------------------------------------------------------------------- */
133

  
134
/* This should only be incremented when either the layout of swig_type_info changes,
135
   or for whatever reason, the runtime changes incompatibly */
136
#define SWIG_RUNTIME_VERSION "4"
137

  
138
/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
139
#ifdef SWIG_TYPE_TABLE
140
# define SWIG_QUOTE_STRING(x) #x
141
# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)
142
# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)
143
#else
144
# define SWIG_TYPE_TABLE_NAME
145
#endif
146

  
147
/*
148
  You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for
149
  creating a static or dynamic library from the SWIG runtime code.
150
  In 99.9% of the cases, SWIG just needs to declare them as 'static'.
151
  
152
  But only do this if strictly necessary, ie, if you have problems
153
  with your compiler or suchlike.
154
*/
155

  
156
#ifndef SWIGRUNTIME
157
# define SWIGRUNTIME SWIGINTERN
158
#endif
159

  
160
#ifndef SWIGRUNTIMEINLINE
161
# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE
162
#endif
163

  
164
/*  Generic buffer size */
165
#ifndef SWIG_BUFFER_SIZE
166
# define SWIG_BUFFER_SIZE 1024
167
#endif
168

  
169
/* Flags for pointer conversions */
170
#define SWIG_POINTER_DISOWN        0x1
171
#define SWIG_CAST_NEW_MEMORY       0x2
172

  
173
/* Flags for new pointer objects */
174
#define SWIG_POINTER_OWN           0x1
175

  
176

  
177
/* 
178
   Flags/methods for returning states.
179
   
180
   The SWIG conversion methods, as ConvertPtr, return an integer 
181
   that tells if the conversion was successful or not. And if not,
182
   an error code can be returned (see swigerrors.swg for the codes).
183
   
184
   Use the following macros/flags to set or process the returning
185
   states.
186
   
187
   In old versions of SWIG, code such as the following was usually written:
188

  
189
     if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) {
190
       // success code
191
     } else {
192
       //fail code
193
     }
194

  
195
   Now you can be more explicit:
196

  
197
    int res = SWIG_ConvertPtr(obj,vptr,ty.flags);
198
    if (SWIG_IsOK(res)) {
199
      // success code
200
    } else {
201
      // fail code
202
    }
203

  
204
   which is the same really, but now you can also do
205

  
206
    Type *ptr;
207
    int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags);
208
    if (SWIG_IsOK(res)) {
209
      // success code
210
      if (SWIG_IsNewObj(res) {
211
        ...
212
	delete *ptr;
213
      } else {
214
        ...
215
      }
216
    } else {
217
      // fail code
218
    }
219
    
220
   I.e., now SWIG_ConvertPtr can return new objects and you can
221
   identify the case and take care of the deallocation. Of course that
222
   also requires SWIG_ConvertPtr to return new result values, such as
223

  
224
      int SWIG_ConvertPtr(obj, ptr,...) {         
225
        if (<obj is ok>) {			       
226
          if (<need new object>) {		       
227
            *ptr = <ptr to new allocated object>; 
228
            return SWIG_NEWOBJ;		       
229
          } else {				       
230
            *ptr = <ptr to old object>;	       
231
            return SWIG_OLDOBJ;		       
232
          } 				       
233
        } else {				       
234
          return SWIG_BADOBJ;		       
235
        }					       
236
      }
237

  
238
   Of course, returning the plain '0(success)/-1(fail)' still works, but you can be
239
   more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the
240
   SWIG errors code.
241

  
242
   Finally, if the SWIG_CASTRANK_MODE is enabled, the result code
243
   allows to return the 'cast rank', for example, if you have this
244

  
245
       int food(double)
246
       int fooi(int);
247

  
248
   and you call
249
 
250
      food(1)   // cast rank '1'  (1 -> 1.0)
251
      fooi(1)   // cast rank '0'
252

  
253
   just use the SWIG_AddCast()/SWIG_CheckState()
254
*/
255

  
256
#define SWIG_OK                    (0) 
257
#define SWIG_ERROR                 (-1)
258
#define SWIG_IsOK(r)               (r >= 0)
259
#define SWIG_ArgError(r)           ((r != SWIG_ERROR) ? r : SWIG_TypeError)  
260

  
261
/* The CastRankLimit says how many bits are used for the cast rank */
262
#define SWIG_CASTRANKLIMIT         (1 << 8)
263
/* The NewMask denotes the object was created (using new/malloc) */
264
#define SWIG_NEWOBJMASK            (SWIG_CASTRANKLIMIT  << 1)
265
/* The TmpMask is for in/out typemaps that use temporal objects */
266
#define SWIG_TMPOBJMASK            (SWIG_NEWOBJMASK << 1)
267
/* Simple returning values */
268
#define SWIG_BADOBJ                (SWIG_ERROR)
269
#define SWIG_OLDOBJ                (SWIG_OK)
270
#define SWIG_NEWOBJ                (SWIG_OK | SWIG_NEWOBJMASK)
271
#define SWIG_TMPOBJ                (SWIG_OK | SWIG_TMPOBJMASK)
272
/* Check, add and del mask methods */
273
#define SWIG_AddNewMask(r)         (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r)
274
#define SWIG_DelNewMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r)
275
#define SWIG_IsNewObj(r)           (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK))
276
#define SWIG_AddTmpMask(r)         (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r)
277
#define SWIG_DelTmpMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r)
278
#define SWIG_IsTmpObj(r)           (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK))
279

  
280
/* Cast-Rank Mode */
281
#if defined(SWIG_CASTRANK_MODE)
282
#  ifndef SWIG_TypeRank
283
#    define SWIG_TypeRank             unsigned long
284
#  endif
285
#  ifndef SWIG_MAXCASTRANK            /* Default cast allowed */
286
#    define SWIG_MAXCASTRANK          (2)
287
#  endif
288
#  define SWIG_CASTRANKMASK          ((SWIG_CASTRANKLIMIT) -1)
289
#  define SWIG_CastRank(r)           (r & SWIG_CASTRANKMASK)
290
SWIGINTERNINLINE int SWIG_AddCast(int r) { 
291
  return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r;
292
}
293
SWIGINTERNINLINE int SWIG_CheckState(int r) { 
294
  return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; 
295
}
296
#else /* no cast-rank mode */
297
#  define SWIG_AddCast
298
#  define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0)
299
#endif
300

  
301

  
302
#include <string.h>
303

  
304
#ifdef __cplusplus
305
extern "C" {
306
#endif
307

  
308
typedef void *(*swig_converter_func)(void *, int *);
309
typedef struct swig_type_info *(*swig_dycast_func)(void **);
310

  
311
/* Structure to store information on one type */
312
typedef struct swig_type_info {
313
  const char             *name;			/* mangled name of this type */
314
  const char             *str;			/* human readable name of this type */
315
  swig_dycast_func        dcast;		/* dynamic cast function down a hierarchy */
316
  struct swig_cast_info  *cast;			/* linked list of types that can cast into this type */
317
  void                   *clientdata;		/* language specific type data */
318
  int                    owndata;		/* flag if the structure owns the clientdata */
319
} swig_type_info;
320

  
321
/* Structure to store a type and conversion function used for casting */
322
typedef struct swig_cast_info {
323
  swig_type_info         *type;			/* pointer to type that is equivalent to this type */
324
  swig_converter_func     converter;		/* function to cast the void pointers */
325
  struct swig_cast_info  *next;			/* pointer to next cast in linked list */
326
  struct swig_cast_info  *prev;			/* pointer to the previous cast */
327
} swig_cast_info;
328

  
329
/* Structure used to store module information
330
 * Each module generates one structure like this, and the runtime collects
331
 * all of these structures and stores them in a circularly linked list.*/
332
typedef struct swig_module_info {
333
  swig_type_info         **types;		/* Array of pointers to swig_type_info structures that are in this module */
334
  size_t                 size;		        /* Number of types in this module */
335
  struct swig_module_info *next;		/* Pointer to next element in circularly linked list */
336
  swig_type_info         **type_initial;	/* Array of initially generated type structures */
337
  swig_cast_info         **cast_initial;	/* Array of initially generated casting structures */
338
  void                    *clientdata;		/* Language specific module data */
339
} swig_module_info;
340

  
341
/* 
342
  Compare two type names skipping the space characters, therefore
343
  "char*" == "char *" and "Class<int>" == "Class<int >", etc.
344

  
345
  Return 0 when the two name types are equivalent, as in
346
  strncmp, but skipping ' '.
347
*/
348
SWIGRUNTIME int
349
SWIG_TypeNameComp(const char *f1, const char *l1,
350
		  const char *f2, const char *l2) {
351
  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
352
    while ((*f1 == ' ') && (f1 != l1)) ++f1;
353
    while ((*f2 == ' ') && (f2 != l2)) ++f2;
354
    if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1;
355
  }
356
  return (int)((l1 - f1) - (l2 - f2));
357
}
358

  
359
/*
360
  Check type equivalence in a name list like <name1>|<name2>|...
361
  Return 0 if not equal, 1 if equal
362
*/
363
SWIGRUNTIME int
364
SWIG_TypeEquiv(const char *nb, const char *tb) {
365
  int equiv = 0;
366
  const char* te = tb + strlen(tb);
367
  const char* ne = nb;
368
  while (!equiv && *ne) {
369
    for (nb = ne; *ne; ++ne) {
370
      if (*ne == '|') break;
371
    }
372
    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
373
    if (*ne) ++ne;
374
  }
375
  return equiv;
376
}
377

  
378
/*
379
  Check type equivalence in a name list like <name1>|<name2>|...
380
  Return 0 if equal, -1 if nb < tb, 1 if nb > tb
381
*/
382
SWIGRUNTIME int
383
SWIG_TypeCompare(const char *nb, const char *tb) {
384
  int equiv = 0;
385
  const char* te = tb + strlen(tb);
386
  const char* ne = nb;
387
  while (!equiv && *ne) {
388
    for (nb = ne; *ne; ++ne) {
389
      if (*ne == '|') break;
390
    }
391
    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
392
    if (*ne) ++ne;
393
  }
394
  return equiv;
395
}
396

  
397

  
398
/*
399
  Check the typename
400
*/
401
SWIGRUNTIME swig_cast_info *
402
SWIG_TypeCheck(const char *c, swig_type_info *ty) {
403
  if (ty) {
404
    swig_cast_info *iter = ty->cast;
405
    while (iter) {
406
      if (strcmp(iter->type->name, c) == 0) {
407
        if (iter == ty->cast)
408
          return iter;
409
        /* Move iter to the top of the linked list */
410
        iter->prev->next = iter->next;
411
        if (iter->next)
412
          iter->next->prev = iter->prev;
413
        iter->next = ty->cast;
414
        iter->prev = 0;
415
        if (ty->cast) ty->cast->prev = iter;
416
        ty->cast = iter;
417
        return iter;
418
      }
419
      iter = iter->next;
420
    }
421
  }
422
  return 0;
423
}
424

  
425
/* 
426
  Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison
427
*/
428
SWIGRUNTIME swig_cast_info *
429
SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) {
430
  if (ty) {
431
    swig_cast_info *iter = ty->cast;
432
    while (iter) {
433
      if (iter->type == from) {
434
        if (iter == ty->cast)
435
          return iter;
436
        /* Move iter to the top of the linked list */
437
        iter->prev->next = iter->next;
438
        if (iter->next)
439
          iter->next->prev = iter->prev;
440
        iter->next = ty->cast;
441
        iter->prev = 0;
442
        if (ty->cast) ty->cast->prev = iter;
443
        ty->cast = iter;
444
        return iter;
445
      }
446
      iter = iter->next;
447
    }
448
  }
449
  return 0;
450
}
451

  
452
/*
453
  Cast a pointer up an inheritance hierarchy
454
*/
455
SWIGRUNTIMEINLINE void *
456
SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) {
457
  return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory);
458
}
459

  
460
/* 
461
   Dynamic pointer casting. Down an inheritance hierarchy
462
*/
463
SWIGRUNTIME swig_type_info *
464
SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
465
  swig_type_info *lastty = ty;
466
  if (!ty || !ty->dcast) return ty;
467
  while (ty && (ty->dcast)) {
468
    ty = (*ty->dcast)(ptr);
469
    if (ty) lastty = ty;
470
  }
471
  return lastty;
472
}
473

  
474
/*
475
  Return the name associated with this type
476
*/
477
SWIGRUNTIMEINLINE const char *
478
SWIG_TypeName(const swig_type_info *ty) {
479
  return ty->name;
480
}
481

  
482
/*
483
  Return the pretty name associated with this type,
484
  that is an unmangled type name in a form presentable to the user.
485
*/
486
SWIGRUNTIME const char *
487
SWIG_TypePrettyName(const swig_type_info *type) {
488
  /* The "str" field contains the equivalent pretty names of the
489
     type, separated by vertical-bar characters.  We choose
490
     to print the last name, as it is often (?) the most
491
     specific. */
492
  if (!type) return NULL;
493
  if (type->str != NULL) {
494
    const char *last_name = type->str;
495
    const char *s;
496
    for (s = type->str; *s; s++)
497
      if (*s == '|') last_name = s+1;
498
    return last_name;
499
  }
500
  else
501
    return type->name;
502
}
503

  
504
/* 
505
   Set the clientdata field for a type
506
*/
507
SWIGRUNTIME void
508
SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
509
  swig_cast_info *cast = ti->cast;
510
  /* if (ti->clientdata == clientdata) return; */
511
  ti->clientdata = clientdata;
512
  
513
  while (cast) {
514
    if (!cast->converter) {
515
      swig_type_info *tc = cast->type;
516
      if (!tc->clientdata) {
517
	SWIG_TypeClientData(tc, clientdata);
518
      }
519
    }    
520
    cast = cast->next;
521
  }
522
}
523
SWIGRUNTIME void
524
SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) {
525
  SWIG_TypeClientData(ti, clientdata);
... Ce différentiel a été tronqué car il excède la taille maximale pouvant être affichée.

Formats disponibles : Unified diff