def end(self, what): watch = self.watches[what] elapsed = toc() - watch[1] watch[0] += elapsed if self.watches[what][3]: self.measuring -= 1 self.last_measurement = toc() info(watch[2]+'. Time: %.4f Total: %.4f' % (elapsed, watch[0]))
def end(self, what): watch = self.watches[what] elapsed = toc() - watch[1] watch[0] += elapsed if self.watches[what][3]: self.measuring -= 1 info(watch[2]+'. Time: %.4f Total: %.4f' % (elapsed, watch[0])) self.last_measurement = toc()
def start(self, what): if what in self.watches: if self.watches[what][3]: self.measuring += 1 self.watches[what][1] = toc() from_last = toc()-self.last_measurement if self.measuring > 1: info('TC (%s): More watches at same time: %d' % (what, self.measuring)) if from_last > 0.1: info('TC (%s): time from last end of measurement: %f' % (what, from_last))
def start(self, what): if what in self.watches: if self.watches[what][3]: self.measuring += 1 self.watches[what][1] = toc() from_last = toc()-self.last_measurement if self.measuring > 1: info('TC (%s): More watches at same time: %d' % (what, self.measuring)) elif from_last > 0.1 and self.watches[what][3]: info('TC (%s): time from last end of measurement: %f' % (what, from_last))
def load_precomputed_bessel_functions(self, PS): """ loads precomputed Bessel functions (modes of analytic solution) """ f = HDF5File(mpi_comm_world(), 'precomputed/precomputed_' + self.precomputed_filename + '.hdf5', 'r') temp = toc() fce = Function(PS) f.read(fce, "parab") self.bessel_parabolic = fce.copy(deepcopy=True) for i in range(8): f.read(fce, "real%d" % i) self.bessel_real.append(fce.copy(deepcopy=True)) f.read(fce, "imag%d" % i) self.bessel_complex.append(fce.copy(deepcopy=True)) print("Loaded partial solution functions. Time: %f" % (toc() - temp))
def majorant_II_nd(u, Ve, w, W, y, f, u0, error_II, gamma, T, mesh, C_FD, dim, v_deg, MAJORANT_OPTIMIZE): tic() m_d, m_f, l, L, m_T = update_majorant_II_components( u, w, y, f, u0, mesh, dim, v_deg, W, Ve, T) maj_II, beta = calculate_majorant_II(m_d, m_f, l, L, m_T, C_FD, gamma) i_eff = sqrt(maj_II / error_II) majorant_reconstruction_time = toc() output_optimization_results(-1, maj_II, m_d, m_f, i_eff, beta, error_II) if MAJORANT_OPTIMIZE: #----------------------------------------------------------------------------# # Optimization algorithm #----------------------------------------------------------------------------# tic() S, K, L, z, g = get_matrices_of_optimization_problem_II( W, u, y, f, u0, T, mesh, dim, v_deg) w = Function(W) W = w.vector() OPT_ITER = 4 # Execute iterative process to optimize majorant with respect to beta and flux for k in range(1, OPT_ITER): #list_linear_solver_methods() #list_krylov_solver_preconditioners() # Solve system with respect to Y solve((1 + beta) * S - (C_FD**2) * beta / (1 + beta) * K, W, -L - (1 + beta) * z - (C_FD**2) * beta / (1 + beta) * g) # lu 3.4 - 3.5 # Calculate majorant m_d, m_f, l, L, m_T = update_majorant_II_components( u, w, y, f, u0, mesh, dim, v_deg, W, Ve, T) maj_II, beta = calculate_majorant_II(m_d, m_f, l, L, m_T, C_FD, gamma) i_eff = sqrt(maj_II / error_II) output_optimization_results(k, maj_II, m_d, m_f, i_eff, beta, error_II) majorant_minimization_time = toc() else: majorant_minimization_time = 0.0 return maj_II, beta, majorant_reconstruction_time, majorant_minimization_time
def load_precomputed_bessel_functions(self, PS): f = HDF5File(mpi_comm_world(), 'precomputed/precomputed_' + self.precomputed_filename + '.hdf5', 'r') temp = toc() fce = Function(PS) f.read(fce, "parab") self.bessel_parabolic = Function(fce) for i in range(8): f.read(fce, "real%d" % i) self.bessel_real.append(Function(fce)) f.read(fce, "imag%d" % i) self.bessel_complex.append(Function(fce)) # plot(coefs_r_prec[i], title="coefs_r_prec", interactive=True) # reasonable values # plot(coefs_i_prec[i], title="coefs_i_prec", interactive=True) # reasonable values # plot(c0_prec,title="c0_prec",interactive=True) # reasonable values print("Loaded partial solution functions. Time: %f" % (toc() - temp))
def load_precomputed_bessel_functions(self, PS): """ loads precomputed Bessel functions (modes of analytic solution) """ f = HDF5File( mpi_comm_world(), 'precomputed/precomputed_' + self.precomputed_filename + '.hdf5', 'r') temp = toc() fce = Function(PS) f.read(fce, "parab") self.bessel_parabolic = fce.copy(deepcopy=True) for i in range(8): f.read(fce, "real%d" % i) self.bessel_real.append(fce.copy(deepcopy=True)) f.read(fce, "imag%d" % i) self.bessel_complex.append(fce.copy(deepcopy=True)) print("Loaded partial solution functions. Time: %f" % (toc() - temp))
def report(self, report_file, str_name): total_time = toc() info('Total time of %.0f s, (%.2f hours).' % (total_time, total_time/3600.0)) sorted_by_time = [] sorted_by_name = [] sum = 0 sum_percent = 0 for value in self.watches.itervalues(): if value[3]: sum += value[0] if value[4]: sum_percent += value[0] if not sorted_by_time: sorted_by_time.append(value) else: i = 0 l = len(sorted_by_time) while i < l and value[0]<sorted_by_time[i][0]: i += 1 sorted_by_time.insert(i, value) for value in sorted_by_time: if value[0] > 0.000001: if value[4]: info(' %-40s: %12.2f s %5.1f %% (%4.1f %%)' % (value[2], value[0], 100.0*value[0]/sum_percent, 100.0*value[0]/total_time)) else: info(' %-40s: %12.2f s (%4.1f %%)' % (value[2], value[0], 100.0*value[0]/total_time)) else: info(' %-40s: %12.2f s NOT USED' % (value[2], value[0])) info(' %-40s: %12.2f s (%4.1f %%)' % ('Measured', sum, 100.0*sum/total_time)) info(' %-40s: %12.2f s 100.0 %% (%4.1f %%)' % ('Base for percent values', sum_percent, 100.0*sum_percent/total_time)) info(' %-40s: %12.2f s (%4.1f %%)' % ('Unmeasured', total_time-sum, 100.0*(total_time-sum)/total_time)) # report to file for key in self.watches.iterkeys(): # sort keys by name if not sorted_by_name: sorted_by_name.append(key) else: l = len(sorted_by_name) i = l while key < sorted_by_name[i-1] and i > 0: i -= 1 sorted_by_name.insert(i, key) report_header = ['Name', 'Total time'] report_data = [str_name, total_time] for key in sorted_by_name: value = self.watches[key] report_header.append(value[2]) report_header.append('part '+value[2]) report_data.append(value[0]) report_data.append(value[0]/total_time) report_header.append('part unmeasured') report_data.append((total_time-sum)/total_time) if report_file is not None: writer = csv.writer(report_file, delimiter=';', quotechar='|', quoting=csv.QUOTE_NONE) writer.writerow(report_header) writer.writerow(report_data)
def report(self, report_file, str_name): """ Writes out complete report. Saves times for the selected watches to csv file (if given). """ total_time = toc() info('Total time of %.0f s, (%.2f hours).' % (total_time, total_time/3600.0)) sorted_by_time = [] sorted_by_name = [] sum = 0 sum_percent = 0 # sort watches by time measured for value in self.watches.itervalues(): if value[3]: sum += value[0] if value[4]: sum_percent += value[0] if not sorted_by_time: sorted_by_time.append(value) else: i = 0 l = len(sorted_by_time) while i < l and value[0]<sorted_by_time[i][0]: i += 1 sorted_by_time.insert(i, value) for value in sorted_by_time: if value[0] > 0.000001: if value[4]: info(' %-40s: %12.2f s %5.1f %% (%4.1f %%)' % (value[2], value[0], 100.0*value[0]/sum_percent, 100.0*value[0]/total_time)) else: info(' %-40s: %12.2f s (%4.1f %%)' % (value[2], value[0], 100.0*value[0]/total_time)) else: info(' %-40s: %12.2f s NOT USED' % (value[2], value[0])) info(' %-40s: %12.2f s (%4.1f %%)' % ('Measured', sum, 100.0*sum/total_time)) info(' %-40s: %12.2f s 100.0 %% (%4.1f %%)' % ('Base for percent values', sum_percent, 100.0*sum_percent/total_time)) info(' %-40s: %12.2f s (%4.1f %%)' % ('Unmeasured', total_time-sum, 100.0*(total_time-sum)/total_time)) # report to file report_header = ['Name', 'Total time'] report_data = [str_name, total_time] for key in sorted(self.watches.keys()): value = self.watches[key] if value[4]: report_header.append(value[2]) report_data.append(value[0]) if report_file is not None: writer = csv.writer(report_file, delimiter=';', quotechar='|', quoting=csv.QUOTE_NONE) writer.writerow(report_header) writer.writerow(report_data)
def report(self): total = toc() md = self.metadata # compare errors measured by assemble and errornorm # TODO implement generally (if listDict[fcional]['testable']) # if self.testErrControl: # for e in [[self.listDict['u_L2']['list'], self.listDict['u_L2test']['list'], 'L2'], # [self.listDict['u_H1']['list'], self.listDict['u_H1test']['list'], 'H1']]: # print('test ', e[2], sum([abs(e[0][i]-e[1][i]) for i in range(len(self.time_list))])) # report error norms, norms of divergence etc. for individual time steps with open(self.str_dir_name + "/report_time_lines.csv", 'w') as reportFile: report_writer = csv.writer(reportFile, delimiter=';', escapechar='\\', quoting=csv.QUOTE_NONE) # report_writer.writerow(self.problem.get_metadata_to_save()) report_writer.writerow(["name", "what", "time"] + self.time_list) keys = sorted(self.listDict.keys()) for key in keys: l = self.listDict[key] if l['list']: abrev = l['abrev'] report_writer.writerow([md['name'], l['name'], abrev] + l['list']) if 'scale' in l: temp_list = [i/l['scale'][0] for i in l['list']] report_writer.writerow([md['name'], "scaled " + l['name'], abrev+"s"] + temp_list + ['scale factor:' + str(l['scale'])]) if 'norm' in l: if l['norm']: temp_list = [i/l['norm'][0] for i in l['list']] report_writer.writerow([md['name'], "normalized " + l['name'], abrev+"n"] + temp_list) else: info('Norm missing:' + str(l)) l['normalized_list_sec'] = [] if 'relative' in l: norm_list = self.listDict[l['relative']]['list'] temp_list = [l['list'][i]/norm_list[i] for i in range(0, len(l['list']))] self.listDict[key]['relative_list'] = temp_list report_writer.writerow([md['name'], "relative " + l['name'], abrev+"r"] + temp_list) # report error norms, norms of divergence etc. averaged over cycles # IFNEED rewrite to averaging over cycles (must track number of steps in cycle, it can be different for each cycle) # NT for cases when cycle_length % dt != 0 will be inacurate (less with smaller time steps) # note: self.stepsInCycle is float # if self.second_list: # with open(self.str_dir_name + "/report_seconds.csv", 'w') as reportFile: # report_writer = csv.writer(reportFile, delimiter=';', escapechar='|', quoting=csv.QUOTE_NONE) # report_writer.writerow(["name", "what", "time"] + self.second_list) # keys = sorted(self.listDict.keys()) # for key in keys: # l = self.listDict[key] # if 'slist' in l and l['list']: # abrev = l['abrev'] # values = l['slist'] # # generate averages over seconds from list # for sec in self.second_list: # N0 = (sec-1)*self.stepsInCycle # N1 = sec*self.stepsInCycle # values.append(sqrt(sum([i*i for i in l['list'][N0:N1]]) / float(self.stepsInCycle))) # # report_writer.writerow([md['name'], l['name'], abrev] + values) # if 'scale' in l: # temp_list = [i/l['scale'][0] for i in values] # report_writer.writerow([md['name'], "scaled " + l['name'], abrev+"s"] + temp_list) # if 'norm' in l: # if l['norm']: # temp_list = [i/l['norm'][0] for i in values] # l['normalized_list_sec'] = temp_list # report_writer.writerow([md['name'], "normalized " + l['name'], abrev+"n"] + temp_list) # else: # info('Norm missing:' + str(l)) # l['normalized_list_sec'] = [] # if 'relative_list' in l: # temp_list = [] # for sec in self.second_list: # N0 = (sec-1)*self.stepsInCycle # N1 = sec*self.stepsInCycle # temp_list.append(sqrt(sum([i*i for i in l['relative_list'][N0:N1]]) / float(self.stepsInCycle))) # l['relative_list_sec'] = temp_list # report_writer.writerow([md['name'], "relative " + l['name'], abrev+"r"] + temp_list) header_row = ["name", "totalTimeHours"] data_row = [md['name'], total / 3600.0] for key in ['u_L2', 'u_H1', 'u_H1w', 'p', 'u2L2', 'u2H1', 'u2H1w', 'p2', 'pgE', 'pgE2', 'd', 'd2', 'force_wall']: if key in self.listDict: l = self.listDict[key] header_row += ['last_cycle_'+l['abrev']] data_row += [l['slist'][-1]] if l['slist'] else [0] if 'relative_list_sec' in l and l['relative_list_sec']: header_row += ['last_cycle_'+l['abrev']+'r'] data_row += [l['relative_list_sec'][-1]] elif key in ['p', 'p2']: header_row += ['last_cycle_'+l['abrev']+'n'] data_row += [l['normalized_list_sec'][-1]] if 'normalized_list_sec' in l \ and l['normalized_list_sec'] else [0] # save metadata. Can be loaded and used in postprocessing with open(self.str_dir_name + "/metadata", 'w') as reportFile: reportFile.write(self.get_metadata_to_save()) # report without header with open(self.str_dir_name + "/report.csv", 'w') as reportFile: report_writer = csv.writer(reportFile, delimiter=';', escapechar='|', quoting=csv.QUOTE_NONE) report_writer.writerow(data_row) # report with header with open(self.str_dir_name + "/report_h.csv", 'w') as reportFile: report_writer = csv.writer(reportFile, delimiter=';', escapechar='|', quoting=csv.QUOTE_NONE) report_writer.writerow(header_row) report_writer.writerow(data_row) # report time cotrol with open(self.str_dir_name + "/report_timecontrol.csv", 'w') as reportFile: self.tc.report(reportFile, self.metadata['name']) self.remove_status_file() # create file showing all was done well f = open(md['name'] + "_OK.report", "w") f.close()
def majorant_nd_t(k, m_incr_k, m0_k, md_k, mf_k, beta_k, e_incr_k, ed_k, et_k, f, sq_f, phi, quadr, v_k, v_k1, grad_v_k, grad_v_k1, V_exact, y_k, y_k1, H_div, mesh, tau, delta, dim, domain, C_FD, majorant_reconstruction_time, majorant_minimization_time): tic() rf_k = problem.Div(y_k, dim) - (v_k1 - v_k) / tau rf_k1 = problem.Div(y_k1, dim) - (v_k1 - v_k) / tau rd_k = y_k - grad_v_k rd_k1 = y_k1 - grad_v_k1 sq_F_ = quadr.f(sq_f, V_exact) F_t_tk_ = quadr.f_t_tk(f, V_exact) F_tk1_t_ = quadr.f_tk1_t(f, V_exact) # Components of mf = || f + div y - v_t || mf_y_k = (sq_F_ + Constant(2.0) / tau * inner(F_tk1_t_, rf_k) + tau / Constant(3.0) * inner(rf_k, rf_k)) * dx(domain=mesh) mf_y_k1 = (Constant(2.0) / tau * inner(F_t_tk_, rf_k1) + tau / Constant(3.0) * (inner(rf_k, rf_k1) + inner(rf_k1, rf_k1))) * dx(domain=mesh) # Components of md = || y - grad v || md_y_k = (tau / Constant(3.0) * inner(rd_k, rd_k)) * dx(domain=mesh) md_y_k1 = (tau / Constant(3.0) * (inner(rd_k, rd_k1) + inner(rd_k1, rd_k1))) * dx(domain=mesh) m0 = assemble(((phi - v_k) * (phi - v_k)) * dx(domain=mesh)) # Assemble components of dual and balance terms of majorant # which stays the same in optimization process Mf_y_k = assemble(mf_y_k) Md_y_k = assemble(md_y_k) Mf_y_k1, Md_y_k1 = update_majorant_on_k1_time_level(mf_y_k1, md_y_k1) m_d, m_f = update_majorant_components(Md_y_k, Md_y_k1, Mf_y_k, Mf_y_k1) maj, beta = calculate_majorant(m_d, m_f, C_FD, delta) i_eff = sqrt(maj / e_incr_k) majorant_reconstruction_time[k] = toc() output_optimization_results(-1, maj, m_d, m_f, i_eff, beta, e_incr_k, ed_k, et_k) #----------------------------------------------------------------------------# # Optimization part #----------------------------------------------------------------------------# tic() S, K, z, q = get_matrices_of_optimization_problem(H_div, F_t_tk_, v_k, v_k1, grad_v_k, grad_v_k1, mesh, tau, dim) OPT_ITER = 4 for opt_iter in range(1, OPT_ITER): # Solve system with respect to Y A = (C_FD**2) * S + beta * K b = -0.5 * A * y_k.vector() - C_FD**2 * 3.0 / (tau**2) * z + beta * q #solve(A, y_k1.vector(), b, "gmres", 'ilu') solve(A, y_k1.vector(), b) mf_y_k1 = ( Constant(2.0) / tau * inner(F_t_tk_, rf_k1) + tau / Constant(3.0) * (inner(rf_k, rf_k1) + inner(rf_k1, rf_k1))) * dx(domain=mesh) md_y_k1 = (tau / Constant(3.0) * (inner(rd_k, rd_k1) + inner(rd_k1, rd_k1))) * dx( domain=mesh) Mf_y_k1, Md_y_k1 = update_majorant_on_k1_time_level(mf_y_k1, md_y_k1) m_d, m_f = update_majorant_components(Md_y_k, Md_y_k1, Mf_y_k, Mf_y_k1) maj, beta = calculate_majorant(m_d, m_f, C_FD, delta) i_eff = sqrt(maj / e_incr_k) output_optimization_results(opt_iter, maj, m_d, m_f, i_eff, beta, e_incr_k, ed_k, et_k) majorant_minimization_time[k] = toc() md_k[k] = m_d mf_k[k] = m_f beta_k[k] = beta m_incr_k[k] = maj m0_k[k] = m0 rf_k = problem.Div(y_k, dim) - (v_k1 - v_k) / tau rf_k1 = problem.Div(y_k1, dim) - (v_k1 - v_k) / tau rd_k = y_k - grad_v_k rd_k1 = y_k1 - grad_v_k1 md_var = tau / Constant(3.0) * (inner(rd_k, rd_k) + inner(rd_k, rd_k1) + inner(rd_k1, rd_k1)) mf_var = 1.0 / delta * ( (1.0 + beta) * md_var + (1.0 + 1.0 / beta) * (C_FD**2) * (sq_F_ + Constant(2.0) / tau * (inner(F_tk1_t_, rf_k) + inner(F_t_tk_, rf_k1)) + tau / Constant(3.0) * (inner(rf_k, rf_k) + inner(rf_k, rf_k1) + inner(rf_k1, rf_k1)))) return m_incr_k, m0_k, md_k, mf_k, beta_k, y_k1, md_var, mf_var
def majorant_nd(u, Ve, y, H_div, f, A, invA, min_eig_A, c_H, eps, lmbd, a, u0, error, mesh, C_FD, dim, test_params): tic() u0_0, O_mesh = get_2d_slice_of_3d_function_on_Oz( mesh, interpolate(u0, Ve), 0, dim, test_params["v_approx_order"], ) u_0, O_mesh = get_2d_slice_of_3d_function_on_Oz( mesh, interpolate(u, Ve), 0, dim, test_params["v_approx_order"], ) r_b = abs(u0_0 - u_0) m_b = assemble(inner(r_b, r_b) * dx(domain=O_mesh)) # Define residuals beta = 1.0 f_bar = f - c_H * D_t(u, dim) - lmbd * u - inner(a, NablaGrad(u, dim)) maj, m_d, m_f, beta, var_m_d, var_m_f_w_opt = calculate_majorant_bar_mu_opt( u, y, beta, f_bar, A, invA, min_eig_A, lmbd, mesh, dim, C_FD) i_eff = sqrt(maj / error) print " " print '%------------------------------------------------------------------------------------%' print "% Majorant before optimization" print '%------------------------------------------------------------------------------------%' print " " majorant_reconstruction_time = toc() output_optimization_results(-1, maj, m_d, m_f, i_eff, beta, error) if test_params['MAJORANT_OPTIMIZE']: #----------------------------------------------------------------------------# # Optimization algorithm #----------------------------------------------------------------------------# print " " print "%-----------------------" print "% optimization " print "%-----------------------" print " " tic() #S, K, z, g = get_matrices_of_optimization_problem(H_div, u, f, c_H, mesh, dim) S, K, z, g = get_matrices_of_optimization_problem( H_div, u, f_bar, invA, mesh, dim) y = Function(H_div) Y = y.vector() # Execute iterative process to optimize majorant with respect to beta and flux for k in range(1, test_params['majorant_optimization_iterations']): #list_linear_solver_methods() #list_krylov_solver_preconditioners() # Solve system with respect to Y solve((C_FD**2) / min_eig_A * S + beta * K, Y, (C_FD**2) / min_eig_A * z + beta * g) # lu 3.4 - 3.5 #solve((C_FD ** 2) * S + beta * K, Y, (C_FD ** 2) * z + beta * g, "gmres", "jacobi") # 3.4 #solve((C_FD ** 2) * S + beta * K, Y, (C_FD ** 2) * z + beta * g, "cg", "ilu") # 3.4 #solve(C_FD * S + beta * K, Y, C_FD * z + beta * g, "cg", "jacobi") #solve(C_FD * S + beta * K, Y, C_FD * z + beta * g, "gmres", "hypre_amg") # 3.4 - 3.5 y.vector = Y # Update majorant maj, m_d, m_f, beta, var_m_d, var_m_f_w_opt = calculate_majorant_bar_mu_opt( u, y, beta, f_bar, A, invA, min_eig_A, lmbd, mesh, dim, C_FD) i_eff = sqrt(maj / error) output_optimization_results(k, maj, m_d, m_f, i_eff, beta, error) majorant_minimization_time = toc() else: majorant_minimization_time = 0.0 return maj, y, beta, m_d, m_f, var_m_d, var_m_f_w_opt, majorant_reconstruction_time, majorant_minimization_time
def majorant_nd(v, y, H_div, f, A, invA, min_eig_A, eps, a, lmbd, error, mesh, dim, C_FD, C_Ntr, problem_params): """ :param v: approximate solution :param y: flux :param H_div: funtional space for the flux function :param f: right-hand side function (modified RHS) :param A: diffusion matrix :param min_eig_A: minimal eigenvalue of diffusion matrix :param a: convection function :param lmbd: reaction function :param error: error value :param mesh: mesh :param dim: geometrical problem dimension :param C_FD: Freidrichs constant of the computational domain :param MAJORANT_OPTIMIZE: test_parameter on weather to optimize majorant of not :return maj: majorant value m_d, m_f_one_minus_mu_opt: majorant components beta: optimal parameter var_m_d, var_m_f_w_opt: variational form of the majorant (to use them later in construction of error estimators) maj, y, beta, m_d, m_f, var_m_d, var_m_f_w_opt, majorant_reconstruction_time, majorant_minimization_time """ tic() # Initialize value beta = 1.0 #for i in range(2): f_bar = f - lmbd * v - inner(a, Grad(v, dim)) #f_bar = f maj, m_d, m_f, beta, var_m_d, var_m_f_w_opt = calculate_majorant_bar_mu_opt( v, y, beta, f_bar, A, invA, min_eig_A, lmbd, mesh, dim, C_FD) i_eff = sqrt(maj / error) print " " print '%------------------------------------------------------------------------------------%' print "% Majorant optimization" print '%------------------------------------------------------------------------------------%' print " " info(parameters, verbose=True) print(parameters.linear_algebra_backend) list_linear_solver_methods() list_krylov_solver_preconditioners() solver = KrylovSolver('gmres', 'ilu') prm = solver.parameters prm.absolute_tolerance = 1e-10 prm.relative_tolerance = 1e-6 prm.maximum_iterations = 1000 output_optimization_results(0, maj, m_d, m_f, i_eff, beta, error) majorant_reconstruction_time = toc() if problem_params["MAJORANT_OPTIMIZE"]: #----------------------------------------------------------------------------# # Optimization algorithm #----------------------------------------------------------------------------# tic() S, K, z, g = get_matrices_of_optimization_problem_bar( H_div, v, f_bar, invA, mesh, dim) y = Function(H_div) Y = y.vector() OPT_ITER = problem_params["majorant_optimization_iterations"] i_eff = 1e8 k = 1 m_d = 1.0 m_f = 10.0 # Execute iterative process to optimize majorant with respect to beta and flux while k in range(0, OPT_ITER): # m_d * min_eig_A /m_f <= 1: #or # Solve system with respect to Y #yMatrix = (C_FD ** 2) / min_eig_A * S + beta * K #yRhs = sum((C_FD ** 2) / min_eig_A * z, beta * g) #solve(yMatrix, Y, yRhs) solve((C_FD**2) / min_eig_A * S + beta * K, Y, (C_FD**2) / min_eig_A * z + beta * g) #if len(Y) <= 1e4: # solve((C_FD ** 2) / min_eig_A * S + beta * K, Y, (C_FD ** 2) / min_eig_A * z + beta * g) #else: # solver.solve((C_FD ** 2) / min_eig_A * S + beta * K, Y, (C_FD ** 2) / min_eig_A * z + beta * g, # "gmres", "ilu") y.vector = Y """ YtSY = assemble(inner(Div(y, dim), Div(y, dim)) * dx(domain=mesh)) YtSz2 = assemble(2 * inner(Div(y, dim), f) * dx(domain=mesh)) FF = assemble(inner(f, f) * dx(domain=mesh)) print "Y^T*S*Y", YtSY print "2*Y^T*z", YtSz2 print "FF", FF print "\| div y + f \|^2", YtSY + YtSz2 + FF YtY = assemble(inner(y, y) * dx(domain=mesh)) YtSz2 = assemble(2 * inner(Grad(v, dim), y) * dx(domain=mesh)) GradVGradV = assemble(inner(Grad(v, dim), Grad(v, dim)) * dx(domain=mesh)) """ # Calculate majorant maj, m_d, m_f, beta, var_m_d, var_m_f_w_opt = calculate_majorant_bar_mu_opt( v, y, beta, f_bar, A, invA, min_eig_A, lmbd, mesh, dim, C_FD) i_eff = sqrt(maj / error) output_optimization_results(k, maj, m_d, m_f, i_eff, beta, error) k = k + 1 majorant_minimization_time = toc() else: majorant_minimization_time = 0.0 return maj, y, beta, m_d, m_f, var_m_d, var_m_f_w_opt, majorant_reconstruction_time, majorant_minimization_time
def report(self): total = toc() md = self.metadata # compare errors measured by assemble and errornorm # TODO implement generally (if listDict[fcional]['testable']) # if self.testErrControl: # for e in [[self.listDict['u_L2']['list'], self.listDict['u_L2test']['list'], 'L2'], # [self.listDict['u_H1']['list'], self.listDict['u_H1test']['list'], 'H1']]: # print('test ', e[2], sum([abs(e[0][i]-e[1][i]) for i in range(len(self.time_list))])) # report error norm, norm of div, and pressure gradients for individual time steps with open(self.str_dir_name + "/report_time_lines.csv", 'w') as reportFile: report_writer = csv.writer(reportFile, delimiter=';', escapechar='\\', quoting=csv.QUOTE_NONE) # report_writer.writerow(self.problem.get_metadata_to_save()) report_writer.writerow(["name", "what", "time"] + self.time_list) for key in self.listDict: l = self.listDict[key] if l['list']: abrev = l['abrev'] report_writer.writerow([md['name'], l['name'], abrev] + l['list']) if 'scale' in l: temp_list = [i/l['scale'][0] for i in l['list']] report_writer.writerow([md['name'], "scaled " + l['name'], abrev+"s"] + temp_list + ['scale factor:' + str(l['scale'])]) if 'norm' in l: if l['norm']: temp_list = [i/l['norm'][0] for i in l['list']] report_writer.writerow([md['name'], "normalized " + l['name'], abrev+"n"] + temp_list) else: info('Norm missing:' + str(l)) l['normalized_list_sec'] = [] if 'relative' in l: norm_list = self.listDict[l['relative']]['list'] temp_list = [l['list'][i]/norm_list[i] for i in range(0, len(l['list']))] self.listDict[key]['relative_list'] = temp_list report_writer.writerow([md['name'], "relative " + l['name'], abrev+"r"] + temp_list) # report error norm, norm of div, and pressure gradients averaged over seconds with open(self.str_dir_name + "/report_seconds.csv", 'w') as reportFile: report_writer = csv.writer(reportFile, delimiter=';', escapechar='|', quoting=csv.QUOTE_NONE) # report_writer.writerow(self.problem.get_metadata_to_save()) report_writer.writerow(["name", "what", "time"] + self.second_list) for key in self.listDict.iterkeys(): l = self.listDict[key] if 'slist' in l: abrev = l['abrev'] value = l['slist'] report_writer.writerow([md['name'], l['name'], abrev] + value) if 'scale' in l: temp_list = [i/l['scale'][0] for i in value] report_writer.writerow([md['name'], "scaled " + l['name'], abrev+"s"] + temp_list) if 'norm' in l: if l['norm']: temp_list = [i/l['norm'][0] for i in value] l['normalized_list_sec'] = temp_list report_writer.writerow([md['name'], "normalized " + l['name'], abrev+"n"] + temp_list) else: info('Norm missing:' + str(l)) l['normalized_list_sec'] = [] if 'relative_list' in l: temp_list = [] # info('relative second list of'+ str(l['abrev'])) for sec in self.second_list: N0 = (sec-1)*self.stepsInSecond N1 = sec*self.stepsInSecond # info([sec, N0, N1]) temp_list.append(sqrt(sum([i*i for i in l['relative_list'][N0:N1]])/float(self.stepsInSecond))) l['relative_list_sec'] = temp_list report_writer.writerow([md['name'], "relative " + l['name'], abrev+"r"] + temp_list) header_row = ["name", 'metadata', "totalTimeHours"] data_row = [md['name'], self.get_metadata_to_save(), total / 3600.0] for key in ['u_L2', 'u_H1', 'u_H1w', 'p', 'u2L2', 'u2H1', 'u2H1w', 'p2', 'pgE', 'pgE2', 'd', 'd2', 'force_wall']: if key in self.listDict: l = self.listDict[key] header_row += ['last_cycle_'+l['abrev']] data_row += [l['slist'][-1]] if l['slist'] else [0] if 'relative_list_sec' in l and l['relative_list_sec']: header_row += ['last_cycle_'+l['abrev']+'r'] data_row += [l['relative_list_sec'][-1]] elif key in ['p', 'p2']: header_row += ['last_cycle_'+l['abrev']+'n'] data_row += [l['normalized_list_sec'][-1]] if l['normalized_list_sec'] else [0] # report without header with open(self.str_dir_name + "/report.csv", 'w') as reportFile: report_writer = csv.writer(reportFile, delimiter=';', escapechar='|', quoting=csv.QUOTE_NONE) report_writer.writerow(data_row) # report with header with open(self.str_dir_name + "/report_h.csv", 'w') as reportFile: report_writer = csv.writer(reportFile, delimiter=';', escapechar='|', quoting=csv.QUOTE_NONE) report_writer.writerow(header_row) report_writer.writerow(data_row) # report time cotrol with open(self.str_dir_name + "/report_timecontrol.csv", 'w') as reportFile: self.tc.report(reportFile, self.metadata['name']) self.remove_status_file() # create file showing all was done well f = open(md['name'] + "_OK.report", "w") f.close()
def majorant_nd(v, y, H_div, V, VV, f, A, invA, lambda_1, a, lmbd, error, mesh, dim, C_FD, C_Ntr, problem_params): """ :param v: approximate solution :param y: flux :param H_div: funtional space for the flux function :param f: right-hand side function (modified RHS) :param A: diffusion matrix :param lambda_1: minimal eigenvalue of diffusion matrix :param a: convection function :param lmbd: reaction function :param error: error value :param mesh: mesh :param dim: geometrical problem dimension :param C_FD: Freidrichs constant of the computational domain :param MAJORANT_OPTIMIZE: test_parameter on weather to optimize majorant of not :return maj: majorant value m_d, m_f_one_minus_mu_opt: majorant components beta: optimal parameter var_m_d, var_m_f_w_opt: variational form of the majorant (to use them later in construction of error estimators) maj, y, beta, m_d, m_f, var_m_d, var_m_f_w_opt, majorant_reconstruction_time, majorant_minimization_time """ tic() # Initialize value beta = 1.0 #for i in range(2): f_bar = f - lmbd * v - inner(a, Grad(v, dim)) #f_bar = f maj, m_d, m_f, beta, var_m_d, var_m_f_w_opt = calculate_majorant_bar_mu_opt( v, y, beta, f_bar, A, invA, lambda_1, lmbd, mesh, dim, C_FD) i_eff = sqrt(maj / error) print " " print '%------------------------------------------------------------------------------------%' print "% Majorant before optimization" print '%------------------------------------------------------------------------------------%' print " " output_optimization_results(0, maj, m_d, m_f, i_eff, beta, error) majorant_reconstruction_time = toc() if problem_params["MAJORANT_OPTIMIZE"]: #----------------------------------------------------------------------------# # Optimization algorithm #----------------------------------------------------------------------------# print " " print "%-----------------------" print "% optimization " print "%-----------------------" print " " tic() S, K, z, g = get_matrices_of_optimization_problem_bar( H_div, v, f_bar, invA, mesh, dim) y = Function(H_div) Y = y.vector() OPT_ITER = problem_params["majorant_optimization_iterations"] # Execute iterative process to optimize majorant with respect to beta and flux for k in range(0, problem_params["majorant_optimization_iterations"]): # Solve system with respect to Y #yMatrix = (C_FD ** 2) / lambda_1 * S + beta * K #yRhs = sum((C_FD ** 2) / lambda_1 * z, beta * g) #solve(yMatrix, Y, yRhs) solve((C_FD**2) / lambda_1 * S + beta * K, Y, (C_FD**2) / lambda_1 * z + beta * g) y.vector = Y ''' YtSY = assemble(inner(Div(y, dim), Div(y, dim)) * dx(domain=mesh)) YtSz2 = assemble(2 * inner(Div(y, dim), f) * dx(domain=mesh)) FF = assemble(inner(f, f) * dx(domain=mesh)) print "Y^T*S*Y", YtSY print "2*Y^T*z", YtSz2 print "FF", FF print "\| div y + f \|^2", YtSY + YtSz2 + FF YtY = assemble(inner(y, y) * dx(domain=mesh)) YtSz2 = assemble(2 * inner(Grad(v, dim), y) * dx(domain=mesh)) GradVGradV = assemble(inner(Grad(v, dim), Grad(v, dim)) * dx(domain=mesh)) print "YtY", YtY print "YtSz2", YtSz2 print "GradVGradV", GradVGradV print "\| y - grad v \|^2", YtY - YtSz2 + GradVGradV print "\| v \|", (norm(v, 'L2'))**2 print "\| grad v \|", (norm(v, 'H1'))**2 print "\| div y \|", (norm(project(div(y), V), 'L2'))**2 print "\| f \|", (norm(project(f, V), 'L2'))**2 ''' # Calculate majorant maj, m_d, m_f, beta, var_m_d, var_m_f_w_opt = calculate_majorant_bar_mu_opt( v, y, beta, f_bar, A, invA, lambda_1, lmbd, mesh, dim, C_FD) i_eff = sqrt(maj / error) output_optimization_results(k + 1, maj, m_d, m_f, i_eff, beta, error) majorant_minimization_time = toc() else: majorant_minimization_time = 0.0 return maj, y, beta, m_d, m_f, var_m_d, var_m_f_w_opt, majorant_reconstruction_time, majorant_minimization_time