def plot_xas(self): self.singleXas = NXdata(self.signal_s, self.energy) self.singleXas.plot(xmin=min(self.energy), xmax=max(self.energy), ymin=min(self.signal_s), ymax=max(self.signal_s)) return
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 initialize_data(self, data): if isinstance(data, NXdata): if len(data.nxsignal.shape) > 1: raise NeXusError("Fitting only possible on one-dimensional arrays") fit_data = NXdata(data.nxsignal, data.nxaxes, title=data.nxtitle) if data.nxerrors: fit_data.errors = data.nxerrors return fit_data else: raise NeXusError("Must be an NXdata group")
def initialize_data(self, data): if isinstance(data, NXdata): if len(data.nxsignal.shape) > 1: raise NeXusError( "Fitting only possible on one-dimensional arrays") fit_data = NXdata(data.nxsignal, data.nxaxes, title=data.nxtitle) if data.nxerrors: fit_data.errors = data.nxerrors return fit_data else: raise NeXusError("Must be an NXdata group")
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 mfit(data, xmin, xmax, ymin, ymax, dy): fs = [Function('Linear', linear), Function('Gaussian', gaussian)] x = np.linspace(xmin, xmax, 200) ylo, yhi = ymin, ymin + dy while yhi < ymax: slab = data[ylo:yhi, xmin:xmax] diff = slab.nxsignal.shape[0] cut = slab.sum([0]) cut.plot() fit = Fit(cut, fs, use_errors=True) y = np.array(fit.y) for f in fs: f.guess_parameters(fit.x, y) y = y - f.function_values(fit.x) fit.fit_data() NXdata(fit.get_model(x), x).oplot('-') if raw_input('Keep? [y,N] ') == 'y': data[ylo:yhi, xmin:xmax] = slab - fit.get_model(f=fs[1]) / diff ylo = yhi yhi = ylo + dy return data
def save(self, x=None): """Save the fit results in a NXprocess group. Parameters ---------- x : ndarray, optional x-values at which to calculate the model. Defaults to `self.x` Returns ------- group : NXprocess NXprocess group that contains the data, models and parameters. """ group = NXprocess(program='lmfit', version=__version__) group['data'] = self.data for f in self.functions: group[f.name] = NXdata(NXfield(self.get_model(x, f), name='model'), NXfield(x, name=self.data.nxaxes[0].nxname), title='Fit Results') 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)) group[f.name]['parameters'] = parameters group['title'] = 'Fit Results' group['fit'] = NXdata(NXfield(self.get_model(x), name='model'), NXfield(x, name=self.data.nxaxes[0].nxname), title='Fit Results') if self.result is not None: fit = NXparameters() fit.nfev = self.result.nfev fit.chisq = self.result.chisqr fit.redchi = self.result.redchi fit.message = self.result.message group['statistics'] = fit group.note = NXnote( self.fit.result.message, f'Chi^2 = {self.fit.result.chisqr}\n' f'Reduced Chi^2 = {self.fit.result.redchi}\n' f'No. of Function Evaluations = {self.fit.result.nfev}\n' f'No. of Variables = {self.fit.result.nvarys}\n' f'No. of Data Points = {self.fit.result.ndata}\n' f'No. of Degrees of Freedom = {self.fit.result.nfree}\n' f'{self.fit.fit_report()}') return group
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 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 plot_map(self): self.x1 = np.array(self.entry['sample/positioner'][self.axis1]) self.y1 = np.array(self.entry['sample/positioner'][self.axis2]) self.sdd = np.array(self.entry['instrument/fluorescence'][self.signal]) row, col = np.shape(self.sdd) self.z1 = np.zeros(row) for i in range(0, row): self.z1[i] = self.sdd[i, self.roi_dn:self.roi_up].sum(axis=0) self.ylen = self.getylen() if self.ylen: self.xlen = len(self.entry['sample/positioner'][self.axis1])/self.ylen else: self.ylen = 100 self.xlen = 100 X,Y,Z,xi,yi = self.grid(self.x1, self.y1, self.z1, self.xlen, self.ylen) self.data = NXdata(Z, [yi, xi]) self.data.plot(xmin = min(self.x1), xmax=max(self.x1), ymin = min(self.y1), ymax = max(self.y1), zmin = min(self.z1), zmax = max(self.z1)) return X, Y, Z, xi, yi
def get_model(self, f=None): self.read_parameters() fit = Fit(self.data, self.functions) if self.plot_checkbox.isChecked(): x = fit.x else: x = np.linspace(float(self.plot_minbox.text()), float(self.plot_maxbox.text()), 1001) return NXdata(NXfield(fit.get_model(x, f), name='model'), NXfield(x, name=fit.data.nxaxes[0].nxname), title='Fit Results')
class XasDialog(BaseDialog): def __init__(self, parent=None): super(XasDialog, self).__init__(parent) self.select_entry() dets_list = {} self.dets = self.entry['instrument/absorbed_beam'] self.signal_combo = self.select_box(self.dets, default='sdd3_2', slot=self.plot_xas) self.lab_sig = self.labels('Signal :', align='left') self.set_layout(self.entry_layout, self.lab_sig, self.signal_combo, self.close_buttons()) self.set_title('Plot Single XAS') @property def signal_s(self): return np.array(self.entry.instrument.absorbed_beam[ self.signal_combo.currentText()]) @property def energy(self): return np.array(self.entry.instrument.monochromator.en) def plot_xas(self): self.singleXas = NXdata(self.signal_s, self.energy) self.singleXas.plot(xmin=min(self.energy), xmax=max(self.energy), ymin=min(self.signal_s), ymax=max(self.signal_s)) return def accept(self): try: self.plot_xas super(XasDialog, self).accept() except NeXusError as error: report_error("Plot Single XAS", error) super(XasDialog, self).reject()
def load_image(filename): if os.path.splitext( filename.lower())[1] in ['.png', '.jpg', '.jpeg', '.gif']: from matplotlib.image import imread im = imread(filename) z = NXfield(im, name='z') y = NXfield(range(z.shape[0]), name='y') x = NXfield(range(z.shape[1]), name='x') if z.ndim > 2: rgba = NXfield(range(z.shape[2]), name='rgba') if len(rgba) == 3: z.interpretation = 'rgb-image' elif len(rgba) == 4: z.interpretation = 'rgba-image' data = NXdata(z, (y, x, rgba)) else: data = NXdata(z, (y, x)) else: try: im = fabio.open(filename) except Exception as error: if fabio: raise NeXusError("Unable to open image") else: raise NeXusError( "Unable to open image. Please install the 'fabio' module") z = NXfield(im.data, name='z') y = NXfield(range(z.shape[0]), name='y') x = NXfield(range(z.shape[1]), name='x') data = NXdata(z, (y, x)) if im.header: header = NXcollection() for k, v in im.header.items(): if v or v == 0: header[k] = v data.header = header if im.getclassname() == 'CbfImage': note = NXnote(type='text/plain', file_name=filename) note.data = im.header.pop('_array_data.header_contents', '') note.description = im.header.pop('_array_data.header_convention', '') data.CBF_header = note data.title = filename return data
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 convert_QE(entry, dQ, dE): """Convert S(phi,eps) to S(Q,eps)""" az = entry.data.azimuthal.nxdata[:] pol = entry.data.polar.nxdata[:] pol, en = centers(entry.data.nxsignal, entry.data.nxaxes) data = entry.data.data.nxdata[:] errors = entry.data.errors.nxdata[:] Ei = entry.instrument.monochromator.incident_energy.nxdata Q = np.zeros((len(pol), len(en))) E = np.zeros((len(pol), len(en))) for i in range(0, len(pol)): for j in range(0, len(en)): Q[i][j] = np.sqrt((2*Ei - en[j] - 2*np.sqrt(Ei*(Ei-en[j])) * np.cos(pol[i]*np.pi/180.0))/2.0721) E[i][j] = en[j] s = Q.shape Qin = Q.reshape(s[0]*s[1]) Ein = E.reshape(s[0]*s[1]) datain = data.reshape(s[0]*s[1]) 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) histe, hbin = np.histogramdd( (Ein, Qin), bins=(Eb, Qb), weights=errorsin * errorsin) histe = histe**0.5 Ib = NXfield(hist/norm, name='S(Q,E)') err = histe/norm Qb = NXfield(Qb[:-1]+dQ/2., name='Q') Eb = NXfield(Eb[:-1]+dE/2., name='E') return NXdata(Ib, (Eb, Qb), errors=NXfield(err))
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 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_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=f'{self.refine.name} Peak Angles'), xmax=self.get_polar_max()) except NeXusError as error: report_error('Plotting Lattice', error)
def export_peaks(self): peaks = list( zip(*[ p for p in self.table_model.peak_list if p[-1] < self.get_hkl_tolerance() ])) idx = NXfield(peaks[0], name='index') x = NXfield(peaks[1], name='x') y = NXfield(peaks[2], name='y') z = NXfield(peaks[3], name='z') pol = NXfield(peaks[4], name='polar_angle', units='degree') azi = NXfield(peaks[5], name='azimuthal_angle', units='degree') polarization = self.refine.get_polarization() intensity = NXfield(peaks[6] / polarization[y, x], name='intensity') H = NXfield(peaks[7], name='H', units='rlu') K = NXfield(peaks[8], name='K', units='rlu') L = NXfield(peaks[9], name='L', units='rlu') diff = NXfield(peaks[10], name='diff') peaks_data = NXdata(intensity, idx, diff, H, K, L, pol, azi, x, y, z) export_dialog = ExportDialog(peaks_data, parent=self) export_dialog.show()
def rebin2D(self, spw, phi, psi, omega, dphi, dpsi): rot = np.linspace(np.round(phi.min() - 0.5 * dphi, 2), np.round(phi.max() + 0.5 * dphi, 2), np.round(phi.ptp() / dphi)).astype(np.float32) tilt = np.linspace(np.round(psi.min() - 0.5 * dpsi, 2), np.round(psi.max() + 0.5 * dpsi, 2), np.round(psi.ptp() / dpsi)).astype(np.float32) en = 0.5*(omega[1:]+omega[:-1]) data = NXfield(name='data', dtype='float32', shape=[ rot.size-1, tilt.size-1, omega.size-1]) rotation_angle = NXfield(rot, name='rotation_angle', units='degree') tilt_angle = NXfield(tilt, name='tilt_angle', units='degree') energy_transfer = NXfield(omega, name='energy_transfer', units='meV') pixels = np.array(zip(np.repeat(phi, en.size), np.repeat( psi, en.size), np.tile(en, phi.size))) hist, edges = np.histogramdd( pixels, [rot, tilt, omega], weights=spw.reshape(spw.size)) return NXdata( NXfield(hist, name='intensity'), (rotation_angle, tilt_angle, energy_transfer))
def plot_cake(self): if 'Cake Plot' in plotviews: plotview = plotviews['Cake Plot'] else: plotview = NXPlotView('Cake Plot') if not self.is_calibrated: raise NeXusError('No refinement performed') res = self.cake_geometry.integrate2d(self.counts, 1024, 1024, method='csr', unit='2th_deg', correctSolidAngle=True) self.cake_data = NXdata(res[0], (NXfield(res[2], name='azimumthal_angle'), NXfield(res[1], name='polar_angle'))) self.cake_data['title'] = 'Cake Plot' plotview.plot(self.cake_data, log=True) wavelength = self.parameters['wavelength'].value polar_angles = [2 * np.degrees(np.arcsin(wavelength/(2*d))) for d in self.calibrant.dSpacing] plotview.vlines([polar_angle for polar_angle in polar_angles if polar_angle < plotview.xaxis.max], linestyle=':', color='r')
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
class MapDialog(BaseDialog): def __init__(self, parent=None): super(MapDialog, self).__init__(parent) self.select_entry() dets_list = {} self.dets = self.entry['instrument/fluorescence'] self.signal_combo = self.select_box(self.dets, default='sdd3') self.axes = self.entry['sample/positioner'] self.axis1_combo = self.select_box(self.axes, default='hex_xp') self.axis2_combo = self.select_box(self.axes, default='hex_yp') roi_peak_layout = QtGui.QHBoxLayout() roi_peak_layout.addWidget(QtGui.QLabel('ROI Peak')) self.roi_peak = QtGui.QSlider(Qt.Horizontal) self.pLabel = QtGui.QLineEdit() self.pLabel.setText('800') self.pLabel.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)) self.pLabel.setAlignment(Qt.AlignRight) self.roi_peak.setMinimum(0) self.roi_peak.setMaximum(256) self.roi_peak.setValue(80) self.roi_peak.setTickPosition(QtGui.QSlider.TicksBelow) self.roi_peak.setTickInterval(1) roi_peak_layout.addWidget(self.roi_peak) self.roi_peak.valueChanged.connect(self.setRoi) self.pLabel.returnPressed.connect(self.setRoi2) self.pUnits = QtGui.QLabel('eV') roi_peak_layout.addWidget(self.pLabel) roi_peak_layout.addWidget(self.pUnits) roi_width_layout = QtGui.QHBoxLayout() roi_width_layout.addWidget(QtGui.QLabel('ROI Width')) self.roi_width = QtGui.QSlider(Qt.Horizontal) self.wLabel = QtGui.QLineEdit() self.wLabel.setText('200') self.wLabel.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)) self.wLabel.setAlignment(Qt.AlignRight) self.roi_width.setMinimum(2) self.roi_width.setMaximum(100) self.roi_width.setValue(20) self.roi_width.setTickPosition(QtGui.QSlider.TicksBelow) self.roi_peak.setTickInterval(1) roi_width_layout.addWidget(self.roi_width) self.roi_width.valueChanged.connect(self.setRoi) self.wLabel.returnPressed.connect(self.setRoi2) self.signal_combo.activated.connect(self.setRoi) self.axis1_combo.activated.connect(self.setRoi) self.axis2_combo.activated.connect(self.setRoi) self.entry_box.activated.connect(self.setRoi) self.wUnits = QtGui.QLabel('eV') roi_width_layout.addWidget(self.wLabel) roi_width_layout.addWidget(self.wUnits) lab_sig_layout = QtGui.QHBoxLayout() self.lab_sig = self.labels('Detector :', align='left') lab_sig_layout.addLayout(self.lab_sig) lab_sig_layout.addWidget(self.signal_combo) lab_sig_layout.addStretch() lab_axis1_layout = QtGui.QHBoxLayout() self.lab_axis1 = self.labels('X-Axis :', align='left') lab_axis1_layout.addLayout(self.lab_axis1) lab_axis1_layout.addWidget(self.axis1_combo) lab_axis1_layout.addStretch() lab_axis2_layout = QtGui.QHBoxLayout() self.lab_axis2 = self.labels('Y-Axis :', align='left') lab_axis2_layout.addLayout(self.lab_axis2) lab_axis2_layout.addWidget(self.axis2_combo) lab_axis2_layout.addStretch() self.set_layout(self.entry_layout, lab_sig_layout, lab_axis1_layout, lab_axis2_layout, roi_peak_layout, roi_width_layout, self.close_buttons()) self.set_title('Convert to 2D map') @property def signal(self): return self.signal_combo.currentText() @property def axis1(self): return self.axis1_combo.currentText() @property def axis2(self): return self.axis2_combo.currentText() def get_pLabel(self): value = int(self.pLabel.text()) value = value/10 return value def get_wLabel(self): value = int(self.wLabel.text()) value = value/10 return value @property def roi_up(self): up = self.peak + self.width/2 if up > 256: return 256 return up @property def roi_dn(self): dn = self.peak - self.width/2 if dn < 0: return 0 return dn def roi_peak_label(self): self.roi_peak.setValue(self.peak) self.pLabel.setText(str(self.peak) + '0') return self.pLabel def roi_width_label(self): self.roi_width.setValue(self.width) self.wLabel.setText(str(self.width) + '0') return self.wLabel def setRoi2(self): self.roi_width.setValue(self.get_wLabel()) self.roi_peak.setValue(self.get_pLabel()) return def setRoi(self): self.peak = self.roi_peak.value() self.width = self.roi_width.value() self.roi_width_label() self.roi_peak_label() self.plot_map() return self.roi_dn, self.roi_up def getylen(self): command = self.entry['command'] if str(command).split(" ")[0] == "cmesh": str_n = str(command).split(" ")[8] num = int(str_n) return num else: return False def grid(self, x, y, z, resX, resY): shift = 0.5 x_ad = x xi = linspace(min(x), max(x), resX) yi = linspace(min(y), max(y), resY) for i in range(1, len(x)): x_ad[i] = x[i] + shift*(x[i] - x[i-1]) Z = griddata(x_ad, y, z, xi, yi, interp='linear') X, Y = meshgrid(xi, yi) return X, Y, Z, xi, yi def plot_map(self): self.x1 = np.array(self.entry['sample/positioner'][self.axis1]) self.y1 = np.array(self.entry['sample/positioner'][self.axis2]) self.sdd = np.array(self.entry['instrument/fluorescence'][self.signal]) row, col = np.shape(self.sdd) self.z1 = np.zeros(row) for i in range(0, row): self.z1[i] = self.sdd[i, self.roi_dn:self.roi_up].sum(axis=0) self.ylen = self.getylen() if self.ylen: self.xlen = len(self.entry['sample/positioner'][self.axis1])/self.ylen else: self.ylen = 100 self.xlen = 100 X,Y,Z,xi,yi = self.grid(self.x1, self.y1, self.z1, self.xlen, self.ylen) self.data = NXdata(Z, [yi, xi]) self.data.plot(xmin = min(self.x1), xmax=max(self.x1), ymin = min(self.y1), ymax = max(self.y1), zmin = min(self.z1), zmax = max(self.z1)) return X, Y, Z, xi, yi 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 accept(self): try: self.save_map() super(MapDialog, self).accept() except NeXusError as error: report_error("Converting 2D map", error) super(MapDialog, self).reject()
def plot_mask(self): self.plotview = NXPlotView('3D Mask') self.plotview.plot( NXdata(self.mask, self.reduce.data.nxaxes, title=f"3D Mask: {self.reduce.name}"))
def convert_QE(self): """Convert S(phi,eps) to S(Q,eps)""" self.read_parameters() Ei = self.Ei dQ = self.dQ dE = self.dE signal = self.entry['data'].nxsignal pol = centers(self.entry['data/polar_angle'], signal.shape[0]) tof = centers(self.entry['data/time_of_flight'], signal.shape[1]) en = self.convert_tof(tof) idx_max = min(np.where(np.abs(en - 0.75 * Ei) < 0.1)[0]) en = en[:idx_max] data = signal.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 Ib = 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(Ib, (Eb, Qb)) if self.entry.data.nxerrors: result.errors = NXfield(err) return result
def accept(self): data = NXdata(self.signal, self.get_axes(), title=self.signal.nxtitle) data.plot(fmt=self.fmt) super(PlotDialog, self).accept()
def convert_QE(self): """Convert S(phi,eps) to S(Q,eps)""" self.read_parameters() entry = self.root['entry'] Ei = self.Ei dQ = self.dQ dE = self.dE pol, tof = centers(entry.data.nxsignal, 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 = entry.data.nxsignal.nxdata[:,:idx_max] if entry.data.nxerrors: errors = 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)): for j in range(0,len(en)): Q[i,j] = np.sqrt((2*Ei - en[j] - 2*np.sqrt(Ei*(Ei-en[j])) * np.cos(pol[i]*np.pi/180.0))/2.0721) E[i,j]=en[j] 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 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 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 entry.data.nxerrors: result.errors = NXfield(err) return result
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