def init_dir(self): """Initialize NeXpy home directory""" home_dir = os.path.abspath(os.path.expanduser('~')) nexpy_dir = os.path.join(home_dir, '.nexpy') if not os.path.exists(nexpy_dir): parent = os.path.dirname(nexpy_dir) if not os.access(parent, os.W_OK): nexpy_dir = tempfile.mkdtemp() else: os.mkdir(nexpy_dir) for subdirectory in ['backups', 'functions', 'plugins', 'readers', 'scripts']: directory = os.path.join(nexpy_dir, subdirectory) if not os.path.exists(directory): os.mkdir(directory) global _nexpy_dir self.nexpy_dir = _nexpy_dir = nexpy_dir self.backup_dir = os.path.join(self.nexpy_dir, 'backups') self.plugin_dir = os.path.join(self.nexpy_dir, 'plugins') self.reader_dir = os.path.join(self.nexpy_dir, 'readers') self.script_dir = os.path.join(self.nexpy_dir, 'scripts') self.function_dir = os.path.join(self.nexpy_dir, 'functions') sys.path.append(self.function_dir) self.scratch_file = os.path.join(self.nexpy_dir, 'w0.nxs') if not os.path.exists(self.scratch_file): NXroot().save(self.scratch_file)
def save_map(self): X,Y,Z, xi, yi = self.plot_map() try: self.tree.map2ddata = NXroot() self.tree.map2ddata['roi' + '_' + str(self.roi_dn) + ':' + str(self.roi_up)] = NXentry() self.tree.map2ddata['roi' + '_' + str(self.roi_dn) + ':' + str(self.roi_up)]['data'] = NXdata(Z, [yi,xi]) except: try: self.tree.map2ddata['roi' + '_' + str(self.roi_dn) + ':' + str(self.roi_up)] = NXentry() self.tree.map2ddata['roi' + '_' + str(self.roi_dn) + ':' + str(self.roi_up)]['data'] = NXdata(Z, [yi,xi]) except: del self.tree.map2ddata['roi' + '_' + str(self.roi_dn) + ':' + str(self.roi_up)] self.tree.map2ddata['roi' + '_' + str(self.roi_dn) + ':' + str(self.roi_up)] = NXentry() self.tree.map2ddata['roi' + '_' + str(self.roi_dn) + ':' + str(self.roi_up)]['data'] = NXdata(Z, [yi,xi]) plt.figure() plt.contourf(X,Y,Z) plt.gca().invert_yaxis() plt.gca().invert_xaxis() plt.xlabel('x (mm)') plt.ylabel('y (mm)') plt.title("2D Contour Map") plt.colorbar() plt.show() return self.tree.map2ddata
def plot_xas(self): self.x1 = np.array(self.energy) self.y1 = np.array(self.entry['instrument/absorbed_beam'][self.signal]) try: self.tree.singleXas = NXroot(NXentry(NXdata(yi, xi))) except: self.tree.singleXas['entry/data'][self.signal] = NXfield(yi) self.tree.singleXas.oplot(xmin = min(self.x1), xmax=max(self.x1), ymin = min(self.y1), ymax = max(self.y1)) return x1, y1
def add(self, node): if isinstance(node, NXgroup): shell_names = self.get_shell_names(node) if shell_names: node.nxname = shell_names[0] if isinstance(node, NXroot): self[node.nxname] = node self[node.nxname]._file_modified = False elif isinstance(node, NXentry): group = NXroot(node) name = self.get_new_name() self[name] = group print("NeXpy: '%s' added to tree in '%s'" % (node.nxname, group.nxname)) else: group = NXroot(NXentry(node)) name = self.get_new_name() self[name] = group print("NeXpy: '%s' added to tree in '%s%s'" % (node.nxname, group.nxname, node.nxgroup.nxpath)) else: raise NeXusError("Only an NXgroup can be added to the tree")
def __init__(self, parent=None): super().__init__(parent) self.settings = NXSettings().settings self.configuration_file = NXroot() self.configuration_file['entry'] = NXentry() self.detectors = {} self.entries = {} self.setup_groups() self.setup_configuration() self.setup_analysis() self.setup_scan() self.setup_instrument() self.set_layout( self.directorybox('Choose Experiment Directory', default=False), self.configuration.grid(header=False), self.analysis.grid(header=False, title='Analysis Settings'), self.scan.grid(header=False, title='Scan Settings'), self.instrument.grid(header=False, title='Detector Settings')) self.set_title('New Configuration')
def __init__(self, exptitle, *items, **opts): self._entry = NXentry(*items, **opts) self._entry.FileName = string_('') self._entry.data = NXdata() self._entry.user1 = NXuser(role=string_('local_contact')) self._entry.user2 = NXuser(role=string_('experiment_team')) # TODO data will not written correctly !!! # look into NexusFile class, where the list of axes has to be written self._entry.monitor = NXmonitor() # axes='channel_number') self._entry.instrument = NXinstrument(platform=string_('Linux')) self._entry.instrument.name = string_('TOFTOF') self._entry.instrument.chopper = NXdisk_chopper() self._entry.instrument.detector = NXdetector() self._entry.sample = NXsample() self.root = NXroot(self._entry)
def save_fit(self): """Saves fit results to an NXentry""" self.read_parameters() entry = NXentry() entry['data'] = self.data for f in self.functions: entry[f.name] = self.get_model(f) parameters = NXparameters() for p in f.parameters: parameters[p.name] = NXfield(p.value, error=p.stderr, initial_value=p.init_value, min=str(p.min), max=str(p.max)) entry[f.name].insert(parameters) if self.fit is not None: entry['title'] = 'Fit Results' entry['fit'] = self.get_model() fit = NXparameters() fit.nfev = self.fit.result.nfev fit.ier = self.fit.result.ier fit.chisq = self.fit.result.chisqr fit.redchi = self.fit.result.redchi fit.message = self.fit.result.message fit.lmdif_message = self.fit.result.lmdif_message entry['statistics'] = fit else: entry['title'] = 'Fit Model' entry['model'] = self.get_model() if 'w0' not in self.tree.keys(): self.tree.add(NXroot(name='w0')) ind = [] for key in self.tree['w0'].keys(): try: if key.startswith('f'): ind.append(int(key[1:])) except ValueError: pass if not ind: ind = [0] name = 'f' + str(sorted(ind)[-1] + 1) self.tree['w0'][name] = entry
class ConfigurationDialog(NXDialog): def __init__(self, parent=None): super().__init__(parent) self.settings = NXSettings().settings self.configuration_file = NXroot() self.configuration_file['entry'] = NXentry() self.detectors = {} self.entries = {} self.setup_groups() self.setup_configuration() self.setup_analysis() self.setup_scan() self.setup_instrument() self.set_layout( self.directorybox('Choose Experiment Directory', default=False), self.configuration.grid(header=False), self.analysis.grid(header=False, title='Analysis Settings'), self.scan.grid(header=False, title='Scan Settings'), self.instrument.grid(header=False, title='Detector Settings')) self.set_title('New Configuration') def setup_groups(self): entry = self.configuration_file['entry'] entry['nxreduce'] = NXparameters() entry['instrument'] = NXinstrument() entry['instrument/monochromator'] = NXmonochromator() entry['instrument/goniometer'] = NXgoniometer() entry['instrument/detector'] = NXdetector() 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 (Å)') def setup_analysis(self): default = self.settings['nxreduce'] entry = self.configuration_file['entry'] entry['nxreduce/threshold'] = NXfield(default['threshold'], dtype=float) entry['nxreduce/monitor'] = NXfield(default['monitor']) entry['nxreduce/norm'] = NXfield(default['norm'], dtype=float) entry['nxreduce/first_frame'] = NXfield(default['first'], dtype=int) entry['nxreduce/last_frame'] = NXfield(default['last'], dtype=int) entry['nxreduce/radius'] = NXfield(default['radius'], dtype=float) self.analysis = GridParameters() self.analysis.add('threshold', entry['nxreduce/threshold'], 'Peak Threshold') self.analysis.add('first', entry['nxreduce/first_frame'], 'First Frame') self.analysis.add('last', entry['nxreduce/last_frame'], 'Last Frame') self.analysis.add('monitor', ['monitor1', 'monitor2'], 'Normalization Monitor') self.analysis['monitor'].value = default['monitor'] self.analysis.add('norm', entry['nxreduce/norm'], 'Normalization Value') self.analysis.add('radius', entry['nxreduce/radius'], 'Punch Radius (Å)') 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)') 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' 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 def get_detector(self): for detector in ALL_DETECTORS: if (ALL_DETECTORS[detector]().name == self.instrument['detector'].value): return ALL_DETECTORS[detector]() @property def positions(self): return int(self.instrument['positions'].value) @property def position(self): try: return int(self.entry_box.currentText()) except ValueError: return 1 def set_entries(self): self.entry_box = self.select_box( [str(i) for i in range(1, self.positions + 1)], slot=self.choose_position) self.entry_layout = self.make_layout( self.labels('Position', header=True), self.entry_box) self.add_layout(self.entry_layout) for position in range(1, self.positions + 1): self.setup_entry(position) self.add_layout(self.detectors[position].grid(header=False)) if position != 1: self.detectors[position].hide_grid() self.add_layout(self.close_buttons(save=True)) def choose_position(self): for i in self.detectors: self.detectors[i].hide_grid() if self.position in self.detectors: self.detectors[self.position].show_grid() def get_parameters(self): entry = self.configuration_file['entry'] entry['nxreduce/threshold'] = self.analysis['threshold'].value entry['nxreduce/first_frame'] = self.analysis['first'].value entry['nxreduce/last_frame'] = self.analysis['last'].value entry['nxreduce/monitor'] = self.analysis['monitor'].value entry['nxreduce/norm'] = self.analysis['norm'].value entry['nxreduce/radius'] = self.analysis['radius'].value entry['instrument/monochromator/wavelength'] = ( self.configuration['wavelength'].value) entry['instrument/monochromator/energy'] = ( 12.398419739640717 / self.configuration['wavelength'].value) detector = self.get_detector() entry['instrument/detector/description'] = detector.name entry['instrument/detector/distance'] = ( self.instrument['distance'].value) entry['instrument/detector/pixel_size'] = detector.pixel1 * 1000 entry['instrument/detector/pixel_size'].attrs['units'] = 'mm' entry['instrument/detector/pixel_mask'] = detector.mask entry['instrument/detector/shape'] = detector.shape entry['instrument/detector/yaw'] = 0.0 entry['instrument/detector/pitch'] = 0.0 entry['instrument/detector/roll'] = 0.0 for position in range(1, self.positions + 1): entry = self.configuration_file[f'f{position}'] entry['instrument'] = self.configuration_file['entry/instrument'] entry['instrument/detector/translation_x'] = ( self.detectors[position]['x'].value) entry['instrument/detector/translation_x'].attrs['units'] = 'mm' entry['instrument/detector/translation_y'] = ( self.detectors[position]['y'].value) entry['instrument/detector/translation_y'].attrs['units'] = 'mm' if self.scan['frame_rate'].value > 0.0: entry['instrument/detector/frame_time'] = ( 1.0 / self.scan['frame_rate'].value) else: entry['instrument/detector/frame_time'] = 0.1 entry['instrument/detector/frame_time'].attrs['units'] = 's' entry['instrument/goniometer/phi'] = self.scan['phi_start'].value entry['instrument/goniometer/phi'].attrs['step'] = ( self.scan['phi_step'].value) entry['instrument/goniometer/phi'].attrs['end'] = ( self.scan['phi_end'].value) entry['instrument/goniometer/chi'] = self.scan['chi'].value entry['instrument/goniometer/omega'] = ( self.detectors[position]['omega'].value) def accept(self): try: experiment_directory = self.get_directory() configuration_directory = os.path.join(experiment_directory, 'configurations') self.mainwindow.default_directory = experiment_directory self.get_parameters() self.configuration_file.save( os.path.join( configuration_directory, self.configuration['configuration'].value + '.nxs')) self.treeview.tree.load(self.configuration_file.nxfilename, 'rw') super().accept() except Exception as error: report_error("Defining New Configuration", error)
class ScanDialog(NXDialog): def __init__(self, parent=None): super().__init__(parent) self.config_file = None self.positions = 1 self.entries = {} self.settings = NXSettings() self.directory_box = self.directorybox('Choose Experiment Directory', self.choose_directory, default=False) self.sample_box = self.select_sample() self.sample_layout = self.make_layout( self.action_buttons(('Choose Sample', self.choose_sample)), self.sample_box) self.configuration_box = self.select_configuration() self.configuration_layout = self.make_layout( self.action_buttons(('Choose Experiment Configuration', self.choose_configuration)), self.configuration_box) self.scan_box = self.select_box(['1'], slot=self.choose_position) self.scan_layout = self.make_layout( self.labels('Position', header=True), self.scan_box) self.set_layout(self.directory_box, self.close_buttons(close=True)) self.set_title('New Scan') @property def configuration(self): return self.configuration_box.currentText() @property def sample(self): return self.sample_box.currentText().split('/')[0] @property def label(self): return self.sample_box.currentText().split('/')[1] @property def position(self): try: return int(self.scan_box.currentText()) except ValueError: return 1 def choose_directory(self): super().choose_directory() self.mainwindow.default_directory = self.get_directory() self.setup_directory() self.insert_layout(1, self.sample_layout) def setup_directory(self): self.sample_box.clear() samples = self.get_samples() for sample in samples: self.sample_box.addItem(sample) self.sample_box.adjustSize() configurations = self.get_configurations() self.configuration_box.clear() for configuration in configurations: self.configuration_box.addItem(configuration) def select_sample(self): return self.select_box(self.get_samples()) def get_samples(self): home_directory = self.get_directory() if os.path.exists(home_directory): sample_directories = [f for f in os.listdir(home_directory) if (not f.startswith('.') and os.path.isdir( os.path.join(home_directory, f)))] else: return [] samples = [] for sample_directory in sample_directories: label_directories = [ f for f in os.listdir( os.path.join(home_directory, sample_directory)) if os.path.isdir( os.path.join(home_directory, sample_directory, f))] for label_directory in label_directories: samples.append(os.path.join(sample_directory, label_directory)) return [sample.strip() for sample in samples] def choose_sample(self): self.insert_layout(2, self.configuration_layout) def select_configuration(self): return self.select_box(self.get_configurations()) def get_configurations(self): home_directory = self.get_directory() if (os.path.exists(home_directory) and 'configurations' in os.listdir(home_directory)): return sorted( [f for f in os.listdir( os.path.join(home_directory, 'configurations')) if f.endswith('.nxs')]) else: return [] def choose_configuration(self): home_directory = self.get_directory() config_file = os.path.join(home_directory, 'configurations', self.configuration) if os.path.exists(config_file): self.config_file = nxload(config_file) self.positions = len(self.config_file.entries) - 1 self.scan_box.clear() for position in range(1, self.positions+1): self.scan_box.addItem(f'{position}') self.scan_box.setCurrentIndex(0) self.copy_configuration() self.setup_scans() self.read_parameters() self.insert_layout(3, self.scan.grid(header=False)) self.insert_layout(4, self.scan_layout) for p in range(1, self.positions+1): self.insert_layout(p+4, self.entries[p].grid_layout) self.insert_layout(self.positions+5, self.action_buttons(('Make Scan File', self.make_scan))) 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) def setup_position(self, position): default = self.settings['nxrefine'] self.entries[position] = GridParameters() self.entries[position].add('chi', default['chi'], 'Chi (deg)') self.entries[position].add('omega', default['omega'], 'Omega (deg)') self.entries[position].add('x', default['x'], 'Translation - x (mm)') self.entries[position].add('y', default['y'], 'Translation - y (mm)') self.entries[position].add('linkfile', f'f{position:d}.h5', 'Detector Filename') self.entries[position].add( 'linkpath', '/entry/data/data', 'Detector Data Path') self.entries[position].grid(header=False) if position != 1: self.entries[position].hide_grid() def choose_position(self): for i in self.entries: self.entries[i].hide_grid() if self.position in self.entries: self.entries[self.position].show_grid() def copy_configuration(self): self.scan_file = NXroot() for entry in self.config_file.entries: self.scan_file[entry] = self.config_file[entry] def read_parameters(self): for position in range(1, self.positions+1): entry = self.scan_file[f'f{position:d}'] if 'instrument/goniometer/chi' in entry: self.entries[position]['chi'].value = ( entry['instrument/goniometer/chi']) if 'instrument/goniometer/omega' in entry: self.entries[position]['omega'].value = ( entry['instrument/goniometer/omega']) if 'instrument/detector/translation_x' in entry: self.entries[position]['x'].value = ( entry['instrument/detector/translation_x']) if 'instrument/detector/translation_y' in entry: self.entries[position]['y'].value = ( entry['instrument/detector/translation_y']) def get_parameters(self): entry = self.scan_file['entry'] if 'sample' not in entry: entry['sample'] = NXsample() entry['sample/name'] = self.sample entry['sample/label'] = self.label entry['sample/temperature'] = self.scan['temperature'].value entry['sample/temperature'].attrs['units'] = 'K' y_size, x_size = entry['instrument/detector/shape'].nxvalue scan = self.scan['scan'].value for position in range(1, self.positions+1): entry = self.scan_file[f'f{position:d}'] entry.makelink(self.scan_file['entry/sample']) phi_start = self.scan['phi_start'].value phi_end = self.scan['phi_end'].value phi_step = self.scan['phi_step'].value chi = self.entries[position]['chi'].value omega = self.entries[position]['omega'].value frame_rate = self.scan['frame_rate'].value if 'goniometer' not in entry['instrument']: entry['instrument/goniometer'] = NXgoniometer() entry['instrument/goniometer/phi'] = phi_start entry['instrument/goniometer/phi_set'] = phi_start entry['instrument/goniometer/phi'].attrs['step'] = phi_step entry['instrument/goniometer/phi'].attrs['end'] = phi_end entry['instrument/goniometer/chi'] = chi entry['instrument/goniometer/chi_set'] = chi entry['instrument/goniometer/omega'] = omega entry['instrument/goniometer/omega_set'] = omega if frame_rate > 0.0: entry['instrument/detector/frame_time'] = 1.0 / frame_rate linkpath = self.entries[position]['linkpath'].value linkfile = os.path.join( scan, self.entries[position]['linkfile'].value) entry['data'] = NXdata() entry['data'].nxsignal = NXlink(linkpath, linkfile) entry['data/x_pixel'] = np.arange(x_size, dtype=np.int32) entry['data/y_pixel'] = np.arange(y_size, dtype=np.int32) entry['data/frame_number'] = np.arange( (phi_end-phi_start)/phi_step, dtype=np.int32) entry['data'].nxaxes = [entry['data/frame_number'], entry['data/y_pixel'], entry['data/x_pixel']] def make_scan(self): home_directory = self.get_directory() self.mainwindow.default_directory = home_directory sample_directory = os.path.join(home_directory, self.sample) label_directory = os.path.join(home_directory, self.sample, self.label) scan_directory = os.path.join( label_directory, str(self.scan['scan'].value)) scan_name = self.sample+'_'+self.scan['scan'].value try: os.makedirs(scan_directory) except Exception: pass self.copy_configuration() self.get_parameters() self.scan_file.save(os.path.join(label_directory, scan_name+'.nxs')) self.treeview.tree.load(self.scan_file.nxfilename, 'r')
def copy_configuration(self): self.scan_file = NXroot() for entry in self.config_file.entries: self.scan_file[entry] = self.config_file[entry]