def analytical_moment_PBE(x_max, x_min, nodes, t_min, t_max, delta_t, moment=0, which_selection_function='Linear', which_disrtibution='OneLargeParticle'): x, x_node_boundaries, delta_x = GridX(x_min, x_max, nodes).UniformLogarithmic() timesteps = (t_max - t_min) / delta_t time = np.linspace(t_min, t_max, int(timesteps) + 1) moment_ana = np.zeros([len(time), 2]) moment_ana[:, 0] = time for timestep in range(len(time)): if which_selection_function == 'Linear' and which_disrtibution == 'OneLargeParticle': moment_ana[timestep, 1] = np.sum( np.power(x, moment) * delta_x * AnalyticalSolution( x, timestep * delta_t).BinaryBreakageLinearSelection()) elif which_selection_function == 'Squared' and which_disrtibution == 'OneLargeParticle': moment_ana[timestep, 1] = np.sum( np.power(x, moment) * delta_x * AnalyticalSolution( x, timestep * delta_t).BinaryBreakageSquareSelection()) elif which_selection_function == 'Linear' and which_disrtibution == 'ExponentialDistribution': moment_ana[timestep, 1] = np.sum( np.power(x, moment) * delta_x * AnalyticalSolution(x, timestep * delta_t). BinaryBreakageLinearSelectionExpInitialCondition()) elif which_selection_function == 'Squared' and which_disrtibution == 'ExponentialDistribution': moment_ana[timestep, 1] = np.sum( np.power(x, moment) * delta_x * AnalyticalSolution(x, timestep * delta_t). BinaryBreakageSquareSelectionExpInitialCondition()) else: print( 'Selection function or Initial condition not mentioned properly' ) return moment_ana
def cost_function(x): '''Function which returns the L2 squared error between solver data and noisy data obtained using the analytical solution. Args: x (float): variable(s) to be optimized Returns: (float): L2 squared error ''' ##### To select the PDE_solver, un-cooment this code ##### ### Due to the PDE_solver currently working correctly, the y_data is generated using itself plus added noise, to test the correctness of the optimizer methods # y_data = AnalyticalSolution(input_data[0], input_data[1]) + var * np.random.randn(len(solver.x_range), len(t)) # u = solver.FN_solver(x_0 = 0, x_n = 20, alpha=0.2) # y_solver = solver.FN_solver(x_0 = 0, x_n = 20, alpha=x) # y_data = u + var * np.random.randn(len(solver.x_range), len(t)) ##### To select the fitzhugh_nagumo_solverl, un-comment this code ##### y_data = AnalyticalSolution( X, T, alpha=0.2) + var * np.random.randn(len(x), len(t)) y_solver, _, _ = fitzhugh_nagumo_solver(alpha=x, beta=1, gamma=1, max_x=1, max_t=10) y_solver = y_solver.T ##### END ##### return np.sum(np.power(y_solver - y_data, 2))
def ErrorForPureBreakage(): minimimum_particle_size = 1e-8 # maximum particle size maximum_particle_size = 1 #initial time no_of_nodes = 31 t_min = 0 # Final Time t_max = 1000 # Save solution after Delta_t time delta_t = 10 """ Evaluating error for a binary pure breakage with respect to number of nodes """ maximum_possible_nodes = 496 minimum_possible_nodes = 3 L1_error = np.zeros( len(range(minimum_possible_nodes, maximum_possible_nodes))) L2_error = np.zeros( len(range(minimum_possible_nodes, maximum_possible_nodes))) for selection_function in ['Linear', 'Squared']: for initial_condition in [ 'OneLargeParticle', 'ExponentialDistribution' ]: for nodes in range(minimum_possible_nodes, maximum_possible_nodes): x, delta_x, num_density = PureBreakagePBESolver( minimimum_particle_size, maximum_particle_size, nodes, t_min, t_max, delta_t, selection_function, initial_condition) if selection_function == 'Linear' and initial_condition == 'OneLargeParticle': num_den_ana = AnalyticalSolution( x, t_max).BinaryBreakageLinearSelection() elif selection_function == 'Squared' and initial_condition == 'OneLargeParticle': num_den_ana = AnalyticalSolution( x, t_max).BinaryBreakageSquareSelection() elif selection_function == 'Linear' and initial_condition == 'ExponentialDistribution': num_den_ana = AnalyticalSolution( x, t_max ).BinaryBreakageLinearSelectionExpInitialCondition() elif selection_function == 'Squared' and initial_condition == 'ExponentialDistribution': num_den_ana = AnalyticalSolution( x, t_max ).BinaryBreakageSquareSelectionExpInitialCondition() else: print( 'Selection function or Initial condition not mentioned properly' ) L1_error[nodes - minimum_possible_nodes] = np.sum( abs((num_density[:, -1] - num_den_ana)) * delta_x) L2_error[nodes - minimum_possible_nodes] = np.sqrt( np.mean( abs( np.power(num_density[:, -1], 2) - np.power(num_den_ana, 2)))) / (nodes + 1) os.chdir('Error\PureBreakage\WithNodes') np.save( 'L1_errorPureBreakage' + selection_function + 'SelectionInitialCond' + initial_condition + '.npy', L1_error) np.save( 'L2_errorPureBreakage' + selection_function + 'SelectionInitialCond' + initial_condition + '.npy', L2_error) os.chdir('..\..\..') for selection_function in ['Linear', 'Squared']: for initial_condition in [ 'OneLargeParticle', 'ExponentialDistribution' ]: delta_t = 1 t_max = 1000 for nodes in [8, 16, 31, 62, 124, 248]: x, delta_x, num_density = PureBreakagePBESolver( minimimum_particle_size, maximum_particle_size, nodes, t_min, t_max, delta_t, selection_function, initial_condition) L1_error_time = np.zeros([len(num_density[-1, :]), 2]) L2_error_time = np.zeros([len(num_density[-1, :]), 2]) for timestep in range(len(num_density[-1, :])): L1_error_time[timestep, 0] = timestep * delta_t L2_error_time[timestep, 0] = timestep * delta_t # at time ## Selecting nalytical solution depending on the choice of kernels if selection_function == 'Linear' and initial_condition == 'OneLargeParticle': num_den_ana = AnalyticalSolution( x, L1_error_time[timestep, 0]).BinaryBreakageLinearSelection() elif selection_function == 'Squared' and initial_condition == 'OneLargeParticle': num_den_ana = AnalyticalSolution( x, L1_error_time[timestep, 0]).BinaryBreakageSquareSelection() elif selection_function == 'Linear' and initial_condition == 'ExponentialDistribution': num_den_ana = AnalyticalSolution( x, L1_error_time[timestep, 0] ).BinaryBreakageLinearSelectionExpInitialCondition() elif selection_function == 'Squared' and initial_condition == 'ExponentialDistribution': num_den_ana = AnalyticalSolution( x, L1_error_time[timestep, 0] ).BinaryBreakageSquareSelectionExpInitialCondition() else: print( 'Selection function or Initial condition not mentioned properly' ) L1_error_time[timestep, 1] = np.sum( abs(num_den_ana - num_density[:, timestep]) * delta_x) L2_error_time[timestep, 1] = np.sqrt( np.mean( abs( np.power(num_density[:, timestep], 2) - np.power(num_den_ana, 2)))) / (nodes + 1) os.chdir('Error\PureBreakage\WithTime') np.save( 'L1_errorTimePureBreakageN' + str(nodes) + selection_function + 'SelectionInitialCond' + initial_condition + '.npy', L1_error_time) np.save( 'L2_errorPureBreakageN' + str(nodes) + selection_function + 'SelectionInitialCond' + initial_condition + '.npy', L2_error_time) os.chdir('..\..\..')
L2_error = np.zeros(len(range(minimum_possible_nodes, maximum_possible_nodes))) for coagulation_function in ['ConstantUnity', 'Product']: for nodes in range(minimum_possible_nodes, maximum_possible_nodes): x, delta_x, t_solve, num_density, total_mass, total_number_of_particles = PureAggregtionPBESolver( minimimum_particle_size, maximum_particle_size, no_of_nodes, t_min, t_max, delta_t, type_coagulation_function=coagulation_function, type_of_initial_condition='ExponentialDistribution', temporal_solver='RK45') if coagulation_function == 'ConstantUnity': num_den_ana = AnalyticalSolution( x, t_max, delta_x=delta_x ).ConstantUnityCoagulationNormExpInitialCondition() elif coagulation_function == 'Product': num_den_ana = AnalyticalSolution( x, t_max, delta_x=delta_x ).ProductKernelCoagulationNormExpInitialCondition() else: print( 'Selection function or Initial condition not mentioned properly' ) L1_error[nodes - minimum_possible_nodes] = np.sum( abs((num_density[-1, :] - num_den_ana)) * delta_x) L2_error[nodes - minimum_possible_nodes] = np.sqrt( np.mean( abs(
import matplotlib import matplotlib.ticker as ticker import matplotlib.ticker as mticker import numpy as np sns.set_theme(context='paper', style='ticks', font='Times New Roman', font_scale=2) x = np.logspace(-8, 0, 1000) final_time = 1 fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(10, 10), sharex=True) for ax, final_time in zip(axs.reshape(-1), [1, 10, 100, 1000]): print(ax, final_time) num_den = AnalyticalSolution(x, final_time).BinaryBreakageLinearSelection() ax.plot(x, num_den, linewidth=2, color='black', linestyle='--') ax.set_xlim(1e-8, 1) ax.set_ylim(0, ) ax.set_title('t = {} s'.format(final_time)) ax.set_xscale('log') path = 'G:\My Drive\Research\Popullation Balance Equation Solver\Images\AnalyticalSolutuionImages' plt.savefig(os.path.join(path, 'MonodisperseLinearSelectionBinaryBreakage.jpg'), dpi=300, bbox_inches='tight') sns.set_theme(context='paper', style='ticks', font='Times New Roman',
i = 0 for nodes in [8, 16, 32]: x, delta_x, num_density = PureBreakagePBESolver(minimimum_particle_size, maximum_particle_size, nodes, t_min, t_max, delta_t, 'Linear', 'ExponentialDistribution') ax1.semilogx(x, num_density[:, -1], linestyles[i], markevery=mk[i], markersize=7, label=r'Numerical ($N_x = {}$)'.format(nodes)) i = i + 1 num_den_ana = AnalyticalSolution( x, t_max).BinaryBreakageLinearSelectionExpInitialCondition() ax1.semilogx(x, num_den_ana, ':k', label='Analytical') plt.legend(fontsize=20) ax1.tick_params(axis='both', labelsize=20, grid_alpha=0.5) ax1.set_xlabel(r'$x$', fontsize=32) ax1.set_ylabel(r'$n$', fontsize=32, rotation='horizontal') ax1.xaxis.set_label_coords(0.55, -0.06) ax1.yaxis.set_label_coords(-0.125, 0.5) ax1.yaxis.offsetText.set_fontsize(20) ax1.set_title(r'Case 1', fontsize=32) ax1.set_xlim(1e-8, 1) ax1.set_ylim(0, ) ax1.grid() ax1.ticklabel_format(axis='y', style='sci') i = 0