def get_data(self): prefix = self.get_prefix() if prefix: self.import_file = prefix else: self.import_file = self.get_directory() filenames = self.get_files() try: import fabio except ImportError: raise NeXusError("Please install the 'fabio' module") im = self.read_image(filenames[0]) v0 = im.data x = NXfield(range(v0.shape[1]), dtype=np.uint16, name='x') y = NXfield(range(v0.shape[0]), dtype=np.uint16, name='y') z = NXfield(range(1, len(filenames)+1), dtype=np.uint16, name='z') v = NXfield(shape=(len(filenames), v0.shape[0], v0.shape[1]), dtype=v0.dtype, name='v') v[0] = v0 if v._memfile: chunk_size = v._memfile['data'].chunks[0] else: chunk_size = v.shape[0]/10 self.progress_bar.setVisible(True) self.progress_bar.setRange(0, len(filenames)) for i in range(0, len(filenames), chunk_size): try: files = [] for j in range(i, i+chunk_size): files.append(filenames[j]) self.progress_bar.setValue(j) self.update_progress() v[i:i+chunk_size, :, :] = self.read_images(files) except IndexError as error: pass global maximum v.maximum = maximum if im.getclassname() == 'CbfImage': note = NXnote(type='text/plain', file_name=self.import_file) note.data = im.header.pop('_array_data.header_contents', '') note.description = im.header.pop( '_array_data.header_convention', '') else: note = None header = NXcollection() for key, value in im.header.items(): header[key] = value if note: return NXentry( NXdata( v, (z, y, x), CBF_header=note, header=header)) else: return NXentry(NXdata(v, (z, y, x), header=header))
def fix_spe(spe_file): entry = NXentry() entry.title = spe_file.nxname entry.incident_energy = spe_file['data/NXSPE_info/fixed_energy'] entry.data = spe_file.data.data entry.data.error.rename('errors') s = raw_input("Emin Emax Phimin Phimax dPhi: ") xmin, xmax, ymin, ymax, dy = [float(i) for i in s.split(' ')] mfit(entry.data, xmin, xmax, ymin, ymax, dy) return entry
def NXspectrum(self, eps=None, sigma=None, T=None, Hx=None, Hz=None): """Returns the neutron scattering cross section as a NXentry group""" from nexusformat.nexus import NXfield, NXentry, NXsample, NXdata if T is None: T = self.T S = self.spectrum(eps, sigma, T, Hx, Hz) entry = NXentry() entry.title = "Crystal Field Spectra for %s at %s K" % (self.title, T) entry.sample = NXsample() entry.sample.temperature = T entry.sample.temperature.units = "K" entry.data = NXdata(NXfield(S, name="intensity", units="mb/sr/meV"), NXfield(eps, name="energy_transfer", units="meV")) return entry
def get_data(self): prefix = self.get_prefix() if prefix: self.import_file = prefix else: self.import_file = self.get_directory() filenames = self.get_files() v0 = self.read_image(filenames[0]) x = NXfield(range(v0.shape[1]), dtype=np.uint16, name='x') y = NXfield(range(v0.shape[0]), dtype=np.uint16, name='y') z = NXfield(range(1, len(filenames) + 1), dtype=np.uint16, name='z') v = NXfield(shape=(len(filenames), v0.shape[0], v0.shape[1]), dtype=v0.dtype, name='v') v[0] = v0 if v._memfile: chunk_size = v._memfile['data'].chunks[0] else: chunk_size = v.shape[0] / 10 self.progress_bar.setVisible(True) self.progress_bar.setRange(0, len(filenames)) for i in range(0, len(filenames)): try: files = [] for j in range(i, i + chunk_size): files.append(filenames[j]) self.progress_bar.setValue(j) self.update_progress() v[i:i + chunk_size, :, :] = self.read_images(files) except IndexError as error: pass global maximum v.maximum = maximum return NXentry(NXdata(v, (z, y, x)))
def get_nxspe(self): spe_file = nxload(self.import_file) entry = NXentry() entry.title = self.get_title() Ei = self.get_energy() if Ei and Ei > 0.0: entry.instrument = NXinstrument() entry.instrument.monochromator = NXmonochromator( NXfield(Ei, name="incident_energy", units="meV")) entry.data = spe_file.NXentry[0].data entry.data.nxsignal = entry.data.data if 'energy' in entry.data.entries: entry.data.energy.rename('energy_transfer') entry.data.nxaxes = [entry.data.polar, entry.data.energy_transfer] if 'error' in entry.data.entries: entry.data.error.rename('errors') return entry
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 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 get_data(self): self.import_file = self.get_filename() if not self.import_file: raise NeXusError("No file specified") try: import tifffile as TIFF except ImportError: raise NeXusError("Please install the 'tifffile' module") im = TIFF.imread(self.import_file) z = NXfield(im, name='z') y = NXfield(np.arange(z.shape[0], dtype=float), name='y') x = NXfield(np.arange(z.shape[1], dtype=float), name='x') return NXentry(NXdata(z, (y, x)))
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 get_data(self): group = NXgroup(name=self.groupbox.text()) group.nxclass = self.groupcombo.selected for i, col in enumerate( [c for c in self.data if self.data[c]['signal'] != 'exclude']): name = self.data[col]['name'] group[name] = NXfield(self.data[col]['data'], dtype=self.data[col]['dtype']) if self.header and name != self.headers[i]: group[name].long_name = self.headers[i] if isinstance(group, NXdata): if self.data[col]['signal'] == 'signal': group.nxsignal = group[name] elif self.data[col]['signal'] == 'axis': group.nxaxes = [group[name]] elif self.data[col]['signal'] == 'signal': group.nxerrors = group[name] return NXentry(group)
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
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 NXchi(self, T=None): """Returns the susceptibility as a NeXus NXentry""" from nexusformat.nexus import NXfield, NXentry, NXdata ChiC_zz, ChiC_xx, ChiV_zz, ChiV_xx = self.chi(T) entry = NXentry() entry.title = self.title temperature = NXfield(T, name="temperature") temperature.units = "K" chi = NXfield(ChiC_zz + ChiV_zz + 2 * (ChiC_xx + ChiV_xx), name="chi") entry.chi = NXdata(chi, temperature) entry.chi.title = "Susceptibility of %s" % self.title entry.invchi = NXdata(1 / chi, temperature) entry.invchi.title = "Inverse Susceptibility of %s" % self.title entry.chiz = NXdata(ChiC_zz + ChiV_zz, temperature) entry.chiz.title = "Susceptibility of %s (z-axis)" % self.title entry.chix = NXdata(ChiC_xx + ChiV_xx, temperature) entry.chix.title = "Susceptibility of %s (x-axis)" % self.title return entry
def get_data(self): return NXentry()
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 get_spe(self, phxfile=None): entry = NXentry() phi, omega, spw, errors = readspe(self.get_filename()) if phxfile: theta, phi, dtheta, dpsi = readphx(phxfile) phip, psi = angles(theta, phi) instrument = NXinstrument(NXdetector()) instrument.detector.polar_angle = NXfield(theta, units="degrees") Ei = self.get_energy() if Ei and Ei > 0.0: instrument.monochromator = NXmonochromator( NXfield(Ei, name="incident_energy", units="meV")) if phi.ptp() > 1.0: # i.e., the azimuthal angle is specified instrument.detector.azimuthal_angle = NXfield( phi, units="degrees") instrument.detector.rotation_angle = NXfield( phip, units="degrees") instrument.detector.tilt_angle = NXfield(psi, units="degrees") data = NXdata( NXfield( spw, name="intensity", long_name="Neutron Intensity"), ( NXfield( np.arange(1, len(theta) + 1), name="spectrum_index", long_name="Spectrum Index"), NXfield( omega, name="energy_transfer", units="meV", long_name="Energy Transfer")), errors=NXfield( np.sqrt(errors), name="errors", long_name="Errors")) if np.median(dtheta) > 0.0 and np.median(dpsi) > 0.0: data2D = rebin2D( spw, phip, psi, omega, np.median(dtheta), np.median(dpsi)) return NXentry(instrument, data, data2D=data2D) else: return NXentry(instrument, data) else: phi = np.zeros(theta.size+1) phi[:-1] = theta - 0.5*dtheta phi[-1] = theta[-1] + 0.5*dtheta[-1] data = NXdata( NXfield( spw, name="intensity", long_name="Neutron Intensity"), ( NXfield( phi, name="polar_angle", long_name="Polar Angle", units="degrees"), NXfield( omega, name="energy_transfer", units="meV", long_name="Energy Transfer")), errors=NXfield( np.sqrt(errors), name="errors", long_name="Errors")) return NXentry(instrument, data) else: Ei = self.get_energy() if Ei and Ei > 0.0: entry = NXentry( NXinstrument( NXmonochromator( NXfield( Ei, name="incident_energy", units="meV")))) else: entry = NXentry() if phi.ptp() > 1.0: entry.data = NXdata( NXfield(spw, name="intensity", long_name="Neutron Intensity"), (NXfield(phi, name="polar_angle", units="degrees", long_name="Polar Angle"), NXfield(omega, name="energy_transfer", units="meV", long_name="Energy Transfer")), errors=NXfield(np.sqrt(errors), name="errors", long_name="Errors")) else: entry.data = NXdata( NXfield(spw, name="intensity", long_name="Neutron Intensity"), (NXfield(np.arange(1, len(phi)+1), name="spectrum_index", long_name="Spectrum Index"), NXfield(omega, name="energy_transfer", units="meV", long_name="Energy Transfer")), errors=NXfield(np.sqrt(errors), name="errors", long_name="Errors")) return entry