File: example3.py

package info (click to toggle)
python-scientific 2.4.11-2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 1,956 kB
  • ctags: 3,063
  • sloc: python: 9,157; ansic: 4,483; xml: 4,145; makefile: 126; sh: 18; csh: 1
file content (42 lines) | stat: -rw-r--r-- 1,270 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from Scientific.BSP import ParFunction, ParRootFunction, ParMessages, \
                           ParConstant, ParIterator, ParIndexIterator, \
                           numberOfProcessors
import operator, string

# The local and global input functions.
def input():
    data = open('numbers').readlines()
    numbers = map(string.atoi, map(string.strip, data))
    chunk_size = (len(numbers)+numberOfProcessors-1)/numberOfProcessors
    chunks = []
    for i in range(numberOfProcessors):
        chunks.append((i, numbers[i*chunk_size:(i+1)*chunk_size]))
    return chunks
def empty():
    return []
global_input = ParRootFunction(input, empty)

# The local and global computation functions.
def square(x):
    return x*x
global_square = ParFunction(square)

# The local and global output functions.
def output(results):
    file = open('results', 'a')
    for value in results:
        file.write(`value` + '\n')
    file.close()
global_output = ParRootFunction(output)

# Read input data.
data = global_input()

# Distribute input data.
items = ParMessages(data).exchange()[0]

# Computation and output loop.
for item in ParIterator(items):
    result = global_square(item)
    collected_results = result.put(ParConstant([0]))
    global_output(collected_results)