Example #1
0
class SampleDialog(BaseDialog):

    def __init__(self, parent=None):
        super(SampleDialog, self).__init__(parent)

        self.sample = GridParameters()
        self.sample.add('sample', 'sample', 'Sample Name')
        self.sample.add('label', 'label', 'Sample Label')

        self.set_layout(self.directorybox('Choose Experiment Directory',
                                          default=False), 
                        self.sample.grid(header=False),
                        self.close_buttons(save=True))

        self.set_title('New Sample')

    def accept(self):
        home_directory = self.get_directory()
        self.mainwindow.default_directory = home_directory
        sample_directory = os.path.join(home_directory, 
                                        self.sample['sample'].value,
                                        self.sample['label'].value)
        if not os.path.exists(sample_directory):
            os.makedirs(sample_directory)
        super(SampleDialog, self).accept()
Example #2
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.select_entry(self.choose_entry)

        default = NXSettings().settings['nxreduce']
        self.parameters = GridParameters()
        self.parameters.add('first', default['first'], 'First Frame')
        self.parameters.add('last', default['last'], 'Last Frame')
        self.parameters.add('threshold1', '2', 'Threshold 1')
        self.parameters.add('horizontal1', '11', 'Horizontal Size 1')
        self.parameters.add('threshold2', '0.8', 'Threshold 2')
        self.parameters.add('horizontal2', '51', 'Horizontal Size 2')
        self.parameters.grid()
        self.prepare_button = NXPushButton('Prepare Mask', self.prepare_mask)
        self.plot_button = NXPushButton('Plot Mask', self.plot_mask)
        self.prepare_layout = self.make_layout(self.prepare_button,
                                               self.plot_button,
                                               align='center')
        self.plot_button.setVisible(False)
        self.set_layout(self.entry_layout,
                        self.close_layout(save=True, progress=True))
        self.set_title('Prepare 3D Mask')
        self.reduce = None
        self.mask = None
        self.plotview = None
Example #3
0
 def setup_instrument(self):
     entry = self.experiment_file['entry']
     entry.instrument = NXinstrument()
     entry.instrument.monochromator = NXmonochromator()
     entry.instrument.detector = NXdetector()
     entry['instrument/monochromator/wavelength'] = NXfield(
         0.5, dtype=np.float32)
     entry['instrument/monochromator/wavelength'].attrs[
         'units'] = 'Angstroms'
     entry['instrument/monochromator/energy'] = NXfield(12.398419739640717 /
                                                        0.5,
                                                        dtype=np.float32)
     entry['instrument/monochromator/energy'].attrs['units'] = 'keV'
     entry['instrument/detector/distance'] = NXfield(100.0,
                                                     dtype=np.float32)
     entry['instrument/detector/distance'].attrs['units'] = 'mm'
     self.instrument = GridParameters()
     self.instrument.add('experiment', 'experiment', 'Experiment Name')
     self.instrument.add('wavelength',
                         entry['instrument/monochromator/wavelength'],
                         'Wavelength (Ang)')
     self.instrument.add('distance', entry['instrument/detector/distance'],
                         'Detector Distance (mm)')
     detector_list = sorted(
         list(set([detector().name
                   for detector in ALL_DETECTORS.values()])))
     self.instrument.add('detector', detector_list, 'Detector')
     self.instrument['detector'].value = 'Pilatus CdTe 2M'
     self.instrument.add('positions', [0, 1, 2, 3, 4],
                         'Number of Detector Positions',
                         slot=self.set_entries)
     self.instrument['positions'].value = '0'
Example #4
0
class MaskDialog(BaseDialog):

    def __init__(self, parent=None):
        super(MaskDialog, self).__init__(parent)
        self.select_entry(self.choose_entry)
        self.parameters = GridParameters()
        self.parameters.add('mask', 'pilatus_mask/entry/mask', 'Mask Path')
        self.action_buttons(('Save Mask', self.save_mask))
        self.set_layout(self.entry_layout, self.parameters.grid(), 
                        self.action_buttons(('Save Mask', self.save_mask)), 
                        self.close_buttons())
        self.set_title('Mask Data')

    def save_mask(self):
        try:
            mask = self.treeview.tree[self.parameters['mask'].value]
            if mask.dtype != np.bool:
                raise NeXusError('Mask must be a Boolean array')
            elif len(mask.shape) == 1:
                raise NeXusError('Mask must be at least two-dimensional')
            elif len(mask.shape) > 2:
                mask = mask[0]                
            self.entry['instrument/detector/pixel_mask'] = mask
            self.entry['instrument/detector/pixel_mask_applied'] = False
        except NeXusError as error:
            report_error('Applying Mask', error)
Example #5
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.plotview = None
        self.data = None
        self.counts = None
        self.points = []
        self.pattern_geometry = None
        self.cake_geometry = None
        self.polarization = None
        self.is_calibrated = False
        self.phi_max = -np.pi

        cstr = str(ALL_CALIBRANTS)
        calibrants = sorted(cstr[cstr.index(':')+2:].split(', '))
        self.parameters = GridParameters()
        self.parameters.add('calibrant', calibrants, 'Calibrant')
        self.parameters['calibrant'].value = 'CeO2'
        self.parameters.add('wavelength', 0.5, 'Wavelength (Ang)', False)
        self.parameters.add('distance', 100.0, 'Detector Distance (mm)', True)
        self.parameters.add('xc', 512, 'Beam Center - x', True)
        self.parameters.add('yc', 512, 'Beam Center - y', True)
        self.parameters.add('yaw', 0.0, 'Yaw (degrees)', True)
        self.parameters.add('pitch', 0.0, 'Pitch (degrees)', True)
        self.parameters.add('roll', 0.0, 'Roll (degrees)', True)
        self.parameters.add('search_size', 10, 'Search Size (pixels)')
        self.rings_box = self.select_box([f'Ring{i}' for i in range(1, 21)])
        self.set_layout(self.select_entry(self.choose_entry),
                        self.progress_layout(close=True))
        self.set_title('Calibrating Powder')
Example #6
0
    def __init__(self, parent=None):
        super(FindDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.parameters = GridParameters()
        self.parameters.add('threshold', '', 'Threshold')
        self.parameters.add('first', '', 'First Frame')
        self.parameters.add('last', '', 'Last Frame')
        find_layout = QtWidgets.QHBoxLayout()
        self.find_button = QtWidgets.QPushButton('Find Peaks')
        self.find_button.clicked.connect(self.find_peaks)
        self.peak_count = QtWidgets.QLabel()
        self.peak_count.setVisible(False)
        find_layout.addStretch()
        find_layout.addWidget(self.find_button)
        find_layout.addWidget(self.peak_count)
        find_layout.addStretch()
        self.set_layout(self.entry_layout, 
                        self.parameters.grid(),
                        find_layout,
                        self.progress_layout(save=True))
        self.progress_bar.setVisible(False)
        self.progress_bar.setValue(0)
        self.set_title('Find Peaks')
        self.reduce = None
Example #7
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parameters = GridParameters()
        self.parameters.add('experiment', 'experiment', 'Experiment')

        self.set_layout(
            self.directorybox('Choose Home Directory', default=False),
            self.parameters.grid(header=False), self.close_layout(save=True))
        self.set_title('New Experiment')
Example #8
0
    def setup_scans(self):
        self.scan = GridParameters()
        self.scan.add('scan', 'scan', 'Scan Label')
        self.scan.add('temperature', 300.0, 'Temperature (K)')
        self.scan.add('phi_start', -5.0, 'Phi Start (deg)')
        self.scan.add('phi_end', 360.0, 'Phi End (deg)')
        self.scan.add('phi_step', 0.1, 'Phi Step (deg)')
        self.scan.add('frame_rate', 10, 'Frame Rate (Hz)')

        for position in range(1, 6):
            self.setup_position(position)
Example #9
0
    def setup_scans(self):
        default = self.settings['nxrefine']
        self.scan = GridParameters()
        self.scan.add('scan', 'scan', 'Scan Label')
        self.scan.add('temperature', 300.0, 'Temperature (K)')
        self.scan.add('phi_start', default['phi'], 'Phi Start (deg)')
        self.scan.add('phi_end', default['phi_end'], 'Phi End (deg)')
        self.scan.add('phi_step', default['phi_step'], 'Phi Step (deg)')
        self.scan.add('frame_rate', default['frame_rate'], 'Frame Rate (Hz)')

        for position in range(1, self.positions+1):
            self.setup_position(position)
Example #10
0
    def __init__(self, parent=None):
        super(SampleDialog, self).__init__(parent)

        self.sample = GridParameters()
        self.sample.add('sample', 'sample', 'Sample Name')
        self.sample.add('label', 'label', 'Sample Label')

        self.set_layout(
            self.directorybox('Choose Experiment Directory', default=False),
            self.sample.grid(header=False), self.close_buttons(save=True))

        self.set_title('New Sample')
Example #11
0
class EnergyDialog(BaseDialog):

    def __init__(self, parent=None):
        super(EnergyDialog, self).__init__(parent)

        layout = QtGui.QVBoxLayout()

        self.select_entry()
        self.parameters = GridParameters()
        self.parameters.add('m1', self.entry['monitor1/distance'], 
                            'Monitor 1 Distance')
        self.parameters.add('m2', self.entry['monitor2/distance'], 
                            'Monitor 2 Distance')
        self.parameters.add('Ei', self.entry['instrument/monochromator/energy'], 
                            'Incident Energy')
        self.parameters.add('mod', self.entry['instrument/source/distance'], 
                            'Moderator Distance')
        layout.addLayout(self.entry_layout)
        layout.addLayout(self.parameters.grid())
        layout.addLayout(self.action_buttons(('Get Ei', self.get_ei)))
        layout.addWidget(self.close_buttons(save=True))
        self.setLayout(layout)
        self.setWindowTitle('Get Incident Energy')

        self.m1 = self.entry['monitor1']
        self.m2 = self.entry['monitor2'] 

    @property
    def m1_distance(self):
        return self.parameters['m1'].value - self.moderator_distance

    @property
    def m2_distance(self):
        return self.parameters['m2'].value - self.moderator_distance

    @property
    def Ei(self):
        return self.parameters['Ei'].value

    @property
    def moderator_distance(self):
        return self.parameters['mod'].value

    def get_ei(self):
        t = 2286.26 * self.m1_distance / np.sqrt(self.Ei)
        m1_time = self.m1[t-200.0:t+200.0].moment()
        t = 2286.26 * self.m2_distance / np.sqrt(self.Ei)
        m2_time = self.m2[t-200.0:t+200.0].moment()
        self.parameters['Ei'].value = (2286.26 * (self.m2_distance - self.m1_distance) /
                                       (m2_time - m1_time))**2

    def accept(self):
        try:
            self.parameters['Ei'].save()
        except NeXusError as error:
            report_error("Getting Incident Energy", error)
        super(EnergyDialog, self).accept()
Example #12
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.select_root(self.choose_entry)

        self.refine = NXRefine()

        self.parameters = GridParameters()
        self.parameters.add('space_group',
                            self.refine.space_group,
                            'Space Group',
                            slot=self.set_groups)
        self.parameters.add('laue_group', self.refine.laue_groups,
                            'Laue Group')
        self.parameters.add('symmetry',
                            self.refine.symmetries,
                            'Symmetry',
                            slot=self.set_lattice_parameters)
        self.parameters.add('centring', self.refine.centrings, 'Cell Centring')
        self.parameters.add('a',
                            self.refine.a,
                            'Unit Cell - a (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('b',
                            self.refine.b,
                            'Unit Cell - b (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('c',
                            self.refine.c,
                            'Unit Cell - c (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('alpha',
                            self.refine.alpha,
                            'Unit Cell - alpha (deg)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('beta',
                            self.refine.beta,
                            'Unit Cell - beta (deg)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('gamma',
                            self.refine.gamma,
                            'Unit Cell - gamma (deg)',
                            slot=self.set_lattice_parameters)
        self.parameters['laue_group'].value = self.refine.laue_group
        self.parameters['symmetry'].value = self.refine.symmetry
        self.parameters['centring'].value = self.refine.centring
        self.import_button = NXPushButton('Import CIF', self.import_cif)
        self.import_checkbox = NXCheckBox('Update Lattice Parameters')
        self.set_layout(self.root_layout, self.close_buttons(save=True))
        self.set_title('Defining Lattice')
Example #13
0
class EnergyDialog(NXDialog):
    def __init__(self, parent=None):

        super().__init__(parent)

        self.select_entry()
        self.parameters = GridParameters()
        self.parameters.add('m1', self.entry['monitor1/distance'],
                            'Monitor 1 Distance')
        self.parameters.add('m2', self.entry['monitor2/distance'],
                            'Monitor 2 Distance')
        self.parameters.add('Ei',
                            self.entry['instrument/monochromator/energy'],
                            'Incident Energy')
        self.parameters.add('mod', self.entry['instrument/source/distance'],
                            'Moderator Distance')
        action_buttons = self.action_buttons(('Get Ei', self.get_ei))
        self.set_layout(self.entry_layout, self.parameters.grid(),
                        action_buttons, self.close_buttons(save=True))
        self.set_title('Get Incident Energy')

        self.m1 = self.entry['monitor1']
        self.m2 = self.entry['monitor2']

    @property
    def m1_distance(self):
        return self.parameters['m1'].value - self.moderator_distance

    @property
    def m2_distance(self):
        return self.parameters['m2'].value - self.moderator_distance

    @property
    def Ei(self):
        return self.parameters['Ei'].value

    @property
    def moderator_distance(self):
        return self.parameters['mod'].value

    def get_ei(self):
        t = 2286.26 * self.m1_distance / np.sqrt(self.Ei)
        m1_time = self.m1[t - 200.0:t + 200.0].moment()
        t = 2286.26 * self.m2_distance / np.sqrt(self.Ei)
        m2_time = self.m2[t - 200.0:t + 200.0].moment()
        self.parameters['Ei'].value = (2286.26 *
                                       (self.m2_distance - self.m1_distance) /
                                       (m2_time - m1_time))**2

    def accept(self):
        try:
            self.parameters['Ei'].save()
        except NeXusError as error:
            report_error("Getting Incident Energy", error)
        super().accept()
Example #14
0
 def define_parameters(self):
     self.refine_parameters = GridParameters()
     defaults = self.settings.settings['nxrefine']
     for p in defaults:
         self.refine_parameters.add(p, defaults[p], p)
     self.reduce_parameters = GridParameters()
     defaults = self.settings.settings['nxreduce']
     for p in defaults:
         self.reduce_parameters.add(p, defaults[p], p)
     if self.layout.count() == 2:
         self.layout.insertLayout(
             1, self.refine_parameters.grid(header=False, title='NXRefine'))
         self.layout.insertLayout(
             2, self.reduce_parameters.grid(header=False, title='NXReduce'))
Example #15
0
 def setup_secondary_grid(self):
     ps_angle = self.refine.angle_peaks(self.primary, self.secondary)
     n_phkl = len(self.ring_list[self.refine.rp[self.primary]])
     self.hkl_parameters = [GridParameters() for i in range(n_phkl)]
     min_diff = self.get_peak_tolerance()
     min_p = None
     min_hkl = None
     for i in range(n_phkl):
         phkl = eval(self.peak_parameters['primary_hkl'].box.items()[i])
         for hkls in self.rings[self.refine.rp[self.secondary]][1]:
             for hkl in hkls:
                 hkl_angle = self.refine.angle_hkls(phkl, hkl)
                 diff = abs(ps_angle - hkl_angle)
                 if diff < self.get_peak_tolerance():
                     self.hkl_parameters[i].add(str(hkl),
                                                hkl_angle,
                                                str(hkl),
                                                vary=False,
                                                readonly=True)
                     if diff < min_diff:
                         min_diff = diff
                         min_p = i
                         min_hkl = str(hkl)
         self.orient_box.insert_layout(
             i + 1, self.hkl_parameters[i].grid(
                 header=['HKL', 'Angle (deg)', 'Select'], spacing=5))
     if min_hkl is None:
         raise NeXusError("No matching peaks found")
     self.peak_parameters['primary_hkl'].box.setCurrentIndex(min_p)
     self.hkl_parameters[min_p][min_hkl].vary = True
     self.choose_secondary_grid()
Example #16
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.select_entry()
     self.parameters = GridParameters()
     self.parameters.add('Ei',
                         self.entry['instrument/monochromator/energy'],
                         'Incident Energy')
     self.parameters.add('dQ', self.round(np.sqrt(self.Ei / 2) / 50),
                         'Q Step')
     self.parameters.add('dE', self.round(self.Ei / 50), 'Energy Step')
     self.set_layout(
         self.entry_layout, self.parameters.grid(),
         self.action_buttons(
             ('Plot', self.plot_data), ('Save', self.save_data)),
         self.close_buttons())
     self.setWindowTitle('Converting to (Q,E)')
Example #17
0
    def __init__(self, parent=None):
        super(Mask3DDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.parameters = GridParameters()
        self.parameters.add('radius', 200, 'Radius')
        self.parameters.add('width', 3, 'Frame Width')
        self.set_layout(
            self.entry_layout, self.parameters.grid(),
            self.action_buttons(('Calculate 3D Mask', self.calculate_mask)),
            self.progress_layout(save=True))
        self.progress_bar.setVisible(False)
        self.progress_bar.setValue(0)
        self.set_title('Calculate 3D Mask')
        self.reduce = None
Example #18
0
    def __init__(self, parent=None):
        super(LatticeDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.refine = NXRefine()

        self.parameters = GridParameters()
        self.parameters.add('symmetry', self.refine.symmetries, 'Symmetry',
                            slot=self.set_lattice_parameters)
        self.parameters.add('centring', self.refine.centrings, 'Cell Centring')
        self.parameters.add('a', self.refine.a, 'Unit Cell - a (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('b', self.refine.b, 'Unit Cell - b (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('c', self.refine.c, 'Unit Cell - c (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('alpha', self.refine.alpha, 'Unit Cell - alpha (deg)', 
                            slot=self.set_lattice_parameters)
        self.parameters.add('beta', self.refine.beta, 'Unit Cell - beta (deg)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('gamma', self.refine.gamma, 'Unit Cell - gamma (deg)', 
                            slot=self.set_lattice_parameters)
        self.parameters['symmetry'].value = self.refine.symmetry
        self.parameters['centring'].value = self.refine.centring
        action_buttons = self.action_buttons(('Plot', self.plot_lattice),
                                             ('Save', self.write_parameters))
        self.set_layout(self.entry_layout, self.parameters.grid(), 
                        action_buttons, self.close_buttons())
        self.set_title('Defining Lattice')
Example #19
0
    def __init__(self, parent=None):
        super(RefineLatticeDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.refine = NXRefine(self.entry)
        self.refine.read_parameters()

        self.parameters = GridParameters()
        self.parameters.add('symmetry', self.refine.symmetries, 'Symmetry', 
                            None, self.set_symmetry)
        self.parameters.add('a', self.refine.a, 'Unit Cell - a (Ang)', True)
        self.parameters.add('b', self.refine.b, 'Unit Cell - b (Ang)', True)
        self.parameters.add('c', self.refine.c, 'Unit Cell - c (Ang)', True)
        self.parameters.add('alpha', self.refine.alpha, 'Unit Cell - alpha (deg)', False)
        self.parameters.add('beta', self.refine.beta, 'Unit Cell - beta (deg)', False)
        self.parameters.add('gamma', self.refine.gamma, 'Unit Cell - gamma (deg)', False)
        self.parameters.add('wavelength', self.refine.wavelength, 'Wavelength (Ang)', False)
        self.parameters.add('distance', self.refine.distance, 'Distance (mm)', False)
        self.parameters.add('yaw', self.refine.yaw, 'Yaw (deg)', False)
        self.parameters.add('pitch', self.refine.pitch, 'Pitch (deg)', False)
        self.parameters.add('roll', self.refine.roll, 'Roll (deg)')
        self.parameters.add('xc', self.refine.xc, 'Beam Center - x', False)
        self.parameters.add('yc', self.refine.yc, 'Beam Center - y', False)
        self.parameters.add('phi_start', self.refine.phi_start, 'Phi Start (deg)', False)
        self.parameters.add('phi_step', self.refine.phi_step, 'Phi Step (deg)')
        self.parameters.add('chi_start', self.refine.chi_start, 'Chi Start (deg)', False)
        self.parameters.add('chi_step', self.refine.chi_step, 'Chi Step (deg)')
        self.parameters.add('omega_start', self.refine.omega_start, 'Omega Start (deg)', False)
        self.parameters.add('omega_step', self.refine.omega_step, 'Omega Step (deg)')
        self.parameters.add('polar', self.refine.polar_max, 
                            'Max. Polar Angle (deg)', None, self.set_polar_max)
        self.parameters.add('polar_tolerance', self.refine.polar_tolerance, 'Polar Angle Tolerance')
        self.parameters.add('peak_tolerance', self.refine.peak_tolerance, 'Peak Angle Tolerance')
        self.parameters.add('orientation_matrix', False, 'Orientation Matrix', False)

        self.refine_buttons = self.action_buttons(
                                  ('Refine Angles', self.refine_angles),
                                  ('Refine HKLs', self.refine_hkls),
                                  ('Restore', self.restore_parameters),
                                  ('Reset', self.reset_parameters))

        self.lattice_buttons = self.action_buttons(
                                   ('Plot', self.plot_lattice),
                                   ('List', self.list_peaks),
                                   ('Save', self.write_parameters))

        self.set_layout(self.entry_layout, self.parameters.grid(), 
                        self.refine_buttons, self.lattice_buttons,
                        self.close_buttons())

        self.parameters.grid_layout.setVerticalSpacing(1)
                                
        self.set_title('Refining Lattice')

        self.parameters['symmetry'].value = self.refine.symmetry
        self.set_symmetry()

        self.peaks_box = None
Example #20
0
    def define_data(self):
        def is_valid(data):
            try:
                valid_axes = [['Ql', 'Qk', 'Qh'], ['l', 'k', 'h'],
                              ['z', 'y', 'x']]
                axis_names = [axis.nxname for axis in data.nxaxes]
                return axis_names in valid_axes
            except Exception:
                return False

        root = self.entry.nxroot
        self.paths = GridParameters()
        i = 0
        for entry in root.NXentry:
            for data in [d for d in entry.NXdata if is_valid(d)]:
                i += 1
                self.paths.add(i, data.nxpath, i, True, width=200)
Example #21
0
 def setup_entry(self, position):
     default = self.settings['nxrefine']
     entry = NXentry()
     self.detectors[position] = GridParameters()
     self.detectors[position].add('x', default['x'], 'Translation - x (mm)')
     self.detectors[position].add('y', default['y'], 'Translation - y (mm)')
     self.detectors[position].add('omega', default['omega'], 'Omega (deg)')
     self.configuration_file[f'f{position}'] = entry
Example #22
0
    def __init__(self, parent=None):
        super(ParametersDialog, self).__init__(parent)

        self.select_root(self.choose_root)

        self.parameters = GridParameters()
        self.parameters.add('threshold', '', 'Threshold')
        self.parameters.add('first', 25, 'First Frame')
        self.parameters.add('last', 3625, 'Last Frame')
        self.parameters.add('radius', 200, 'Radius')
        self.parameters.add('width', 3, 'Frame Width')
        self.parameters.add('norm', '', 'Normalization')

        self.set_layout(self.root_layout,
                        self.parameters.grid(),
                        self.close_buttons(save=True))
        self.set_title('Choose Parameters')
Example #23
0
 def setup_instrument(self):
     default = self.settings['nxrefine']
     entry = self.configuration_file['entry']
     entry['instrument/detector/distance'] = NXfield(default['distance'],
                                                     dtype=float)
     entry['instrument/detector/distance'].attrs['units'] = 'mm'
     self.instrument = GridParameters()
     self.instrument.add('distance', entry['instrument/detector/distance'],
                         'Detector Distance (mm)')
     detector_list = sorted(
         list(set([detector().name
                   for detector in ALL_DETECTORS.values()])))
     self.instrument.add('detector', detector_list, 'Detector')
     self.instrument['detector'].value = 'Pilatus CdTe 2M'
     self.instrument.add('positions', [0, 1, 2, 3, 4, 5, 6, 7, 8],
                         'Number of Detector Positions',
                         slot=self.set_entries)
     self.instrument['positions'].value = '0'
Example #24
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.select_entry(self.choose_entry)

        self.parameters = GridParameters()
        self.parameters.add('first', '', 'First Frame')
        self.parameters.add('last', '', 'Last Frame')

        self.output = NXLabel('Maximum Value:')
        self.set_layout(
            self.entry_layout, self.output, self.parameters.grid(),
            self.action_buttons(('Find Maximum', self.find_maximum)),
            self.progress_layout(save=True))
        self.progress_bar.setVisible(False)
        self.progress_bar.setValue(0)
        self.set_title('Find Maximum Value')
        self.reduce = None
Example #25
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.select_entry(self.choose_entry)

        self.refine = NXRefine()

        self.parameters = GridParameters()
        self.parameters.add('wavelength', self.refine.wavelength,
                            'Wavelength (Ang)')
        self.parameters.add('distance', self.refine.distance,
                            'Detector Distance (mm)')
        self.parameters.add('xc', self.refine.xc, 'Beam Center - x')
        self.parameters.add('yc', self.refine.yc, 'Beam Center - y')
        self.parameters.add('pixel', self.refine.pixel_size, 'Pixel Size (mm)')
        self.action_buttons = self.action_buttons(
            ('Plot', self.plot_lattice), ('Save', self.write_parameters))
        self.set_layout(self.entry_layout, self.close_buttons())
        self.set_title('Calculate Angles')
Example #26
0
    def __init__(self, parent=None):
        super(LatticeDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.refine = NXRefine()

        self.parameters = GridParameters()
        self.parameters.add('symmetry',
                            self.refine.symmetries,
                            'Symmetry',
                            slot=self.set_lattice_parameters)
        self.parameters.add('centring', self.refine.centrings, 'Cell Centring')
        self.parameters.add('a',
                            self.refine.a,
                            'Unit Cell - a (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('b',
                            self.refine.b,
                            'Unit Cell - b (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('c',
                            self.refine.c,
                            'Unit Cell - c (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('alpha',
                            self.refine.alpha,
                            'Unit Cell - alpha (deg)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('beta',
                            self.refine.beta,
                            'Unit Cell - beta (deg)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('gamma',
                            self.refine.gamma,
                            'Unit Cell - gamma (deg)',
                            slot=self.set_lattice_parameters)
        self.parameters['symmetry'].value = self.refine.symmetry
        self.parameters['centring'].value = self.refine.centring
        action_buttons = self.action_buttons(('Plot', self.plot_lattice),
                                             ('Save', self.write_parameters))
        self.set_layout(self.entry_layout, self.parameters.grid(),
                        action_buttons, self.close_buttons())
        self.set_title('Defining Lattice')
Example #27
0
 def setup_position(self, position):
     self.entries[position] = GridParameters()
     self.entries[position].add('chi', -90.0, 'Chi (deg)')
     self.entries[position].add('omega', 0.0, 'Omega (deg)')
     self.entries[position].add('x', 0.0, 'Translation - x (mm)')
     self.entries[position].add('y', 0.0, 'Translation - y (mm)')
     self.entries[position].add('linkfile', 'f%d.h5' % position,
                                'Detector Filename')
     self.entries[position].add('linkpath', '/entry/data/data',
                                'Detector Data Path')
Example #28
0
 def setup_scans(self):
     if self.scans:
         self.scans.delete_grid()
     self.scans = GridParameters()
     all_files = [
         self.sample + '_' + d + '.nxs'
         for d in os.listdir(self.sample_directory)
         if os.path.isdir(os.path.join(self.sample_directory, d))
     ]
     filenames = sorted([
         f for f in all_files
         if os.path.exists(os.path.join(self.sample_directory, f))
     ],
                        key=natural_sort)
     for i, f in enumerate(filenames):
         scan = 'f%d' % i
         self.scans.add(scan, i + 1, f, True, self.update_scans)
         self.scans[scan].checkbox.stateChanged.connect(self.update_scans)
     self.insert_layout(2, self.scans.grid(header=False))
Example #29
0
 def setup_configuration(self):
     default = self.settings['nxrefine']
     entry = self.configuration_file['entry']
     entry['instrument/monochromator/wavelength'] = NXfield(
         default['wavelength'], dtype=np.float32)
     entry['instrument/monochromator/wavelength'].attrs['units'] = (
         'Angstroms')
     entry['instrument/monochromator/energy'] = NXfield(12.398419739640717 /
                                                        0.5,
                                                        dtype=np.float32)
     entry['instrument/monochromator/energy'].attrs['units'] = 'keV'
     entry['instrument/goniometer'] = NXgoniometer()
     entry['instrument/detector'] = NXdetector()
     self.configuration = GridParameters()
     self.configuration.add('configuration', 'configuration',
                            'Configuration Filename')
     self.configuration.add('wavelength',
                            entry['instrument/monochromator/wavelength'],
                            'Wavelength (Ã…)')
Example #30
0
 def __init__(self, parent=None):
     super(MaskDialog, self).__init__(parent)
     self.select_entry(self.choose_entry)
     self.parameters = GridParameters()
     self.parameters.add('mask', 'pilatus_mask/entry/mask', 'Mask Path')
     self.action_buttons(('Save Mask', self.save_mask))
     self.set_layout(self.entry_layout, self.parameters.grid(), 
                     self.action_buttons(('Save Mask', self.save_mask)), 
                     self.close_buttons())
     self.set_title('Mask Data')
Example #31
0
 def setup_sample(self):
     self.scan_file['entry/sample'] = NXsample()
     self.scan_file['entry/sample/name'] = 'sample'
     self.scan_file['entry/sample/label'] = 'label'
     self.scan_file['entry/sample/temperature'] = NXfield(300.0, dtype=np.float32)
     self.scan_file['entry/sample/temperature'].attrs['units'] = 'K'
     self.sample = GridParameters()
     self.sample.add('sample', self.scan_file['entry/sample/name'], 'Sample Name')
     self.sample.add('label', self.scan_file['entry/sample/label'], 'Sample Label')
     self.sample.add('scan', 'scan', 'Scan Label')
     self.sample.add('temperature', self.scan_file['entry/sample/temperature'], 'Temperature (K)')
Example #32
0
 def setup_scans(self):
     if self.scans:
         self.scans.delete_grid()
     self.scans = GridParameters()
     all_files = [self.sample+'_'+d+'.nxs'
                  for d in os.listdir(self.sample_directory)
                  if os.path.isdir(os.path.join(self.sample_directory, d))]
     filenames = sorted([f for f in all_files if os.path.exists(
         os.path.join(self.sample_directory, f))], key=natural_sort)
     for i, f in enumerate(filenames):
         scan = f'f{i}'
         self.scans.add(scan, i+1, f, True, self.update_scans)
         self.scans[scan].checkbox.stateChanged.connect(self.update_scans)
     scroll_widget = NXWidget()
     scroll_widget.set_layout(self.scans.grid(header=False))
     scroll_area = NXScrollArea(scroll_widget)
     scroll_area.setMinimumHeight(min(scroll_widget.sizeHint().height(),
                                      600))
     scroll_area.setWidgetResizable(True)
     self.insert_layout(2, scroll_area)
Example #33
0
 def setup_scans(self):
     self.scan = GridParameters()
     self.scan.add('scan', 'scan', 'Scan Label')
     self.scan.add('temperature', 300.0, 'Temperature (K)')
     self.scan.add('phi_start', -5.0, 'Phi Start (deg)')
     self.scan.add('phi_end', 360.0, 'Phi End (deg)')
     self.scan.add('phi_step', 0.1, 'Phi Step (deg)')
     self.scan.add('frame_rate', 10, 'Frame Rate (Hz)')
     
     for position in range(1, 6):
         self.setup_position(position)
Example #34
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.select_root(self.choose_root)

        default = NXSettings().settings['nxreduce']
        self.parameters = GridParameters()
        self.parameters.add('threshold', default['threshold'],
                            'Peak Threshold')
        self.parameters.add('first', default['first'], 'First Frame')
        self.parameters.add('last', default['last'], 'Last Frame')
        self.parameters.add('monitor', ['monitor1', 'monitor2'],
                            'Normalization Monitor')
        self.parameters['monitor'].value = default['monitor']
        self.parameters.add('norm', default['norm'], 'Normalization Value')
        self.parameters.add('radius', default['radius'], 'Punch Radius (Ã…)')
        self.parameters.add('qmax', default['qmax'], 'Maximum Taper Q (Ã…-1)')

        self.set_layout(self.root_layout,
                        self.close_buttons(save=True))
        self.set_title('Choose Parameters')
Example #35
0
 def setup_scan(self):
     default = self.settings['nxrefine']
     entry = self.configuration_file['entry']
     entry['instrument/goniometer/chi'] = (NXfield(default['chi'],
                                                   dtype=float))
     entry['instrument/goniometer/chi'].attrs['units'] = 'degree'
     entry['instrument/goniometer/phi'] = (NXfield(default['phi'],
                                                   dtype=float))
     entry['instrument/goniometer/phi'].attrs['step'] = (NXfield(
         default['phi_step'], dtype=float))
     entry['instrument/goniometer/phi'].attrs['end'] = (NXfield(
         default['phi_end'], dtype=float))
     entry['instrument/goniometer/phi'].attrs['units'] = 'degree'
     entry['instrument/detector/frame_time'] = (NXfield(
         1 / float(default['frame_rate']), dtype=float))
     self.scan = GridParameters()
     self.scan.add('chi', default['chi'], 'Chi (deg)')
     self.scan.add('phi_start', default['phi'], 'Phi Start (deg)')
     self.scan.add('phi_end', default['phi_end'], 'Phi End (deg)')
     self.scan.add('phi_step', default['phi_step'], 'Phi Step (deg)')
     self.scan.add('frame_rate', default['frame_rate'], 'Frame Rate (Hz)')
Example #36
0
    def __init__(self, parent=None):
        super(EnergyDialog, self).__init__(parent)

        self.select_entry()
        self.parameters = GridParameters()
        self.parameters.add('m1', self.entry['monitor1/distance'],
                            'Monitor 1 Distance')
        self.parameters.add('m2', self.entry['monitor2/distance'],
                            'Monitor 2 Distance')
        self.parameters.add('Ei',
                            self.entry['instrument/monochromator/energy'],
                            'Incident Energy')
        self.parameters.add('mod', self.entry['instrument/source/distance'],
                            'Moderator Distance')
        action_buttons = self.action_buttons(('Get Ei', self.get_ei))
        self.set_layout(self.entry_layout, self.parameters.grid(),
                        action_buttons, self.close_buttons(save=True))
        self.set_title('Get Incident Energy')

        self.m1 = self.entry['monitor1']
        self.m2 = self.entry['monitor2']
    def __init__(self, parent=None):
        super(OrientationDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.refine = NXRefine(self.entry)
        self.refine.read_parameters()

        self.parameters = GridParameters()
        self.parameters.add('phi_start', self.refine.phi, 'Phi Start (deg)')
        self.parameters.add('phi_step', self.refine.phi_step, 'Phi Step (deg)')
        self.parameters.add('chi', self.refine.chi, 'Chi (deg)')
        self.parameters.add('omega', self.refine.omega, 'Omega (deg)')
        self.parameters.add('polar', self.refine.polar_max,
                            'Max. Polar Angle (deg)')
        self.parameters.add('polar_tolerance', self.refine.polar_tolerance,
                            'Polar Angle Tolerance')
        self.parameters.add('peak_tolerance', self.refine.peak_tolerance,
                            'Peak Angle Tolerance')
        action_buttons = self.action_buttons(
            ('Generate Grains', self.generate_grains),
            ('List Peaks', self.list_peaks))
        self.grain_layout = QtWidgets.QHBoxLayout()
        self.grain_combo = QtWidgets.QComboBox()
        self.grain_combo.setSizeAdjustPolicy(
            QtWidgets.QComboBox.AdjustToContents)
        self.grain_combo.currentIndexChanged.connect(self.set_grain)
        self.grain_textbox = QtWidgets.QLabel()
        self.grain_layout.addWidget(self.grain_combo)
        self.grain_layout.addStretch()
        self.grain_layout.addWidget(self.grain_textbox)
        bottom_layout = QtWidgets.QHBoxLayout()
        self.result_textbox = QtWidgets.QLabel()
        bottom_layout.addWidget(self.result_textbox)
        bottom_layout.addStretch()
        bottom_layout.addWidget(self.close_buttons())
        self.set_layout(self.entry_layout, self.parameters.grid(),
                        action_buttons, bottom_layout)
        self.set_title('Defining Orientation')
Example #38
0
    def __init__(self, parent=None):
        super(SampleDialog, self).__init__(parent)

        self.sample = GridParameters()
        self.sample.add('sample', 'sample', 'Sample Name')
        self.sample.add('label', 'label', 'Sample Label')

        self.set_layout(self.directorybox('Choose Experiment Directory',
                                          default=False), 
                        self.sample.grid(header=False),
                        self.close_buttons(save=True))

        self.set_title('New Sample')
Example #39
0
    def __init__(self, parent=None):
        super(CalibrateDialog, self).__init__(parent)

        self.plotview = None
        self.data = None
        self.counts = None
        self.points = []
        self.pattern_geometry = None
        self.cake_geometry = None
        self.is_calibrated = False

        cstr = str(ALL_CALIBRANTS)
        calibrants = sorted(cstr[cstr.index(':') + 2:].split(', '))
        self.parameters = GridParameters()
        self.parameters.add('calibrant', calibrants, 'Calibrant')
        self.parameters['calibrant'].value = 'CeO2'
        self.parameters.add('wavelength', 0.5, 'Wavelength (Ang)', False)
        self.parameters.add('distance', 100.0, 'Detector Distance (mm)', True)
        self.parameters.add('xc', 512, 'Beam Center - x', True)
        self.parameters.add('yc', 512, 'Beam Center - y', True)
        self.parameters.add('yaw', 0.0, 'Yaw (degrees)', True)
        self.parameters.add('pitch', 0.0, 'Pitch (degrees)', True)
        self.parameters.add('roll', 0.0, 'Roll (degrees)', True)
        self.parameters.add('search_size', 10, 'Search Size (pixels)')
        rings = ['Ring1', 'Ring2', 'Ring3', 'Ring4', 'Ring5']
        self.rings_box = self.select_box(rings)
        self.set_layout(
            self.select_entry(self.choose_entry),
            self.action_buttons(('Plot Calibration', self.plot_data)),
            self.parameters.grid(header=False),
            self.make_layout(
                self.action_buttons(('Select Points', self.select)),
                self.rings_box),
            self.action_buttons(('Calibrate', self.calibrate),
                                ('Plot Cake', self.plot_cake),
                                ('Restore', self.restore_parameters),
                                ('Save', self.save_parameters)),
            self.close_buttons(close=True))
        self.set_title('Calibrating Powder')
Example #40
0
 def __init__(self, parent=None):
     super(ConvertDialog, self).__init__(parent)
     self.select_entry()
     self.parameters = GridParameters()
     self.parameters.add('Ei', self.entry['instrument/monochromator/energy'],
                         'Incident Energy')
     self.parameters.add('dQ', self.round(np.sqrt(self.Ei/2)/50), 'Q Step')
     self.parameters.add('dE', self.round(self.Ei/50), 'Energy Step')
     self.set_layout(self.entry_layout, 
                     self.parameters.grid(),
                     self.action_buttons(('Plot', self.plot_data),
                                         ('Save', self.save_data)),
                     self.close_buttons())
     self.setWindowTitle('Converting to (Q,E)')
Example #41
0
 def setup_scans(self):
     if self.scans:
         self.scans.delete_grid()
     self.scans = GridParameters()
     all_files = [self.sample+'_'+d+'.nxs' 
                 for d in os.listdir(self.sample_directory) 
                 if os.path.isdir(os.path.join(self.sample_directory, d))]
     filenames = sorted([f for f in all_files 
                 if os.path.exists(os.path.join(self.sample_directory, f))], 
                 key=natural_sort)
     for i, f in enumerate(filenames):
         scan = 'f%d' % i
         self.scans.add(scan, i+1, f, True, self.update_scans)
         self.scans[scan].checkbox.stateChanged.connect(self.update_scans)
     self.insert_layout(2, self.scans.grid(header=False))
Example #42
0
    def __init__(self, parent=None):
        super(EnergyDialog, self).__init__(parent)

        self.select_entry()
        self.parameters = GridParameters()
        self.parameters.add("m1", self.entry["monitor1/distance"], "Monitor 1 Distance")
        self.parameters.add("m2", self.entry["monitor2/distance"], "Monitor 2 Distance")
        self.parameters.add("Ei", self.entry["instrument/monochromator/energy"], "Incident Energy")
        self.parameters.add("mod", self.entry["instrument/source/distance"], "Moderator Distance")
        action_buttons = self.action_buttons(("Get Ei", self.get_ei))
        self.set_layout(self.entry_layout, self.parameters.grid(), action_buttons, self.close_buttons(save=True))
        self.set_title("Get Incident Energy")

        self.m1 = self.entry["monitor1"]
        self.m2 = self.entry["monitor2"]
Example #43
0
    def __init__(self, parent=None):
        super(Mask3DDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.parameters = GridParameters()
        self.parameters.add('radius', 200, 'Radius')
        self.parameters.add('width', 3, 'Frame Width')
        self.set_layout(self.entry_layout, 
                        self.parameters.grid(),
                        self.action_buttons(('Calculate 3D Mask', self.calculate_mask)),
                        self.progress_layout(save=True))
        self.progress_bar.setVisible(False)
        self.progress_bar.setValue(0)
        self.set_title('Calculate 3D Mask')
        self.reduce = None
Example #44
0
 def setup_instrument(self):
     entry = self.scan_file['entry']
     entry.instrument = NXinstrument()
     entry.instrument.monochromator = NXmonochromator()
     entry.instrument.detector = NXdetector()
     entry['instrument/monochromator/wavelength'] = NXfield(0.5, dtype=np.float32)
     entry['instrument/monochromator/wavelength'].attrs['units'] = 'Angstroms'
     entry['instrument/detector/distance'] = NXfield(100.0, dtype=np.float32)
     entry['instrument/detector/distance'].attrs['units'] = 'mm'
     entry['instrument/detector/pixel_size'] = NXfield(0.172, dtype=np.float32)
     entry['instrument/detector/pixel_size'].attrs['units'] = 'mm'
     self.instrument = GridParameters()
     self.instrument.add('wavelength', entry['instrument/monochromator/wavelength'], 'Wavelength (Ang)')
     self.instrument.add('distance', entry['instrument/detector/distance'], 'Detector Distance (mm)')
     self.instrument.add('pixel', entry['instrument/detector/pixel_size'], 'Pixel Size (mm)')
     self.instrument.add('positions', [0,1,2,3,4], 'Number of Detector Positions', slot=self.set_entries)
     self.instrument['positions'].value = '0'
Example #45
0
    def __init__(self, parent=None):
        super(MaximumDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.parameters = GridParameters()
        self.parameters.add('first', '', 'First Frame')
        self.parameters.add('last', '', 'Last Frame')

        self.output = QtWidgets.QLabel('Maximum Value:')
        self.set_layout(self.entry_layout, self.output,
                        self.parameters.grid(),
                        self.action_buttons(('Find Maximum', self.find_maximum)),
                        self.progress_layout(save=True))
        self.progress_bar.setVisible(False)
        self.progress_bar.setValue(0)
        self.set_title('Find Maximum Value')
        self.reduce = None
Example #46
0
    def __init__(self, parent=None):
        super(CalculateDialog, self).__init__(parent)
        
        self.select_entry(self.choose_entry)

        self.refine = NXRefine()

        self.parameters = GridParameters()
        self.parameters.add('wavelength', self.refine.wavelength, 'Wavelength (Ang)')
        self.parameters.add('distance', self.refine.distance, 'Detector Distance (mm)')
        self.parameters.add('xc', self.refine.xc, 'Beam Center - x')
        self.parameters.add('yc', self.refine.yc, 'Beam Center - y')
        self.parameters.add('pixel', self.refine.pixel_size, 'Pixel Size (mm)')
        action_buttons = self.action_buttons(('Plot', self.plot_lattice),
                                             ('Save', self.write_parameters))
        self.set_layout(self.entry_layout, self.parameters.grid(), 
                        action_buttons, self.close_buttons())
        self.set_title('Calculate Angles')
Example #47
0
class EnergyDialog(BaseDialog):
    def __init__(self, parent=None):
        super(EnergyDialog, self).__init__(parent)

        self.select_entry()
        self.parameters = GridParameters()
        self.parameters.add("m1", self.entry["monitor1/distance"], "Monitor 1 Distance")
        self.parameters.add("m2", self.entry["monitor2/distance"], "Monitor 2 Distance")
        self.parameters.add("Ei", self.entry["instrument/monochromator/energy"], "Incident Energy")
        self.parameters.add("mod", self.entry["instrument/source/distance"], "Moderator Distance")
        action_buttons = self.action_buttons(("Get Ei", self.get_ei))
        self.set_layout(self.entry_layout, self.parameters.grid(), action_buttons, self.close_buttons(save=True))
        self.set_title("Get Incident Energy")

        self.m1 = self.entry["monitor1"]
        self.m2 = self.entry["monitor2"]

    @property
    def m1_distance(self):
        return self.parameters["m1"].value - self.moderator_distance

    @property
    def m2_distance(self):
        return self.parameters["m2"].value - self.moderator_distance

    @property
    def Ei(self):
        return self.parameters["Ei"].value

    @property
    def moderator_distance(self):
        return self.parameters["mod"].value

    def get_ei(self):
        t = 2286.26 * self.m1_distance / np.sqrt(self.Ei)
        m1_time = self.m1[t - 200.0 : t + 200.0].moment()
        t = 2286.26 * self.m2_distance / np.sqrt(self.Ei)
        m2_time = self.m2[t - 200.0 : t + 200.0].moment()
        self.parameters["Ei"].value = (2286.26 * (self.m2_distance - self.m1_distance) / (m2_time - m1_time)) ** 2

    def accept(self):
        try:
            self.parameters["Ei"].save()
        except NeXusError as error:
            report_error("Getting Incident Energy", error)
        super(EnergyDialog, self).accept()
Example #48
0
 def setup_instrument(self):
     entry = self.experiment_file['entry']
     entry.instrument = NXinstrument()
     entry.instrument.monochromator = NXmonochromator()
     entry.instrument.detector = NXdetector()
     entry['instrument/monochromator/wavelength'] = NXfield(0.5, dtype=np.float32)
     entry['instrument/monochromator/wavelength'].attrs['units'] = 'Angstroms'
     entry['instrument/monochromator/energy'] = NXfield(12.398419739640717/0.5, dtype=np.float32)
     entry['instrument/monochromator/energy'].attrs['units'] = 'keV'
     entry['instrument/detector/distance'] = NXfield(100.0, dtype=np.float32)
     entry['instrument/detector/distance'].attrs['units'] = 'mm'
     self.instrument = GridParameters()
     self.instrument.add('experiment', 'experiment', 'Experiment Name')
     self.instrument.add('wavelength', entry['instrument/monochromator/wavelength'], 'Wavelength (Ang)')
     self.instrument.add('distance', entry['instrument/detector/distance'], 'Detector Distance (mm)')
     detector_list = sorted(list(set([detector().name for detector in ALL_DETECTORS.values()])))
     self.instrument.add('detector', detector_list, 'Detector')
     self.instrument['detector'].value = 'Pilatus CdTe 2M'
     self.instrument.add('positions', [0,1,2,3,4], 'Number of Detector Positions', slot=self.set_entries)
     self.instrument['positions'].value = '0'
Example #49
0
    def __init__(self, parent=None):

        super(EnergyDialog, self).__init__(parent)

        self.select_entry()
        self.parameters = GridParameters()
        self.parameters.add('m1', self.entry['monitor1/distance'], 
                            'Monitor 1 Distance')
        self.parameters.add('m2', self.entry['monitor2/distance'], 
                            'Monitor 2 Distance')
        self.parameters.add('Ei', self.entry['instrument/monochromator/energy'], 
                            'Incident Energy')
        self.parameters.add('mod', self.entry['instrument/source/distance'], 
                            'Moderator Distance')
        action_buttons = self.action_buttons(('Get Ei', self.get_ei))
        self.set_layout(self.entry_layout, self.parameters.grid(), 
                        action_buttons, self.close_buttons(save=True))
        self.set_title('Get Incident Energy')

        self.m1 = self.entry['monitor1']
        self.m2 = self.entry['monitor2'] 
Example #50
0
    def __init__(self, parent=None):
        super(CalibrateDialog, self).__init__(parent)

        self.plotview = None
        self.data = None
        self.counts = None
        self.points = []
        self.pattern_geometry = None
        self.cake_geometry = None
        self.is_calibrated = False    

        cstr = str(ALL_CALIBRANTS)
        calibrants = sorted(cstr[cstr.index(':')+2:].split(', '))
        self.parameters = GridParameters()
        self.parameters.add('calibrant', calibrants, 'Calibrant')
        self.parameters['calibrant'].value = 'CeO2'
        self.parameters.add('wavelength', 0.5, 'Wavelength (Ang)', False)
        self.parameters.add('distance', 100.0, 'Detector Distance (mm)', True)
        self.parameters.add('xc', 512, 'Beam Center - x', True)
        self.parameters.add('yc', 512, 'Beam Center - y', True)
        self.parameters.add('yaw', 0.0, 'Yaw (degrees)', True)
        self.parameters.add('pitch', 0.0, 'Pitch (degrees)', True)
        self.parameters.add('roll', 0.0, 'Roll (degrees)', True)
        self.parameters.add('search_size', 10, 'Search Size (pixels)')
        rings = ['Ring%s' % i for i in range(1,21)]
        self.rings_box = self.select_box(rings)
        self.set_layout(self.select_entry(self.choose_entry),
                        self.action_buttons(('Plot Calibration', self.plot_data)),
                        self.parameters.grid(header=False),
                        self.make_layout(
                            self.action_buttons(('Select Points', self.select)),
                            self.rings_box),
                        self.action_buttons(('Calibrate', self.calibrate),
                                            ('Plot Cake', self.plot_cake),
                                            ('Restore', self.restore_parameters),
                                            ('Save', self.save_parameters)), 
                        self.close_buttons(close=True))
        self.set_title('Calibrating Powder')
Example #51
0
    def __init__(self, parent=None):
        super(OrientationDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.refine = NXRefine(self.entry)
        self.refine.read_parameters()

        self.parameters = GridParameters()
        self.parameters.add('phi_start', self.refine.phi, 'Phi Start (deg)')
        self.parameters.add('phi_step', self.refine.phi_step, 'Phi Step (deg)')
        self.parameters.add('chi', self.refine.chi, 'Chi (deg)')
        self.parameters.add('omega', self.refine.omega, 'Omega (deg)')
        self.parameters.add('polar', self.refine.polar_max, 
                            'Max. Polar Angle (deg)')
        self.parameters.add('polar_tolerance', self.refine.polar_tolerance, 
                            'Polar Angle Tolerance')
        self.parameters.add('peak_tolerance', self.refine.peak_tolerance, 
                            'Peak Angle Tolerance')
        action_buttons = self.action_buttons(
                             ('Generate Grains', self.generate_grains),
                             ('List Peaks', self.list_peaks))
        self.grain_layout = QtWidgets.QHBoxLayout()
        self.grain_combo = QtWidgets.QComboBox()
        self.grain_combo.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
        self.grain_combo.currentIndexChanged.connect(self.set_grain)
        self.grain_textbox = QtWidgets.QLabel()
        self.grain_layout.addWidget(self.grain_combo)
        self.grain_layout.addStretch()
        self.grain_layout.addWidget(self.grain_textbox)
        bottom_layout = QtWidgets.QHBoxLayout()
        self.result_textbox = QtWidgets.QLabel()
        bottom_layout.addWidget(self.result_textbox)
        bottom_layout.addStretch()
        bottom_layout.addWidget(self.close_buttons())
        self.set_layout(self.entry_layout, self.parameters.grid(), 
                        action_buttons, bottom_layout)
        self.set_title('Defining Orientation')
Example #52
0
    def __init__(self, parent=None):
        super(FindDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        try:
            threshold = np.float32(self.entry.data.attrs["maximum"]) / 20
            max_frame = np.int32(len(self.entry.data.nxaxes[0]))
        except Exception:
            threshold = 5000
            max_frame = 0

        self.parameters = GridParameters()
        self.parameters.add("threshold", threshold, "Threshold")
        self.parameters.add("min", 0, "First Frame")
        self.parameters.add("max", max_frame, "Last Frame")
        self.parameters.add("pixel_tolerance", 50, "Pixel Tolerance")
        self.parameters.add("frame_tolerance", 10, "Frame Tolerance")
        find_layout = QtGui.QHBoxLayout()
        self.find_button = QtGui.QPushButton("Find Peaks")
        self.find_button.clicked.connect(self.find_peaks)
        self.peak_count = QtGui.QLabel()
        self.peak_count.setVisible(False)
        find_layout.addStretch()
        find_layout.addWidget(self.find_button)
        find_layout.addWidget(self.peak_count)
        find_layout.addStretch()
        self.set_layout(self.entry_layout, self.parameters.grid(), find_layout)
        self.set_title("Find Peaks")

        self.npk = 0
        try:
            self.parameters["max"].value = self.entry["data"].nxsignal.shape[0]
            self.parameters["threshold"].value = self.entry["data"].attrs["maximum"] / 20
        except Exception:
            pass
Example #53
0
class LatticeDialog(BaseDialog):

    def __init__(self, parent=None):
        super(LatticeDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.refine = NXRefine()

        self.parameters = GridParameters()
        self.parameters.add('symmetry', self.refine.symmetries, 'Symmetry',
                            slot=self.set_lattice_parameters)
        self.parameters.add('centring', self.refine.centrings, 'Cell Centring')
        self.parameters.add('a', self.refine.a, 'Unit Cell - a (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('b', self.refine.b, 'Unit Cell - b (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('c', self.refine.c, 'Unit Cell - c (Ang)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('alpha', self.refine.alpha, 'Unit Cell - alpha (deg)', 
                            slot=self.set_lattice_parameters)
        self.parameters.add('beta', self.refine.beta, 'Unit Cell - beta (deg)',
                            slot=self.set_lattice_parameters)
        self.parameters.add('gamma', self.refine.gamma, 'Unit Cell - gamma (deg)', 
                            slot=self.set_lattice_parameters)
        self.parameters['symmetry'].value = self.refine.symmetry
        self.parameters['centring'].value = self.refine.centring
        action_buttons = self.action_buttons(('Plot', self.plot_lattice),
                                             ('Save', self.write_parameters))
        self.set_layout(self.entry_layout, self.parameters.grid(), 
                        action_buttons, self.close_buttons())
        self.set_title('Defining Lattice')

    def choose_entry(self):
        self.refine = NXRefine(self.entry)
        self.update_parameters()

    def update_parameters(self):
        self.parameters['symmetry'].value = self.refine.symmetry
        self.parameters['centring'].value = self.refine.centring
        self.parameters['a'].value = self.refine.a
        self.parameters['b'].value = self.refine.b
        self.parameters['c'].value = self.refine.c
        self.parameters['alpha'].value = self.refine.alpha
        self.parameters['beta'].value = self.refine.beta
        self.parameters['gamma'].value = self.refine.gamma

    def get_symmetry(self):
        return self.parameters['symmetry'].value

    def get_centring(self):
        return self.parameters['centring'].value

    def get_lattice_parameters(self):
        return (self.parameters['a'].value,
                self.parameters['b'].value,
                self.parameters['c'].value,
                self.parameters['alpha'].value,
                self.parameters['beta'].value,
                self.parameters['gamma'].value)

    def set_lattice_parameters(self):
        symmetry = self.get_symmetry()
        if symmetry == 'cubic':
            self.parameters['b'].value = self.parameters['a'].value
            self.parameters['c'].value = self.parameters['a'].value
            self.parameters['alpha'].value = 90.0
            self.parameters['beta'].value = 90.0
            self.parameters['gamma'].value = 90.0
        elif symmetry == 'tetragonal':
            self.parameters['b'].value = self.parameters['a'].value
            self.parameters['alpha'].value = 90.0
            self.parameters['beta'].value = 90.0
            self.parameters['gamma'].value = 90.0
        elif symmetry == 'orthorhombic':
            self.parameters['alpha'].value = 90.0
            self.parameters['beta'].value = 90.0
            self.parameters['gamma'].value = 90.0
        elif symmetry == 'hexagonal':
            self.parameters['b'].value = self.parameters['a'].value
            self.parameters['alpha'].value = 90.0
            self.parameters['beta'].value = 90.0
            self.parameters['gamma'].value = 120.0
        elif symmetry == 'monoclinic':
            self.parameters['alpha'].value = 90.0
            self.parameters['gamma'].value = 90.0

    def get_parameters(self):
        (self.refine.a, self.refine.b, self.refine.c, 
         self.refine.alpha, self.refine.beta, self.refine.gamma) = (
            self.get_lattice_parameters())
        self.refine.symmetry = self.get_symmetry()
        self.refine.centring = self.get_centring()

    def plot_lattice(self):
        try:
            self.get_parameters()
            self.plot_peaks(self.refine.xp, self.refine.yp)
            polar_min, polar_max = plotview.xaxis.get_limits()
            self.plot_rings(polar_max)
        except NeXusError as error:
            report_error('Plotting Lattice', error)

    def write_parameters(self):
        try:
            self.get_parameters()
            self.refine.write_parameters()
        except NeXusError as error:
            report_error('Defining Lattice', error)

    def plot_peaks(self, x, y):
        try:
            polar_angles, azimuthal_angles = self.refine.calculate_angles(x, y)
            if polar_angles[0] > polar_angles[-1]:
                polar_angles = polar_angles[::-1]
                azimuthal_angles = azimuthal_angles[::-1]
            azimuthal_field = NXfield(azimuthal_angles, name='azimuthal_angle')
            azimuthal_field.long_name = 'Azimuthal Angle'
            polar_field = NXfield(polar_angles, name='polar_angle')
            polar_field.long_name = 'Polar Angle'
            plotview = get_plotview()
            plotview.plot(NXdata(azimuthal_field, polar_field, title='Peak Angles'))
        except NeXusError as error:
            report_error('Plotting Lattice', error)

    def plot_rings(self, polar_max=None):
        if polar_max is None:
            polar_max = self.refine.polar_max
        peaks = self.refine.calculate_rings(polar_max)
        plotview = get_plotview()
        plotview.vlines(peaks, colors='r', linestyles='dotted')
        plotview.draw()
Example #54
0
class RefineLatticeDialog(BaseDialog):

    def __init__(self, parent=None):
        super(RefineLatticeDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.refine = NXRefine(self.entry)
        self.refine.read_parameters()

        self.parameters = GridParameters()
        self.parameters.add('symmetry', self.refine.symmetries, 'Symmetry', 
                            None, self.set_symmetry)
        self.parameters.add('a', self.refine.a, 'Unit Cell - a (Ang)', True)
        self.parameters.add('b', self.refine.b, 'Unit Cell - b (Ang)', True)
        self.parameters.add('c', self.refine.c, 'Unit Cell - c (Ang)', True)
        self.parameters.add('alpha', self.refine.alpha, 'Unit Cell - alpha (deg)', False)
        self.parameters.add('beta', self.refine.beta, 'Unit Cell - beta (deg)', False)
        self.parameters.add('gamma', self.refine.gamma, 'Unit Cell - gamma (deg)', False)
        self.parameters.add('wavelength', self.refine.wavelength, 'Wavelength (Ang)', False)
        self.parameters.add('distance', self.refine.distance, 'Distance (mm)', False)
        self.parameters.add('yaw', self.refine.yaw, 'Yaw (deg)', False)
        self.parameters.add('pitch', self.refine.pitch, 'Pitch (deg)', False)
        self.parameters.add('roll', self.refine.roll, 'Roll (deg)')
        self.parameters.add('xc', self.refine.xc, 'Beam Center - x', False)
        self.parameters.add('yc', self.refine.yc, 'Beam Center - y', False)
        self.parameters.add('phi_start', self.refine.phi_start, 'Phi Start (deg)', False)
        self.parameters.add('phi_step', self.refine.phi_step, 'Phi Step (deg)')
        self.parameters.add('chi_start', self.refine.chi_start, 'Chi Start (deg)', False)
        self.parameters.add('chi_step', self.refine.chi_step, 'Chi Step (deg)')
        self.parameters.add('omega_start', self.refine.omega_start, 'Omega Start (deg)', False)
        self.parameters.add('omega_step', self.refine.omega_step, 'Omega Step (deg)')
        self.parameters.add('polar', self.refine.polar_max, 
                            'Max. Polar Angle (deg)', None, self.set_polar_max)
        self.parameters.add('polar_tolerance', self.refine.polar_tolerance, 'Polar Angle Tolerance')
        self.parameters.add('peak_tolerance', self.refine.peak_tolerance, 'Peak Angle Tolerance')
        self.parameters.add('orientation_matrix', False, 'Orientation Matrix', False)

        self.refine_buttons = self.action_buttons(
                                  ('Refine Angles', self.refine_angles),
                                  ('Refine HKLs', self.refine_hkls),
                                  ('Restore', self.restore_parameters),
                                  ('Reset', self.reset_parameters))

        self.lattice_buttons = self.action_buttons(
                                   ('Plot', self.plot_lattice),
                                   ('List', self.list_peaks),
                                   ('Save', self.write_parameters))

        self.set_layout(self.entry_layout, self.parameters.grid(), 
                        self.refine_buttons, self.lattice_buttons,
                        self.close_buttons())

        self.parameters.grid_layout.setVerticalSpacing(1)
                                
        self.set_title('Refining Lattice')

        self.parameters['symmetry'].value = self.refine.symmetry
        self.set_symmetry()

        self.peaks_box = None
        
    def choose_entry(self):
        self.refine = NXRefine(self.entry)
        self.update_parameters()

    def update_parameters(self):
        self.parameters['a'].value = self.refine.a
        self.parameters['b'].value = self.refine.b
        self.parameters['c'].value = self.refine.c
        self.parameters['alpha'].value = self.refine.alpha
        self.parameters['beta'].value = self.refine.beta
        self.parameters['gamma'].value = self.refine.gamma
        self.parameters['wavelength'].value = self.refine.wavelength
        self.parameters['distance'].value = self.refine.distance
        self.parameters['yaw'].value = self.refine.yaw
        self.parameters['pitch'].value = self.refine.pitch
        self.parameters['roll'].value = self.refine.roll
        self.parameters['xc'].value = self.refine.xc
        self.parameters['yc'].value = self.refine.yc
        self.parameters['phi_start'].value = self.refine.phi_start
        self.parameters['phi_step'].value = self.refine.phi_step
        self.parameters['chi_start'].value = self.refine.chi_start
        self.parameters['chi_step'].value = self.refine.chi_step
        self.parameters['omega_start'].value = self.refine.omega_start
        self.parameters['omega_step'].value = self.refine.omega_step
        self.parameters['polar'].value = self.refine.polar_max
        self.parameters['polar_tolerance'].value = self.refine.polar_tolerance
        try:
            self.refine.polar_angles, self.refine.azimuthal_angles = \
                self.refine.calculate_angles(self.refine.xp, self.refine.yp)
        except Exception:
            pass

    def transfer_parameters(self):
        self.refine.a, self.refine.b, self.refine.c, \
            self.refine.alpha, self.refine.beta, self.refine.gamma = \
                self.get_lattice_parameters()
        self.refine.set_symmetry()
        self.refine.wavelength = self.get_wavelength()
        self.refine.distance = self.get_distance()
        self.refine.yaw, self.refine.pitch, self.refine.roll = self.get_tilts()
        self.refine.xc, self.refine.yc = self.get_centers()
        self.refine.phi_start, self.refine.phi_step = self.get_phi()
        self.refine.chi_start, self.refine.chi_step = self.get_chi()
        self.refine.omega_start, self.refine.omega_step = self.get_omega()
        self.refine.polar_max = self.get_polar_max()
        self.refine.polar_tol = self.get_tolerance()
        self.refine.polar_angles

    def write_parameters(self):
        self.transfer_parameters()
        polar_angles, azimuthal_angles = self.refine.calculate_angles(
                                             self.refine.xp, self.refine.yp)
        self.refine.write_angles(polar_angles, azimuthal_angles)
        self.refine.write_parameters()

    def get_symmetry(self):
        return self.parameters['symmetry'].value

    def set_symmetry(self):
        self.refine.symmetry = self.get_symmetry()
        self.refine.set_symmetry()
        self.update_parameters()
        if self.refine.symmetry == 'cubic':
            self.parameters['b'].vary = False
            self.parameters['c'].vary = False
            self.parameters['alpha'].vary = False
            self.parameters['beta'].vary = False
            self.parameters['gamma'].vary = False
        elif self.refine.symmetry == 'tetragonal':
            self.parameters['b'].vary = False
            self.parameters['alpha'].vary = False
            self.parameters['beta'].vary = False
            self.parameters['gamma'].vary = False
        elif self.refine.symmetry == 'orthorhombic':
            self.parameters['alpha'].vary = False
            self.parameters['beta'].vary = False
            self.parameters['gamma'].vary = False
        elif self.refine.symmetry == 'hexagonal':
            self.parameters['b'].vary = False
            self.parameters['alpha'].vary = False
            self.parameters['beta'].vary = False
            self.parameters['gamma'].vary = False
        elif self.refine.symmetry == 'monoclinic':
            self.parameters['alpha'].vary = False
            self.parameters['gamma'].vary = False

    def get_lattice_parameters(self):
        return (self.parameters['a'].value,
                self.parameters['b'].value,
                self.parameters['c'].value,
                self.parameters['alpha'].value,
                self.parameters['beta'].value,
                self.parameters['gamma'].value)

    def get_wavelength(self):
        return self.parameters['wavelength'].value

    def get_distance(self):
        return self.parameters['distance'].value

    def get_tilts(self):
        return (self.parameters['yaw'].value,
                self.parameters['pitch'].value,
                self.parameters['roll'].value)

    def get_centers(self):
        return self.parameters['xc'].value, self.parameters['yc'].value

    def get_polar_max(self):
        return self.parameters['polar'].value

    def set_polar_max(self):
        self.refine.polar_max = self.get_polar_max()

    def get_tolerance(self):
        return self.parameters['polar_tolerance'].value

    def get_phi(self):
        return (self.parameters['phi_start'].value, 
                self.parameters['phi_step'].value)

    def get_chi(self):
        return (self.parameters['chi_start'].value, 
                self.parameters['chi_step'].value)

    def get_omega(self):
        return (self.parameters['omega_start'].value, 
                self.parameters['omega_step'].value)

    def get_hkl_tolerance(self):
        try:
            return np.float32(self.tolerance_box.text())
        except Exception:
            return self.refine.hkl_tolerance

    def plot_lattice(self):
        self.transfer_parameters()
        self.set_polar_max()
        self.plot_peaks()
        self.plot_rings()

    def plot_peaks(self):
        try:
            x, y = self.refine.xp[self.refine.idx], self.refine.yp[self.refine.idx]
            polar_angles, azimuthal_angles = self.refine.calculate_angles(x, y)
            if polar_angles[0] > polar_angles[-1]:
                polar_angles = polar_angles[::-1]
                azimuthal_angles = azimuthal_angles[::-1]
            azimuthal_field = NXfield(azimuthal_angles, name='azimuthal_angle')
            azimuthal_field.long_name = 'Azimuthal Angle'
            polar_field = NXfield(polar_angles, name='polar_angle')
            polar_field.long_name = 'Polar Angle'
            plotview = get_plotview()
            plotview.plot(NXdata(azimuthal_field, polar_field, title='Peak Angles'))
        except NeXusError as error:
            report_error('Plotting Lattice', error)

    def plot_rings(self, polar_max=None):
        if polar_max is None:
            polar_max = self.refine.polar_max
        peaks = self.refine.calculate_rings(polar_max)
        plotview = get_plotview()
        plotview.vlines(peaks, colors='r', linestyles='dotted')
        plotview.draw()
    
    def plot_peak(self, i):
        x, y, z = self.refine.xp[i], self.refine.yp[i], self.refine.zp[i]/10.0
        xmin, xmax = max(0,int(x)-200), min(int(x)+200,data.v.shape[2])
        ymin, ymax = max(0,int(y)-200), min(int(y)+200,data.v.shape[1])
        zmin, zmax = max(0.0,z-20.0), min(z+20.0, 360.0)
        xslab=np.s_[zmin:zmax,ymin:ymax,x]
        yslab=np.s_[zmin:zmax,y,xmin:xmax]
        zslab=np.s_[z,ymin:ymax,xmin:xmax]
        pvz.plot(data[zslab], log=True)
        pvz.crosshairs(x, y)
        pvy.plot(data[yslab], log=True)
        pvy.crosshairs(x, z)
        pvx.plot(data[xslab], log=True)
        pvx.crosshairs(y, z)

    def refine_angles(self):
        self.parameters['orientation_matrix'].vary = False
        self.parameters['phi_start'].vary = False
        self.parameters['chi_start'].vary = False
        self.parameters['omega_start'].vary = False
        self.parameters.refine_parameters(self.angle_residuals)
        self.update_parameters()

    def angle_residuals(self, p):
        self.parameters.get_parameters(p)
        self.transfer_parameters()
        polar_angles, _ = self.refine.calculate_angles(self.refine.x, self.refine.y)
        rings = self.refine.calculate_rings()
        residuals = np.array([find_nearest(rings, polar_angle) - polar_angle 
                              for polar_angle in polar_angles])
        return np.sum(residuals**2)

    def refine_hkls(self):
        self.parameters.refine_parameters(self.hkl_residuals)
        self.update_parameters()
        if self.peaks_box is None:
            self.list_peaks()
        else:
            self.update_table()

    def hkl_residuals(self, p):
        self.parameters.get_parameters(p)
        self.transfer_parameters()
        return self.refine.score(self.refine.idx)

    def restore_parameters(self):
        self.parameters.restore_parameters()
        self.transfer_parameters()

    def reset_parameters(self):
        self.refine.read_parameters()
        self.update_parameters()

    def list_peaks(self):
        if self.peaks_box is not None:
            self.update_table()
            return
        self.peaks_box = BaseDialog(self)
        self.peaks_box.setMinimumWidth(600)
        self.peaks_box.setMinimumHeight(600)
        header = ['i', 'x', 'y', 'z', 'Polar', 'Azi', 'Intensity',
                  'H', 'K', 'L', 'Diff']
        peak_list = self.refine.get_peaks()
        self.refine.assign_rings()
        self.rings = self.refine.get_ring_hkls()
        orient_layout = QtGui.QHBoxLayout()
        if self.refine.primary is None:
            self.refine.primary = 0
        if self.refine.secondary is None:
            self.refine.secondary = 1
        self.primary_box = QtGui.QLineEdit(str(self.refine.primary))
        self.primary_box.setAlignment(QtCore.Qt.AlignRight)
        self.primary_box.setFixedWidth(80)
        self.secondary_box = QtGui.QLineEdit(str(self.refine.secondary))
        self.secondary_box.setAlignment(QtCore.Qt.AlignRight)
        self.secondary_box.setFixedWidth(80)
        orient_button = QtGui.QPushButton('Orient')
        orient_button.clicked.connect(self.orient)

        orient_layout.addStretch()
        orient_layout.addWidget(QtGui.QLabel('Primary'))
        orient_layout.addWidget(self.primary_box)
        orient_layout.addWidget(QtGui.QLabel('Secondary'))
        orient_layout.addWidget(self.secondary_box)
        orient_layout.addStretch()
        orient_layout.addWidget(orient_button)     
 
        self.table_view = QtGui.QTableView()
        self.table_model = NXTableModel(self, peak_list, header)
        self.table_view.setModel(self.table_model)
        self.table_view.resizeColumnsToContents()
        self.table_view.horizontalHeader().stretchLastSection()
        self.table_view.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.table_view.doubleClicked.connect(self.plot_peak)
        self.table_view.setSortingEnabled(True)
        self.table_view.sortByColumn(0, QtCore.Qt.AscendingOrder)
        layout = QtGui.QVBoxLayout()
        layout.addLayout(orient_layout)
        layout.addWidget(self.table_view)
        close_layout = QtGui.QHBoxLayout()
        self.status_text = QtGui.QLabel('Score: %.4f' % self.refine.score())
        self.tolerance_box = QtGui.QLineEdit(str(self.refine.hkl_tolerance))
        self.tolerance_box.setAlignment(QtCore.Qt.AlignRight)
        self.tolerance_box.setMaxLength(5)
        self.tolerance_box.editingFinished.connect(self.update_table)
        self.tolerance_box.setFixedWidth(80)
        save_button = QtGui.QPushButton('Save Orientation')
        save_button.clicked.connect(self.save_orientation)
        close_button = QtGui.QPushButton('Close Window')
        close_button.clicked.connect(self.close_peaks_box)
        close_layout.addWidget(self.status_text)
        close_layout.addStretch()
        close_layout.addWidget(QtGui.QLabel('Threshold'))
        close_layout.addWidget(self.tolerance_box)
        close_layout.addStretch()
        close_layout.addWidget(save_button)
        close_layout.addStretch()
        close_layout.addWidget(close_button)
        layout.addLayout(close_layout)
        self.peaks_box.setLayout(layout)
        self.peaks_box.setWindowTitle('%s Peak Table' % self.entry.nxtitle)
        self.peaks_box.adjustSize()
        self.peaks_box.show()
        self.plotview = None

    def update_table(self):
        self.transfer_parameters()
        self.refine.hkl_tolerance = self.get_hkl_tolerance()
        self.table_model.peak_list = self.refine.get_peaks()
        rows, columns = len(self.table_model.peak_list), 11
        self.table_model.dataChanged.emit(self.table_model.createIndex(0, 0),
                                          self.table_model.createIndex(rows-1, columns-1))
        self.status_text.setText('Score: %.4f' % self.refine.score())


    def plot_peak(self):
        row = self.table_view.currentIndex().row()
        data = self.entry.data
        x, y, z = [self.table_view.model().peak_list[row][i] for i in range(1, 4)]
        xmin, xmax = max(0,x-200), min(x+200,data.nxsignal.shape[2])
        ymin, ymax = max(0,y-200), min(y+200,data.nxsignal.shape[1])
        zmin, zmax = max(0,z-200), min(z+200,data.nxsignal.shape[0])
        zslab=np.s_[z,ymin:ymax,xmin:xmax]
        if self.plotview is None:
            self.plotview = NXPlotView('X-Y Projection')
        self.plotview.plot(data[zslab], log=True)
        self.plotview.crosshairs(x, y)

    def orient(self):
        self.refine.primary = int(self.primary_box.text())
        self.refine.secondary = int(self.secondary_box.text())
        self.refine.Umat = self.refine.get_UBmat(self.refine.primary, 
                                                 self.refine.secondary) \
                           * self.refine.Bimat
        self.update_table()

    def save_orientation(self):
        self.write_parameters()

    def close_peaks_box(self):
        self.peaks_box.close()
        self.peaks_box = None
Example #55
0
class ScanDialog(BaseDialog):

    def __init__(self, parent=None):
        super(ScanDialog, self).__init__(parent)

        self.scan_file = NXroot()
        self.scan_file['entry'] = NXentry()

        self.detectors = {}
        self.entries = {}

        self.setup_sample()
        self.setup_instrument()

        self.set_layout(self.directorybox('Choose Data Directory'), 
                        self.sample.grid(header=False), 
                        self.instrument.grid(header=False))
        self.set_title('New Scan')

    def setup_sample(self):
        self.scan_file['entry/sample'] = NXsample()
        self.scan_file['entry/sample/name'] = 'sample'
        self.scan_file['entry/sample/label'] = 'label'
        self.scan_file['entry/sample/temperature'] = NXfield(300.0, dtype=np.float32)
        self.scan_file['entry/sample/temperature'].attrs['units'] = 'K'
        self.sample = GridParameters()
        self.sample.add('sample', self.scan_file['entry/sample/name'], 'Sample Name')
        self.sample.add('label', self.scan_file['entry/sample/label'], 'Sample Label')
        self.sample.add('scan', 'scan', 'Scan Label')
        self.sample.add('temperature', self.scan_file['entry/sample/temperature'], 'Temperature (K)')

    def setup_instrument(self):
        entry = self.scan_file['entry']
        entry.instrument = NXinstrument()
        entry.instrument.monochromator = NXmonochromator()
        entry.instrument.detector = NXdetector()
        entry['instrument/monochromator/wavelength'] = NXfield(0.5, dtype=np.float32)
        entry['instrument/monochromator/wavelength'].attrs['units'] = 'Angstroms'
        entry['instrument/detector/distance'] = NXfield(100.0, dtype=np.float32)
        entry['instrument/detector/distance'].attrs['units'] = 'mm'
        entry['instrument/detector/pixel_size'] = NXfield(0.172, dtype=np.float32)
        entry['instrument/detector/pixel_size'].attrs['units'] = 'mm'
        self.instrument = GridParameters()
        self.instrument.add('wavelength', entry['instrument/monochromator/wavelength'], 'Wavelength (Ang)')
        self.instrument.add('distance', entry['instrument/detector/distance'], 'Detector Distance (mm)')
        self.instrument.add('pixel', entry['instrument/detector/pixel_size'], 'Pixel Size (mm)')
        self.instrument.add('positions', [0,1,2,3,4], 'Number of Detector Positions', slot=self.set_entries)
        self.instrument['positions'].value = '0'

    def setup_entry(self, position):
        entry = self.scan_file['f%s' % position] = NXentry()
        entry.instrument = NXinstrument()
        entry.instrument.detector = NXdetector()
        entry.instrument.monochromator = NXmonochromator()
        entry['instrument/detector/beam_center_x'] = NXfield(1024.0, dtype=np.float32)
        entry['instrument/detector/beam_center_y'] = NXfield(1024.0, dtype=np.float32)
        self.detectors[position] = GridParameters()
        self.detectors[position].add('xc', entry['instrument/detector/beam_center_x'], 'Beam Center - x')
        self.detectors[position].add('yc', entry['instrument/detector/beam_center_y'], 'Beam Center - y')

    @property
    def positions(self):
        return int(self.instrument['positions'].value)
 
    def set_entries(self):
        for position in range(1,self.positions+1):
            self.setup_entry(position)
            self.layout.addLayout(self.detectors[position].grid(header=False, title='Position %s'%position))
        self.layout.addWidget(self.close_buttons(save=True))

    def get_parameters(self):
        entry = self.scan_file['entry']
        entry['sample/name'] = self.sample['sample'].value
        entry['sample/label'] = self.sample['label'].value
        entry['sample/temperature'] = self.sample['temperature'].value
        entry['instrument/monochromator/wavelength'] = self.instrument['wavelength'].value
        entry['instrument/detector/distance'] = self.instrument['distance'].value
        entry['instrument/detector/pixel_size'] = self.instrument['pixel'].value
        for position in range(1, self.positions+1):
            entry = self.scan_file['f%s' % position]
            entry['instrument/monochromator/wavelength'] = self.instrument['wavelength'].value
            entry['instrument/detector/distance'] = self.instrument['distance'].value
            entry['instrument/detector/pixel_size'] = self.instrument['pixel'].value
            entry['instrument/detector/beam_center_x'] = self.detectors[position]['xc'].value
            entry['instrument/detector/beam_center_y'] = self.detectors[position]['yc'].value
            entry.makelink(self.scan_file['entry/sample'])

    def accept(self):
        home_directory = self.get_directory()
        sample_directory = os.path.join(home_directory, self.sample['sample'].value)
        label_directory = os.path.join(home_directory, self.sample['sample'].value, self.sample['label'].value)
        scan_directory = os.path.join(label_directory, self.sample['scan'].value)
        scan_name = self.sample['sample'].value+'_'+self.sample['scan'].value
        try: 
            os.makedirs(scan_directory)
            for position in range(1, self.positions+1):
                os.mkdir(os.path.join(scan_directory, 'f%s' % position))
        except Exception:
            pass
        self.get_parameters()
        self.scan_file.save(os.path.join(label_directory, scan_name+'.nxs'))
        self.treeview.tree.load(self.scan_file.nxfilename, 'rw')
        super(ScanDialog, self).accept()
Example #56
0
class CalculateDialog(BaseDialog):

    def __init__(self, parent=None):
        super(CalculateDialog, self).__init__(parent)
        
        self.select_entry(self.choose_entry)

        self.refine = NXRefine(self.entry)
        self.refine.read_parameters()

        self.parameters = GridParameters()
        self.parameters.add('wavelength', self.refine.wavelength, 'Wavelength (Ang)')
        self.parameters.add('distance', self.refine.distance, 'Detector Distance (mm)')
        self.parameters.add('xc', self.refine.xc, 'Beam Center - x')
        self.parameters.add('yc', self.refine.yc, 'Beam Center - y')
        self.parameters.add('pixel', self.refine.pixel_size, 'Pixel Size (mm)')
        action_buttons = self.action_buttons(('Plot', self.plot_lattice),
                                             ('Save', self.write_parameters))
        self.set_layout(self.entry_layout, self.parameters.grid(), 
                        action_buttons, self.close_buttons())
        self.set_title('Calculate Angles')

    def choose_entry(self):
        self.refine = NXRefine(self.entry)
        self.update_parameters()

    def update_parameters(self):
        self.parameters['wavelength'].value = self.refine.wavelength
        self.parameters['distance'].value = self.refine.distance
        self.parameters['xc'].value = self.refine.xc
        self.parameters['yc'].value = self.refine.yc
        self.parameters['pixel'].value = self.refine.pixel_size

    def get_wavelength(self):
        return self.parameters['wavelength'].value

    def get_distance(self):
        return self.parameters['distance'].value

    def get_centers(self):
        return self.parameters['xc'].value, self.parameters['yc'].value

    def get_pixel_size(self):
        return self.parameters['pixel'].value

    def get_parameters(self):
        self.refine.wavelength = self.get_wavelength()
        self.refine.distance = self.get_distance()
        self.refine.xc, self.refine.yc = self.get_centers()
        self.refine.pixel_size = self.get_pixel_size()
        self.refine.yaw = self.refine.pitch = self.refine.roll = None

    def plot_lattice(self):
        try:
            self.get_parameters()
            self.plot_peaks(self.refine.xp, self.refine.yp)
        except NeXusError as error:
            report_error('Calculating Angles', error)

    def plot_peaks(self, x, y):
        try:
            polar_angles, azimuthal_angles = self.refine.calculate_angles(x, y)
            if polar_angles[0] > polar_angles[-1]:
                polar_angles = polar_angles[::-1]
                azimuthal_angles = azimuthal_angles[::-1]
            azimuthal_field = NXfield(azimuthal_angles, name='azimuthal_angle')
            azimuthal_field.long_name = 'Azimuthal Angle'
            polar_field = NXfield(polar_angles, name='polar_angle')
            polar_field.long_name = 'Polar Angle'
            plotview = get_plotview()
            plotview.plot(NXdata(azimuthal_field, polar_field, title='Peak Angles'))
        except NeXusError as error:
            report_error('Plotting Lattice', error)

    def write_parameters(self):
        try:
            self.get_parameters()
            polar_angles, azimuthal_angles = self.refine.calculate_angles(
                                                 self.refine.xp, self.refine.yp)
            self.refine.write_angles(polar_angles, azimuthal_angles)
            self.refine.write_parameters()
        except NeXusError as error:
            report_error('Calculating Angles', error)
Example #57
0
class ConvertDialog(BaseDialog):

    def __init__(self, parent=None):
        super(ConvertDialog, self).__init__(parent)
        layout = QtGui.QVBoxLayout()
        self.select_entry()
        self.parameters = GridParameters()
        self.parameters.add('Ei', self.entry['instrument/monochromator/energy'],
                            'Incident Energy')
        self.parameters.add('dQ', self.round(np.sqrt(self.Ei/2)/50), 'Q Step')
        self.parameters.add('dE', self.round(self.Ei/50), 'Energy Step')
        layout.addLayout(self.entry_layout)
        layout.addLayout(self.parameters.grid())
        layout.addLayout(self.action_buttons(('Plot', self.plot_data),
                                             ('Save', self.save_data)))
        layout.addWidget(self.close_buttons())
        self.setLayout(layout)
        self.setWindowTitle('Converting to (Q,E)')

    @property
    def Ei(self):
        return self.parameters['Ei'].value

    @property
    def dQ(self):
        return self.parameters['dQ'].value

    @property
    def dE(self):
        return self.parameters['dE'].value

    def read_parameters(self):
        self.L1 = - self.entry['sample/distance']
        self.L2 = np.mean(self.entry['instrument/detector/distance'])
        self.m1 = self.entry['monitor1']
        self.t_m1 = self.m1.moment()
        self.d_m1 = self.entry['monitor1/distance']

    def convert_tof(self, tof):
        ki = np.sqrt(self.Ei / 2.0721)
        ts = self.t_m1 + 1588.254 * (self.L1 - self.d_m1) / ki
        kf = 1588.254 * self.L2 / (tof - ts)
        eps = self.Ei - 2.0721*kf**2
        return eps

    def convert_QE(self):
        """Convert S(phi,eps) to S(Q,eps)"""

        self.read_parameters()

        Ei = self.Ei
        dQ = self.dQ
        dE = self.dE

        pol, tof = centers(self.entry['data'].nxsignal, self.entry['data'].nxaxes)
        en = self.convert_tof(tof)

        idx_max = min(np.where(np.abs(en-0.75*Ei)<0.1)[0])

        en = en[:idx_max]

        data = self.entry['data'].nxsignal.nxdata[:,:idx_max]
        if self.entry['data'].nxerrors:
            errors = self.entry['data'].nxerrors.nxdata[:]

        Q = np.zeros((len(pol), len(en)))
        E = np.zeros((len(pol), len(en)))

        for i in range(0,len(pol)):
            p = pol[i]
            Q[i,:] = np.array(np.sqrt((2*Ei - en - 2*np.sqrt(Ei*(Ei-en))
                               * np.cos(p*np.pi/180.0))/2.0721))
            E[i,:] = np.array(en)

        s = Q.shape
        Qin = Q.reshape(s[0]*s[1])
        Ein = E.reshape(s[0]*s[1])
        datain = data.reshape(s[0]*s[1])
        if self.entry['data'].nxerrors:
            errorsin = errors.reshape(s[0]*s[1])

        qmin = Q.min()
        qmax = Q.max()
        emin = E.min()
        emax = E.max()
        NQ = int((qmax-qmin)/dQ) + 1
        NE = int((emax-emin)/dE) + 1
        Qb = np.linspace(qmin, qmax, NQ)
        Eb = np.linspace(emin, emax, NE)
        #histogram and normalize 
        norm, nbin = np.histogramdd((Ein,Qin), bins=(Eb,Qb))
        hist, hbin = np.histogramdd((Ein,Qin), bins=(Eb,Qb), weights=datain)
        if self.entry['data'].nxerrors:
            histe, hbin = np.histogramdd((Ein,Qin), bins=(Eb,Qb), weights=errorsin*errorsin)
            histe = histe**0.5
            err = histe/norm

        I = NXfield(hist/norm, name='S(Q,E)')

        Qb = NXfield(Qb[:-1]+dQ/2., name='Q')
        Eb = NXfield(Eb[:-1]+dE/2., name='E')

        result = NXdata(I, (Eb, Qb))
        if self.entry.data.nxerrors:
            result.errors = NXfield(err)
        return result

    def round(self, x, prec=2, base=.05):
        return round(base * round(float(x)/base), prec)

    def plot_data(self):
        self.convert_QE().plot()

    def save_data(self):
        self.entry['sqe'] = self.convert_QE()
Example #58
0
class OrientationDialog(BaseDialog):

    def __init__(self, parent=None):
        super(OrientationDialog, self).__init__(parent)

        self.select_entry(self.choose_entry)

        self.refine = NXRefine(self.entry)
        self.refine.read_parameters()

        self.parameters = GridParameters()
        self.parameters.add('phi_start', self.refine.phi, 'Phi Start (deg)')
        self.parameters.add('phi_step', self.refine.phi_step, 'Phi Step (deg)')
        self.parameters.add('chi', self.refine.chi, 'Chi (deg)')
        self.parameters.add('omega', self.refine.omega, 'Omega (deg)')
        self.parameters.add('polar', self.refine.polar_max, 
                            'Max. Polar Angle (deg)')
        self.parameters.add('polar_tolerance', self.refine.polar_tolerance, 
                            'Polar Angle Tolerance')
        self.parameters.add('peak_tolerance', self.refine.peak_tolerance, 
                            'Peak Angle Tolerance')
        action_buttons = self.action_buttons(
                             ('Generate Grains', self.generate_grains),
                             ('List Peaks', self.list_peaks))
        self.grain_layout = QtWidgets.QHBoxLayout()
        self.grain_combo = QtWidgets.QComboBox()
        self.grain_combo.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
        self.grain_combo.currentIndexChanged.connect(self.set_grain)
        self.grain_textbox = QtWidgets.QLabel()
        self.grain_layout.addWidget(self.grain_combo)
        self.grain_layout.addStretch()
        self.grain_layout.addWidget(self.grain_textbox)
        bottom_layout = QtWidgets.QHBoxLayout()
        self.result_textbox = QtWidgets.QLabel()
        bottom_layout.addWidget(self.result_textbox)
        bottom_layout.addStretch()
        bottom_layout.addWidget(self.close_buttons())
        self.set_layout(self.entry_layout, self.parameters.grid(), 
                        action_buttons, bottom_layout)
        self.set_title('Defining Orientation')

    def choose_entry(self):
        self.refine = NXRefine(self.entry)
        self.update_parameters()

    def update_parameters(self):
        self.parameters['phi_start'].value = self.refine.phi
        self.parameters['phi_step'].value = self.refine.phi_step
        self.parameters['chi'].value = self.refine.chi
        self.parameters['omega'].value = self.refine.omega
        self.parameters['polar'].value = self.refine.polar_max
        self.parameters['polar_tolerance'].value = self.refine.polar_tolerance
        self.parameters['peak_tolerance'].value = self.refine.peak_tolerance

    def get_phi(self):
        return (self.parameters['phi_start'].value,
                self.parameters['phi_step'].value) 

    def set_phi(self):
        self.refine.phi_start, self.refine.phi_step = self.get_phi() 

    def get_chi(self):
        return self.parameters['chi'].value

    def set_chi(self):
        self.refine.chi = self.get_chi() 

    def get_omega(self):
        return self.parameters['omega'].value 

    def set_omega(self):
        self.refine.omega = self.get_omega() 

    @property
    def polar_max(self):
        return self.parameters['polar'].value

    def set_polar_max(self):
        self.refine.polar_max = self.polar_max

    def get_polar_tolerance(self):
        return self.parameters['polar_tolerance'].value

    def set_polar_tolerance(self):
        self.refine.polar_tolerance = self.get_polar_tolerance()

    def get_peak_tolerance(self):
        return self.parameters['peak_tolerance'].value

    def set_peak_tolerance(self):
        self.refine.peak_tolerance = self.get_peak_tolerance()

    def generate_grains(self):
        self.set_polar_max()
        self.refine.generate_grains()
        if self.refine.grains is not None:
            self.layout.insertLayout(2, self.grain_layout)
        self.grain_combo.clear()
        for i in range(len(self.refine.grains)):
            self.grain_combo.addItem('Grain %s' % i)
        self.grain_combo.setCurrentIndex(0)
        self.set_grain()

    def set_grain(self):
        try:
            grain = self.refine.grains[self.get_grain()]
            self.grain_textbox.setText('%s peaks; Score: %.4f' 
                                       % (len(grain), grain.score))
            self.refine.Umat = grain.Umat
            self.refine.primary = grain.primary
            self.refine.secondary = grain.secondary
            self.get_score()
        except:
            self.grain_textbox.setText('')

    def get_grain(self):
        return int(self.grain_combo.currentText().split()[-1])

    def list_peaks(self):
        self.refine.phi = self.get_phi()
        self.refine.chi = self.get_chi()
        self.refine.omega = self.get_omega()
        if self.refine.grains is not None:
            grain = self.refine.grains[self.get_grain()]
            self.refine.Umat = grain.Umat
            self.list_orientations()
        else:
            self.list_orientations()

    def get_score(self):
        if self.refine.Umat is not None:
            self.score = self.refine.score()
            self.result_textbox.setText('%s peaks; Score: %.4f'
                                        % (len(self.refine.idx), self.score))

    def list_orientations(self):
        message_box = BaseDialog(self)
        message_box.setMinimumWidth(600)
        message_box.setMinimumHeight(600)
        header = ['i', 'x', 'y', 'z', 'Polar', 'Azi', 'Intensity',
                  'H', 'K', 'L', 'Diff']
        peak_list = self.refine.get_peaks()
        self.refine.assign_rings()
        self.rings = self.refine.get_ring_hkls()
        orient_layout = QtWidgets.QHBoxLayout()
        if self.refine.primary is None:
            self.refine.primary = 0
        if self.refine.secondary is None:
            self.refine.secondary = 1
        self.primary_box = QtWidgets.QLineEdit(str(self.refine.primary))
        self.primary_box.setAlignment(QtCore.Qt.AlignRight)
        self.primary_box.setFixedWidth(80)
        self.secondary_box = QtWidgets.QLineEdit(str(self.refine.secondary))
        self.secondary_box.setAlignment(QtCore.Qt.AlignRight)
        self.secondary_box.setFixedWidth(80)
        orient_button = QtWidgets.QPushButton('Orient')
        orient_button.clicked.connect(self.orient)
        refine_button = QtWidgets.QPushButton('Refine')
        refine_button.clicked.connect(self.refine_orientation)
        restore_button = QtWidgets.QPushButton('Restore')
        restore_button.clicked.connect(self.restore_orientation)
        orient_layout.addStretch()
        orient_layout.addWidget(QtWidgets.QLabel('Primary'))
        orient_layout.addWidget(self.primary_box)
        orient_layout.addWidget(QtWidgets.QLabel('Secondary'))
        orient_layout.addWidget(self.secondary_box)
        orient_layout.addStretch()
        orient_layout.addWidget(orient_button)     
        orient_layout.addWidget(refine_button)
        orient_layout.addWidget(restore_button)

        grid = QtWidgets.QGridLayout()
        grid.setSpacing(10)
        self.lattice = GridParameters()
        self.lattice.add('a', self.refine.a, 'a', False)
        self.lattice.add('b', self.refine.b, 'b', False)
        self.lattice.add('c', self.refine.c, 'c', False)
        self.lattice.add('alpha', self.refine.alpha, 'alpha', False)
        self.lattice.add('beta', self.refine.beta, 'beta', False)
        self.lattice.add('gamma', self.refine.gamma, 'gamma', False)
        p = self.lattice['a']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 0, 0, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 0, 1, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 0, 2, QtCore.Qt.AlignHCenter)
        p = self.lattice['b']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 0, 3, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 0, 4, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 0, 5, QtCore.Qt.AlignHCenter)
        p = self.lattice['c']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 0, 6, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 0, 7, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 0, 8, QtCore.Qt.AlignHCenter)
        p = self.lattice['alpha']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 1, 0, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 1, 1, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 1, 2, QtCore.Qt.AlignHCenter)
        p = self.lattice['beta']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 1, 3, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 1, 4, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 1, 5, QtCore.Qt.AlignHCenter)
        p = self.lattice['gamma']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 1, 6, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 1, 7, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 1, 8, QtCore.Qt.AlignHCenter)
        self.table_view = QtWidgets.QTableView()
        self.table_model = NXTableModel(self, peak_list, header)
        self.table_view.setModel(self.table_model)
        self.table_view.resizeColumnsToContents()
        self.table_view.horizontalHeader().stretchLastSection()
        self.table_view.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.table_view.doubleClicked.connect(self.plot_peak)
        self.table_view.setSortingEnabled(True)
        self.table_view.sortByColumn(0, QtCore.Qt.AscendingOrder)
        layout = QtWidgets.QVBoxLayout()
        layout.addLayout(orient_layout)
        layout.addLayout(grid)
        layout.addWidget(self.table_view)
        close_layout = QtWidgets.QHBoxLayout()
        self.status_text = QtWidgets.QLabel('Score: %.4f' % self.refine.score())
        self.tolerance_box = QtWidgets.QLineEdit(str(self.refine.hkl_tolerance))
        self.tolerance_box.setAlignment(QtCore.Qt.AlignRight)
        self.tolerance_box.setMaxLength(5)
        self.tolerance_box.editingFinished.connect(self.update_table)
        self.tolerance_box.setFixedWidth(80)
        save_button = QtWidgets.QPushButton('Save Orientation')
        save_button.clicked.connect(self.save_orientation)
        close_button = QtWidgets.QPushButton('Close Window')
        close_button.clicked.connect(message_box.close)
        close_layout.addWidget(self.status_text)
        close_layout.addStretch()
        close_layout.addWidget(QtWidgets.QLabel('Threshold'))
        close_layout.addWidget(self.tolerance_box)
        close_layout.addStretch()
        close_layout.addWidget(save_button)
        close_layout.addStretch()
        close_layout.addWidget(close_button)
        layout.addLayout(close_layout)
        message_box.setLayout(layout)
        message_box.setWindowTitle('%s Peak Table' % self.entry.nxtitle)
        message_box.adjustSize()
        message_box.show()
        self.plotview = None

    def plot_peak(self):
        row = self.table_view.currentIndex().row()
        data = self.entry.data
        x, y, z = [self.table_view.model().peak_list[row][i] for i in range(1, 4)]
        xmin, xmax = max(0,x-200), min(x+200,data.nxsignal.shape[2])
        ymin, ymax = max(0,y-200), min(y+200,data.nxsignal.shape[1])
        zmin, zmax = max(0,z-200), min(z+200,data.nxsignal.shape[0])
        zslab=np.s_[z,ymin:ymax,xmin:xmax]
        if self.plotview is None:
            self.plotview = NXPlotView('X-Y Projection')
        self.plotview.plot(data[zslab], log=True)
        self.plotview.crosshairs(x, y)

    def orient(self):
        self.refine.primary = int(self.primary_box.text())
        self.refine.secondary = int(self.secondary_box.text())
        self.refine.Umat = self.refine.get_UBmat(self.refine.primary, 
                                                 self.refine.secondary) \
                           * self.refine.Bimat
        self.update_table()

    def refine_orientation(self):
        idx = self.refine.idx
        intensities = self.refine.intensity[idx]
        sigma = np.average(intensities) / intensities
        p0 = self.set_parameters(idx)
        def diffs(p):
            self.get_parameters(p)
            UBimat = np.linalg.inv(self.refine.UBmat)
            Q = [UBimat * self.Gvec[i] for i in idx]
            dQ = Q - np.rint(Q)
            return np.array([np.linalg.norm(self.refine.Bmat*np.matrix(dQ[i])) 
                             for i in idx]) / sigma
        popt, C, info, msg, success = leastsq(diffs, p0, full_output=1)
        self.get_parameters(popt)
        self.update_lattice()
        self.update_table()
        self.status_text.setText('Score: %.4f' % self.refine.score())

    def restore_orientation(self):
        self.refine.Umat = self.Umat
        for par in self.lattice.values():
            par.value = par.init_value
        self.update_table()

    def update_table(self):
        self.refine.hkl_tolerance = np.float32(self.tolerance_box.text())
        self.table_model.peak_list = self.refine.get_peaks()
        rows, columns = len(self.table_model.peak_list), 11
        self.table_model.dataChanged.emit(self.table_model.createIndex(0, 0),
                                          self.table_model.createIndex(rows-1, columns-1))
        self.status_text.setText('Score: %.4f' % self.refine.score())

    def update_lattice(self):
        self.lattice['a'].value = self.refine.a
        self.lattice['b'].value = self.refine.b
        self.lattice['c'].value = self.refine.c
        self.lattice['alpha'].value = self.refine.alpha
        self.lattice['beta'].value = self.refine.beta
        self.lattice['gamma'].value = self.refine.gamma

    def set_parameters(self, idx):
        x, y, z = self.refine.xp[idx], self.refine.yp[idx], self.refine.zp[idx]
        self.Gvec = [self.refine.Gvec(xx,yy,zz) for xx,yy,zz in zip(x,y,z)]
        self.Umat = self.refine.Umat
        pars = []
        for par in self.lattice.values():
            par.init_value = par.value
            if par.vary:
                pars.append(par.value)
        p0 = np.zeros(shape=(len(pars)+9), dtype=np.float32)
        p0[:len(pars)] = pars
        p0[len(pars):] = np.ravel(self.refine.Umat)
        return p0

    def get_parameters(self, p):
        i = 0
        for par in self.lattice.values():
            if par.vary:
                par.value = p[i]
                i += 1
        self.refine.a, self.refine.b, self.refine.c, \
            self.refine.alpha, self.refine.beta, self.refine.gamma = \
                [par.value for par in self.lattice.values()]
        self.refine.set_symmetry()
        self.refine.Umat = np.matrix(p[i:]).reshape(3,3)

    def save_orientation(self):
        self.write_parameters()

    def write_parameters(self):
        try:
            self.refine.write_parameters()
        except NeXusError as error:
            report_error('Defining Orientation', error)
Example #59
0
    def list_orientations(self):
        message_box = BaseDialog(self)
        message_box.setMinimumWidth(600)
        message_box.setMinimumHeight(600)
        header = ['i', 'x', 'y', 'z', 'Polar', 'Azi', 'Intensity',
                  'H', 'K', 'L', 'Diff']
        peak_list = self.refine.get_peaks()
        self.refine.assign_rings()
        self.rings = self.refine.get_ring_hkls()
        orient_layout = QtWidgets.QHBoxLayout()
        if self.refine.primary is None:
            self.refine.primary = 0
        if self.refine.secondary is None:
            self.refine.secondary = 1
        self.primary_box = QtWidgets.QLineEdit(str(self.refine.primary))
        self.primary_box.setAlignment(QtCore.Qt.AlignRight)
        self.primary_box.setFixedWidth(80)
        self.secondary_box = QtWidgets.QLineEdit(str(self.refine.secondary))
        self.secondary_box.setAlignment(QtCore.Qt.AlignRight)
        self.secondary_box.setFixedWidth(80)
        orient_button = QtWidgets.QPushButton('Orient')
        orient_button.clicked.connect(self.orient)
        refine_button = QtWidgets.QPushButton('Refine')
        refine_button.clicked.connect(self.refine_orientation)
        restore_button = QtWidgets.QPushButton('Restore')
        restore_button.clicked.connect(self.restore_orientation)
        orient_layout.addStretch()
        orient_layout.addWidget(QtWidgets.QLabel('Primary'))
        orient_layout.addWidget(self.primary_box)
        orient_layout.addWidget(QtWidgets.QLabel('Secondary'))
        orient_layout.addWidget(self.secondary_box)
        orient_layout.addStretch()
        orient_layout.addWidget(orient_button)     
        orient_layout.addWidget(refine_button)
        orient_layout.addWidget(restore_button)

        grid = QtWidgets.QGridLayout()
        grid.setSpacing(10)
        self.lattice = GridParameters()
        self.lattice.add('a', self.refine.a, 'a', False)
        self.lattice.add('b', self.refine.b, 'b', False)
        self.lattice.add('c', self.refine.c, 'c', False)
        self.lattice.add('alpha', self.refine.alpha, 'alpha', False)
        self.lattice.add('beta', self.refine.beta, 'beta', False)
        self.lattice.add('gamma', self.refine.gamma, 'gamma', False)
        p = self.lattice['a']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 0, 0, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 0, 1, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 0, 2, QtCore.Qt.AlignHCenter)
        p = self.lattice['b']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 0, 3, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 0, 4, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 0, 5, QtCore.Qt.AlignHCenter)
        p = self.lattice['c']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 0, 6, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 0, 7, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 0, 8, QtCore.Qt.AlignHCenter)
        p = self.lattice['alpha']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 1, 0, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 1, 1, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 1, 2, QtCore.Qt.AlignHCenter)
        p = self.lattice['beta']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 1, 3, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 1, 4, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 1, 5, QtCore.Qt.AlignHCenter)
        p = self.lattice['gamma']
        p.box.setFixedWidth(80)
        label, value, checkbox = p.label, p.value, p.vary
        grid.addWidget(p.label, 1, 6, QtCore.Qt.AlignRight)
        grid.addWidget(p.box, 1, 7, QtCore.Qt.AlignHCenter)
        grid.addWidget(p.checkbox, 1, 8, QtCore.Qt.AlignHCenter)
        self.table_view = QtWidgets.QTableView()
        self.table_model = NXTableModel(self, peak_list, header)
        self.table_view.setModel(self.table_model)
        self.table_view.resizeColumnsToContents()
        self.table_view.horizontalHeader().stretchLastSection()
        self.table_view.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.table_view.doubleClicked.connect(self.plot_peak)
        self.table_view.setSortingEnabled(True)
        self.table_view.sortByColumn(0, QtCore.Qt.AscendingOrder)
        layout = QtWidgets.QVBoxLayout()
        layout.addLayout(orient_layout)
        layout.addLayout(grid)
        layout.addWidget(self.table_view)
        close_layout = QtWidgets.QHBoxLayout()
        self.status_text = QtWidgets.QLabel('Score: %.4f' % self.refine.score())
        self.tolerance_box = QtWidgets.QLineEdit(str(self.refine.hkl_tolerance))
        self.tolerance_box.setAlignment(QtCore.Qt.AlignRight)
        self.tolerance_box.setMaxLength(5)
        self.tolerance_box.editingFinished.connect(self.update_table)
        self.tolerance_box.setFixedWidth(80)
        save_button = QtWidgets.QPushButton('Save Orientation')
        save_button.clicked.connect(self.save_orientation)
        close_button = QtWidgets.QPushButton('Close Window')
        close_button.clicked.connect(message_box.close)
        close_layout.addWidget(self.status_text)
        close_layout.addStretch()
        close_layout.addWidget(QtWidgets.QLabel('Threshold'))
        close_layout.addWidget(self.tolerance_box)
        close_layout.addStretch()
        close_layout.addWidget(save_button)
        close_layout.addStretch()
        close_layout.addWidget(close_button)
        layout.addLayout(close_layout)
        message_box.setLayout(layout)
        message_box.setWindowTitle('%s Peak Table' % self.entry.nxtitle)
        message_box.adjustSize()
        message_box.show()
        self.plotview = None