Fixed non-interactive pylab plotting setup in common.py
[calibcant.git] / calibcant / T_analyze.py
1 #!/usr/bin/python
2 #
3 # calibcant - tools for thermally calibrating AFM cantilevers
4 #
5 # Copyright (C) 2007,2008, William Trevor King
6 #
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License as
9 # published by the Free Software Foundation; either version 3 of the
10 # License, or (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 # See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20 # 02111-1307, USA.
21 #
22 # The author may be contacted at <wking@drexel.edu> on the Internet, or
23 # write to Trevor King, Drexel University, Physics Dept., 3141 Chestnut St.,
24 # Philadelphia PA 19104, USA.
25
26 """
27 Separate the more general T_analyze() from the other T_*()
28 functions in calibcant.  Also provide a command line interface
29 for analyzing data acquired through other workflows.
30
31 The relevant physical quantities are :
32  T Temperature at which thermal vibration measurements were aquired
33 """
34
35 import numpy
36 import common # common module for the calibcant package
37 import config # config module for the calibcant package
38 import data_logger
39 import linfit
40
41 def C_to_K(celsius) :
42     "Convert Celsius -> Kelvin."
43     return celsius + 273.15
44
45 def T_analyze(T, convert_to_K=C_to_K) :
46     """
47     Not much to do here, just convert to Kelvin.
48     Uses C_to_K (defined above) by default.
49     """
50     try : # if T is an array, convert element by element
51         for i in range(len(T)) :
52             T[i] = convert_to_K(T[i])
53     except TypeError : # otherwise, make an array from a single T
54         T = [convert_to_K(T)]
55     return T
56
57 def T_save(T, log_dir=None) :
58     """
59     Save either a single T (if you are crazy :p),
60     or an array of them (more reasonable)
61     """
62     T = numpy.array(T, dtype=numpy.float)
63     if log_dir != None :
64         log = data_logger.data_log(log_dir, noclobber_logsubdir=False,
65                                    log_name="T_float")
66         log.write_binary(T.tostring())
67     if LOG_DATA != None :
68         log = data_logger.data_log(LOG_DIR, noclobber_logsubdir=False,
69                                    log_name="T_float")
70         log.write_binary(T.tostring())
71         
72 def T_load(datafile=None) :
73     """
74     Load the saved T array (possibly of length 1), and return it.  If
75     datafile == None, return an array of one config.DEFAULT_TEMP
76     instead.
77     """
78     if datafile == None :
79         return numpy.array([config.DEFAULT_TEMP], dtype=numpy.float)
80     else :
81         dl = data_logger.data_load()
82         return dl.read_binary(datafile)
83
84 def T_plot(T, plotVerbose) :
85     """
86     Umm, just print the temperature?
87     """
88     if plotVerbose or PYLAB_VERBOSE or TEXT_VERBOSE :
89         print "Temperature ", T
90
91 def T_load_analyze_tweaked(tweak_file, convert_to_K=C_to_K, textVerboseFile=None) :
92     "Load all the T array files from a tweak file and return a single array"
93     Ts = []
94     for line in file(tweak_file, 'r') :
95         parsed = line.split()
96         path = parsed[0].split('\n')[0]
97         if textVerboseFile != None :
98             print >> textVerboseFile, "Reading data from %s" % (path)
99         # read the data
100         data = T_load(path)
101         Ts.extend(data)
102     return numpy.array(Ts, dtype=numpy.float)
103
104 # commandline interface functions
105 import scipy.io, sys
106
107 def read_data(ifile):
108     "ifile can be a filename string or open (seekable) file object"
109     if ifile == None :  ifile = sys.stdin
110     unlabeled_data=scipy.io.read_array(ifile)
111     return unlabeled_data
112
113 if __name__ == '__main__' :
114     # command line interface
115     from optparse import OptionParser
116     
117     usage_string = ('%prog <input-file>\n'
118                     '2008, W. Trevor King.\n'
119                     '\n'
120                     'There are two operation modes, one to analyze a single T (temperature) file,\n'
121                     'and one to analyze tweak files.\n'
122                     '\n'
123                     'Single file mode (the default) :\n'
124                     'Reads in single column ASCII file of temperatures and... prints them back out.\n'
125                     'No need to do this, but the option is available for consistency with the other\n'
126                     'calibcant modules.\n'
127                     '\n'
128                     'Tweak file mode:\n'
129                     'Runs the same analysis as in single file mode for each T file in\n'
130                     'a tweak file.  Each line in the tweak file specifies a single T file.\n'
131                     'A T file contains a sequence of 32 bit floats representing temperature in K.\n'
132                     )
133     parser = OptionParser(usage=usage_string, version='%prog 0.1')
134     parser.add_option('-C', '--celsius', dest='celsius',
135                       help='Use Celsius input temperatures instead of Kelvin (defaul %default)\n',
136                       action='store_true', default=False)
137     parser.add_option('-o', '--output-file', dest='ofilename',
138                       help='write output to FILE (default stdout)',
139                       type='string', metavar='FILE')
140     parser.add_option('-c', '--comma-out', dest='comma_out', action='store_true',
141                       help='Output comma-seperated values (default %default)',
142                       default=False)
143     parser.add_option('-t', '--tweak-mode', dest='tweakmode', action='store_true',
144                       help='Run in tweak-file mode',
145                       default=False)
146     parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
147                       help='Print lots of debugging information',
148                       default=False)
149
150     options,args = parser.parse_args()
151     parser.destroy()
152     assert len(args) >= 1, "Need an input file"
153         
154     ifilename = args[0]
155
156     if options.ofilename != None :
157         ofile = file(options.ofilename, 'w')
158     else :
159         ofile = sys.stdout
160     if options.verbose == True :
161         vfile = sys.stderr
162     else :
163         vfile = None
164     config.TEXT_VERBOSE = options.verbose
165     config.PYLAB_VERBOSE = False
166     config.GNUPLOT_VERBOSE = False
167     if options.celsius :
168         convert_to_K = C_to_K
169     else :
170         convert_to_K = lambda T : T # no-change function
171
172     if options.tweakmode == False :
173         data = read_data(ifilename)
174         Ts = T_analyze(T, convert_to_K)
175     else : # tweak file mode
176         Ts = T_load_analyze_tweaked(ifilename, convert_to_K, textVerboseFile=vfile)
177
178     if options.comma_out :
179         sep = ','
180     else :
181         sep = '\n'
182     common.write_array(ofile, Ts, sep)
183     
184     if options.ofilename != None :
185         ofile.close()