Skip to content

Commit 49f3314

Browse files
authored
Merge pull request #344 from Kvieta1990/master
Major update to Mantid interface
2 parents 071890b + e2ccfca commit 49f3314

File tree

12 files changed

+198
-277
lines changed

12 files changed

+198
-277
lines changed

addie/config.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
"max": 40,
3030
"delta": 0.02
3131
},
32-
"reduction_configuration_file": "",
3332
"characterization_file": ""
3433
},
3534
"bragg": {

addie/main.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,9 @@ class MainWindow(QMainWindow):
131131
intermediate_grouping = copy.deepcopy(grouping_dict)
132132
output_grouping = copy.deepcopy(grouping_dict)
133133

134+
advanced_dict = {'push_bkg': False,
135+
'ele_size': "1.0"}
136+
134137
statusbar_display_time = 5000 # 5s
135138

136139
# external ui (use to make sure there is only one open at a time

addie/processing/mantid/launch_reduction.py

100644100755
Lines changed: 54 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,8 @@
11
import os
2-
import traceback
3-
from mantidqt.utils.asynchronous import AsyncTask
2+
import json
43

54
from addie.processing.mantid.master_table.master_table_exporter import TableFileExporter as MantidTableExporter
65

7-
# Mantid Total Scattering integration
8-
# (https://github.com/neutrons/mantid_total_scattering)
9-
try:
10-
import total_scattering
11-
print("Mantid Total Scattering Version: ", total_scattering.__version__)
12-
from total_scattering.reduction.total_scattering_reduction import TotalScatteringReduction
13-
MANTID_TS_ENABLED = True
14-
except ImportError:
15-
print('total_scattering module not found. Functionality disabled')
16-
MANTID_TS_ENABLED = False
17-
18-
19-
class JobPool(object):
20-
task_output = None,
21-
running = None
22-
task_exc_type, task_exc, task_exc_stack = None, None, None
23-
24-
def __init__(self, configurations):
25-
self.jobs = []
26-
for config in configurations:
27-
print("CONFIG:", config)
28-
self.jobs.append(AsyncTask(TotalScatteringReduction, args=(config,),
29-
success_cb=self.on_success, error_cb=self.on_error,
30-
finished_cb=self.on_finished))
31-
32-
def _start_next(self):
33-
if self.jobs:
34-
self.running = self.jobs.pop(0)
35-
self.running.start()
36-
else:
37-
self.running = None
38-
39-
def start(self):
40-
if not self.jobs:
41-
raise RuntimeError('Cannot start empty job list')
42-
self._start_next()
43-
44-
def on_success(self, task_result):
45-
# TODO should emit a signal
46-
self.task_output = task_result.output
47-
print('SUCCESS!!! {}'.format(self.task_output))
48-
49-
def on_error(self, task_result):
50-
# TODO should emit a signal
51-
print('ERROR!!!')
52-
self.task_exc_type = task_result.exc_type
53-
self.task_exc = task_result.exc_value
54-
self.task_exc_stack = traceback.extract_tb(task_result.stack)
55-
traceback.print_tb(task_result.stack)
56-
print(task_result)
57-
58-
def on_finished(self):
59-
'''Both success and failure call this method afterwards'''
60-
# TODO should emit a signal
61-
self._start_next() # kick off the next one in the pool
62-
636

647
def run_mantid(parent):
658
num_rows = parent.processing_ui.h3_table.rowCount()
@@ -87,28 +30,56 @@ def run_mantid(parent):
8730
filename = os.path.join(os.path.expanduser('~'),'.mantid' ,'JSON_output',dictionary['Title'] +'_'+ str(row) + '.json')
8831
exporter.export(filename,row)
8932
print("Row",row,"Successfully output to",filename)
90-
91-
# append the individual rows to input list (reduction_inputs)
92-
reduction_inputs = []
93-
for row in range(num_rows):
94-
if not exporter.isActive(row):
95-
print('skipping row {} - inactive'.format(row + 1)) # REMOVE?
96-
continue
97-
print('Will be running row {} for reduction'.format(row + 1)) # TODO should be debug logging
98-
json_input = exporter.retrieve_row_info(row)[0]
99-
reduction_input = exporter.convert_from_row_to_reduction(json_input)
100-
if not reduction_input:
101-
return
102-
reduction_inputs.append(reduction_input)
103-
if len(reduction_inputs) == 0:
104-
print('None of the rows were activated')
105-
return
106-
107-
# locate total scattering script
108-
if MANTID_TS_ENABLED:
109-
pool = JobPool(reduction_inputs)
110-
pool.start()
111-
else:
112-
# TODO should be on the status bar
113-
print('total_scattering module not found. Functionality disabled')
114-
return
33+
with open(filename) as json_file:
34+
data_tmp = json.load(json_file)
35+
dict_out_tmp = {}
36+
container_type=""
37+
for key, item in data_tmp.items():
38+
if "Sample" in key:
39+
sample_tmp = {}
40+
for key_s, item_s in item.items():
41+
if "Density" not in key_s:
42+
if "Material" in key_s:
43+
string_tmp = item_s.replace("(", "").replace(")", "")
44+
sample_tmp[key_s] = string_tmp
45+
else:
46+
sample_tmp[key_s] = item_s
47+
if "Geometry" in key_s:
48+
known_shape = ["PAC03", "PAC06", "PAC08",
49+
"PAC10", "QuartzTube03"]
50+
if item_s["Shape"] in known_shape:
51+
shape_tmp = "Cylinder"
52+
container_type = item_s["Shape"]
53+
else:
54+
shape_tmp = item_s["Shape"]
55+
geo_dict_tmp = {}
56+
for key_tmp in item_s:
57+
geo_dict_tmp[key_tmp] = item_s[key_tmp]
58+
geo_dict_tmp["Shape"] = shape_tmp
59+
sample_tmp[key_s] = geo_dict_tmp
60+
else:
61+
sample_tmp["MassDensity"] = float(item_s["MassDensity"])
62+
dict_out_tmp[key] = sample_tmp
63+
elif "Normalization" in key or "Normalisation" in key:
64+
van_tmp = {}
65+
for key_v, item_v in item.items():
66+
if "Density" not in key_v:
67+
if "Material" in key_v:
68+
string_tmp = item_v.replace("(", "").replace(")", "")
69+
van_tmp[key_v] = string_tmp
70+
else:
71+
van_tmp[key_v] = item_v
72+
else:
73+
van_tmp["MassDensity"] = float(item_v["MassDensity"])
74+
dict_out_tmp[key] = van_tmp
75+
else:
76+
dict_out_tmp[key] = item
77+
if container_type:
78+
dict_out_tmp["Environment"] = { "Name": "InAir",
79+
"Container": container_type}
80+
filename_to_run = os.path.join(os.path.expanduser('~'),'.mantid' ,'JSON_output', 'running_tmp.json')
81+
with open(filename_to_run, 'w') as outfile:
82+
json.dump(dict_out_tmp, outfile, indent=2)
83+
_script_to_run = "bash /SNS/NOM/shared/scripts/mantidtotalscattering/run_mts.sh " + filename_to_run
84+
parent.launch_job_manager(job_name='MantidTotalScattering',
85+
script_to_run=_script_to_run)

addie/processing/mantid/make_calibration_handler/make_calibration.py

100644100755
Lines changed: 34 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
from qtpy.QtWidgets import (QMainWindow, QComboBox, QFileDialog, QHBoxLayout, QLabel, QDateEdit, QLineEdit, QPushButton,
44
QTableWidgetItem, QVBoxLayout, QWidget)
55
from addie.utilities import load_ui
6-
from addie.widgets.filedialog import get_save_file
76
from qtpy import QtCore
87

98
import datetime
@@ -34,7 +33,7 @@ def __init__(self, parent=None):
3433

3534
class MakeCalibrationWindow(QMainWindow):
3635

37-
table_column_width = [60, 250, 350, 350, 90, 300]
36+
table_column_width = [60, 250, 600, 90, 300]
3837
table_row_height = 85
3938
entry_level = 0
4039

@@ -49,9 +48,6 @@ class MakeCalibrationWindow(QMainWindow):
4948
"calibration_value",
5049
"calibration_browser",
5150
"calibration_browser_value",
52-
"vanadium_value",
53-
"vanadium_browser",
54-
"vanadium_browser_value",
5551
"date",
5652
"output_dir_browser",
5753
"output_dir_value",
@@ -175,17 +171,6 @@ def get_run_number_from_nexus_file_name(self, base_nexus_name=''):
175171
return result.group(1)
176172
return None
177173

178-
def vanadium_browser_clicked(self, entry=""):
179-
sample_type = "Vanadium"
180-
value_ui = self.master_list_ui[entry].vanadium_browser_value
181-
182-
[_file, run_number] = self._general_browser_clicked(sample_type=sample_type,
183-
value_ui=value_ui)
184-
if _file:
185-
self.master_list_value[entry]["vanadium_browser"] = _file
186-
self.master_list_ui[entry].vanadium_value.setText(str(run_number))
187-
self.check_run_calibration_status()
188-
189174
def calibration_browser_clicked(self, entry=""):
190175
sample_type = "Calibration"
191176
value_ui = self.master_list_ui[entry].calibration_browser_value
@@ -273,41 +258,14 @@ def __insert_new_row(self, row=-1):
273258
col1_widget.setLayout(verti_layout)
274259
self.ui.tableWidget.setCellWidget(row, col, col1_widget)
275260

276-
# new column - Vanadium
277-
col = 3
278-
# first row
279-
# first row
280-
label = QLabel("Run #:")
281-
vana_value = QLineEdit("")
282-
vana_value.returnPressed.connect(lambda entry=_name: self.run_entered(entry))
283-
vana_browser_button = QPushButton("Browse...")
284-
vana_browser_button.setMinimumWidth(button_width)
285-
vana_browser_button.setMaximumWidth(button_width)
286-
vana_browser_button.clicked.connect(lambda state, entry=_name: self.vanadium_browser_clicked(entry))
287-
first_row = QHBoxLayout()
288-
first_row.addWidget(label)
289-
first_row.addWidget(vana_value)
290-
first_row.addWidget(vana_browser_button)
291-
first_row_widget = QWidget()
292-
first_row_widget.setLayout(first_row)
293-
# second row
294-
vana_browser_button_value = QLabel("N/A")
295-
296-
verti_layout = QVBoxLayout()
297-
verti_layout.addWidget(first_row_widget)
298-
verti_layout.addWidget(vana_browser_button_value)
299-
col1_widget = QWidget()
300-
col1_widget.setLayout(verti_layout)
301-
self.ui.tableWidget.setCellWidget(row, col, col1_widget)
302-
303261
# new column - date
304-
col = 4
262+
col = 3
305263
date = QDateEdit()
306264
date.setDate(self.master_date_value)
307265
self.ui.tableWidget.setCellWidget(row, col, date)
308266

309267
# new column - output dir
310-
col = 5
268+
col = 4
311269
browser_button = QPushButton("Browse...")
312270
browser_button.setMinimumWidth(button_width)
313271
browser_button.setMaximumWidth(button_width)
@@ -329,18 +287,13 @@ def __insert_new_row(self, row=-1):
329287
calibration_value=cali_value,
330288
calibration_browser=cali_browser_button,
331289
calibration_browser_value=cali_browser_button_value,
332-
vanadium_value=vana_value,
333-
vanadium_browser=vana_browser_button,
334-
vanadium_browser_value=vana_browser_button_value,
335290
date=date,
336291
output_dir_browser=browser_button,
337292
output_dir_value=browser_value,
338293
output_reset=reset)
339294
self.master_list_ui[_name] = list_local_ui
340295

341-
list_local_name = dict(vanadium_run_number="",
342-
vanadium_browser="",
343-
calibration_run_number="",
296+
list_local_name = dict(calibration_run_number="",
344297
calibration_browser="")
345298
self.master_list_value[_name] = list_local_name
346299

@@ -359,10 +312,6 @@ def _check_status_of_row(self, row=-1):
359312
if not self._check_local_column(run_value = local_list_ui.calibration_value):
360313
return False
361314

362-
# Vanadium column
363-
if not self._check_local_column(run_value=local_list_ui.vanadium_value):
364-
return False
365-
366315
# output dir
367316
browse_label = local_list_ui.output_dir_value
368317
if browse_label.text() == 'N/A':
@@ -395,15 +344,37 @@ def check_run_calibration_status(self):
395344
self.ui.run_calibration_button.setEnabled(_status)
396345

397346
def run_calibration_button_clicked(self):
398-
# make dictionary of all infos
347+
instr_dict = {"NOM": "NOMAD",
348+
"PG3": "PG3}"}
399349
o_dict = MakeCalibrationDictionary(parent=self)
400-
_file, _ = get_save_file(parent=self,
401-
caption="Select where and name of json file to create...",
402-
# directory = '/SNS/users/ntm/',
403-
filter={'json (*.json)':'json'})
404-
if _file:
405-
with open(_file, 'w') as fp:
406-
simplejson.dump(o_dict.dictionary, fp, indent=2, ignore_nan=True)
350+
for calibrant in o_dict.dictionary['Calibrants'].keys():
351+
calib_tmp_dict = o_dict.dictionary['Calibrants'][calibrant]
352+
calib_file = calib_tmp_dict['Filename']
353+
calib_date = calib_tmp_dict['Date'].replace("_", "-")
354+
calib_senv = calib_tmp_dict['SampleEnvironment']
355+
calib_outd = calib_tmp_dict['CalDirectory']
356+
if "/" in calib_file:
357+
instrument_name = calib_file.split("/")[2]
358+
else:
359+
instrument_name = calib_file.split("_")[0]
360+
calib_control_file = os.path.join('/SNS/', instrument_name,
361+
'shared/CALIBRATION/Group_calib_scripts',
362+
'control_' + calibrant + ".dat")
363+
with open(calib_control_file, "w") as calib_f:
364+
calib_f.write("{0:<25s}:: {1:s}\n".format("diamond file", calib_file))
365+
calib_f.write("{0:<25s}:: {1:s}\n".format("instrument",
366+
instr_dict[instrument_name]))
367+
calib_f.write("{0:<25s}:: {1:s}\n".format("date", calib_date))
368+
calib_f.write("{0:<25s}:: {1:s}\n".format("sample environment",
369+
calib_senv))
370+
calib_f.write("{0:<25s}:: {1:s}\n".format("output directory",
371+
calib_outd))
372+
running_script = os.path.join('/SNS/', instrument_name,
373+
'shared/CALIBRATION/Group_calib_scripts',
374+
'running')
375+
running_script += (" " + calib_control_file)
376+
self.parent.launch_job_manager(job_name='MakeCalibration',
377+
script_to_run=running_script)
407378

408379
def closeEvent(self, c):
409380
self.parent.make_calibration_ui = None
@@ -452,15 +423,6 @@ def built_dict(self):
452423
else:
453424
cali_filename = None
454425

455-
# vanadium run number
456-
vana_run_number = str(local_list_ui.vanadium_value.text())
457-
458-
# vanadium full file name (if any)
459-
if str(local_list_ui.vanadium_browser.text()) != "N/A":
460-
vana_filename = str(local_list_value["vanadium_browser"])
461-
else:
462-
vana_filename = None
463-
464426
# local date
465427
_date = local_list_ui.date.date()
466428
[year, month, day] = _date.getDate()
@@ -472,14 +434,7 @@ def built_dict(self):
472434
# local output dir
473435
local_output_dir = str(local_list_ui.output_dir_value.text())
474436

475-
# save data in vanadium dict
476-
vanadium_dict = {}
477-
vanadium_dict["RunNumber"] = vana_run_number
478-
if vana_filename:
479-
vanadium_dict["Filename"] = vana_filename
480-
481437
cali_dict = {}
482-
cali_dict["Vanadium"] = vanadium_dict
483438
if cali_filename:
484439
cali_dict["Filename"] = cali_filename
485440

0 commit comments

Comments
 (0)