fb465ee2c0083a6a0b251c9dc9da5f6464fc326e
[hooke.git] / hooke / driver / csvdriver.py
1 '''
2 csvdriver.py
3
4 Simple driver to read general comma-separated values in Hooke
5
6 Columns are read this way:
7
8 X1 , Y1 , X2 , Y2 , X3 , Y3 ...
9
10 If the number of columns is odd, the last column is ignored.
11
12 (c)Massimo Sandal, 2008
13 '''
14
15 import libhookecurve as lhc
16 import libhooke as lh
17 import csv
18
19 class csvdriverDriver(lhc.Driver):
20
21         def __init__(self, filename):
22
23             self.filedata = open(filename,'r')
24             self.data = list(self.filedata)
25             self.filedata.close()
26
27             self.filetype = 'generic'
28             self.experiment = ''
29
30             self.filename=filename
31
32         def is_me(self):
33             myfile=file(self.filename)
34             headerline=myfile.readlines()[0]
35             myfile.close()
36
37             #using a custom header makes things much easier...
38             #(looking for raw CSV data is at strong risk of confusion)
39             if headerline[:-1]=='Hooke data':
40                 return True
41             else:
42                 return False
43
44         def close_all(self):
45             self.filedata.close()
46
47         def default_plots(self):
48             rrows=csv.reader(self.data)
49             rows=list(rrows) #transform the csv.reader iterator in a normal list
50             columns=lh.transposed2(rows[1:])
51
52             main_plot=lhc.PlotObject()
53             main_plot.vectors=[]
54
55             for index in range(0,len(columns),2):
56                 main_plot.vectors.append([])
57                 temp_x=columns[index]
58                 temp_y=columns[index+1]
59
60                 #convert to float (the csv gives strings)
61                 temp_x=[float(item) for item in temp_x]
62                 temp_y=[float(item) for item in temp_y]
63
64                 main_plot.vectors[-1].append(temp_x)
65                 main_plot.vectors[-1].append(temp_y)
66
67             main_plot.units=['x','y']
68             main_plot.title=self.filename
69             main_plot.destination=0
70
71             return [main_plot]