├── .gitattributes
├── .gitignore
├── Chapter 1
├── fft.f
├── fft.py
├── leap.asm
├── leap.f
├── order.txt
├── parallel_hailstone.py
└── serial_hailstone.py
├── Chapter 3
├── prog1.py
├── prog2.py
├── prog3.py
├── prog4.py
└── prog5.py
├── Chapter 4
├── hellompi.py
├── mpi_broad.py
├── mpi_master.py
├── mpi_p2p.py
├── mpi_reduce.py
├── mpi_worker.py
├── order.txt
├── pair_client.py
├── pair_server.py
├── publisher.py
├── rep_client.py
├── rep_server1.py
├── rep_server2.py
├── req_client.py
├── req_server.py
├── sink.py
├── subscriber.py
├── ventilator.py
└── worker.py
├── Chapter 5
├── hail2.py
├── misc.py
├── order.txt
└── prog1.py
├── Chapter 6
├── hy1.hy
└── hy2.hy
├── Chapter 7
├── code1.py
├── code10.py
├── code2.py
├── code3.py
├── code4.py
├── code5.py
├── code6.py
├── code7.py
├── code8.py
└── code9.py
├── Chapter 8
├── hail1.py
├── hail2.py
├── myrand.py
├── nose2-junit.xml
├── test1.py
├── test2.py
├── test_1.py
├── test_2.py
├── test_nose_test1.py
├── testrand.py
├── testrand2.py
├── testrand_1.py
├── testrand_2.py
├── testrand_nose2_1.py
├── testrand_nose2_2.py
└── testrand_nose2decs_1.py
├── Chapter 9
├── code1.py
├── code2.py
├── crt1.py
├── hail1.py
├── rst2.txt
├── rst3.txt
├── rst4.txt
└── rst5.txt
├── LICENSE
└── README.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs diff=csharp
6 |
7 | # Standard to msysgit
8 | *.doc diff=astextplain
9 | *.DOC diff=astextplain
10 | *.docx diff=astextplain
11 | *.DOCX diff=astextplain
12 | *.dot diff=astextplain
13 | *.DOT diff=astextplain
14 | *.pdf diff=astextplain
15 | *.PDF diff=astextplain
16 | *.rtf diff=astextplain
17 | *.RTF diff=astextplain
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Windows image file caches
2 | Thumbs.db
3 | ehthumbs.db
4 |
5 | # Folder config file
6 | Desktop.ini
7 |
8 | # Recycle Bin used on file shares
9 | $RECYCLE.BIN/
10 |
11 | # Windows Installer files
12 | *.cab
13 | *.msi
14 | *.msm
15 | *.msp
16 |
17 | # Windows shortcuts
18 | *.lnk
19 |
20 | # =========================
21 | # Operating System Files
22 | # =========================
23 |
24 | # OSX
25 | # =========================
26 |
27 | .DS_Store
28 | .AppleDouble
29 | .LSOverride
30 |
31 | # Thumbnails
32 | ._*
33 |
34 | # Files that might appear in the root of a volume
35 | .DocumentRevisions-V100
36 | .fseventsd
37 | .Spotlight-V100
38 | .TemporaryItems
39 | .Trashes
40 | .VolumeIcon.icns
41 |
42 | # Directories potentially created on remote AFP share
43 | .AppleDB
44 | .AppleDesktop
45 | Network Trash Folder
46 | Temporary Items
47 | .apdisk
48 |
--------------------------------------------------------------------------------
/Chapter 1/fft.f:
--------------------------------------------------------------------------------
1 | module fft_mod
2 | implicit none
3 | integer, parameter :: dp=selected_real_kind(15,300)
4 | real(kind=dp), parameter :: pi=3.141592653589793238460_dp
5 | contains
6 |
7 | ! In place Cooley-Tukey FFT
8 | recursive subroutine fft(x)
9 | complex(kind=dp), dimension(:), intent(inout) :: x
10 | complex(kind=dp) :: t
11 | integer :: N
12 | integer :: i
13 | complex(kind=dp), dimension(:), allocatable :: even, odd
14 |
15 | N=size(x)
16 |
17 | if(N .le. 1) return
18 |
19 | allocate(odd((N+1)/2))
20 | allocate(even(N/2))
21 |
22 | ! divide
23 | odd =x(1:N:2)
24 | even=x(2:N:2)
25 |
26 | ! conquer
27 | call fft(odd)
28 | call fft(even)
29 |
30 | ! combine
31 | do i=1,N/2
32 | t=exp(cmplx(0.0_dp,-2.0_dp*pi*real(i-1,dp)/real(N,dp),kind=dp))*even(i)
33 | x(i) = odd(i) + t
34 | x(i+N/2) = odd(i) - t
35 | end do
36 |
37 | deallocate(odd)
38 | deallocate(even)
39 |
40 | end subroutine fft
41 |
42 | end module fft_mod
43 |
44 | program test
45 | use fft_mod
46 | implicit none
47 | complex(kind=dp), dimension(8) :: data = (/1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0/)
48 | integer :: i
49 |
50 | call fft(data)
51 |
52 | do i=1,8
53 | write(*,'("(", F20.15, ",", F20.15, "i )")') data(i)
54 | end do
55 |
56 | end program test
57 |
--------------------------------------------------------------------------------
/Chapter 1/fft.py:
--------------------------------------------------------------------------------
1 | from cmath import exp, pi
2 |
3 | def fft(x):
4 | N = len(x)
5 | if N <= 1: return x
6 | even = fft(x[0::2])
7 | odd = fft(x[1::2])
8 | T= [exp(-2j*pi*k/N)*odd[k] for k in range(N//2)]
9 | return [even[k] + T[k] for k in range(N//2)] + [even[k] - T[k] for k in range(N//2)]
10 |
11 | print( ' '.join("%5.3f" % abs(f)
12 | for f in fft([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0])) )
13 |
--------------------------------------------------------------------------------
/Chapter 1/leap.asm:
--------------------------------------------------------------------------------
1 | align 16
2 | ; Input year as signed dword in EAX
3 | IsLeapYear:
4 | test eax,11b
5 | jz .4
6 | retn ; 75% : ZF=0, not a leap year
7 | .4:
8 | mov ecx,100
9 | cdq
10 | idiv ecx
11 | test edx,edx
12 | jz .100
13 | cmp edx,edx
14 | retn ; 24% : ZF=1, leap year
15 | .100:
16 | test eax,11b
17 | retn ; 1% : ZF=?, leap year if EAX%400=0
18 |
--------------------------------------------------------------------------------
/Chapter 1/leap.f:
--------------------------------------------------------------------------------
1 | pure elemental function leap_year(y) result(is_leap)
2 | implicit none
3 | logical :: is_leap
4 | integer,intent(in) :: y
5 |
6 | is_leap = (mod(y,4)==0 .and. .not. mod(y,100)==0) .or. (mod(y,400)==0)
7 |
8 | end function leap_year
9 |
--------------------------------------------------------------------------------
/Chapter 1/order.txt:
--------------------------------------------------------------------------------
1 | leap.asm
2 | leap.f
3 | fft.f
4 | fft.py
5 | serial_hailstone.py
6 | parallel_hailstone.py
7 |
--------------------------------------------------------------------------------
/Chapter 1/parallel_hailstone.py:
--------------------------------------------------------------------------------
1 | def f(n):
2 | curr = n
3 | tmp = 1
4 | while curr != 1:
5 | tmp = tmp + 1
6 | if curr % 2 == 1:
7 | curr = 3 * curr + 1
8 | else:
9 | curr = curr/2
10 | return tmp
11 |
12 | def main( ):
13 | sum = 0
14 | procs = getProcs(100)
15 | i = 1
16 |
17 | for proc in procs:
18 | proc.setFun(f, i)
19 | i = i + 1
20 |
21 | for proc in procs:
22 | sum = sum + proc.execute( )
23 |
24 | avg = sum / 100.0
25 |
26 |
--------------------------------------------------------------------------------
/Chapter 1/serial_hailstone.py:
--------------------------------------------------------------------------------
1 | def f(n):
2 | curr = n
3 | tmp = 1
4 | while curr != 1:
5 | tmp = tmp + 1
6 | if curr % 2 == 1:
7 | curr = 3 * curr + 1
8 | else:
9 | curr = curr/2
10 | return tmp
11 |
12 | def main( ):
13 | sum = 0
14 | for i in range(1, 101):
15 | sum = sum + f(i)
16 | avg = sum / 100.0
17 |
--------------------------------------------------------------------------------
/Chapter 3/prog1.py:
--------------------------------------------------------------------------------
1 | import queue
2 | import threading
3 |
4 | def f(n, q):
5 | curr = n
6 | tmp = 1
7 | while curr != 1:
8 | tmp = tmp + 1
9 | if curr % 2 == 1:
10 | curr = 3 * curr + 1
11 | else:
12 | curr = curr/2
13 | q.put(tmp)
14 |
15 | def main( ):
16 | sum = 0
17 | q = Queue.Queue()
18 | threads = []
19 |
20 | for i in range(100):
21 | t = threading.Thread(target=f, args=(i+1, q))
22 | threads.append(t)
23 |
24 | for thread in threads:
25 | thread.start()
26 |
27 | for thread in threads:
28 | threads[i].join()
29 |
30 | while (not q.empty()):
31 | sum = sum + q.get()
32 |
33 | avg = sum / 100.0
34 | print(“avg = “, avg)
35 |
36 |
--------------------------------------------------------------------------------
/Chapter 3/prog2.py:
--------------------------------------------------------------------------------
1 | import numpy
2 | from numbapro import vectorize
3 |
4 | @vectorize(["float32(float32, float32)"], target="gpu")
5 | def vectorAdd(a, b):
6 | return a + b
7 |
8 | def useGPUs( ):
9 | N = 64
10 |
11 | A = numpy.random.rand(N).astype(numpy.float32)
12 | B = numpy.random.rand(N).astype(numpy.float32)
13 | C = numpy.zeros(N, dtype=numpy.float32)
14 |
15 | C = vectorAdd(A, B)
16 | print(C)
17 |
18 | def f(n, q):
19 | curr = n
20 | tmp = 1
21 | while curr != 1:
22 | tmp = tmp + 1
23 | if curr % 2 == 1:
24 | curr = 3 * curr + 1
25 | else:
26 | curr = curr/2
27 | q.put(tmp)
28 |
29 |
--------------------------------------------------------------------------------
/Chapter 3/prog3.py:
--------------------------------------------------------------------------------
1 | def gpuWrap(dv, q):
2 | q.add(dv.apply(useGPUs))
3 |
4 | def fWrap(dv, i, q):
5 | q.add(dv.apply(f, i))
6 |
7 |
8 | # we assume that the engines have been correctly instantiated
9 | def main( ):
10 | q = Queue.Queue() # collect results in here
11 | threads = []
12 | seqNum = 1
13 |
14 | c = Client()
15 |
16 | for i in range(100):
17 | dv = c[i]
18 | if i % 4 == 0:
19 | # we assume the GPU is attached to processing element 0
20 | t = threading.Thread(target=gpuWrap, args=(dv, q))
21 | else:
22 | t = threading.Thread(target=fWrap, args=(dv, seqNum, q))
23 | seqNum = seqNum + 1
24 |
25 | threads.append(t)
26 |
27 | for thread in threads:
28 | thread.start()
29 |
30 | for thread in threads:
31 | threads[i].join()
32 |
33 | # at this point q should be full of AsyncResult objects that can be used to
34 | # get the results of the individual processes as they complete
35 |
36 |
--------------------------------------------------------------------------------
/Chapter 3/prog4.py:
--------------------------------------------------------------------------------
1 | def monteCarloPI(n):
2 | s = 0
3 | for i in xrange(n):
4 | x = random()
5 | y = random()
6 | if x*x + y*y <= 1:
7 | s+=1
8 | return 4.*s/n
9 |
10 | def parCalcPI(view, n):
11 | p = len(view.targets)
12 |
13 | ar = view.apply(monteCarloPI, n)
14 | return sum(ar)/p
15 |
16 |
--------------------------------------------------------------------------------
/Chapter 3/prog5.py:
--------------------------------------------------------------------------------
1 | def countWords(filename):
2 | int numWords = 0
3 | f = open(filename, “r”)
4 | for line in f:
5 | words = line.split( )
6 | numWords += len(words)
7 | return numWords
8 |
9 | c = Client()
10 | numEngines = 4
11 | dv = c[:]
12 | asyncResults = []
13 |
14 | for i in range(numFiles):
15 | filename = “infile” + i + “.txt”
16 | dv.targets = i % numEngines]
17 | asyncResults.append(dv.apply(countWords, fileName))
18 |
19 | for r in asyncResults:
20 | results.append(r.get())
21 |
22 |
--------------------------------------------------------------------------------
/Chapter 4/hellompi.py:
--------------------------------------------------------------------------------
1 | from mpi4py import MPI
2 | comm = MPI.COMM_WORLD
3 | rank = comm.Get_rank()
4 | print("hello world from process ", rank)
5 |
--------------------------------------------------------------------------------
/Chapter 4/mpi_broad.py:
--------------------------------------------------------------------------------
1 | from mpi4py import MPI
2 |
3 | comm = MPI.COMM_WORLD
4 | rank = comm.Get_rank()
5 |
6 | if rank == 0:
7 | data = input(“Please enter random number seed”)
8 | else:
9 | data = None
10 |
11 | # mpi4py wants to send an object, so we will leave the input in that format
12 | data = comm.bcast(data, root=0)
13 |
14 |
--------------------------------------------------------------------------------
/Chapter 4/mpi_master.py:
--------------------------------------------------------------------------------
1 | from mpi4py import MPI
2 | import numpy
3 | import sys
4 |
5 | comm = MPI.COMM_SELF.Spawn(sys.executable,
6 | args=['workermpi.py'],
7 | maxprocs=5)
8 |
9 | N = numpy.array(100, 'i')
10 | comm.Bcast([N, MPI.INT], root=MPI.ROOT)
11 | PI = numpy.array(0.0, 'd')
12 | comm.Reduce(None, [PI, MPI.DOUBLE],
13 | op=MPI.SUM, root=MPI.ROOT)
14 | print(PI)
15 |
16 | comm.Disconnect()
17 |
18 |
--------------------------------------------------------------------------------
/Chapter 4/mpi_p2p.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Mastering-IPython-4/86f153a54f38124108ef5074a44602b174cabb2f/Chapter 4/mpi_p2p.py
--------------------------------------------------------------------------------
/Chapter 4/mpi_reduce.py:
--------------------------------------------------------------------------------
1 | import numpy
2 | import sys
3 | from mpi4py import MPI
4 |
5 | comm = MPI.COMM_WORLD
6 | rank = comm.Get_rank()
7 |
8 | # integrate from in [0, 4] using 8 rectangles
9 | a = 0
10 | b = 4
11 | n = 8
12 |
13 | # the function to integrate
14 | def f(x):
15 | return x*x*x
16 |
17 | # use the left-most point in the range as the height
18 | def calcArea(lft, dx):
19 | ht = f(lft)
20 | return ht * dx
21 |
22 | # use regular intervals
23 | dx = (b-a)/n
24 |
25 | # local_a is the leftmost point
26 | local_a = rank * dx
27 |
28 | # initializing variables
29 | # when using capital-R Recv, mpi4py requires that we pass buffer-like
30 | # objects, so why not use numpy?
31 | integral = numpy.zeros(1)
32 | total = numpy.zeros(1)
33 |
34 | # perform local computation
35 | integral[0] = calcArea(local_a, dx)
36 |
37 | # communication
38 | # root node receives results with a collective "reduce"
39 | comm.Reduce(integral, total, op=MPI.SUM, root=0)
40 |
41 | # root process prints results
42 | if comm.rank == 0:
43 | print("With n =", n, "trapezoids, our estimate of the integral from", a, "to", b, "is", total)
44 |
45 |
--------------------------------------------------------------------------------
/Chapter 4/mpi_worker.py:
--------------------------------------------------------------------------------
1 | from mpi4py import MPI
2 | import numpy
3 |
4 | comm = MPI.Comm.Get_parent()
5 | size = comm.Get_size()
6 | rank = comm.Get_rank()
7 |
8 | N = numpy.array(0, dtype='i')
9 | comm.Bcast([N, MPI.INT], root=0)
10 | h = 1.0 / N; s = 0.0
11 | for i in range(rank, N, size):
12 | x = h * (i + 0.5)
13 | s += 4.0 / (1.0 + x**2)
14 | PI = numpy.array(s * h, dtype='d')
15 | comm.Reduce([PI, MPI.DOUBLE], None,
16 | op=MPI.SUM, root=0)
17 |
18 | comm.Disconnect()
19 |
20 |
--------------------------------------------------------------------------------
/Chapter 4/order.txt:
--------------------------------------------------------------------------------
1 | req_server.py
2 | req_client.py
3 | pair_server.py
4 | pair_client.py
5 | rep_server1.py
6 | rep_server2.py
7 | rep_client.py
8 | publisher.py
9 | subscriber.py
10 | ventilator.py
11 | worker.py
12 | sink.py
13 | hellompi.py
14 | mpi_p2p.py
15 | mpi_broad.py
16 | mpi_reduce.py
17 | mpi_master.py
18 | mpi_worker.py
--------------------------------------------------------------------------------
/Chapter 4/pair_client.py:
--------------------------------------------------------------------------------
1 | import zmq
2 |
3 | context = zmq.Context()
4 | socket = context.socket(zmq.PAIR)
5 | socket.bind("tcp://*:5555" % port)
6 |
7 | while True:
8 | socket.send("What time is it?")
9 | msg = socket.recv()
10 | print msg
11 | time.sleep(1)
12 |
13 |
--------------------------------------------------------------------------------
/Chapter 4/pair_server.py:
--------------------------------------------------------------------------------
1 | import zmq
2 | import time
3 |
4 | context = zmq.Context()
5 | socket = context.socket(zmq.PAIR)
6 | socket.connect("tcp://localhost:5555")
7 |
8 | while True:
9 | msg = socket.recv()
10 | timeStr = str(time.time())
11 | socket.send(timeStr)
12 |
13 |
--------------------------------------------------------------------------------
/Chapter 4/publisher.py:
--------------------------------------------------------------------------------
1 | import zmq
2 | import time
3 |
4 | context = zmq.Context()
5 | socket = context.socket(zmq.PUB)
6 | socket.bind("tcp://*:5555")
7 |
8 | while True:
9 | topic = “time”
10 | messagedata = str(time.time())
11 | socket.send(topic + “ “ + messagedata)
12 |
13 | topic = “weather”
14 | messagedata = “dark and stormy night”
15 | socket.send(topic + “ “ + messagedata)
16 |
17 | time.sleep(1)
18 |
19 |
--------------------------------------------------------------------------------
/Chapter 4/rep_client.py:
--------------------------------------------------------------------------------
1 | import zmq
2 |
3 | context = zmq.Context()
4 | socket = context.socket(zmq.REQ)
5 | socket.connect("tcp://localhost:5555" % port)
6 | socket.connect("tcp://localhost:5556" % port)
7 |
8 | while True:
9 | socket.send("What time is it?")
10 | msg = socket.recv()
11 | print msg
12 | time.sleep(1)
13 |
14 |
--------------------------------------------------------------------------------
/Chapter 4/rep_server1.py:
--------------------------------------------------------------------------------
1 | import zmq
2 | import time
3 |
4 | context = zmq.Context()
5 | socket = context.socket(zmq.REP)
6 | socket.bind("tcp://*:5555")
7 |
8 | while True:
9 | msg = socket.recv()
10 | timeStr = str(time.time())
11 | socket.send(timeStr)
12 |
13 |
--------------------------------------------------------------------------------
/Chapter 4/rep_server2.py:
--------------------------------------------------------------------------------
1 | import zmq
2 |
3 | context = zmq.Context()
4 | socket = context.socket(zmq.REP)
5 | socket.bind("tcp://*:5556")
6 |
7 | while True:
8 | msg = socket.recv()
9 | socket.send(“peanut butter jelly time”)
10 |
11 |
--------------------------------------------------------------------------------
/Chapter 4/req_client.py:
--------------------------------------------------------------------------------
1 | import zmq
2 |
3 | context = zmq.Context()
4 |
5 | # Socket to talk to server
6 | socket = context.socket(zmq.REQ)
7 | socket.connect("tcp://localhost:5555")
8 |
9 | # Do 10 requests, waiting each time for a response
10 | for request in range(10):
11 | print("Sending request %s ..." % request)
12 | socket.send("Hello")
13 |
14 | # Get the reply
15 | message = socket.recv()
16 | print("Received reply %s [ %s ]" % (request, message))
17 |
18 |
--------------------------------------------------------------------------------
/Chapter 4/req_server.py:
--------------------------------------------------------------------------------
1 | import time
2 | import zmq
3 |
4 | context = zmq.Context()
5 | socket = context.socket(zmq.REP)
6 | socket.bind("tcp://*:5555")
7 |
8 | while True:
9 | # Wait for next request from client
10 | message = socket.recv()
11 | print("Received request: %s" % message)
12 |
13 | # So everything does not happen too fast to see
14 | time.sleep(1)
15 |
16 | # Send reply back to client
17 | socket.send("World")
18 |
19 |
--------------------------------------------------------------------------------
/Chapter 4/sink.py:
--------------------------------------------------------------------------------
1 | import zmq
2 |
3 | context = zmq.Context()
4 |
5 | # socket to receive messages on
6 | receiver = context.socket(zmq.PULL)
7 | receiver.bind("tcp://localhost:5556")
8 |
9 | while True:
10 | s = receiver.recv_string()
11 | # do work – maybe log time for each completed process
12 |
13 |
--------------------------------------------------------------------------------
/Chapter 4/subscriber.py:
--------------------------------------------------------------------------------
1 | import zmq
2 |
3 | context = zmq.Context()
4 | socket = context.socket(zmq.SUB)
5 | socket.connect("tcp://localhost:5555")
6 | socket.setsockopt_string(zmq.SUBSCRIBE, “weather”)
7 |
8 | while True:
9 | wtr = socket.recv_string()
10 | print(“the weather is: “ + wtr)
11 |
12 |
--------------------------------------------------------------------------------
/Chapter 4/ventilator.py:
--------------------------------------------------------------------------------
1 | import zmq
2 | import random
3 | import time
4 |
5 | context = zmq.Context()
6 |
7 | # socket to send messages on
8 | sender = context.socket(zmq.PUSH)
9 | sender.bind("tcp://localhost:5555")
10 |
11 | while True:
12 | # messages come in batches of 16, for this example
13 | # perhaps there are 16 workers
14 | for i in range(16):
15 | seed = random.randint(1, 20000)
16 | sender.send_string(str(seed))
17 |
18 | # give 0MQ time to deliver and workers time to work
19 | time.sleep(10)
20 |
21 |
--------------------------------------------------------------------------------
/Chapter 4/worker.py:
--------------------------------------------------------------------------------
1 | import zmq
2 | import random
3 | import time
4 |
5 | context = zmq.Context()
6 |
7 | # from the ventilator
8 | receiver = context.socket(zmq.PULL)
9 | receiver.connect("tcp://localhost:5555")
10 |
11 | # to the sink
12 | sender = context.socket(zmq.PUSH)
13 | sender.connect("tcp://localhost:5556")
14 |
15 | while True:
16 | s = receiver.recv()
17 |
18 | #do some “work”
19 | time.sleep(int(s)*0.001)
20 |
21 | #send “results” to sink
22 | tm = str(time.time())
23 | sender.send_string(tm)
24 |
25 |
--------------------------------------------------------------------------------
/Chapter 5/hail2.py:
--------------------------------------------------------------------------------
1 | import time
2 | import random
3 |
4 | def f(n):
5 | curr = n
6 | tmp = 0
7 | time.sleep(random.random())
8 | while curr != 1:
9 | tmp = tmp + 1
10 | if curr % 2 == 1:
11 | curr = 3 * curr + 1
12 | else:
13 | curr = curr/2
14 | return tmp
15 |
--------------------------------------------------------------------------------
/Chapter 5/misc.py:
--------------------------------------------------------------------------------
1 | from ipyparallel import Client
2 | import os
3 |
4 | c = Client( )
5 | dv = c[:]
6 |
7 | def f(n):
8 | from time import sleep
9 | import random
10 | curr = n
11 | tmp = 0
12 | while curr != 1:
13 | sleep(random.random( )/1000)
14 | tmp = tmp + 1
15 | if curr % 2 == 1:
16 | curr = 3 * curr + 1
17 | else:
18 | curr = curr/2
19 | return tmp
20 |
21 | x = dv.apply(f, 1109)
22 | print(type(x))
23 | results = x.get_dict( )
24 | print("results = ", results)
25 |
26 | x = dv.apply_async(f, 63728127)
27 | print(type(x))
28 | print("done yet? ", x.ready( ))
29 | results = x.get( )
30 | print("done now? ", x.ready())
31 | print("results = ", results)
32 |
33 | x = dv.map(f, range(1, 10))
34 | print(type(x))
35 | results = x.get_dict( )
36 | print("results in dict = ", results)
37 |
38 | x = dv.map(f, range(1, 10))
39 | print(type(x))
40 | results = x.get( )
41 | print("results in list = ", results)
42 |
43 | x = dv.map_async(f, range(1100, 1110))
44 | print(type(x))
45 | results = x.get( )
46 | print("results = ", results)
47 |
48 | lbv = c.load_balanced_view( )
49 |
50 | x = lbv.map(f, range(1100, 1110))
51 | print(type(x))
52 | results = x.get( )
53 | print("results = ", results)
54 |
55 |
--------------------------------------------------------------------------------
/Chapter 5/order.txt:
--------------------------------------------------------------------------------
1 | prog1.py
2 | misc.py
3 | hail2.py
4 |
--------------------------------------------------------------------------------
/Chapter 5/prog1.py:
--------------------------------------------------------------------------------
1 | from multiprocessing import Pool
2 |
3 | def f(n):
4 | curr = n
5 | tmp = 1
6 | while curr != 1:
7 | tmp = tmp + 1
8 | if curr % 2 == 1:
9 | curr = 3 * curr + 1
10 | else:
11 | curr = curr/2
12 | return tmp
13 |
14 | if __name__ == '__main__':
15 | pool = Pool(processes=4)
16 |
17 | x = pool.apply(f, (1109,))
18 | print(type(x))
19 | print(x)
20 |
21 | x = pool.apply_async(f, (1109, ))
22 | print(type(x))
23 | print(x.get())
24 |
25 | x = pool.map(f, range(1100, 1110))
26 | print(type(x))
27 | print(x)
28 |
29 | x = pool.map_async(f, range(1100, 1110))
30 | print(type(x))
31 | print(x.get( ))
32 |
33 | x = pool.imap(f, range(1100, 1110))
34 | print(type(x))
35 | for i in x:
36 | print(i)
37 |
38 | x = pool.imap_unordered(f, range(1100, 1110))
39 | print(type(x))
40 | for i in x:
41 | print(i)
42 |
43 |
--------------------------------------------------------------------------------
/Chapter 6/hy1.hy:
--------------------------------------------------------------------------------
1 | %%hylang
2 | (import math)
3 | (defn safesqrt [x]
4 | (if (< x 0)
5 | (math.sqrt (- 0 x))
6 | (math.sqrt x)
7 | )
8 | )
9 |
--------------------------------------------------------------------------------
/Chapter 6/hy2.hy:
--------------------------------------------------------------------------------
1 | %%hylang
2 | (defn categorize [x]
3 | (cond
4 | [(< x 0) (print "negative")]
5 | [(= x 0) (print "zero")]
6 | [(> x 0) (print "positive")]
7 | )
8 | )
9 |
10 |
--------------------------------------------------------------------------------
/Chapter 7/code1.py:
--------------------------------------------------------------------------------
1 | locs, labels = xticks()
2 | xticks(locs, ("-10%", "-6.7%", "-3.3%", "0", "3.3%", "6.7%", "10%"))
3 | xlabel("Percentage change")
4 | ylabel("Number of Stocks")
5 | title("Simulated Market Performance")
6 |
--------------------------------------------------------------------------------
/Chapter 7/code10.py:
--------------------------------------------------------------------------------
1 | from nvd3 import pieChart
2 | %load_ext rpy2.ipython
3 | xs = %R sort(unique(mtcars$cyl))
4 | ys = %R table(mtcars$cyl)
5 | chart = pieChart(name="Cylinders", color_category='category10', height=500, width=400)
6 | chart.add_serie(x=xs.tolist(), y=ys.tolist())
7 | output_file = open('nvd3-3.html', 'w')
8 | chart.buildhtml()
9 | output_file.write(chart.htmlcontent)
10 | output_file.close()
11 |
--------------------------------------------------------------------------------
/Chapter 7/code2.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import bokeh.plotting as bp
3 | bp.output_file("bokeh1.html")
4 | x = np.linspace(0, 2 * np.pi, 1024)
5 | y = np.cos(x)
6 | fig = bp.figure( )
7 | fig.line(x, y)
8 | bp.show(fig)
9 |
--------------------------------------------------------------------------------
/Chapter 7/code3.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import bokeh.plotting as bp
3 | bp.output_file("bokeh2.html")
4 | x = np.linspace(0, 2 * np.pi, 1024)
5 | y = np.cos(x)
6 | fig = bp.figure(title="simple line example", x_axis_label="x", y_axis_label="y")
7 | fig.line(x, y, legend="cos(x)", color="red", line_width=2)
8 | bp.show(fig)
9 |
--------------------------------------------------------------------------------
/Chapter 7/code4.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import bokeh.plotting as bp
3 | import bokeh.models as bm
4 | bp.output_file("bokeh4.html")
5 | x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
6 | y0 = np.cos(x)
7 | y1 = np.sin(x)
8 | mySource = bm.ColumnDataSource(data=dict(x=x, y0=y0, y1=y1))
9 | myTools = "box_select,lasso_select,help"
10 | left = bp.figure(tools=myTools, width=300, height=300, title="Left")
11 | left.circle('x', 'y0', source=mySource)
12 | right = bp.figure(tools=myTools, width=300, height=300, title="Right")
13 | right.circle('x', 'y1', source=mySource)
14 | p = bp.gridplot([[left, right]])
15 | bp.show(p)
16 |
--------------------------------------------------------------------------------
/Chapter 7/code5.py:
--------------------------------------------------------------------------------
1 | %load_ext rpy2.ipython
2 | from rpy2.robjects import pandas2ri
3 | pandas2ri.activate()
4 | from rpy2.robjects import r
5 | df_cars = pandas2ri.ri2py(r['mtcars'])
6 | type(df_cars)
7 | df_cars.describe()
8 |
--------------------------------------------------------------------------------
/Chapter 7/code6.py:
--------------------------------------------------------------------------------
1 | %load_ext rpy2.ipython
2 | from rpy2.robjects import pandas2ri
3 | pandas2ri.activate()
4 | from rpy2.robjects import r
5 | import pandas
6 | from rpy2.robjects.lib import ggplot2
7 | df_cars = pandas2ri.ri2py(r['mtcars'])
8 | wt = df_cars['wt']
9 | mpg = df_cars['mpg']
10 | type(mpg)
11 | df_wtVsMpg = pandas.DataFrame()
12 | df_wtVsMpg['wt'] = wt
13 | df_wtVsMpg['mpg'] = mpg
14 | p = ggplot2.ggplot(df_wtVsMpg)
15 | type(p)
16 | p.plot()
17 |
--------------------------------------------------------------------------------
/Chapter 7/code7.py:
--------------------------------------------------------------------------------
1 | df_wtVsMpg['cyl'] = df_cars['cyl']
2 | p2 = ggplot2.ggplot(df_wtVsMpg)
3 | p2 = p2 + ggplot2.aes_string(x="mpg", fill="factor(cyl)")
4 | p2 = p2 + ggplot2.geom_histogram( )
5 | p2.plot( )
6 |
--------------------------------------------------------------------------------
/Chapter 7/code8.py:
--------------------------------------------------------------------------------
1 | from nvd3 import scatterChart
2 | xs = [1, 2, 3, 4, 5]
3 | ys = [2, 3, 5, 7, 11]
4 | kwargs = {'shape': 'circle', 'size': '1'}
5 | chart = scatterChart(name='The first few primes', height=400, width=400)
6 | chart.add_serie(name="Primes", x=xs, y=ys, **kwargs)
7 | output_file = open('nvd3-1.html', 'w')
8 | chart.buildhtml()
9 | output_file.write(chart.htmlcontent)
10 | output_file.close()
11 |
--------------------------------------------------------------------------------
/Chapter 7/code9.py:
--------------------------------------------------------------------------------
1 | from nvd3 import scatterChart
2 | %load_ext rpy2.ipython
3 | from rpy2.robjects import pandas2ri
4 | pandas2ri.activate()
5 | from rpy2.robjects import r
6 | import pandas
7 | df_cars = pandas2ri.ri2py(r['mtcars'])
8 | wt = df_cars['wt']
9 | mpg = df_cars['mpg']
10 | kwargs = {'shape': 'circle', 'size': '1'}
11 | chart = scatterChart(name='Weight vs MPG', height=400, width=800, y_axis_scale_min='0', show_legend='False')
12 | chart.add_serie(name="Cars", x=wt, y=mpg, **kwargs)
13 | output_file = open('nvd3-2.html', 'w')
14 | chart.buildhtml()
15 | output_file.write(chart.htmlcontent)
16 | output_file.close()
17 |
--------------------------------------------------------------------------------
/Chapter 8/hail1.py:
--------------------------------------------------------------------------------
1 | def f(n):
2 | curr = n
3 | tmp = 1
4 | while curr != 1:
5 | tmp = tmp + 1
6 | if curr % 2 == 1:
7 | curr = 3 * curr + 1
8 | else:
9 | curr = curr/2
10 | return tmp
11 |
12 |
--------------------------------------------------------------------------------
/Chapter 8/hail2.py:
--------------------------------------------------------------------------------
1 | def f(n):
2 | curr = n
3 | tmp = 0
4 | while curr != 1:
5 | tmp = tmp + 1
6 | if curr % 2 == 1:
7 | curr = 3 * curr + 1
8 | else:
9 | curr = curr/2
10 | return tmp
11 |
12 |
--------------------------------------------------------------------------------
/Chapter 8/myrand.py:
--------------------------------------------------------------------------------
1 | class MyRand(object):
2 |
3 | def set(self, p1, p2, x0, modulus):
4 | self.__p1 = p1
5 | self.__p2 = p2
6 | self.__x = x0
7 | self.__modulus = modulus
8 |
9 | def next(self):
10 | self.__x = (self.__p1 * self.__x + self.__p2) % self.__modulus
11 | return self.__x
12 |
13 | def reset(self):
14 | self.__p1 = 2
15 | self.__p2 = 2
16 | self.__x = 2
17 | self.__modulus = 2
18 |
--------------------------------------------------------------------------------
/Chapter 8/nose2-junit.xml:
--------------------------------------------------------------------------------
1 |
Simply click on the link to claim your free PDF.
43 |