1 | """Read realisations and return MxN Numeric array: data, where M is the number of timesteps and N the number of realisations |
---|
2 | """ |
---|
3 | |
---|
4 | import os |
---|
5 | import project |
---|
6 | from Numeric import Float, zeros |
---|
7 | from caching import cache |
---|
8 | |
---|
9 | def read_realisations(subdir, max_realisations = None, gauge_number=0, |
---|
10 | exclude=None, use_cache=False, verbose=True): |
---|
11 | """Read realisations |
---|
12 | """ |
---|
13 | |
---|
14 | if use_cache is True: |
---|
15 | result = cache(_read_realisations, |
---|
16 | (subdir,), |
---|
17 | {'max_realisations': max_realisations, |
---|
18 | 'gauge_number': gauge_number, |
---|
19 | 'exclude': exclude}, |
---|
20 | verbose=verbose) |
---|
21 | else: |
---|
22 | result = _read_realisations(subdir, |
---|
23 | max_realisations = max_realisations, |
---|
24 | gauge_number=gauge_number, |
---|
25 | exclude=exclude) |
---|
26 | |
---|
27 | return result |
---|
28 | |
---|
29 | def _read_realisations(subdir, max_realisations = None, gauge_number=0, |
---|
30 | exclude=None, use_cache=False, verbose=True): |
---|
31 | """Read realisations |
---|
32 | """ |
---|
33 | |
---|
34 | |
---|
35 | gauge = '%s.txt' %project.gauge_names[gauge_number] |
---|
36 | |
---|
37 | if subdir[-1] != os.sep: |
---|
38 | subdir += os.sep |
---|
39 | |
---|
40 | # Establish dimensions and record filenames |
---|
41 | filenames = [] |
---|
42 | for filename in os.listdir(project.working_dir + subdir): |
---|
43 | if filename.startswith(project.basename) and filename.endswith(gauge): |
---|
44 | if exclude is not None and filename.find(exclude) >= 0: |
---|
45 | print 'Excluded: %s' %filename |
---|
46 | else: |
---|
47 | filenames.append(project.working_dir + subdir + filename) |
---|
48 | |
---|
49 | if max_realisations is not None and len(filenames) == max_realisations: |
---|
50 | break |
---|
51 | |
---|
52 | time = zeros(project.number_of_timesteps, Float) |
---|
53 | data = zeros((project.number_of_timesteps, len(filenames)), Float) |
---|
54 | |
---|
55 | # Read data |
---|
56 | |
---|
57 | for j, filename in enumerate(filenames): |
---|
58 | print 'Reading filename %s (column %d)' %(filename, j) |
---|
59 | fid = open(filename) |
---|
60 | for i, line in enumerate(fid.readlines()): |
---|
61 | if i < data.shape[0]: |
---|
62 | fields = line.strip().split() |
---|
63 | time[i] = float(fields[0]) |
---|
64 | data[i,j] = float(fields[1]) |
---|
65 | |
---|
66 | fid.close() |
---|
67 | |
---|
68 | |
---|
69 | return time, data, filenames |
---|