1 """Reads label files produced by ESPS xwaves.
2 Writes labels files that ESPS xwaves can read.
3 """
4
5 import os
6 import sys
7 from gmisclib import die
8 from gmisclib.xwaves_errs import *
9
10
11 -def read(filename, loose=0):
12 """read in .lab files produced by ESPS xlabel. returns (header, data).
13 Data = [(time, label), ...].
14 Note that leading or trailing spaces in the label are removed.
15 """
16 HUGE = 1e30
17 hdr = {}
18 if filename == '-':
19 fd = sys.stdin
20 else:
21 try:
22 fd = open(filename, "r")
23 except IOError, x:
24 raise NoSuchFileError, x
25 n = 0
26 comments = []
27 while True:
28 l = fd.readline()
29 n += 1
30 if not l:
31 raise BadFileFormatError, '%s:%d' % (filename, n)
32 if l.startswith('#'):
33 break
34 if l.startswith('comment'):
35 comments.append(l[len('comment'):].strip())
36 continue
37 try:
38 a, v = l.split(None, 1)
39 except ValueError:
40 if loose:
41 hdr[l.strip()] = ''
42 loose -= 1
43 else:
44 die.warn( ("Line %d:" % n) + l.strip())
45 raise BadFileFormatError, '%s:%d' % (filename, n)
46 else:
47 hdr[a.strip()] = v.strip()
48
49 t_last = -HUGE
50 d = []
51 while True:
52 l = fd.readline()
53 if not l:
54 break
55 n += 1
56
57 l = l.lstrip().rstrip('\r\n')
58 if not l:
59 continue
60
61 lsplit = l.split(None, 2)
62
63 if len(lsplit)==2 and (l.endswith(' ') or l.endswith('\t')):
64 t, junk = lsplit
65 label = ''
66 elif len(lsplit)==2 and loose > 0:
67 loose -= 1
68 t,junk = lsplit
69 label = ''
70 comments.append('Two columns: assuming third is empty: line %d: %s' % (n, l))
71 elif len(lsplit) == 2:
72 raise BadFileFormatError, 'Two columns: should be three: %s:%d' % (filename, n)
73 else:
74 t, junk, label = lsplit
75
76 t = float(t)
77 if t >= t_last:
78 d.append((t, label))
79 elif loose > 0:
80 d.append((t, label))
81 loose -= 1
82 else:
83 raise DataOutOfOrderError, '%s:%d' % (filename, n)
84 t_last = t
85
86 fd.flush()
87
88 fd = None
89
90
91
92 hdr['_COMMENT'] = '\n'.join(comments)
93 hdr['_NAME'] = filename
94 hdr['_FILETYPE'] = 'xlabel'
95 hdr['NAXIS'] = 2
96 hdr['NAXIS2'] = len(d)
97 hdr['NAXIS1'] = 2
98 hdr['TTYPE1'] = 'time'
99 hdr['TUNIT1'] = 's'
100 hdr['TTYPE2'] = 'label'
101
102 return (hdr, d)
103
104
106 """Converts data in (end_time, label) format to (t_start, t_stop, label)"""
107 o = []
108 last = None
109 for (time, label) in d:
110 o.append( (last, time, label) )
111 last = time
112 if dropfirst and len(o)>0:
113 o.pop(0)
114 return o
115
116
117 -def end_marks(d, beglabel, delta=0.001, interlabel=None):
118 """Converts data in a (start, stop, label) format to (end_time, label).
119 It introduces extra labels if neccessary.
120 A beginning label is required, to mark the start of the first segment."""
121 if len(d) == 0:
122 return []
123 if interlabel is None:
124 interlabel = beglabel
125 start, stop, label = d[0]
126 o = [ (start, beglabel), (stop, label) ]
127 laststop = stop
128 for (start, stop, label) in d[1:]:
129 if start > laststop + delta:
130 o.append( (start, interlabel) )
131 o.append( (stop, label) )
132 laststop = stop
133 return o
134
135
136 -def write(fd, header, data):
137 """Expects data in [(t, label), ...] form.
138 """
139 h = {'font': '-misc-*-bold-*-*-*-15-*-*-*-*-*-*-*',
140 'separator': ';',
141 'nfields': ';'
142 }
143 h.update(header)
144 d = list(data)
145 d.sort()
146
147 alist = h.items()
148 alist.sort()
149 for (a, v) in alist:
150 if v != '':
151 for tmp in str(v).split('\n'):
152 fd.write('%s %s\n' % (a, tmp))
153 fd.write('#\n')
154 fd.flush()
155 for (t, mark) in data:
156 fd.write('%12.5f -1 %s\n' % (t, str(mark).strip()))
157 fd.flush()
158
159
160 if __name__ == '__main__':
161 hdr, data = read(sys.argv[1])
162 for (t, l) in data:
163 print t, l
164