171f9430dd500beede280e6b18fc7b0f1c8b0def
[hooke.git] / plugins / export.py
1 #!/usr/bin/env python
2
3 '''
4 export.py
5
6 Export commands for Hooke.
7
8 Copyright 2010 by Dr. Rolf Schmidt (Concordia University, Canada)
9
10 This program is released under the GNU General Public License version 2.
11 '''
12
13 import lib.libhooke as lh
14 import wxversion
15 wxversion.select(lh.WX_GOOD)
16
17 import copy
18 import os.path
19 import time
20 import wx
21
22 class exportCommands(object):
23     '''
24     Export force curves, fits and results in different formats
25     '''
26
27     def _plug_init(self):
28         pass
29
30     def do_fits(self):
31         '''
32         Exports all fitting results (if available) in a columnar ASCII format.
33         '''
34
35         ext = self.GetStringFromConfig('export', 'fits', 'ext')
36         folder = self.GetStringFromConfig('export', 'fits', 'folder')
37         prefix = self.GetStringFromConfig('export', 'fits', 'prefix')
38         separator = self.GetStringFromConfig('export', 'fits', 'separator')
39         #TODO: add list for Tab, Space, Comma, Other
40         #add string for Other
41
42         active_file = self.GetActiveFile()
43         plot = self.GetDisplayedPlot()
44
45         #add empty columns before adding new results if necessary
46         if plot is not None:
47             for results_str, results in plot.results.items():
48                 for curve in results.results:
49                     output = []
50                     header_str = ''
51                     if curve.visible:
52                         header_str += curve.label + '_x (' + curve.units.x + ')' + separator + curve.label + '_y (' + curve.units.y + ')'
53                         output.append(header_str)
54                         for index, row in enumerate(curve.x):
55                             output.append(separator.join([str(curve.x[index]), str(curve.y[index])]))
56                     if output:
57                         #TODO: add option to replace or add the new file extension
58                         #add option to rename file from default.000 to default_000
59                         filename = os.path.basename(active_file.filename)
60                         filename = ''.join([prefix, filename, '_', curve.label, '.', ext])
61                         filename = os.path.join(folder, filename)
62                         output_file = open(filename, 'w')
63                         output_file.write('\n'.join(output))
64                         output_file.close
65
66     def do_force_curve(self):
67         '''
68         TXT
69         Saves the current curve as a text file
70         Columns are, in order:
71         X1 , Y1 , X2 , Y2 , X3 , Y3 ...
72
73         -------------
74         Syntax: txt [filename] {plot to export}
75         '''
76
77         ext = self.GetStringFromConfig('export', 'force_curve', 'ext')
78         folder = self.GetStringFromConfig('export', 'force_curve', 'folder')
79         prefix = self.GetStringFromConfig('export', 'force_curve', 'prefix')
80         separator = self.GetStringFromConfig('export', 'force_curve', 'separator')
81         #TODO: add list for Tab, Space, Comma, Other
82         #add string for Other
83
84         active_file = self.GetActiveFile()
85         #create the header from the raw plot (i.e. only the force curve)
86         plot = self.GetDisplayedPlotRaw()
87
88         output = []
89         header_str = ''
90         for index, curve in enumerate(plot.curves):
91             #TODO: only add labels for original curves (i.e. excluding anything added after the fact)
92             header_str += curve.label + '_x (' + curve.units.x + ')' + separator + curve.label + '_y (' + curve.units.y + ')'
93             if index < len(plot.curves) - 1:
94                 header_str += separator
95         output.append(header_str)
96
97         #export the displayed plot
98         plot = self.GetDisplayedPlot()
99         extension = plot.curves[lh.EXTENSION]
100         retraction = plot.curves[lh.RETRACTION]
101         for index, row in enumerate(extension.x):
102             output.append(separator.join([str(extension.x[index]), str(extension.y[index]), str(retraction.x[index]), str(retraction.y[index])]))
103
104         if output:
105             #TODO: add option to replace or add the new file extension
106             #add option to rename file from default.000 to default_000
107             filename = os.path.basename(active_file.filename)
108             filename = ''.join([prefix, filename, '.', ext])
109             filename = os.path.join(folder, filename)
110             output_file = open(filename, 'w')
111             output_file.write('\n'.join(output))
112             output_file.close
113
114     def do_overlay(self):
115         '''
116         Exports all retraction files in a playlist with the same scale.
117         The files can then be overlaid in a graphing program to see which
118         ones have the same shape.
119         Use this export command only on filtered lists as it takes a long time
120         to complete even with a small number of curves.
121         '''
122         playlist = self.GetActivePlaylist()
123
124         filename_prefix = self.GetStringFromConfig('export', 'overlay', 'prefix')
125
126         differences_x = []
127         differences_y = []
128         number_of_curves = playlist.count
129         message_str = ''.join([str(number_of_curves), ' files to load.\n\n'])
130         progress_dialog = wx.ProgressDialog('Loading', message_str, maximum=number_of_curves, parent=self, style=wx.PD_APP_MODAL|wx.PD_SMOOTH|wx.PD_AUTO_HIDE)
131         for index, current_file in enumerate(playlist.files):
132             current_file.identify(self.drivers)
133             plot = current_file.plot
134
135             plot.raw_curves = copy.deepcopy(plot.curves)
136             #apply all active plotmanipulators and add the 'manipulated' data
137             for plotmanipulator in self.plotmanipulators:
138                 if self.GetBoolFromConfig('core', 'plotmanipulators', plotmanipulator.name):
139                     plot = plotmanipulator.method(plot, current_file)
140             #add corrected curves to plot
141             plot.corrected_curves = copy.deepcopy(plot.curves)
142
143             curve = current_file.plot.corrected_curves[lh.RETRACTION]
144             differences_x.append(curve.x[0] - curve.x[-1])
145             differences_y.append(curve.x[0] - curve.y[-1])
146             progress_dialog.Update(index, ''.join([message_str, 'Loading ', str(index + 1), '/', str(number_of_curves)]))
147         progress_dialog.Destroy()
148
149         max_x = max(differences_x)
150         max_y = max(differences_y)
151         message_str = ''.join([str(number_of_curves), ' files to export.\n\n'])
152         for index, current_file in enumerate(playlist.files):
153             curve = current_file.plot.corrected_curves[lh.RETRACTION]
154             first_x = curve.x[0]
155             first_y = curve.y[0]
156             new_x = [x - first_x for x in curve.x]
157             new_y = [y - first_y for y in curve.y]
158             new_x.append(-max_x)
159             new_y.append(-max_y)
160             output_str = ''
161             for row_index, row in enumerate(new_x):
162                 output_str += ''.join([str(new_x[row_index]), ', ', str(new_y[row_index]), '\n'])
163
164             if output_str != '':
165                 filename = ''.join([filename_prefix, current_file.name])
166                 filename = current_file.filename.replace(current_file.name, filename)
167                 output_file = open(filename, 'w')
168                 output_file.write(output_str)
169                 output_file.close
170         progress_dialog.Destroy()
171
172     def do_results(self, append=None, filename='', separator=''):
173         '''
174         Exports all visible fit results in a playlist into a delimited text file
175         append: set append to True if you want to append to an existing results file
176         filename: the filename and path of the results file
177         separator: the separator between columns
178         '''
179         if not append:
180             append = self.GetStringFromConfig('export', 'results', 'append')
181         if filename == '':
182             filename = self.GetStringFromConfig('export', 'results', 'filename')
183         if separator == '':
184             separator = self.GetStringFromConfig('export', 'results', 'separator')
185
186         playlist = self.GetActivePlaylist()
187         output_str = ''
188         header_str = ''
189         for current_file in playlist.files:
190             if len(current_file.plot.results) > 0:
191                 for key in current_file.plot.results.keys():
192                     #if there are different types of fit results in the playlist, the header might have to change
193                     #here, we generate a temporary header and compare it to the current header
194                     #if they are different, the tempeorary header is used
195                     #we get the header from the fit and add the 'filename' column
196                     temporary_header_str = ''.join([current_file.plot.results[key].get_header_as_str(), separator, 'Filename'])
197                     if temporary_header_str != header_str:
198                         header_str = ''.join([current_file.plot.results[key].get_header_as_str(), separator, 'Filename'])
199                         output_str = ''.join([output_str, header_str, '\n'])
200                     for index, result in enumerate(current_file.plot.results[key].results):
201                         if result.visible:
202                             #similar to above, we get the result from the fit and add the filename
203                             line_str = current_file.plot.results[key].get_result_as_string(index)
204                             line_str = ''.join([line_str, separator, current_file.filename])
205                             output_str = ''.join([output_str, line_str, '\n'])
206         if output_str != '':
207             output_str = ''.join(['Analysis started ', time.asctime(), '\n', output_str])
208
209             if append and os.path.isfile(filename):
210                 output_file = open(filename,'a')
211             else:
212                 output_file = open(filename, 'w')
213             output_file.write(output_str)
214             output_file.close
215         else:
216             dialog = wx.MessageDialog(None, 'No results found, file not saved.', 'Info', wx.OK)
217             dialog.ShowModal()