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

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 503cc34 was 503cc34, checked in by lewis, 8 years ago

Refactor metadata dict into private variables

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