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