-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathReadConfig.py
305 lines (276 loc) · 11.8 KB
/
ReadConfig.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""
Copyright (c) 2020 Sergio Augusto Barcellos Lins & Giovanni Ettore Gigante
The example data distributed together with XISMuS was kindly provided by
Giovanni Ettore Gigante and Roberto Cesareo. It is intelectual property of
the universities "La Sapienza" University of Rome and Università degli studi di
Sassari. Please do not publish, commercialize or distribute this data alone
without any prior authorization.
This software is distrubuted with an MIT license.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Credits:
Few of the icons used in the software were obtained under a Creative Commons
Attribution-No Derivative Works 3.0 Unported License (http://creativecommons.org/licenses/by-nd/3.0/)
from the Icon Archive website (http://www.iconarchive.com).
XISMuS source-code can be found at https://github.com/linssab/XISMuS
"""
import logging, os
import Constants
from win32com.shell import shell, shellcon
def pop_error(title,message):
""" Displays TK error message """
from tkinter import messagebox
messagebox.showerror(title,message)
return 0
""" Get working path and config.cfg path """
docs = shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, None, 0)
__PERSONAL__ = os.path.join(docs,"XISMuS")
__BIN__ = os.path.join(__PERSONAL__,"bin")
cfgfile = os.path.join(__BIN__,"config.cfg")
logger = logging.getLogger("logfile")
logger.debug("Importing module ReadConfig.py...")
def check_config():
""" Tries to read Config.cfg and verifies it contain all needed entries.
Returns tags found in file. """
lines, tags = [],[]
try: c_file = open(cfgfile, 'r')
except:
pop_error("Configuration Error","No calibration file {0} found!".format(cfgfile))
raise FileNotFoundError("No calibration file {0} found!".format(cfgfile))
for line in c_file:
line = line.replace('\n','')
lines.append(line)
for sentence in lines:
if "<<CONFIG_START>>" in sentence: tags.append(sentence)
elif "<<CALIBRATION>>" in sentence: tags.append(sentence)
elif "<<END>>" in sentence: tags.append(sentence)
if "<<CONFIG_START>>" not in tags: raise IOError("Cant find <<CONFIG_START>>")
if "<<CALIBRATION>>" not in tags: raise IOError("No <<CALIBRATION>>!")
if "<<END>>" not in tags: raise IOError("No <<END>> of configuration!")
return tags
def getconfig():
""" Extracts all configuration information in Config.cfg
--------------------------------------------------------
OUTPUT:
modesdict; dict
CalParam; 2D-list """
tags = check_config()
modesdict = {}
CalParam = []
configfile = open(cfgfile, 'r')
line = configfile.readline()
if "<<CONFIG_START>>" in line:
line = configfile.readline()
while "<<CALIBRATION>>" not in line:
if 'directory' in line:
line=line.replace('\r','')
line=line.replace('\n','')
line=line.replace('\t',' ')
aux = line.split()
# removes key and "="
aux.pop(0)
aux.pop(0)
directory = ""
# build up the folder name with spaces. can't have space at the end
for i in range(len(aux)):
if i < len(aux)-1: directory += aux[i] + " "
else: directory += aux[i]
modesdict['directory'] = directory
if 'bgstrip' in line:
line=line.replace('\r','')
line=line.replace('\n','')
line=line.replace('\t',' ')
aux = line.split()
modesdict['bgstrip'] = str(aux[2])
if 'ratio' in line:
line=line.replace('\r','')
line=line.replace('\n','')
line=line.replace('\t',' ')
aux = line.split()
if aux[2] == 'True': modesdict['ratio'] = True
elif aux[2] == 'False': modesdict['ratio'] = False
if 'thickratio' in line:
line=line.replace('\r','')
line=line.replace('\n','')
line=line.replace('\t',' ')
aux = line.split()
modesdict['thickratio'] = float(aux[2])
if 'calibration' in line:
line=line.replace('\r','')
line=line.replace('\n','')
line=line.replace('\t',' ')
aux = line.split()
modesdict['calibration'] = str(aux[2])
if 'enhance' in line:
line=line.replace('\r','')
line=line.replace('\n','')
line=line.replace('\t',' ')
aux = line.split()
if aux[2] == 'True': modesdict['enhance'] = True
elif aux[2] == 'False': modesdict['enhance'] = False
if 'peakmethod' in line:
line=line.replace('\r','')
line=line.replace('\n','')
line=line.replace('\t',' ')
aux = line.split()
modesdict['peakmethod'] = str(aux[2])
if 'bg_settings' in line:
line=line.replace('\r','')
line=line.replace('\n','')
line=line.replace('\t','')
line=line.replace(',','')
line=line.replace('(','')
line=line.replace(')','')
aux = line.split(" ")
bs_list = []
for i in aux:
if i.isdigit(): bs_list.append(int(i))
modesdict['bg_settings'] = bs_list
del bs_list
line = configfile.readline()
line = configfile.readline()
while "<<END>>" not in line:
line=line.replace('\r','')
line=line.replace('\n','')
line=line.replace('\t',' ')
aux = line.split()
try: CalParam.append([float(aux[0]),float(aux[1])])
except: CalParam = [[0,0]]
line = configfile.readline()
configfile.close()
for parameter in CalParam:
if len(CalParam) <= 1: raise IOError("Need at least two calibration points!")
if parameter[0] < 0 or parameter[1] < 0:
raise IOError("Cant receive negative channel or energy!")
else: pass
return modesdict,CalParam
def checkout_config():
""" Re-sets Config.cfg file with default values if any tag is missing. """
cfgfile = os.path.join(__BIN__,"config.cfg")
lines, tags = [],[]
c_file = open(cfgfile, "r")
for line in c_file:
line = line.replace("\n","")
lines.append(line)
for sentence in lines:
if "<<CONFIG_START>>" in sentence: tags.append(sentence)
elif "<<CALIBRATION>>" in sentence: tags.append(sentence)
elif "<<END>>" in sentence: tags.append(sentence)
c_file.close()
if "<<CONFIG_START>>" not in tags:
c_file = open(cfgfile, "a+")
c_file.write("<<CONFIG_START>>\r")
c_file.write("directory = None\r")
c_file.write("bgstrip = None\r")
c_file.write("ratio = False\r")
c_file.write("thickratio = 0\r")
c_file.write("calibration = manual\r")
c_file.write("enhance = False\r")
c_file.write("peakmethod = simple_roi\r")
c_file.write("bgsettings = None\r")
c_file.write("<<CALIBRATION>>\r")
c_file.write("<<END>>\r")
c_file.close()
pop_error("Configuration issue",\
"Config.cfg file corrupted, re-setting default configuration.")
elif "<<CALIBRATION>>" not in tags:
c_file = open(cfgfile, "a")
c_file.write("<<CALIBRATION>>\r")
c_file.write("<<END>>\r")
c_file.close()
elif "<<END>>" not in tags:
c_file = open(cfgfile, "a")
c_file.write("<<END>>\r")
c_file.close()
return 0
def unpack_cfg():
""" Calls getconfig to get configuration parameters """
all_parameters = getconfig()
CONFIG = all_parameters[0]
CALIB = all_parameters[1]
return CONFIG, CALIB
def set_settings(inifile):
ColorMapMode = Constants.COLORMAP
CoreMode = Constants.MULTICORE
PlotMode = Constants.PLOTMODE
RAMMode = Constants.RAM_LIMIT
WlcmMode = Constants.WELCOME
PeakTolerance = Constants.SETROI_TOLERANCE
Cycles = Constants.FIT_CYCLES
Sensitivity = Constants.PEAK_TOLERANCE
ContSuppr = Constants.CONTINUUM_SUPPRESSION
WizTol = Constants.CHECK_TOLERANCE
SaveInterval = Constants.SAVE_INTERVAL
SavePlot = Constants.SAVE_FIT_FIGURES
ini = open(inifile,"r")
for line in ini:
line = line.replace("\n","")
line = line.replace("\r","")
if line.split("\t")[0] == "<ColorMap>":
ColorMapMode = str(line.split("\t")[1])
ColorMapMode = ColorMapMode.replace("\n","")
elif line.split("\t")[0] == "<MultiCore>":
if line.split("\t")[1] == "False":
CoreMode = False
else: CoreMode = True
elif line.split("\t")[0] == "<PlotMode>":
PlotMode = str(line.split("\t")[1])
elif line.split("\t")[0] == "<RAMLimit>":
if line.split("\t")[1] == "False":
RAMMode = False
else: RAMMode = True
elif line.split("\t")[0] == "<welcome>":
if line.split("\t")[1] == "False":
WlcmMode = False
else: WlcmMode = True
elif line.split("\t")[0] == "<Tolerance>":
PeakTolerance=[]
line = line.split("\t")[1].replace("[","").replace("]","")
line = line.split(",")
for i in line:
PeakTolerance.append(float(i))
elif line.split("\t")[0] == "<Cycles>":
Cycles = int(line.split("\t")[1])
elif line.split("\t")[0] == "<Sensitivity>":
Sensitivity = float(line.split("\t")[1])
elif line.split("\t")[0] == "<Suppression>":
ContSuppr = float(line.split("\t")[1])
elif line.split("\t")[0] == "<WizTolerance>":
WizTol = float(line.split("\t")[1])
elif line.split("\t")[0] == "<SaveInterval>":
SaveInterval = int(line.split("\t")[1])
elif line.split("\t")[0] == "<SavePlot>":
if line.split("\t")[1] == "False":
SavePlot = False
else: SavePlot = True
ini.close()
Constants.COLORMAP = ColorMapMode
Constants.MULTICORE = CoreMode
Constants.PLOTMODE = PlotMode
Constants.RAM_LIMIT = RAMMode
Constants.WELCOME = WlcmMode
Constants.SETROI_TOLERANCE = PeakTolerance
Constants.FIT_CYCLES = Cycles
Constants.PEAK_TOLERANCE = Sensitivity
Constants.CONTINUUM_SUPPRESSION = ContSuppr
Constants.CHECK_TOLERANCE = WizTol
Constants.SAVE_INTERVAL = SaveInterval
Constants.SAVE_FIT_FIGURES = SavePlot
if PlotMode == "Logarithmic": Constants.PLOTSCALE = "-semilogy"
else: Constants.PLOTSCALE = None
return
if __name__ == "__main__":
logger.info("This is ReadConfig")