source: sasview/src/sas/sasgui/perspectives/file_converter/converter_panel.py @ d112c30

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since d112c30 was d112c30, checked in by lewis, 8 years ago

Write run_name to SASentry.name instead of Run.name to agree with Mantid output

  • Property mode set to 100644
File size: 14.3 KB
Line 
1"""
2This module provides a GUI for the file converter
3"""
4
5import wx
6import sys
7import numpy as np
8from wx.lib.scrolledpanel import ScrolledPanel
9from sas.sasgui.guiframe.panel_base import PanelBase
10from sas.sasgui.perspectives.calculator import calculator_widgets as widget
11from sas.sasgui.perspectives.file_converter.converter_widgets import VectorInput
12from sas.sasgui.perspectives.file_converter.meta_panels import MetadataWindow
13from sas.sasgui.perspectives.file_converter.meta_panels import DetectorPanel
14from sas.sasgui.perspectives.file_converter.meta_panels import SamplePanel
15from sas.sasgui.perspectives.file_converter.meta_panels import SourcePanel
16from sas.sasgui.guiframe.events import StatusEvent
17from sas.sasgui.guiframe.documentation_window import DocumentationWindow
18from sas.sasgui.guiframe.dataFitting import Data1D
19from sas.sasgui.guiframe.utils import check_float
20from sas.sascalc.dataloader.readers.cansas_reader import Reader as CansasReader
21from sas.sasgui.perspectives.file_converter.bsl_loader import BSLLoader
22from sas.sascalc.dataloader.data_info import Detector
23from sas.sascalc.dataloader.data_info import Sample
24from sas.sascalc.dataloader.data_info import Source
25from sas.sascalc.dataloader.data_info import Vector
26
27# Panel size
28if sys.platform.count("win32") > 0:
29    PANEL_TOP = 0
30    _STATICBOX_WIDTH = 410
31    _BOX_WIDTH = 200
32    PANEL_SIZE = 480
33    FONT_VARIANT = 0
34else:
35    PANEL_TOP = 60
36    _STATICBOX_WIDTH = 430
37    _BOX_WIDTH = 200
38    PANEL_SIZE = 500
39    FONT_VARIANT = 1
40
41class ConverterPanel(ScrolledPanel, PanelBase):
42
43    def __init__(self, parent, base=None, *args, **kwargs):
44        ScrolledPanel.__init__(self, parent, *args, **kwargs)
45        PanelBase.__init__(self)
46        self.SetupScrolling()
47        self.SetWindowVariant(variant=FONT_VARIANT)
48
49        self.base = base
50        self.parent = parent
51        self.meta_frames = []
52
53        self.q_input = None
54        self.iq_input = None
55        self.output = None
56        self.data_type = "ascii"
57
58        self.title = None
59        self.run = None
60        self.run_name = None
61        self.instrument = None
62        self.detector = Detector()
63        self.sample = Sample()
64        self.source = Source()
65        self.properties = ['title', 'run', 'run_name', 'instrument']
66
67        self.detector.name = ''
68        self.source.radiation = 'neutron'
69
70        self._do_layout()
71        self.SetAutoLayout(True)
72        self.Layout()
73
74    def convert_to_cansas(self, data, filename):
75        reader = CansasReader()
76        reader.write(filename, data,
77            sasentry_attrs={ 'name': self.run_name })
78
79    def extract_data(self, filename):
80        data = np.loadtxt(filename, dtype=str)
81
82        if len(data.shape) != 1:
83            msg = "Error reading {}: Only one column of data is allowed"
84            raise Exception(msg.format(filename.split('\\')[-1]))
85
86        is_float = True
87        try:
88            float(data[0])
89        except:
90            is_float = False
91
92        if not is_float:
93            end_char = data[0][-1]
94            # If lines end with comma or semi-colon, trim the last character
95            if end_char == ',' or end_char == ';':
96                data = map(lambda s: s[0:-1], data)
97            else:
98                msg = ("Error reading {}: Lines must end with a digit, comma "
99                    "or semi-colon").format(filename.split('\\')[-1])
100                raise Exception(msg)
101
102        return np.array(data, dtype=np.float32)
103
104    def on_convert(self, event):
105        if not self.validate_inputs():
106            return
107
108        self.sample.ID = self.title
109
110        try:
111            if self.data_type == 'ascii':
112                qdata = self.extract_data(self.q_input.GetPath())
113                iqdata = self.extract_data(self.iq_input.GetPath())
114            else: # self.data_type == 'bsl'
115                loader = BSLLoader(self.q_input.GetPath(),
116                    self.iq_input.GetPath())
117                bsl_data = loader.load_bsl_data()
118                qdata = bsl_data.q_axis.data[0]
119                iqdata = bsl_data.data_axis.data[0]
120        except Exception as ex:
121            msg = str(ex)
122            wx.PostEvent(self.parent.manager.parent,
123                StatusEvent(status=msg, info='error'))
124            return
125
126        output_path = self.output.GetPath()
127        data = Data1D(x=qdata, y=iqdata)
128        data.filename = output_path.split('\\')[-1]
129
130        if self.run is None:
131            self.run = []
132        elif not isinstance(self.run, list):
133            self.run = [self.run]
134
135        metadata = {
136            'title': self.title,
137            'run': self.run,
138            'intrument': self.instrument,
139            'detector': [self.detector],
140            'sample': self.sample,
141            'source': self.source
142        }
143
144        for key, value in metadata.iteritems():
145            setattr(data, key, value)
146
147        self.convert_to_cansas(data, output_path)
148        wx.PostEvent(self.parent.manager.parent,
149            StatusEvent(status="Conversion completed."))
150
151    def on_help(self, event):
152        tree_location = ("user/sasgui/perspectives/file_converter/"
153            "file_converter_help.html")
154        doc_viewer = DocumentationWindow(self, -1, tree_location,
155            "", "File Converter Help")
156
157    def validate_inputs(self):
158        msg = "You must select a"
159        if self.q_input.GetPath() == '':
160            msg += " Q Axis input file."
161        elif self.iq_input.GetPath() == '':
162            msg += "n Intensity input file."
163        elif self.output.GetPath() == '':
164            msg += "destination for the converted file."
165        if msg != "You must select a":
166            wx.PostEvent(self.parent.manager.parent,
167                StatusEvent(status=msg, info='error'))
168            return
169
170        return True
171
172    def show_detector_window(self, event):
173        if self.meta_frames != []:
174            for frame in self.meta_frames:
175                frame.panel.on_close()
176        detector_frame = MetadataWindow(DetectorPanel,
177            parent=self.parent.manager.parent, manager=self,
178            metadata=self.detector, title='Detector Metadata')
179        self.meta_frames.append(detector_frame)
180        self.parent.manager.put_icon(detector_frame)
181        detector_frame.Show(True)
182
183    def show_sample_window(self, event):
184        if self.meta_frames != []:
185            for frame in self.meta_frames:
186                frame.panel.on_close()
187        sample_frame = MetadataWindow(SamplePanel,
188            parent=self.parent.manager.parent, manager=self,
189            metadata=self.sample, title='Sample Metadata')
190        self.meta_frames.append(sample_frame)
191        self.parent.manager.put_icon(sample_frame)
192        sample_frame.Show(True)
193
194    def show_source_window(self, event):
195        if self.meta_frames != []:
196            for frame in self.meta_frames:
197                frame.panel.on_close()
198        source_frame = MetadataWindow(SourcePanel,
199            parent=self.parent.manager.parent, manager=self,
200            metadata=self.source, title="Source Metadata")
201        self.meta_frames.append(source_frame)
202        self.parent.manager.put_icon(source_frame)
203        source_frame.Show(True)
204
205    def on_collapsible_pane(self, event):
206        self.Freeze()
207        self.SetupScrolling()
208        self.parent.Layout()
209        self.Thaw()
210
211    def datatype_changed(self, event):
212        event.Skip()
213        dtype = event.GetEventObject().GetName()
214        self.data_type = dtype
215
216    def radiationtype_changed(self, event):
217        event.Skip()
218        rtype = event.GetEventObject().GetValue().lower()
219        self.source.radiation = rtype
220
221    def metadata_changed(self, event):
222        event.Skip()
223        textbox = event.GetEventObject()
224        attr = textbox.GetName()
225        value = textbox.GetValue().strip()
226
227        if value == '': value = None
228
229        setattr(self, attr, value)
230
231
232    def _do_layout(self):
233        vbox = wx.BoxSizer(wx.VERTICAL)
234
235        instructions = ("Select either single column ASCII files or BSL/OTOKO"
236            " files containing the Q-Axis and Intensity-axis data, chose where"
237            " to save the converted file, then click Convert to convert them "
238            "to CanSAS XML format. If required, metadata can also be input "
239            "below.")
240        instruction_label = wx.StaticText(self, -1, instructions,
241            size=(_STATICBOX_WIDTH+40, -1))
242        instruction_label.Wrap(_STATICBOX_WIDTH+40)
243        vbox.Add(instruction_label, flag=wx.TOP | wx.LEFT | wx.RIGHT, border=5)
244
245        section = wx.StaticBox(self, -1)
246        section_sizer = wx.StaticBoxSizer(section, wx.VERTICAL)
247        section_sizer.SetMinSize((_STATICBOX_WIDTH, -1))
248
249        input_grid = wx.GridBagSizer(5, 5)
250
251        y = 0
252
253        q_label = wx.StaticText(self, -1, "Q-Axis Data: ")
254        input_grid.Add(q_label, (y,0), (1,1), wx.ALIGN_CENTER_VERTICAL, 5)
255
256        self.q_input = wx.FilePickerCtrl(self, -1,
257            size=(_STATICBOX_WIDTH-80, -1),
258            message="Chose the Q-Axis data file.")
259        input_grid.Add(self.q_input, (y,1), (1,1), wx.ALL, 5)
260        y += 1
261
262        iq_label = wx.StaticText(self, -1, "Intensity-Axis Data: ")
263        input_grid.Add(iq_label, (y,0), (1,1), wx.ALIGN_CENTER_VERTICAL, 5)
264
265        self.iq_input = wx.FilePickerCtrl(self, -1,
266            size=(_STATICBOX_WIDTH-80, -1),
267            message="Chose the Intensity-Axis data file.")
268        input_grid.Add(self.iq_input, (y,1), (1,1), wx.ALL, 5)
269        y += 1
270
271        data_type_label = wx.StaticText(self, -1, "Input Format: ")
272        input_grid.Add(data_type_label, (y,0), (1,1),
273            wx.ALIGN_CENTER_VERTICAL, 5)
274        radio_sizer = wx.BoxSizer(wx.HORIZONTAL)
275        ascii_btn = wx.RadioButton(self, -1, "ASCII", name="ascii",
276            style=wx.RB_GROUP)
277        ascii_btn.Bind(wx.EVT_RADIOBUTTON, self.datatype_changed)
278        radio_sizer.Add(ascii_btn)
279        bsl_btn = wx.RadioButton(self, -1, "BSL/OTOKO", name="bsl")
280        bsl_btn.Bind(wx.EVT_RADIOBUTTON, self.datatype_changed)
281        radio_sizer.Add(bsl_btn)
282        input_grid.Add(radio_sizer, (y,1), (1,1), wx.ALL, 5)
283        y += 1
284
285        radiation_label = wx.StaticText(self, -1, "Radiation Type: ")
286        input_grid.Add(radiation_label, (y,0), (1,1), wx.ALL, 5)
287        radiation_input = wx.ComboBox(self, -1,
288            choices=["Neutron", "X-Ray", "Muon", "Electron"],
289            name="radiation", style=wx.CB_READONLY, value="Neutron")
290        radiation_input.Bind(wx.EVT_COMBOBOX, self.radiationtype_changed)
291        input_grid.Add(radiation_input, (y,1), (1,1))
292        y += 1
293
294        output_label = wx.StaticText(self, -1, "Output File: ")
295        input_grid.Add(output_label, (y,0), (1,1), wx.ALIGN_CENTER_VERTICAL, 5)
296
297        self.output = wx.FilePickerCtrl(self, -1,
298            size=(_STATICBOX_WIDTH-80, -1),
299            message="Chose where to save the output file.",
300            style=wx.FLP_SAVE | wx.FLP_OVERWRITE_PROMPT | wx.FLP_USE_TEXTCTRL,
301            wildcard="*.xml")
302        input_grid.Add(self.output, (y,1), (1,1), wx.ALL, 5)
303        y += 1
304
305        convert_btn = wx.Button(self, wx.ID_OK, "Convert")
306        input_grid.Add(convert_btn, (y,0), (1,1), wx.ALL, 5)
307        convert_btn.Bind(wx.EVT_BUTTON, self.on_convert)
308
309        help_btn = wx.Button(self, -1, "HELP")
310        input_grid.Add(help_btn, (y,1), (1,1), wx.ALL, 5)
311        help_btn.Bind(wx.EVT_BUTTON, self.on_help)
312
313        section_sizer.Add(input_grid)
314
315        vbox.Add(section_sizer, flag=wx.ALL, border=5)
316
317        metadata_section = wx.CollapsiblePane(self, -1, "Metadata",
318            size=(_STATICBOX_WIDTH+40, -1), style=wx.WS_EX_VALIDATE_RECURSIVELY)
319        metadata_pane = metadata_section.GetPane()
320        metadata_grid = wx.GridBagSizer(5, 5)
321
322        metadata_section.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED,
323            self.on_collapsible_pane)
324
325        y = 0
326        for item in self.properties:
327            # Capitalise each word
328            label_txt = " ".join(
329                [s.capitalize() for s in item.replace('_', ' ').split(' ')])
330            if item == 'run':
331                label_txt = "Run Number"
332            label = wx.StaticText(metadata_pane, -1, label_txt,
333                style=wx.ALIGN_CENTER_VERTICAL)
334            input_box = wx.TextCtrl(metadata_pane, name=item,
335                size=(_STATICBOX_WIDTH-80, -1))
336            input_box.Bind(wx.EVT_TEXT, self.metadata_changed)
337            metadata_grid.Add(label, (y,0), (1,1),
338                wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
339            metadata_grid.Add(input_box, (y,1), (1,2), wx.EXPAND)
340            y += 1
341
342        detector_label = wx.StaticText(metadata_pane, -1,
343            "Detector:")
344        metadata_grid.Add(detector_label, (y, 0), (1,1), wx.ALL | wx.EXPAND, 5)
345        detector_btn = wx.Button(metadata_pane, -1, "Enter Detector Metadata")
346        metadata_grid.Add(detector_btn, (y, 1), (1,1), wx.ALL | wx.EXPAND, 5)
347        detector_btn.Bind(wx.EVT_BUTTON, self.show_detector_window)
348        y += 1
349
350        sample_label = wx.StaticText(metadata_pane, -1, "Sample: ")
351        metadata_grid.Add(sample_label, (y,0), (1,1), wx.ALL | wx.EXPAND, 5)
352        sample_btn = wx.Button(metadata_pane, -1, "Enter Sample Metadata")
353        metadata_grid.Add(sample_btn, (y,1), (1,1), wx.ALL | wx.EXPAND, 5)
354        sample_btn.Bind(wx.EVT_BUTTON, self.show_sample_window)
355        y += 1
356
357        source_label = wx.StaticText(metadata_pane, -1, "Source: ")
358        metadata_grid.Add(source_label, (y,0), (1,1), wx.ALL | wx.EXPAND, 5)
359        source_btn = wx.Button(metadata_pane, -1, "Enter Source Metadata")
360        source_btn.Bind(wx.EVT_BUTTON, self.show_source_window)
361        metadata_grid.Add(source_btn, (y,1), (1,1), wx.ALL | wx.EXPAND, 5)
362        y += 1
363
364        metadata_pane.SetSizer(metadata_grid)
365
366        vbox.Add(metadata_section, proportion=0, flag=wx.ALL, border=5)
367
368        vbox.Fit(self)
369        self.SetSizer(vbox)
370
371class ConverterWindow(widget.CHILD_FRAME):
372
373    def __init__(self, parent=None, title='File Converter', base=None,
374        manager=None, size=(PANEL_SIZE * 1.05, PANEL_SIZE / 1.25),
375        *args, **kwargs):
376        kwargs['title'] = title
377        kwargs['size'] = size
378        widget.CHILD_FRAME.__init__(self, parent, *args, **kwargs)
379
380        self.manager = manager
381        self.panel = ConverterPanel(self, base=None)
382        self.Bind(wx.EVT_CLOSE, self.on_close)
383        self.SetPosition((wx.LEFT, PANEL_TOP))
384        self.Show(True)
385
386    def on_close(self, event):
387        if self.manager is not None:
388            self.manager.converter_frame = None
389        self.Destroy()
Note: See TracBrowser for help on using the repository browser.