def plot(result): """ Runs different plotting functions one by one to demonstrate trivial data presentation tasks. """ fig = plt.figure(figsize=(12.80, 10.24)) plt.subplot(2, 2, 1) ba.plot_colormap(result) plt.title("Intensity as colormap") plt.subplot(2, 2, 2) plot_cropped_map(result) plt.title("Cropping") plt.subplot(2, 2, 3) plot_relative_difference(result) plt.title("Relative difference") plt.subplot(2, 2, 4) plot_slices(result) plt.title("Various slicing of 2D into 1D") save_to_file(result) plt.subplots_adjust(left=0.07, right=0.97, top=0.9, bottom=0.1, hspace=0.25) plt.show()
def run_simulation(): """ Run simulation one by one for every form factor from the list and plot results on a single canvas """ fig = plt.figure(figsize=(12.80, 10.24)) for nplot, ff in enumerate(formfactors): name = ff.__class__.__name__ name = name.replace("FormFactor", "") print("Generating intensity map in BA for '{0}'".format(name)) result = simulate(ff) # showing the result plt.subplot(5, 5, nplot + 1) plt.subplots_adjust(wspace=0.3, hspace=0.3) ba.plot_colormap(result, xlabel="", ylabel="", zlabel="", cmap='jet', aspect='auto') plt.tick_params(axis='both', which='major', labelsize=8) plt.tick_params(axis='both', which='minor', labelsize=6) plt.xticks(numpy.arange(phi_min, phi_max + 0.0001, 1.0)) plt.text(-0.1, 2.15, name, horizontalalignment='center', verticalalignment='center', fontsize=9)
def plot_relative_difference(hist): """ Creates noisy histogram made of original histogram, then creates and plots a relative difference histogram: (noisy-hist)/hist """ noisy = get_noisy_image(hist) diff = noisy.relativeDifferenceHistogram(hist) ba.plot_colormap(diff, zmin=1e-03, zmax=10)
def plot(result): plt.figure(figsize=(12.80, 10.24)) plt.subplot() ba.plot_colormap(result, units=ba.AxesUnits.QSPACE, title="Q-space", xlabel=r'$Q_{y} [1/nm]$', ylabel=r'$Q_{z} [1/nm]$', zlabel=None) plt.savefig('Fe_{id:03d}.png'.format(id=i))
def plot(result): plt.figure(figsize=(12.80, 10.24)) plt.subplot() ba.plot_colormap(result, units=ba.AxesUnits.QSPACE, title="Q-space", xlabel=r'$Q_{y} [1/nm]$', ylabel=r'$Q_{z} [1/nm]$', zmin=0.2, zmax=1e+5) plt.savefig('{id:03d}.jpg'.format(id=j))
def plot(results): """ Draw results of several simulations on canvas """ from matplotlib import pyplot as plt plt.figure(figsize=(12.80, 10.24)) for nplot, hist in results.items(): plt.subplot(2, 2, nplot+1) ba.plot_colormap(hist) plt.show()
def plot(results): """ Draw results of several simulations on canvas """ from matplotlib import pyplot as plt plt.figure(figsize=(12.80, 10.24)) for nplot, hist in results.items(): plt.subplot(2, 2, nplot + 1) ba.plot_colormap(hist, zlabel="", cmap='jet', aspect='auto') plt.tight_layout() plt.show()
def run_simulation(): """ Run simulation and plot results 4 times: for small and large cylinders, with and without integration """ fig = plt.figure(figsize=(12.80, 10.24)) # conditions to define cylinders scale factor and integration flag conditions = [{ 'title': "Small cylinders, analytical calculations", 'scale': 1, 'integration': False }, { 'title': "Small cylinders, Monte-Carlo integration", 'scale': 1, 'integration': True }, { 'title': "Large cylinders, analytical calculations", 'scale': 100, 'integration': False }, { 'title': "Large cylinders, Monte-Carlo integration", 'scale': 100, 'integration': True }] # run simulation 4 times and plot results for i_plot, condition in enumerate(conditions): scale = condition['scale'] integration_flag = condition['integration'] sample = get_sample(default_cylinder_radius * scale, default_cylinder_height * scale) simulation = get_simulation(integration_flag) simulation.setSample(sample) simulation.runSimulation() result = simulation.result() # plotting results plt.subplot(2, 2, i_plot + 1) plt.subplots_adjust(wspace=0.3, hspace=0.3) ba.plot_colormap(result, zmin=1e-2) plt.text(0.0, 2.1, conditions[i_plot]['title'], horizontalalignment='center', verticalalignment='center', fontsize=12)
def plot(result): """ Plots simulation results for different detectors. """ # set plotting parameters rcParams['image.cmap'] = 'jet' rcParams['image.aspect'] = 'auto' fig = plt.figure(figsize=(12.80, 10.24)) plt.subplot(2, 2, 1) # default units for rectangular detector are millimeters ba.plot_colormap(result, title="In default units", xlabel=r'$X_{mm}$', ylabel=r'$Y_{mm}$', zlabel=None) plt.subplot(2, 2, 2) ba.plot_colormap(result, units=ba.AxesUnits.NBINS, title="In number of bins", xlabel=r'$X_{nbins}$', ylabel=r'$Y_{nbins}$', zlabel=None) plt.subplot(2, 2, 3) ba.plot_colormap(result, units=ba.AxesUnits.DEGREES, title="In degs", xlabel=r'$\phi_f ^{\circ}$', ylabel=r'$\alpha_f ^{\circ}$', zlabel=None) plt.subplot(2, 2, 4) ba.plot_colormap(result, units=ba.AxesUnits.QSPACE, title="Q-space", xlabel=r'$Q_{y} [1/nm]$', ylabel=r'$Q_{z} [1/nm]$', zlabel=None) plt.subplots_adjust(left=0.07, right=0.97, top=0.9, bottom=0.1, hspace=0.25) plt.show()
def plot(results): """ Plots results of two simulations and their relative difference on one canvas """ from matplotlib import colors fig = plt.figure(figsize=(13.6, 5.12)) # showing result of spherical detector simulation plt.subplot(1, 3, 1) ba.plot_colormap(results['spherical'], title="Spherical detector", xlabel=r'$\phi_f ^{\circ}$', ylabel=r'$\alpha_f ^{\circ}$', zlabel="", cmap='jet', aspect='auto') # showing result of rectangular detector simulation plt.subplot(1, 3, 2) ba.plot_colormap(results['rectangular'], title="Rectangular detector", xlabel='X, mm', ylabel='Y, mm', zlabel="", cmap='jet', aspect='auto') # show relative difference between two plots (sph[i]-rect[i])/rect[i] # for every detector pixel sph_array = results['spherical'].array() rect_array = results['rectangular'].array() rel_diff = 2.0 * numpy.abs(sph_array - rect_array) / (sph_array + rect_array) plt.subplot(1, 3, 3) im = plt.imshow(rel_diff, norm=colors.LogNorm(1e-6, 1.0), aspect='auto', cmap='jet') cb = plt.colorbar(im, pad=0.025) plt.xlabel('X, bins', fontsize=14) plt.ylabel('Y, bins', fontsize=14) plt.title("Relative difference") plt.subplots_adjust(left=0.05, right=0.92, top=0.88, bottom=0.12) plt.tight_layout() plt.show()
def plot_dataset(fit_objective, canvas): for i_dataset in range(0, fit_objective.fitObjectCount()): real_data = fit_objective.experimentalData(i_dataset) simul_data = fit_objective.simulationResult(i_dataset) chi2_map = fit_objective.relativeDifference(i_dataset) zmax = real_data.histogram2d().getMaximum() plt.subplot(canvas[i_dataset * 3]) ba.plot_colormap(real_data, title="\"Real\" data - #" + str(i_dataset + 1), zmin=1.0, zmax=zmax, zlabel="") plt.subplot(canvas[1 + i_dataset * 3]) ba.plot_colormap(simul_data, title="Simulated data - #" + str(i_dataset + 1), zmin=1.0, zmax=zmax, zlabel="") plt.subplot(canvas[2 + i_dataset * 3]) ba.plot_colormap(chi2_map, title="Chi2 map - #" + str(i_dataset + 1), zmin=0.001, zmax=10.0, zlabel="")
def test_plot_utils(): simulation = SimulationBuilder().build_simulation() # simulation.runSimulation() result = simulation.result() fig = plt.figure(figsize=(12.80, 10.24)) plt.subplot(2, 2, 1) arr = np.zeros((5, 3)) ba.plot_array(arr) plt.subplot(2, 2, 2) arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]) ba.plot_array(arr) plt.subplot(2, 2, 3) ba.plot_colormap(result) plt.subplot(2, 2, 4) ba.plot_histogram(result.histogram2d()) fig.tight_layout()
def plot(results): """ Plots simulation results for different detectors. """ fig = plt.figure(figsize=(12.80, 10.24)) plt.subplot(2, 2, 1) # default units for rectangular detector are millimeters ba.plot_colormap(results['mm'], title="In default units", xlabel=r'$X_{mm}$', ylabel=r'$Y_{mm}$', zlabel=None) plt.subplot(2, 2, 2) ba.plot_colormap(results['nbins'], title="In number of bins", xlabel=r'$X_{nbins}$', ylabel=r'$Y_{nbins}$', zlabel=None) plt.subplot(2, 2, 3) ba.plot_colormap(results['deg'], title="In degs", xlabel=r'$\phi_f ^{\circ}$', ylabel=r'$\alpha_f ^{\circ}$', zlabel=None) plt.subplot(2, 2, 4) ba.plot_colormap(results['qyqz'], title="Q-space", xlabel=r'$Q_{y} [1/nm]$', ylabel=r'$Q_{z} [1/nm]$', zlabel=None) plt.subplots_adjust(left=0.07, right=0.97, top=0.9, bottom=0.1, hspace=0.25) plt.show()
def plot(self, params, iter, residual): self.reset() sim_data = self.m_fit_object.simulationResult() real_data = self.m_fit_object.experimentalData() diff = self.m_fit_object.relativeDifference() # same limits for both plots arr = real_data.array() zmax = np.amax(arr) zmin = zmax * 1e-6 self.make_subplot(1) ba.plot_colormap(real_data, title="Real data", zmin=zmin, zmax=zmax, zlabel='') self.make_subplot(2) ba.plot_colormap(sim_data, title="Simulated data", zmin=zmin, zmax=zmax, zlabel='') self.make_subplot(3) ba.plot_colormap(diff, title="Relative difference", zmin=1e-03, zmax=10, zlabel='') self.make_subplot(4) plt.title('Parameters') plt.axis('off') plt.text(0.01, 0.85, "Iterations {:d}".format(iter)) for index, p in enumerate(params): print(index, p) plt.text(0.01, 0.55 - index * 0.1, '{:30.30s}: {:6.3f}'.format(p, params[p].value)) plt.tight_layout() plt.pause(0.03)
def plot_simulation(result): fig = plt.figure(figsize=(12, 8)) ba.plot_colormap(result, zmin=100, zmax=1e+07, units=ba.AxesUnits.QSPACE, cmap="jet") fig.tight_layout() return fig
def plot_colormap(data, zmin=1e+03, zmax=1e+07, units=ba.AxesUnits.MM, zlabel="", cmap="jet", aspect="auto"): ba.plot_colormap(data, zmin=zmin, zmax=zmax, units=units, zlabel=zlabel, cmap=cmap, aspect=aspect)
def plot(self, fit_objective): Plotter.reset(self) real_data = fit_objective.experimentalData() sim_data = fit_objective.simulationResult() diff = fit_objective.absoluteDifference() self.make_subplot(1) # same limits for both plots arr = real_data.array() zmax = np.amax(arr) if self._zmax is None else self._zmax zmin = zmax * 1e-6 if self._zmin is None else self._zmin ba.plot_colormap(real_data, title="Experimental data", zmin=zmin, zmax=zmax, units=self._units, xlabel=self._xlabel, ylabel=self._ylabel, zlabel='', aspect=self._aspect) self.make_subplot(2) ba.plot_colormap(sim_data, title="Simulated data", zmin=zmin, zmax=zmax, units=self._units, xlabel=self._xlabel, ylabel=self._ylabel, zlabel='', aspect=self._aspect) self.make_subplot(3) ba.plot_colormap(diff, title="Difference", zmin=zmin, zmax=zmax, units=self._units, xlabel=self._xlabel, ylabel=self._ylabel, zlabel='', aspect=self._aspect) self.make_subplot(4) plt.title('Parameters') plt.axis('off') iteration_info = fit_objective.iterationInfo() plt.text( 0.01, 0.85, "Iterations " + '{:d}'.format(iteration_info.iterationCount())) plt.text(0.01, 0.75, "Chi2 " + '{:8.4f}'.format(iteration_info.chi2())) index = 0 params = iteration_info.parameterMap() for key in params: plt.text(0.01, 0.55 - index * 0.1, '{:30.30s}: {:6.3f}'.format(key, params[key])) index = index + 1 Plotter.plot(self)
def plot_update(self, fit_objective): self.fig.clf() real_data = fit_objective.experimentalData() sim_data = fit_objective.simulationResult() diff = fit_objective.relativeDifference() self.make_subplot(1) zmin = 0.1 zmax = 100 ba.plot_colormap(real_data, title="Experimental data", zmin=zmin, zmax=zmax, units=ba.AxesUnits.QSPACE, xlabel=None, ylabel=None, zlabel='', aspect=None) self.make_subplot(2) ba.plot_colormap(sim_data, title="Simulation result", zmin=zmin, zmax=zmax, units=ba.AxesUnits.QSPACE, xlabel=None, ylabel=None, zlabel='', aspect=None) self.make_subplot(3) ba.plot_colormap(diff, title="Relative difference", zmin=0.001, zmax=10.0, units=ba.AxesUnits.QSPACE, xlabel=None, ylabel=None, zlabel='', aspect=None) self.make_subplot(4) plt.title('Parameters') plt.axis('off') iteration_info = fit_objective.iterationInfo() plt.text( 0.01, 0.85, "Iterations " + '{:d}'.format(iteration_info.iterationCount())) plt.text(0.01, 0.75, "Chi2 " + '{:8.4f}'.format(iteration_info.chi2())) index = 0 params = iteration_info.parameterMap() for key in params: plt.text(0.01, 0.55 - index * 0.1, '{:30.30s}: {:6.3f}'.format(key, params[key])) index = index + 1 self.fig.tight_layout() plt.pause(0.03)
def run_fitting(i_img): # for this thesis just batch simulations, no fitting. # passing the simulation through the fitting mechanism # still useful for processing experimental and # simulation patterns simultaneously global first_run global batch_sim global init_radius global init_height global init_height_flattening_ratio global init_lattice_length global init_damping_length global init_disorder_parameter global init_beam_intensity if batch_sim == True: # setting the simulation parameters d_eff = 11.6 * (0.1 * (i_img - 11)) / 150 init_lattice_length = 2 * np.pi / (0.628 + 1.499 * math.exp(-d_eff / 3.31)) init_height = 1.519 + 1.367 * d_eff - 0.038 * (d_eff**2) init_radius = init_height / 3.1 init_height_flattening_ratio = 0.66 init_disorder_parameter = 0.25 init_damping_length = 30 * nm init_beam_intensity = 4.15e+09 real_data = load_real_data(i_img) fit_objective = ba.FitObjective() fit_objective.addSimulationAndData(get_simulation, real_data) fit_objective.initPrint(1) fit_objective.initPlot(1, PlotObserver( )) #plotting frequency on screen (increase if OpenGL error) params = ba.Parameters( ) #parameter limits only relevant for full fitting, otherwise ignored min_height = 0.1 max_height = 20 min_lattice_length = 0.1 max_lattice_length = 20 min_radius = 0.1 max_radius = 20 min_damping_length = 10 max_damping_length = 1000 min_disorder_parameter = 0.1 max_disorder_parameter = 0.5 min_beam_intensity = 1e+8 max_beam_intensity = 1e+12 params.add("radius", value=init_radius, min=min_radius, max=max_radius, step=0.1 * nm, vary=True) params.add("height", value=init_height, min=min_height, max=max_height, step=0.1 * nm, vary=True) params.add("height_flattening_ratio", value=init_height_flattening_ratio, min=0.55, max=0.75, step=0.01, vary=True) params.add("lattice_length", value=init_lattice_length, min=min_lattice_length, max=max_lattice_length, step=0.1 * nm, vary=True) params.add("damping_length", value=init_damping_length, min=min_damping_length, max=max_damping_length, step=10 * nm, vary=True) params.add("disorder_parameter", value=init_disorder_parameter, min=min_disorder_parameter, max=max_disorder_parameter, step=0.01, vary=True) params.add("beam_intensity", init_beam_intensity, min=min_beam_intensity, max=max_beam_intensity, vary=False) minimizer = ba.Minimizer() minimizer.setMinimizer("Test") # normal simulation (no fitting) #minimizer.setMinimizer("Minuit2", "Migrad", "MaxFunctionCalls=0;Strategy=2;") # minimizer for fitting result = minimizer.minimize(fit_objective.evaluate, params) # runs the simulation fit_objective.finalize(result) fig_name = output_folder + 'fitting_img_#32_' + repr(i_img) + '.png' plt.savefig(fig_name, dpi=500) plt.close(1) print("Fitting completed.") print("chi2:", result.minValue()) for fitPar in result.parameters(): print(fitPar.name(), fitPar.value, fitPar.error) experimental_data = fit_objective.experimentalData() simulation_data = fit_objective.simulationResult() difference = fit_objective.relativeDifference() zmin = 0.1 # range of the colormap zmax = 100 mpl.rcParams['image.cmap'] = 'jet' # saves figures in jet colormap plt.figure(2, figsize=(8, 6)) ba.plot_colormap(experimental_data, title="Experimental data", zmin=zmin, zmax=zmax, units=ba.AxesUnits.QSPACE, xlabel=None, ylabel=None, zlabel='', aspect=None) fig_name = output_folder + 'exp_data_#32_' + repr(i_img) + '_jet' + '.png' plt.savefig(fig_name, dpi=500) plt.close(2) plt.figure(3, figsize=(8, 6)) ba.plot_colormap(simulation_data, title="Simulation result", zmin=zmin, zmax=zmax, units=ba.AxesUnits.QSPACE, xlabel=None, ylabel=None, zlabel='', aspect=None) fig_name = output_folder + 'sim_data_#32_' + repr(i_img) + '_jet' + '.png' plt.savefig(fig_name, dpi=500) plt.close(3) mpl.rcParams[ 'image.cmap'] = 'nipy_spectral' #saves figures in spectral colormap plt.figure(4, figsize=(8, 6)) ba.plot_colormap(experimental_data, title="Experimental data", zmin=zmin, zmax=zmax, units=ba.AxesUnits.QSPACE, xlabel=None, ylabel=None, zlabel='', aspect=None) fig_name = output_folder + 'exp_data_#32_' + repr( i_img) + '_spectrum' + '.png' plt.savefig(fig_name, dpi=500) plt.close(4) plt.figure(5, figsize=(8, 6)) ba.plot_colormap(simulation_data, title="Simulation result", zmin=zmin, zmax=zmax, units=ba.AxesUnits.QSPACE, xlabel=None, ylabel=None, zlabel='', aspect=None) fig_name = output_folder + 'sim_data_#32_' + repr( i_img) + '_spectrum' + '.png' plt.savefig(fig_name, dpi=500) plt.close(5)
def plot_cropped_map(hist): """ Plot cropped version of intensity data """ crop = hist.crop(-1.0 * deg, 0.5 * deg, 1.0 * deg, 1.0 * deg) ba.plot_colormap(crop)
""" Returns an off-specular simulation with beam and detector defined. """ simulation = ba.OffSpecSimulation() simulation.setDetectorParameters(20, phi_f_min * deg, phi_f_max * deg, 200, alpha_f_min * deg, alpha_f_max * deg) # define the beam with alpha_i varied between alpha_i_min and alpha_i_max alpha_i_axis = ba.FixedBinAxis("alpha_i", 200, alpha_i_min * deg, alpha_i_max * deg) simulation.setBeamParameters(1.0 * angstrom, alpha_i_axis, 0.0 * deg) simulation.setBeamIntensity(1e9) return simulation def run_simulation(): """ Runs simulation and returns intensity map. """ sample = get_sample() simulation = get_simulation() simulation.setSample(sample) simulation.runSimulation() return simulation.getIntensityData() if __name__ == '__main__': result = run_simulation() ba.plot_colormap(result, xlabel=r'$\alpha_i ^{\circ}$') from matplotlib import pyplot as plt plt.show()
def plot(fontsize=16): """ Creates 4 plots: 2D experiment, 2D simulation, slice along Qz and slice along Qy """ plt.style.use('seaborn-talk') matplotlib.rcParams['xtick.labelsize'] = fontsize matplotlib.rcParams['ytick.labelsize'] = fontsize data = load_data() plt.figure(figsize=(22, 17)) zmin = 0.1 zmax = 2.0e+06 qz_slice = 0.4 qy_slice = 0.64 # ==================== # Experiment 2D # ==================== plt.subplot(2, 2, 1) ba.plot_colormap(data, units=ba.AxesUnits.QSPACE, zmin=zmin, zmax=zmax) plt.axhline(y=qz_slice, color='0.5', linestyle='--', linewidth=1) plt.axvline(x=qy_slice, color='0.5', linestyle='--', linewidth=1) plt.title("Experiment", fontsize=fontsize) # ax.tick_params(axis='both', which='major', labelsize=fontsize) # ==================== # Simulation 2D # ==================== result = run_simulation() axes_labels = ba.get_axes_labels(result, ba.AxesUnits.QSPACE) plt.subplot(2, 2, 2) ba.plot_colormap(result, units=ba.AxesUnits.QSPACE, zmin=zmin, zmax=zmax) plt.axhline(y=qz_slice, color='0.5', linestyle='--', linewidth=1) plt.axvline(x=qy_slice, color='0.5', linestyle='--', linewidth=1) plt.title("BornAgain simulation", fontsize=fontsize) # ==================== # projection along Qz # ==================== plt.subplot(2, 2, 3) exp_qz = data.histogram2d(ba.AxesUnits.QSPACE).projectionY(qy_slice) sim_qz = result.histogram2d(ba.AxesUnits.QSPACE).projectionY(qy_slice) plt.semilogy(exp_qz.getBinCenters(), exp_qz.getBinValues(), color='k', marker='.', markersize=5, linestyle='None', label="Experiment") plt.semilogy(sim_qz.getBinCenters(), sim_qz.getBinValues(), color='g', linewidth=2, label="Simulation") # plt.xlim(0.1, 1.21) # uncomment and edit to set x axis limits # plt.ylim(0.5, zmax) # uncomment and edit to set y axis limits plt.xlabel(axes_labels[1], fontsize=fontsize) plt.ylabel(r'$\mathrm{I(Q_z)}$, a.u.', fontsize=fontsize) plt.legend(fontsize=fontsize) plt.title(r"Slice along $Q_z$", fontsize=fontsize) # ===================== # projection along Qy # ===================== plt.subplot(2, 2, 4) exp_qy = data.histogram2d(ba.AxesUnits.QSPACE).projectionX(qz_slice) sim_qy = result.histogram2d(ba.AxesUnits.QSPACE).projectionX(qz_slice) plt.semilogy(exp_qy.getBinCenters(), exp_qy.getBinValues(), color='k', marker='.', markersize=5, linestyle='None', label="Experiment") plt.semilogy(sim_qy.getBinCenters(), sim_qy.getBinValues(), color='g', linewidth=2, label="Simulation") # plt.xlim(-0.81, 0.71) # uncomment and edit to set x axis limits # plt.ylim(0.5, zmax) # uncomment and edit to set y axis limits plt.xlabel(axes_labels[0], fontsize=fontsize) plt.ylabel(r'$\mathrm{I(Q_y)}$, a.u.', fontsize=fontsize) plt.legend(fontsize=fontsize) plt.title(r"Slice along $Q_y$", fontsize=fontsize) # plt.savefig("{}.png".format("my_meso")) # uncomment to save figure # uncomment to save slices to text files # np.savetxt("{}_slice_qz.txt".format("my_meso"), np.column_stack([sim_qz.getBinCenters(), sim_qz.getBinValues()])) # np.savetxt("{}_slice_qy.txt".format("my_meso"), np.column_stack([sim_qy.getBinCenters(), sim_qy.getBinValues()])) plt.show()