# --- Extract data timeseries = np.array([]) for i in range(op.num_meshes): fname = os.path.join( op.di, "inlet_salinity_diff_{:s}.npy".format(index_string(i))) if not os.path.exists(fname): raise IOError("Need to run the model in order to get QoI timeseries.") timeseries = np.append(timeseries, np.load(fname)) # --- Plot fig, axes = plt.subplots(figsize=(8, 5)) time_seconds = np.linspace(0.0, op.end_time, len(timeseries)) time_hours = time_seconds / 3600 axes.plot(time_hours, timeseries) axes.set_xlabel(r"Time [$\mathrm h$]") axes.set_ylabel(r"Inlet salinity difference [$\mathrm{g\,L}^{-1}$]") axes.set_xlim([0, op.end_time / 3600]) axes.grid(True) non_dimensionalise = lambda time: 3600 * time / op.T_tide dimensionalise = lambda time: 3600 * time * op.T_tide secax = axes.secondary_xaxis('top', functions=(non_dimensionalise, dimensionalise)) secax.set_xlabel("Time/Tidal period") fname = approach plot_dir = create_directory(os.path.join(os.path.dirname(__file__), "plots")) savefig('_'.join([fname, "array_power_output", index_str]), plot_dir, extensions=['pdf', 'png'])
'debug_mode': args.debug_mode or 'basic', } qois, num_cells, dofs = [], [], [] discrete_turbines = True # discrete_turbines = False op = TurbineArrayOptions(**kwargs) hierarchy = MeshHierarchy(op.default_mesh, levels) # --- Loop over mesh hierarchy for level in range(levels): op.default_mesh = hierarchy[level] di = 'uniform_level{:d}_offset{:d}'.format(level, offset) di = create_directory(os.path.join(op.di, di)) tp = AdaptiveSteadyTurbineProblem(op, discrete_turbines=discrete_turbines, callback_dir=di) # Solve forward problem tp.solve_forward() # Store diagnostics num_cells.append(tp.num_cells[-1][0]) dofs.append(sum(tp.V[0].dof_count)) J = tp.quantity_of_interest()*1.030e-03 qois.append(J) op.print_debug("\nMesh {:d} in the hierarchy, offset = {:d}".format(level+1, op.offset)) op.print_debug(" Number of elements : {:d}".format(num_cells[-1])) op.print_debug(" Number of dofs : {:d}".format(dofs[-1])) op.print_debug(" Power output : {:.4f} MW".format(qois[-1]))
assert ext in ('cg', 'dg') if ext == 'dg': if args.stabilisation in ('lf', 'LF', 'lax_friedrichs'): ext += '_lf' else: if args.stabilisation in ('su', 'SU'): ext += '_su' if args.stabilisation in ('supg', 'SUPG'): ext += '_supg' if anisotropic_stabilisation: ext += '_anisotropic' fname = 'qoi_{:s}'.format(ext) # Arrays etc. num_levels = 7 di = create_directory( os.path.join(os.path.dirname(__file__), 'outputs', 'fixed_mesh', 'hdf5')) qois = {'aligned': [], 'offset': []} num_cells = [] dofs = [] qois_exact = {'aligned': [], 'offset': []} # Loop over mesh hierarchy for level in range(num_levels): # Solve PDE op = PointDischarge2dOptions(level=level, aligned=True) op.tracer_family = args.family stabilisation = args.stabilisation or 'supg' op.stabilisation_tracer = None if stabilisation == 'none' else stabilisation op.anisotropic_stabilisation = False if args.anisotropic_stabilisation == '0' else True tp = AdaptiveSteadyProblem(op)
# Convergence analysis 'target_base': 2, 'outer_iterations': int(args.outer_iterations or 8), # I/O and debugging 'plot_pvd': True, 'debug': bool(args.debug or 0), } op = PointDischarge2dOptions(**kwargs) op.tracer_family = family op.stabilisation_tracer = None if stabilisation == 'none' else stabilisation op.anisotropic_stabilisation = anisotropic_stabilisation op.normalisation = args.normalisation or 'complexity' # FIXME: error op.print_debug(op) di = os.path.dirname(__file__) di = create_directory( os.path.join(di, 'outputs', op.approach, op.enrichment_method, 'hdf5')) # --- Solve elements = [] dofs = [] qois = [] estimators = [] for n in range(op.outer_iterations): op.target = target * op.target_base**n op.default_mesh = RectangleMesh(100 * 2**level, 20 * 2**level, 50, 10) tp = problem(op) tp.run() elements.append(tp.num_cells[-1][0]) print("Element count: ", elements) dofs.append(tp.num_vertices[-1][0])
nonlinear_method = 'solve' if solve_forward else 'prolong' kwargs = { 'approach': 'dwr', 'solve_enriched_forward': solve_forward, 'offset': offset, 'plot_pvd': False, 'debug': bool(args.debug or 0), } # --- Loop over enrichment methods levels = 3 methods = ('GE_hp', 'GE_h', 'GE_p') out = {method: {'time': [], 'num_cells': [], 'dofs': []} for method in methods} di = create_directory('outputs/dwr/enrichment') fname = os.path.join(di, '{:s}_{:s}.p'.format(alignment, nonlinear_method)) for method in methods: print(method) for level in range(levels): op = TurbineArrayOptions(level=level, **kwargs) op.enrichment_method = method # Solve problems in base space tp = AdaptiveSteadyTurbineProblem(op, print_progress=False, discrete_adjoint=True) out[method]['num_cells'].append(tp.mesh.num_cells()) out[method]['dofs'].append(sum(tp.V[0].dof_count)) tp.solve_forward() tp.solve_adjoint() # Indicate error
import matplotlib.pyplot as plt import numpy as np import os from adapt_utils.io import create_directory from adapt_utils.case_studies.tohoku.options.options import TohokuInversionOptions from adapt_utils.plotting import * # NOQA di = create_directory(os.path.join(os.path.dirname(__file__), 'plots')) # Instantiate TohokuOptions object and setup interpolator op = TohokuInversionOptions() gauges = list(op.gauges) num_gauges = len(gauges) for smoothed in (True, False): for gauge in gauges: sample = 60 if smoothed and (gauge[0] == 'P' or 'PG' in gauge) else 1 op.sample_timeseries(gauge, sample=sample) op.gauges[gauge]["data"] = [] # Interpolate timeseries data from file t = 0.0 t_epsilon = 1.0e-05 time_seconds = [] while t < op.end_time - t_epsilon: time_seconds.append(t) for gauge in gauges: op.gauges[gauge]["data"].append( float(op.gauges[gauge]["interpolator"](t))) t += op.dt
'max_adapt': int(args.max_adapt or 3), 'hessian_time_combination': args.hessian_time_combination or 'integrate', 'norm_order': 1, 'normalisation': 'complexity', # I/O and debugging 'plot_pvd': False, 'debug': bool(args.debug or False), } op = BubbleOptions(approach='hessian', n=int(args.n or 1)) op.update(kwargs) if args.dt is not None: op.dt = float(args.dt) if args.end_time is not None: op.end_time = float(args.end_time) op.di = create_directory(os.path.join(op.di, op.hessian_time_combination)) # --- Solve the tracer transport problem assert op.approach != 'fixed_mesh' for n in range(int(args.min_level or 0), int(args.max_level or 5)): op.target = 1000*2**n op.dt = 0.01*0.5**n op.dt_per_export = 2**n # Run simulation tp = AdaptiveProblem(op) cpu_timestamp = perf_counter() tp.run() times = [perf_counter() - cpu_timestamp] dofs = [Q.dof_count for Q in tp.Q]
# Model "stabilisation": args.stabilisation, "viscosity_sponge_type": args.viscosity_sponge_type, # NOTE: Defaults to None "family": "dg-cg", # I/O and debugging "plot_pvd": plot_pvd, "debug": bool(args.debug or False), 'debug_mode': args.debug_mode or 'basic', } plt.rc('font', **{'size': 18}) op = SpaceshipOptions(approach=approach) op.update(kwargs) if op.viscosity_sponge_type is not None: op.di = create_directory(os.path.join(op.di, op.viscosity_sponge_type)) if op.debug: op.solver_parameters_momentum['snes_monitor'] = None op.solver_parameters_pressure['snes_monitor'] = None # Create directories and check if spun-up solution exists data_dir = create_directory(os.path.join(os.path.dirname(__file__), "data")) ramp_dir = create_directory(os.path.join(data_dir, "ramp")) data_dir = create_directory(os.path.join(data_dir, approach, index_str)) op.spun = np.all([ os.path.isfile(os.path.join(ramp_dir, f + ".h5")) for f in ('velocity', 'elevation') ]) sea_water_density = 1030.0 power_watts = [np.array([]) for i in range(15)] if op.spun:
"arrowprops": { "arrowstyle": "<->", "color": "b", }, } plt.rc('font', **{'size': 18}) op = TurbineArrayOptions(base_viscosity, **kwargs) if args.max_reynolds_number is not None: op.max_reynolds_number = float(args.max_reynolds_number) op.end_time = op.T_tide # Only adapt over a single tidal cycle # Create directories and check if spun-up solution exists ramp_dir = os.path.join(os.path.dirname(__file__), "data", "ramp") if args.extension is not None: ramp_dir = "_".join([ramp_dir, args.extension]) op.di = create_directory(os.path.join(os.path.dirname(__file__), "outputs", approach)) if args.extension is not None: op.di = "_".join([op.di, args.extension]) op.spun = np.all([os.path.isfile(os.path.join(ramp_dir, f + ".h5")) for f in ('velocity', 'elevation')]) # --- Run model # Run forward model and save QoI timeseries if not plot_only: if not op.spun: raise ValueError("Please spin up the simulation before applying mesh adaptation.") swp = AdaptiveTurbineProblem(op, meshes=load_mesh, callback_dir=op.di, ramp_dir=ramp_dir) # Solve forward problem cpu_timestamp = perf_counter()
# Set parameters kwargs = { 'approach': 'fixed_mesh', 'level': int(args.level or 2), 'box': True, 'plot_pvd': True, 'debug': False if args.debug == "0" else True, 'debug_mode': args.debug_mode or 'basic', } discrete_turbines = True # discrete_turbines = False op = TurbineArrayOptions(**kwargs) op.update({ 'spun': False, 'di': create_directory(os.path.join(op.di, 'unsteady')), # Extend to time-dependent case 'timestepper': 'CrankNicolson', 'dt': 5.0, 'dt_per_export': 1, 'end_time': 600.0, # Crank down viscosity and plot vorticity 'base_viscosity': Constant(1.0e-05), 'characteristic_velocity': Constant(op.inflow_velocity), 'grad_depth_viscosity': True, 'max_reynolds_number': 5.0e+05, 'recover_vorticity': True, # Only consider the first turbine
parser.add_argument('-debug', help="Toggle debugging mode.") args = parser.parse_args() # Set parameters offset = bool(args.offset or False) alignment = 'offset' if offset else 'aligned' kwargs = { 'approach': 'dwr', 'level': int(args.level or 1), 'aligned': not offset, 'plot_pvd': False, 'debug': bool(args.debug or 0), } methods = ('GE_hp', 'GE_h', 'GE_p', 'DQ') assert args.enrichment_method in methods plot_dir = create_directory('plots') op = PointDischarge2dOptions(**kwargs) op.tracer_family = 'cg' op.stabilisation_tracer = 'supg' op.anisotropic_stabilisation = True op.enrichment_method = args.enrichment_method # Evaluate error indicator field tp = AdaptiveSteadyProblem(op, print_progress=False) tp.solve_forward() tp.solve_adjoint() tp.indicate_error('tracer') minpower = -15 maxpower = -3 minvalue = 1.0001*10**minpower maxvalue = 0.9999*10**maxpower
approach = 'fixed_mesh' load_mesh = None if args.load_mesh is None else 'plex' plot_pvd = bool(args.plot_pvd or False) kwargs = { 'approach': approach, 'num_meshes': int(args.num_meshes or 1), 'plot_pvd': plot_pvd, 'debug': bool(args.debug or False), 'debug_mode': args.debug_mode or 'basic', } op = TurbineArrayOptions(3.0, **kwargs) mode = 'memory' # TODO: disk # Create directories and check if spun-up solution exists data_dir = create_directory(os.path.join(os.path.dirname(__file__), "data")) ramp_dir = create_directory(os.path.join(data_dir, "ramp")) data_dir = create_directory(os.path.join(data_dir, approach)) spun = np.all([os.path.isfile(os.path.join(ramp_dir, f + ".h5")) for f in ('velocity', 'elevation')]) power_watts = [np.array([]) for i in range(15)] if spun: for i, turbine in enumerate(op.farm_ids): fname = os.path.join(ramp_dir, "power_output_{:d}.npy".format(turbine)) power_watts[i] = np.append(power_watts[i], np.load(fname)*op.sea_water_density) else: op.end_time += op.T_ramp # --- Forward solve # Run forward model and save QoI timeseries
nonlinear = False with open(filename, 'r') as logfile: for line in logfile: words = line.split() if words[0] == 'Elements' and words[1] == 'QoI': use = True continue if words[0] == 'nonlinear': nonlinear = words[-1] == 'True' if use: elements.append(int(words[0])) qois.append(float(words[1])) qois = np.array(qois) # init_diff = np.zeros(len(qois)) if qois_old is None else qois[0] - qois_old[0] # qois_old = qois # plt.semilogx(elements, qois - init_diff, label='Nonlinear SWEs' if nonlinear else 'Linear SWEs') plt.semilogx(elements, qois, linestyle='--', marker='o', label='Nonlinear SWEs' if nonlinear else 'Linear SWEs') plt.xlabel("Element count") plt.ylabel(r"Quantity of interest, $J(\mathbf{u},\eta)$") plt.legend() date = datetime.date.today() date = '{:d}-{:d}-{:d}'.format(date.year, date.month, date.day) di = create_directory( os.path.join(di, '{:s}-runs-{:s}'.format(date, '-'.join([r for r in runs])))) plt.savefig(os.path.join(di, 'qoi_convergence.png'))
'norm_order': p, 'convergence_rate': alpha, 'min_adapt': int(args.min_adapt or 3), 'max_adapt': int(args.max_adapt or 35), 'enrichment_method': args.enrichment_method or ('GE_p' if adjoint else 'DQ'), # I/O and debugging 'plot_pvd': True, 'debug': bool(args.debug or 0), } op = PointDischarge2dOptions(**kwargs) op.tracer_family = family stabilisation = args.stabilisation or 'supg' op.stabilisation_tracer = None if stabilisation == 'none' else stabilisation op.anisotropic_stabilisation = False if args.anisotropic_stabilisation == '0' else True op.di = create_directory(os.path.join(op.di, op.stabilisation_tracer or family, op.enrichment_method)) op.normalisation = args.normalisation or 'complexity' # FIXME: error op.print_debug(op) # --- Solve tp = problem(op) tp.run() if bool(args.plot_indicator or False): indicator_file = File(os.path.join(op.di, "indicator.pvd")) indicator_file.write(tp.indicator[op.enrichment_method]) # Export to HDF5 save_mesh(tp.mesh, "mesh", fpath=op.di)