MOM.F90
1! This file is part of MOM6, the Modular Ocean Model version 6.
2! See the LICENSE file for licensing information.
3! SPDX-License-Identifier: Apache-2.0
4
5!> The central module of the MOM6 ocean model
6module mom
7
8! Infrastructure modules
9use mom_array_transform, only : rotate_array, rotate_vector
10use mom_debugging, only : mom_debugging_init, hchksum, uvchksum, totaltands
11use mom_debugging, only : check_redundant, query_debugging_checks
12use mom_checksum_packages, only : mom_thermo_chksum, mom_state_chksum
13use mom_checksum_packages, only : mom_accel_chksum, mom_surface_chksum
14use mom_coms, only : num_pes
15use mom_cpu_clock, only : cpu_clock_id, cpu_clock_begin, cpu_clock_end
16use mom_cpu_clock, only : clock_component, clock_subcomponent
17use mom_cpu_clock, only : clock_module_driver, clock_module, clock_routine
18use mom_diag_mediator, only : diag_mediator_init, enable_averaging, enable_averages
20use mom_diag_mediator, only : diag_set_state_ptrs, diag_update_remap_grids
21use mom_diag_mediator, only : disable_averaging, post_data, safe_alloc_ptr
22use mom_diag_mediator, only : register_diag_field, register_cell_measure
23use mom_diag_mediator, only : set_axes_info, diag_ctrl, diag_masks_set
24use mom_diag_mediator, only : set_masks_for_axes
25use mom_diag_mediator, only : diag_grid_storage, diag_grid_storage_init
26use mom_diag_mediator, only : diag_save_grids, diag_restore_grids
27use mom_diag_mediator, only : diag_copy_storage_to_diag, diag_copy_diag_to_storage
28use mom_domains, only : mom_domains_init, mom_domain_type
29use mom_domains, only : sum_across_pes, pass_var, pass_vector
30use mom_domains, only : clone_mom_domain, deallocate_mom_domain
31use mom_domains, only : to_north, to_east, to_south, to_west
32use mom_domains, only : to_all, omit_corners, cgrid_ne, scalar_pair
33use mom_domains, only : create_group_pass, do_group_pass, group_pass_type
34use mom_domains, only : start_group_pass, complete_group_pass, omit_corners
35use mom_error_handler, only : mom_error, mom_mesg, fatal, warning, is_root_pe
36use mom_error_handler, only : mom_set_verbosity, calltree_showquery
37use mom_error_handler, only : calltree_enter, calltree_leave, calltree_waypoint
38use mom_file_parser, only : read_param, get_param, log_version, param_file_type
39use mom_file_parser, only : openparameterblock, closeparameterblock
40use mom_forcing_type, only : forcing, mech_forcing, find_ustar
41use mom_forcing_type, only : mom_forcing_chksum, mom_mech_forcing_chksum
42use mom_get_input, only : get_mom_input, directories
43use mom_io, only : mom_io_init, vardesc, var_desc
44use mom_io, only : slasher, file_exists, mom_read_data
45use mom_obsolete_params, only : find_obsolete_params
46use mom_restart, only : register_restart_field, register_restart_pair, save_restart
47use mom_restart, only : query_initialized, set_initialized, restart_registry_lock
48use mom_restart, only : restart_init, is_new_run, determine_is_new_run, mom_restart_cs
49use mom_spatial_means, only : global_mass_integral
50use mom_time_manager, only : time_type, real_to_time, operator(+)
51use mom_time_manager, only : operator(-), operator(>), operator(*), operator(/)
52use mom_time_manager, only : operator(>=), operator(==), increment_date
53use mom_unit_tests, only : unit_tests
54
55! MOM core modules
56use mom_ale, only : ale_init, ale_end, ale_regrid, ale_cs, adjustgridforintegrity
57use mom_ale, only : ale_getcoordinate, ale_getcoordinateunits, ale_writecoordinatefile
58use mom_ale, only : ale_updateverticalgridtype, ale_remap_init_conds, pre_ale_adjustments
59use mom_ale, only : ale_remap_tracers, ale_remap_velocities
60use mom_ale, only : ale_remap_set_h_vel, ale_remap_set_h_vel_via_dz
61use mom_ale, only : ale_update_regrid_weights, pre_ale_diagnostics, ale_register_diags
62use mom_ale, only : ale_set_extrap_boundaries
63use mom_ale_sponge, only : rotate_ale_sponge, update_ale_sponge_field
64use mom_barotropic, only : barotropic_cs
65use mom_boundary_update, only : call_obc_register, obc_register_end, update_obc_cs
66use mom_check_scaling, only : check_mom6_scaling_factors
67use mom_coord_initialization, only : mom_initialize_coord, write_vertgrid_file
68use mom_diabatic_driver, only : diabatic, diabatic_driver_init, diabatic_cs, extract_diabatic_member
69use mom_diabatic_driver, only : adiabatic, adiabatic_driver_init, diabatic_driver_end
70use mom_diabatic_driver, only : register_diabatic_restarts
71use mom_stochastics, only : stochastics_init, update_stochastics, stochastic_cs, apply_skeb
72use mom_diagnostics, only : calculate_diagnostic_fields, mom_diagnostics_init
73use mom_diagnostics, only : register_transport_diags, post_transport_diagnostics
74use mom_diagnostics, only : register_surface_diags, write_static_fields
75use mom_diagnostics, only : post_surface_dyn_diags, post_surface_thermo_diags
76use mom_diagnostics, only : diagnostics_cs, surface_diag_ids, transport_diag_ids
77use mom_diagnostics, only : mom_diagnostics_end
79use mom_dynamics_unsplit, only : initialize_dyn_unsplit, end_dyn_unsplit
80use mom_dynamics_unsplit, only : mom_dyn_unsplit_cs
82use mom_dynamics_split_rk2, only : initialize_dyn_split_rk2, end_dyn_split_rk2
84use mom_dynamics_split_rk2, only : init_dyn_split_rk2_diabatic
86use mom_dynamics_split_rk2b, only : initialize_dyn_split_rk2b, end_dyn_split_rk2b
90use mom_dynamics_unsplit_rk2, only : mom_dyn_unsplit_rk2_cs
91use mom_dyn_horgrid, only : dyn_horgrid_type, create_dyn_horgrid, destroy_dyn_horgrid
92use mom_dyn_horgrid, only : rotate_dyn_horgrid
93use mom_eos, only : eos_init, calculate_density, calculate_tfreeze, eos_domain
94use mom_fixed_initialization, only : mom_initialize_fixed
95use mom_forcing_type, only : allocate_forcing_type, allocate_mech_forcing
96use mom_forcing_type, only : deallocate_mech_forcing, deallocate_forcing_type
97use mom_forcing_type, only : rotate_forcing, rotate_mech_forcing
98use mom_forcing_type, only : copy_common_forcing_fields, set_derived_forcing_fields
99use mom_forcing_type, only : homogenize_forcing, homogenize_mech_forcing
100use mom_grid, only : ocean_grid_type, mom_grid_init, mom_grid_end
101use mom_grid, only : set_first_direction
102use mom_harmonic_analysis, only : ha_accum, harmonic_analysis_cs
103use mom_hor_index, only : hor_index_type, hor_index_init
104use mom_hor_index, only : rotate_hor_index
105use mom_interface_heights, only : find_eta, calc_derived_thermo, thickness_to_dz
106use mom_interface_filter, only : interface_filter, interface_filter_init, interface_filter_end
107use mom_interface_filter, only : interface_filter_cs
108use mom_internal_tides, only : int_tide_cs
109use mom_kappa_shear, only : kappa_shear_at_vertex
110use mom_lateral_mixing_coeffs, only : calc_slope_functions, varmix_init, varmix_end
111use mom_lateral_mixing_coeffs, only : calc_resoln_function, calc_depth_function, varmix_cs
112use mom_meke, only : meke_alloc_register_restart, step_forward_meke
114use mom_meke_types, only : meke_type
115use mom_mixed_layer_restrat, only : mixedlayer_restrat, mixedlayer_restrat_init, mixedlayer_restrat_cs
116use mom_mixed_layer_restrat, only : mixedlayer_restrat_register_restarts
117use mom_obsolete_diagnostics, only : register_obsolete_diagnostics
118use mom_open_boundary, only : ocean_obc_type, open_boundary_end
120use mom_open_boundary, only : read_obc_dynamics_data, read_obc_tracer_data
121use mom_open_boundary, only : initialize_obc_segment_reservoirs
122use mom_open_boundary, only : setup_obc_tracer_reservoirs
123use mom_open_boundary, only : setup_obc_thickness_reservoirs
124use mom_open_boundary, only : open_boundary_register_restarts, remap_obc_fields
125use mom_open_boundary, only : open_boundary_setup_vert, initialize_segment_data
126use mom_open_boundary, only : update_obc_dynamics_data, update_obc_tracer_data
127use mom_open_boundary, only : rotate_obc_config
128use mom_open_boundary, only : open_boundary_halo_update, write_obc_info, chksum_obc_segments
129use mom_open_boundary, only : segment_thickness_reservoir_init
130use mom_open_boundary, only : copy_obc_radiation_coefs
131use mom_open_boundary, only : copy_obc_tracer_reservoirs, copy_obc_thickness_reservoirs
132use mom_porous_barriers, only : porous_widths_layer, porous_widths_interface, porous_barriers_init
133use mom_porous_barriers, only : porous_barrier_cs
134use mom_set_visc, only : set_viscous_bbl, set_viscous_ml, set_visc_cs
135use mom_set_visc, only : set_visc_register_restarts, remap_vertvisc_aux_vars
136use mom_set_visc, only : set_visc_init, set_visc_end
137use mom_shared_initialization, only : write_ocean_geometry_file
138use mom_sponge, only : init_sponge_diags, sponge_cs
139use mom_state_initialization, only : mom_initialize_state, mom_initialize_obcs
140use mom_stoch_eos, only : mom_stoch_eos_init, mom_stoch_eos_run, mom_stoch_eos_cs
141use mom_stoch_eos, only : stoch_eos_register_restarts, post_stoch_eos_diags, mom_calc_vart
142use mom_sum_output, only : write_energy, accumulate_net_input
143use mom_sum_output, only : mom_sum_output_init, mom_sum_output_end
144use mom_sum_output, only : sum_output_cs
145use mom_ale_sponge, only : init_ale_sponge_diags, ale_sponge_cs
146use mom_thickness_diffuse, only : thickness_diffuse, thickness_diffuse_init
147use mom_thickness_diffuse, only : thickness_diffuse_end, thickness_diffuse_cs
148use mom_tracer_advect, only : advect_tracer, tracer_advect_init
149use mom_tracer_advect, only : tracer_advect_end, tracer_advect_cs
150use mom_tracer_hor_diff, only : tracer_hordiff, tracer_hor_diff_init
151use mom_tracer_hor_diff, only : tracer_hor_diff_end, tracer_hor_diff_cs
152use mom_tracer_registry, only : tracer_registry_type, register_tracer, tracer_registry_init
154use mom_tracer_registry, only : post_tracer_transport_diagnostics, mom_tracer_chksum
155use mom_tracer_registry, only : post_tracer_integral_diagnostics
156use mom_tracer_registry, only : preale_tracer_diagnostics, postale_tracer_diagnostics
157use mom_tracer_registry, only : lock_tracer_registry, tracer_registry_end
158use mom_tracer_flow_control, only : call_tracer_register, tracer_flow_control_cs
159use mom_tracer_flow_control, only : tracer_flow_control_init, call_tracer_surface_state
161use mom_transcribe_grid, only : copy_dyngrid_to_mom_grid, copy_mom_grid_to_dyngrid
162use mom_unit_scaling, only : unit_scale_type, unit_scaling_init, unit_scaling_end
163use mom_variables, only : surface, allocate_surface_state, deallocate_surface_state
164use mom_variables, only : thermo_var_ptrs, vertvisc_type, porous_barrier_type
165use mom_variables, only : accel_diag_ptrs, cont_diag_ptrs, ocean_internal_state
166use mom_variables, only : rotate_surface_state
167use mom_verticalgrid, only : verticalgrid_type, verticalgridinit, verticalgridend
168use mom_verticalgrid, only : get_thickness_units, get_flux_units, get_tr_flux_units
169use mom_wave_interface, only : wave_parameters_cs, waves_end, waves_register_restarts
170use mom_wave_interface, only : update_stokes_drift
171
172! Database client used for machine-learning interface
173use mom_database_comms, only : dbcomms_cs_type, database_comms_init, dbclient_type
174
175! ODA modules
176use mom_oda_driver_mod, only : oda_cs, oda, init_oda, oda_end
177use mom_oda_driver_mod, only : set_prior_tracer, set_analysis_time, apply_oda_tracer_increments
178use mom_oda_incupd, only : oda_incupd_cs, init_oda_incupd_diags
179
180! Offline modules
181use mom_offline_main, only : offline_transport_cs, offline_transport_init, update_offline_fields
182use mom_offline_main, only : insert_offline_main, extract_offline_main, post_offline_convergence_diags
183use mom_offline_main, only : register_diags_offline_transport, offline_advection_ale
184use mom_offline_main, only : offline_redistribute_residual, offline_diabatic_ale
185use mom_offline_main, only : offline_fw_fluxes_into_ocean, offline_fw_fluxes_out_ocean
186use mom_offline_main, only : offline_advection_layer, offline_transport_end
187use mom_ice_shelf, only : ice_shelf_cs, ice_shelf_query, initialize_ice_shelf
188use mom_particles_mod, only : particles, particles_init, particles_run, particles_save_restart, particles_end
189use mom_particles_mod, only : particles_to_k_space, particles_to_z_space
190implicit none ; private
191
192#include <MOM_memory.h>
193
194! A note on unit descriptions in comments: MOM6 uses units that can be rescaled for dimensional
195! consistency testing. These are noted in comments with units like Z, H, L, and T, along with
196! their mks counterparts with notation like "a velocity [Z T-1 ~> m s-1]". If the units
197! vary with the Boussinesq approximation, the Boussinesq variant is given first.
198
199!> A structure with diagnostic IDs of the state variables
200type mom_diag_ids
201 !>@{ 3-d state field diagnostic IDs
202 integer :: id_u = -1, id_v = -1, id_h = -1
203 !>@}
204 !> 2-d state field diagnostic ID
205 integer :: id_ssh_inst = -1
206end type mom_diag_ids
207
208!> Control structure for the MOM module, including the variables that describe
209!! the state of the ocean.
210type, public :: mom_control_struct ; private
211 real allocable_, dimension(NIMEM_,NJMEM_,NKMEM_) :: &
212 h, & !< layer thickness [H ~> m or kg m-2]
213 t, & !< potential temperature [C ~> degC]
214 s !< salinity [S ~> ppt]
215 real allocable_, dimension(NIMEMB_PTR_,NJMEM_,NKMEM_) :: &
216 u, & !< zonal velocity component [L T-1 ~> m s-1]
217 uh, & !< uh = u * h * dy at u grid points [H L2 T-1 ~> m3 s-1 or kg s-1]
218 uhtr !< accumulated zonal thickness fluxes to advect tracers [H L2 ~> m3 or kg]
219 real allocable_, dimension(NIMEM_,NJMEMB_PTR_,NKMEM_) :: &
220 v, & !< meridional velocity [L T-1 ~> m s-1]
221 vh, & !< vh = v * h * dx at v grid points [H L2 T-1 ~> m3 s-1 or kg s-1]
222 vhtr !< accumulated meridional thickness fluxes to advect tracers [H L2 ~> m3 or kg]
223 real allocable_, dimension(NIMEM_,NJMEM_) :: ssh_rint
224 !< A running time integral of the sea surface height [T Z ~> s m].
225 real allocable_, dimension(NIMEM_,NJMEM_) :: ave_ssh_ibc
226 !< time-averaged (over a forcing time step) sea surface height
227 !! with a correction for the inverse barometer [Z ~> m]
228 real allocable_, dimension(NIMEM_,NJMEM_) :: eta_av_bc
229 !< free surface height or column mass time averaged over the last
230 !! baroclinic dynamics time step [H ~> m or kg m-2]
231 real, dimension(:,:), pointer :: hml => null()
232 !< active mixed layer depth, or 0 if there is no boundary layer scheme [Z ~> m]
233 real :: time_in_cycle !< The running time of the current time-stepping cycle
234 !! in calls that step the dynamics, and also the length of
235 !! the time integral of ssh_rint [T ~> s].
236 real :: time_in_thermo_cycle !< The running time of the current time-stepping
237 !! cycle in calls that step the thermodynamics [T ~> s].
238
239 type(ocean_grid_type) :: g_in !< Input grid metric
240 type(ocean_grid_type), pointer :: g => null() !< Model grid metric
241 logical :: rotate_index = .false. !< True if index map is rotated
242 logical :: homogenize_forcings = .false. !< True if all inputs are homogenized
243 logical :: update_ustar = .false. !< True to update ustar from homogenized tau
244 logical :: vertex_shear = .false. !< True if vertex shear is on
245
246 type(verticalgrid_type), pointer :: &
247 gv => null() !< structure containing vertical grid info
248 type(unit_scale_type), pointer :: &
249 us => null() !< structure containing various unit conversion factors
250 type(thermo_var_ptrs) :: tv !< structure containing pointers to available thermodynamic fields
251 real :: t_dyn_rel_adv !< The time of the dynamics relative to tracer advection and lateral mixing
252 !! [T ~> s], or equivalently the elapsed time since advectively updating the
253 !! tracers. t_dyn_rel_adv is invariably positive and may span multiple coupling timesteps.
254 integer :: n_dyn_steps_in_adv !< The number of dynamics time steps that contributed to uhtr
255 !! and vhtr since the last time tracer advection occured.
256 real :: t_dyn_rel_thermo !< The time of the dynamics relative to diabatic processes and remapping
257 !! [T ~> s]. t_dyn_rel_thermo can be negative or positive depending on whether
258 !! the diabatic processes are applied before or after the dynamics and may span
259 !! multiple coupling timesteps.
260 real :: t_dyn_rel_diag !< The time of the diagnostics relative to diabatic processes and remapping
261 !! [T ~> s]. t_dyn_rel_diag is always positive, since the diagnostics must lag.
262 logical :: preadv_h_stored = .false. !< If true, the thicknesses from before the advective cycle
263 !! have been stored for use in diagnostics.
264
265 type(diag_ctrl) :: diag !< structure to regulate diagnostic output timing
266 type(vertvisc_type) :: visc !< structure containing vertical viscosities,
267 !! bottom drag viscosities, and related fields
268 type(meke_type) :: meke !< Fields related to the Mesoscale Eddy Kinetic Energy
269 logical :: adiabatic !< If true, there are no diapycnal mass fluxes, and no calls
270 !! to routines to calculate or apply diapycnal fluxes.
271 logical :: diabatic_first !< If true, apply diabatic and thermodynamic processes before time
272 !! stepping the dynamics.
273 logical :: use_ale_algorithm !< If true, use the ALE algorithm rather than layered
274 !! isopycnal/stacked shallow water mode. This logical is set by calling the
275 !! function useRegridding() from the MOM_regridding module.
276 logical :: remap_aux_vars !< If true, apply ALE remapping to all of the auxiliary 3-D
277 !! variables that are needed to reproduce across restarts,
278 !! similarly to what is done with the primary state variables.
279 logical :: remap_uv_using_old_alg !< If true, use the old "remapping via a delta z" method for
280 !! velocities. If false, remap between two grids described by thicknesses.
281
282 type(mom_stoch_eos_cs) :: stoch_eos_cs !< structure containing random pattern for stoch EOS
283 logical :: alternate_first_direction !< If true, alternate whether the x- or y-direction
284 !! updates occur first in directionally split parts of the calculation.
285 real :: first_dir_restart = -1.0 !< A real copy of G%first_direction for use in restart files [nondim]
286 logical :: offline_tracer_mode = .false.
287 !< If true, step_offline() is called instead of step_MOM().
288 !! This is intended for running MOM6 in offline tracer mode
289 logical :: meke_in_dynamics !< If .true. (default), MEKE is called in the dynamics routine otherwise
290 !! it is called during the tracer dynamics
291
292 type(time_type), pointer :: time !< pointer to the ocean clock
293 real :: dt !< (baroclinic) dynamics time step [T ~> s]
294 real :: dt_therm !< diabatic time step [T ~> s]
295 real :: dt_tr_adv !< tracer advection time step [T ~> s]
296 logical :: thermo_spans_coupling !< If true, thermodynamic and tracer time
297 !! steps can span multiple coupled time steps.
298 logical :: tradv_spans_coupling !< If true, thermodynamic and tracer time
299 integer :: nstep_tot = 0 !< The total number of dynamic timesteps taken
300 !! so far in this run segment
301 logical :: count_calls = .false. !< If true, count the calls to step_MOM, rather than the
302 !! number of dynamics steps in nstep_tot
303 logical :: debug !< If true, write verbose checksums for debugging purposes.
304 logical :: debug_obcs !< If true, write verbose OBC values for debugging purposes.
305 integer :: ntrunc !< number u,v truncations since last call to write_energy
306
307 integer :: cont_stencil !< The stencil for thickness from the continuity solver.
308 integer :: dyn_h_stencil !< The stencil for thickness for the dynamics based on
309 !! the continuity solver and Coriolis schemes.
310 ! These elements are used to control the dynamics updates.
311 logical :: do_dynamics !< If false, does not call step_MOM_dyn_*. This is an
312 !! undocumented run-time flag that is fragile.
313 logical :: split !< If true, use the split time stepping scheme.
314 logical :: use_alt_split !< If true, use a version of the split explicit time stepping
315 !! scheme that exchanges velocities with step_MOM that have the
316 !! average barotropic phase over a baroclinic timestep rather
317 !! than the instantaneous barotropic phase.
318 logical :: use_rk2 !< If true, use RK2 instead of RK3 in unsplit mode
319 !! (i.e., no split between barotropic and baroclinic).
320 logical :: interface_filter !< If true, apply an interface height filter immediately
321 !! after any calls to thickness_diffuse.
322 logical :: thickness_diffuse !< If true, diffuse interface height w/ a diffusivity KHTH.
323 logical :: thickness_diffuse_first !< If true, diffuse thickness before dynamics.
324 logical :: interface_filter_dt_bug !< If true, uses the wrong time interval in
325 !! calls to interface_filter and thickness_diffuse.
326 logical :: mixedlayer_restrat !< If true, use submesoscale mixed layer restratifying scheme.
327 logical :: usemeke !< If true, call the MEKE parameterization.
328 logical :: use_stochastic_eos !< If true, use the stochastic EOS parameterizations.
329 logical :: usewaves !< If true, update Stokes drift
330 logical :: stokesmost !< If true, use Stokes Similarity package. Needed to decide if Lam2 should
331 !! be passed to mixedlayer_restrat.
332 logical :: wave_enhanced_ustar !< If true, enhance ustar in Bodner23. Needed to decide if Lam2 should
333 !! be passed to mixedlayer_restrat.
334 real :: dtbt_reset_period !< The time interval between dynamic recalculation of the
335 !! barotropic time step [T ~> s]. If this is negative dtbt is never
336 !! calculated, and if it is 0, dtbt is calculated every step.
337 type(time_type) :: dtbt_reset_interval !< A time_time representation of dtbt_reset_period.
338 type(time_type) :: dtbt_reset_time !< The next time DTBT should be calculated.
339 real :: dt_obc_seg_period !< The time interval between OBC segment updates for OBGC
340 !! tracers [T ~> s], or a negative value if the segment
341 !! data are time-invarant, or zero to update the OBGC
342 !! segment data with every call to update_OBC_tracer_data.
343 type(time_type) :: dt_obc_seg_interval !< A time_time representation of dt_obc_seg_period.
344 type(time_type) :: dt_obc_seg_time !< The next time OBC segment update is applied to OBGC tracers.
345
346 real, dimension(:,:), pointer :: frac_shelf_h => null() !< fraction of total area occupied
347 !! by ice shelf [nondim]
348 real, dimension(:,:), pointer :: mass_shelf => null() !< Mass of ice shelf [R Z ~> kg m-2]
349 type(accel_diag_ptrs) :: adp !< structure containing pointers to accelerations,
350 !! for derived diagnostics (e.g., energy budgets)
351 type(cont_diag_ptrs) :: cdp !< structure containing pointers to continuity equation
352 !! terms, for derived diagnostics (e.g., energy budgets)
353 real, dimension(:,:,:), pointer :: &
354 u_prev => null(), & !< previous value of u stored for diagnostics [L T-1 ~> m s-1]
355 v_prev => null() !< previous value of v stored for diagnostics [L T-1 ~> m s-1]
356
357 logical :: interp_p_surf !< If true, linearly interpolate surface pressure
358 !! over the coupling time step, using specified value
359 !! at the end of the coupling step. False by default.
360 logical :: p_surf_prev_set !< If true, p_surf_prev has been properly set from
361 !! a previous time-step or the ocean restart file.
362 !! This is only valid when interp_p_surf is true.
363 real, dimension(:,:), pointer :: &
364 p_surf_prev => null(), & !< surface pressure [R L2 T-2 ~> Pa] at end previous call to step_MOM
365 p_surf_begin => null(), & !< surface pressure [R L2 T-2 ~> Pa] at start of step_MOM_dyn_...
366 p_surf_end => null() !< surface pressure [R L2 T-2 ~> Pa] at end of step_MOM_dyn_...
367
368 ! Variables needed to reach between start and finish phases of initialization
369 logical :: write_ic !< If true, then the initial conditions will be written to file
370 character(len=120) :: ic_file !< A file into which the initial conditions are
371 !! written in a new run if SAVE_INITIAL_CONDS is true.
372
373 logical :: calc_rho_for_sea_lev !< If true, calculate rho to convert pressure to sea level
374
375 ! These elements are used to control the calculation and error checking of the surface state
376 real :: hmix !< Diagnostic mixed layer thickness over which to
377 !! average surface tracer properties when a bulk
378 !! mixed layer is not used [H ~> m or kg m-2], or a negative value
379 !! if a bulk mixed layer is being used.
380 real :: hfrz !< If HFrz > 0, the nominal depth over which melt potential is computed
381 !! [H ~> m or kg m-2]. The actual depth over which melt potential is
382 !! computed is min(HFrz, OBLD), where OBLD is the boundary layer depth.
383 !! If HFrz <= 0 (default), melt potential will not be computed.
384 real :: hmix_uv !< Depth scale over which to average surface flow to
385 !! feedback to the coupler/driver [H ~> m or kg m-2] when
386 !! bulk mixed layer is not used, or a negative value
387 !! if a bulk mixed layer is being used.
388 logical :: check_bad_sfc_vals !< If true, scan surface state for ridiculous values.
389 real :: bad_val_ssh_max !< Maximum SSH before triggering bad value message [Z ~> m]
390 real :: bad_val_sst_max !< Maximum SST before triggering bad value message [C ~> degC]
391 real :: bad_val_sst_min !< Minimum SST before triggering bad value message [C ~> degC]
392 real :: bad_val_sss_max !< Maximum SSS before triggering bad value message [S ~> ppt]
393 real :: bad_val_col_thick !< Minimum column thickness before triggering bad value message [Z ~> m]
394 integer :: answer_date !< The vintage of the expressions for the surface properties. Values
395 !! below 20190101 recover the answers from the end of 2018, while
396 !! higher values use more appropriate expressions that differ at
397 !! roundoff for non-Boussinesq cases.
398 logical :: use_particles !< Turns on the particles package
399 logical :: use_uh_particles !< particles are advected by uh/h
400 logical :: uh_particles_bug !< If true, uses an inconsistent timestep for particle advection
401 logical :: use_dbclient !< Turns on the database client used for ML inference/analysis
402 character(len=10) :: particle_type !< Particle types include: surface(default), profiling and sail drone.
403
404 type(mom_diag_ids) :: ids !< Handles used for diagnostics.
405 type(transport_diag_ids) :: transport_ids !< Handles used for transport diagnostics.
406 type(surface_diag_ids) :: sfc_ids !< Handles used for surface diagnostics.
407 type(diag_grid_storage) :: diag_pre_sync !< The grid (thicknesses) before remapping
408 type(diag_grid_storage) :: diag_pre_dyn !< The grid (thicknesses) before dynamics
409
410 logical :: accumulate_resolved_flux = .false. !< If true, accumulate resolved flux for tracers for diagnostics
411 !! separating the tracer flux due to resolved and parameterized flow
412 logical :: do_resolved_advection = .false. !< If true, calculate advection by resolved flow
413 logical :: do_param_advection = .false. !< If true, calculate advection by parameterized flow
414 real, allocatable, dimension(:,:,:) :: &
415 uhtr_resolved !< accumulated zonal thickness fluxes due to resolved flow to advect tracers [H L2 ~> m3 or kg]
416 real, allocatable, dimension(:,:,:) :: &
417 vhtr_resolved !< accumulated meridional thickness fluxes due to resolved flow to advect tracers [H L2 ~> m3 or kg]
418
419 ! The remainder of this type provides pointers to child module control structures.
420
421 type(mom_dyn_unsplit_cs), pointer :: dyn_unsplit_csp => null()
422 !< Pointer to the control structure used for the unsplit dynamics
423 type(mom_dyn_unsplit_rk2_cs), pointer :: dyn_unsplit_rk2_csp => null()
424 !< Pointer to the control structure used for the unsplit RK2 dynamics
425 type(mom_dyn_split_rk2_cs), pointer :: dyn_split_rk2_csp => null()
426 !< Pointer to the control structure used for the mode-split RK2 dynamics
427 type(mom_dyn_split_rk2b_cs), pointer :: dyn_split_rk2b_csp => null()
428 !< Pointer to the control structure used for an alternate version of the mode-split RK2 dynamics
429 type(harmonic_analysis_cs), pointer :: ha_csp => null()
430 !< Pointer to the control structure for harmonic analysis
431 type(thickness_diffuse_cs) :: thickness_diffuse_csp
432 !< Pointer to the control structure used for the isopycnal height diffusive transport.
433 !! This is also common referred to as Gent-McWilliams diffusion
434 type(interface_filter_cs) :: interface_filter_csp
435 !< Control structure used for the interface height smoothing operator.
436 type(mixedlayer_restrat_cs) :: mixedlayer_restrat_csp
437 !< Pointer to the control structure used for the mixed layer restratification
438 type(set_visc_cs) :: set_visc_csp
439 !< Pointer to the control structure used to set viscosities
440 type(diabatic_cs), pointer :: diabatic_csp => null()
441 !< Pointer to the control structure for the diabatic driver
442 type(meke_cs) :: meke_csp
443 !< Pointer to the control structure for the MEKE updates
444 type(varmix_cs) :: varmix
445 !< Control structure for the variable mixing module
446 type(tracer_registry_type), pointer :: tracer_reg => null()
447 !< Pointer to the MOM tracer registry
448 type(tracer_advect_cs), pointer :: tracer_adv_csp => null()
449 !< Pointer to the MOM tracer advection control structure
450 type(tracer_hor_diff_cs), pointer :: tracer_diff_csp => null()
451 !< Pointer to the MOM along-isopycnal tracer diffusion control structure
452 type(tracer_flow_control_cs), pointer :: tracer_flow_csp => null()
453 !< Pointer to the control structure that orchestrates the calling of tracer packages
454 ! Although update_OBC_CS is not used directly outside of initialization, other modules
455 ! set pointers to this type, so it should be kept for the duration of the run.
456 type(update_obc_cs), pointer :: update_obc_csp => null()
457 !< Pointer to the control structure for updating open boundary condition properties
458 type(ocean_obc_type), pointer :: obc => null()
459 !< Pointer to the MOM open boundary condition type
460 type(sponge_cs), pointer :: sponge_csp => null()
461 !< Pointer to the layered-mode sponge control structure
462 type(ale_sponge_cs), pointer :: ale_sponge_csp => null()
463 !< Pointer to the ALE-mode sponge control structure
464 type(oda_incupd_cs), pointer :: oda_incupd_csp => null()
465 !< Pointer to the oda incremental update control structure
466 type(int_tide_cs), pointer :: int_tide_csp => null()
467 !< Pointer to the internal tides control structure
468 type(ale_cs), pointer :: ale_csp => null()
469 !< Pointer to the Arbitrary Lagrangian Eulerian (ALE) vertical coordinate control structure
470
471 ! Pointers to control structures used for diagnostics
472 type(sum_output_cs), pointer :: sum_output_csp => null()
473 !< Pointer to the globally summed output control structure
474 type(diagnostics_cs) :: diagnostics_csp
475 !< Pointer to the MOM diagnostics control structure
476 type(offline_transport_cs), pointer :: offline_csp => null()
477 !< Pointer to the offline tracer transport control structure
478 type(porous_barrier_cs) :: por_bar_cs
479 !< Control structure for porous barrier
480
481 logical :: ensemble_ocean !< if true, this run is part of a
482 !! larger ensemble for the purpose of data assimilation
483 !! or statistical analysis.
484 type(oda_cs), pointer :: odacs => null() !< a pointer to the control structure for handling
485 !! ensemble model state vectors and data assimilation
486 !! increments and priors
487 type(dbcomms_cs_type) :: dbcomms_cs !< Control structure for database client used for online ML/AI
488 logical :: use_porbar !< If true, use porous barrier to constrain the widths and face areas
489 !! at the edges of the grid cells.
490 type(porous_barrier_type) :: pbv !< porous barrier fractional cell metrics
491 type(particles), pointer :: particles => null() !<Lagrangian particles
492 type(stochastic_cs), pointer :: stoch_cs => null() !< a pointer to the stochastics control structure
493 type(mom_restart_cs), pointer :: restart_cs => null()
494 !< Pointer to MOM's restart control structure
495end type mom_control_struct
496
497public initialize_mom, finish_mom_initialization, mom_end
498public step_mom, step_offline
499public extract_surface_state, get_ocean_stocks
500public get_mom_state_elements, mom_state_is_synchronized
501public allocate_surface_state, deallocate_surface_state
502public save_mom_restart
503
504!>@{ CPU time clock IDs
505integer :: id_clock_ocean
506integer :: id_clock_dynamics
507integer :: id_clock_thermo
508integer :: id_clock_mom_end
509integer :: id_clock_remap
510integer :: id_clock_tracer
511integer :: id_clock_diabatic
512integer :: id_clock_adiabatic
513integer :: id_clock_continuity ! also in dynamics s/r
514integer :: id_clock_thick_diff
515integer :: id_clock_int_filter
516integer :: id_clock_bbl_visc
517integer :: id_clock_ml_restrat
518integer :: id_clock_diagnostics
519integer :: id_clock_z_diag
520integer :: id_clock_init
521integer :: id_clock_mom_init
522integer :: id_clock_pass ! also in dynamics d/r
523integer :: id_clock_pass_init ! also in dynamics d/r
524integer :: id_clock_ale
525integer :: id_clock_other
526integer :: id_clock_offline_tracer
527integer :: id_clock_save_restart
528integer :: id_clock_unit_tests
529integer :: id_clock_stoch
530integer :: id_clock_vart
531!>@}
532
533contains
534
535!> This subroutine orchestrates the time stepping of MOM. The adiabatic
536!! dynamics are stepped by calls to one of the step_MOM_dyn_...routines.
537!! The action of lateral processes on tracers occur in calls to
538!! advect_tracer and tracer_hordiff. Vertical mixing and possibly remapping
539!! occur inside of diabatic.
540subroutine step_mom(forces_in, fluxes_in, sfc_state, Time_start, time_int_in, CS, &
541 Waves, do_dynamics, do_thermodynamics, start_cycle, &
542 end_cycle, cycle_length, reset_therm)
543 type(mech_forcing), target, intent(inout) :: forces_in !< A structure with the driving mechanical forces
544 type(forcing), target, intent(inout) :: fluxes_in !< A structure with pointers to themodynamic,
545 !! tracer and mass exchange forcing fields
546 type(surface), target, intent(inout) :: sfc_state !< surface ocean state
547 type(time_type), intent(in) :: time_start !< starting time of a segment, as a time type
548 real, intent(in) :: time_int_in !< time interval covered by this run segment [T ~> s].
549 type(mom_control_struct), intent(inout), target :: cs !< control structure from initialize_MOM
550 type(wave_parameters_cs), &
551 optional, pointer :: waves !< An optional pointer to a wave property CS
552 logical, optional, intent(in) :: do_dynamics !< Present and false, do not do updates due
553 !! to the dynamics.
554 logical, optional, intent(in) :: do_thermodynamics !< Present and false, do not do updates due
555 !! to the thermodynamics or remapping.
556 logical, optional, intent(in) :: start_cycle !< This indicates whether this call is to be
557 !! treated as the first call to step_MOM in a
558 !! time-stepping cycle; missing is like true.
559 logical, optional, intent(in) :: end_cycle !< This indicates whether this call is to be
560 !! treated as the last call to step_MOM in a
561 !! time-stepping cycle; missing is like true.
562 real, optional, intent(in) :: cycle_length !< The amount of time in a coupled time
563 !! stepping cycle [T ~> s].
564 logical, optional, intent(in) :: reset_therm !< This indicates whether the running sums of
565 !! thermodynamic quantities should be reset.
566 !! If missing, this is like start_cycle.
567
568 ! local variables
569 type(ocean_grid_type), pointer :: g => null() ! pointer to a structure containing
570 ! metrics and related information
571 type(ocean_grid_type), pointer :: g_in => null() ! Input grid metric
572 type(verticalgrid_type), pointer :: gv => null() ! Pointer to the vertical grid structure
573 type(unit_scale_type), pointer :: us => null() ! Pointer to a structure containing
574 ! various unit conversion factors
575 integer :: ntstep ! number of time steps between diabatic forcing updates
576 integer :: ntastep ! number of time steps between tracer advection updates
577 integer :: n_max ! number of steps to take in this call
578 integer :: halo_sz, dynamics_stencil
579
580 integer :: i, j, k, is, ie, js, je, isq, ieq, jsq, jeq, nz, n
581 integer :: isd, ied, jsd, jed, isdb, iedb, jsdb, jedb
582
583 real :: time_interval ! time interval covered by this run segment [T ~> s].
584 real :: dt ! baroclinic time step [T ~> s]
585 real :: dtdia ! time step for diabatic processes [T ~> s]
586 real :: dt_tr_adv ! time step for tracer advection [T ~> s]
587 real :: dt_therm ! a limited and quantized version of CS%dt_therm [T ~> s]
588 real :: dt_tradv_here ! a further limited value of dt_tr_adv [T ~> s]
589
590 real :: wt_end, wt_beg ! Fractional weights of the future pressure at the end
591 ! and beginning of the current time step [nondim]
592 real :: bbl_time_int ! The amount of time over which the calculated BBL
593 ! properties will apply, for use in diagnostics, or 0
594 ! if it is not to be calculated anew [T ~> s].
595 real :: rel_time = 0.0 ! relative time since start of this call [T ~> s].
596
597 logical :: do_advection ! If true, do tracer advection.
598 logical :: do_diabatic ! If true, do diabatic update.
599 logical :: thermo_does_span_coupling ! If true,thermodynamic (diabatic) forcing spans
600 ! multiple coupling timesteps.
601 logical :: tradv_does_span_coupling ! If true, tracer advection spans
602 ! multiple coupling timesteps.
603 logical :: do_dyn ! If true, dynamics are updated with this call.
604 logical :: do_thermo ! If true, thermodynamics and remapping may be applied with this call.
605 logical :: debug_redundant ! If true, check redundant values on PE boundaries when debugging.
606 logical :: nonblocking_p_surf_update ! A flag to indicate whether surface properties
607 ! can use nonblocking halo updates
608 logical :: cycle_start ! If true, do calculations that are only done at the start of
609 ! a stepping cycle (whatever that may mean).
610 logical :: cycle_end ! If true, do calculations and diagnostics that are only done at
611 ! the end of a stepping cycle (whatever that may mean).
612 logical :: therm_reset ! If true, reset running sums of thermodynamic quantities.
613 real :: cycle_time ! The length of the coupled time-stepping cycle [T ~> s].
614 real, dimension(SZI_(CS%G),SZJ_(CS%G)) :: &
615 u_star ! The wind friction velocity, calculated using the Boussinesq reference density or
616 ! the time-evolving surface density in non-Boussinesq mode [Z T-1 ~> m s-1]
617 real, dimension(SZI_(CS%G),SZJ_(CS%G)) :: &
618 ssh ! sea surface height, which may be based on eta_av [Z ~> m]
619 real, dimension(SZI_(CS%G),SZJ_(CS%G),SZK_(CS%GV)) :: &
620 dz ! Vertical distance across layers [Z ~> m]
621
622 real, dimension(:,:,:), pointer :: &
623 u => null(), & ! u : zonal velocity component [L T-1 ~> m s-1]
624 v => null(), & ! v : meridional velocity component [L T-1 ~> m s-1]
625 h => null() ! h : layer thickness [H ~> m or kg m-2]
626 real, dimension(:,:), pointer :: &
627 p_surf => null() ! A pointer to the ocean surface pressure [R L2 T-2 ~> Pa].
628 real :: i_wt_ssh ! The inverse of the time weights [T-1 ~> s-1]
629
630 type(time_type) :: time_local, end_time_thermo
631 type(time_type) :: time_end_diag ! End time of a diagnostic segment, as a time type
632
633 type(group_pass_type) :: pass_tau_ustar_psurf
634 logical :: showcalltree
635
636 ! External forcing fields on the model index map
637 type(mech_forcing), pointer :: forces ! Mechanical forcing
638 type(forcing), pointer :: fluxes ! Boundary fluxes
639 type(surface), pointer :: sfc_state_diag ! Surface boundary fields
640 integer :: turns ! Number of quarter turns from input to model indexing
641
642 g => cs%G ; g_in => cs%G_in ; gv => cs%GV ; us => cs%US
643 is = g%isc ; ie = g%iec ; js = g%jsc ; je = g%jec ; nz = gv%ke
644 isq = g%IscB ; ieq = g%IecB ; jsq = g%JscB ; jeq = g%JecB
645 isd = g%isd ; ied = g%ied ; jsd = g%jsd ; jed = g%jed
646 isdb = g%IsdB ; iedb = g%IedB ; jsdb = g%JsdB ; jedb = g%JedB
647 u => cs%u ; v => cs%v ; h => cs%h
648
649 time_interval = time_int_in
650 do_dyn = .true. ; if (present(do_dynamics)) do_dyn = do_dynamics
651 do_thermo = .true. ; if (present(do_thermodynamics)) do_thermo = do_thermodynamics
652 if (.not.(do_dyn .or. do_thermo)) call mom_error(fatal,"Step_MOM: "//&
653 "Both do_dynamics and do_thermodynamics are false, which makes no sense.")
654 cycle_start = .true. ; if (present(start_cycle)) cycle_start = start_cycle
655 cycle_end = .true. ; if (present(end_cycle)) cycle_end = end_cycle
656 cycle_time = time_interval ; if (present(cycle_length)) cycle_time = cycle_length
657 therm_reset = cycle_start ; if (present(reset_therm)) therm_reset = reset_therm
658
659 call cpu_clock_begin(id_clock_ocean)
660 call cpu_clock_begin(id_clock_other)
661
662 if (cs%debug) then
663 call query_debugging_checks(do_redundant=debug_redundant)
664 call mom_state_chksum("Beginning of step_MOM ", u, v, h, cs%uh, cs%vh, g, gv, us)
665 endif
666
667 showcalltree = calltree_showquery()
668 if (showcalltree) call calltree_enter("step_MOM(), MOM.F90")
669
670 ! Rotate the forces from G_in to G
671 if (cs%rotate_index) then
672 turns = g%HI%turns
673 allocate(forces)
674 call allocate_mech_forcing(forces_in, g, forces)
675 call rotate_mech_forcing(forces_in, turns, forces)
676
677 allocate(fluxes)
678 call allocate_forcing_type(fluxes_in, g, fluxes, turns=turns)
679 call rotate_forcing(fluxes_in, fluxes, turns)
680 else
681 forces => forces_in
682 fluxes => fluxes_in
683 endif
684
685 ! Homogenize the forces
686 if (cs%homogenize_forcings) then
687 ! Homogenize all forcing and fluxes fields.
688 call homogenize_mech_forcing(forces, g, us, gv%Rho0, cs%update_ustar)
689 ! Note the following computes the mean ustar as the mean of ustar rather than
690 ! ustar of the mean of tau.
691 call homogenize_forcing(fluxes, g, gv, us)
692 if (cs%update_ustar) then
693 ! These calls corrects the ustar values
694 call copy_common_forcing_fields(forces, fluxes, g)
695 call set_derived_forcing_fields(forces, fluxes, g, us, gv%Rho0)
696 endif
697 endif
698
699 ! This will be replaced later with the pressures from forces or fluxes if they are available.
700 if (associated(cs%tv%p_surf)) cs%tv%p_surf(:,:) = 0.0
701
702 ! First determine the time step that is consistent with this call and an
703 ! integer fraction of time_interval.
704 if (do_dyn) then
705 n_max = 1
706 if (time_interval > cs%dt) n_max = ceiling(time_interval/cs%dt - 0.001)
707
708 dt = time_interval / real(n_max)
709 thermo_does_span_coupling = (cs%thermo_spans_coupling .and. &
710 (cs%dt_therm > 1.5*cycle_time))
711 tradv_does_span_coupling = (cs%tradv_spans_coupling .and. &
712 (cs%dt_tr_adv > 1.5*cycle_time))
713 if (thermo_does_span_coupling) then
714 ! Set dt_therm to be an integer multiple of the coupling time step.
715 dt_therm = cycle_time * floor(cs%dt_therm / cycle_time + 0.001)
716 ntstep = floor(dt_therm/dt + 0.001)
717 elseif (.not.do_thermo) then
718 dt_therm = cs%dt_therm
719 if (present(cycle_length)) dt_therm = min(cs%dt_therm, cycle_length)
720 ntstep = 1 ! ntstep is initialized to avoid an error in a secondary logical test,
721 ! but the nonzero value of ntstep does not matter when do_thermo is false.
722 else
723 ntstep = max(1, min(n_max, floor(cs%dt_therm/dt + 0.001)))
724 dt_therm = dt*ntstep
725 endif
726 if (tradv_does_span_coupling) then
727 ! Set dt_tr_adv to be an integer multiple of the coupling time step.
728 dt_tr_adv = cycle_time * floor(cs%dt_tr_adv / cycle_time + 0.001)
729 ntastep = floor(dt_tr_adv/dt + 0.001)
730 elseif (.not.do_thermo) then
731 dt_tr_adv = cs%dt_tr_adv
732 if (present(cycle_length)) dt_tr_adv = min(cs%dt_tr_adv, cycle_length)
733 ! ntastep is not used.
734 else
735 ntastep = max(1, min(n_max, floor(cs%dt_tr_adv/dt + 0.001)))
736 dt_tr_adv = dt*ntastep
737 endif
738
739 !---------- Initiate group halo pass of the forcing fields
740 call cpu_clock_begin(id_clock_pass)
741 ! Halo updates for surface pressure need to be completed before calling calc_resoln_function
742 ! among other routines if the surface pressure is used in the equation of state.
743 nonblocking_p_surf_update = g%nonblocking_updates .and. &
744 .not.(associated(cs%tv%p_surf) .and. associated(forces%p_surf) .and. &
745 allocated(cs%tv%SpV_avg) .and. associated(cs%tv%T))
746 if (.not.associated(forces%taux) .or. .not.associated(forces%tauy)) &
747 call mom_error(fatal,'step_MOM:forces%taux,tauy not associated')
748 call create_group_pass(pass_tau_ustar_psurf, forces%taux, forces%tauy, g%Domain)
749 if (associated(forces%ustar)) &
750 call create_group_pass(pass_tau_ustar_psurf, forces%ustar, g%Domain)
751 if (associated(forces%tau_mag)) &
752 call create_group_pass(pass_tau_ustar_psurf, forces%tau_mag, g%Domain)
753 if (associated(forces%p_surf)) &
754 call create_group_pass(pass_tau_ustar_psurf, forces%p_surf, g%Domain)
755 if (nonblocking_p_surf_update) then
756 call start_group_pass(pass_tau_ustar_psurf, g%Domain)
757 else
758 call do_group_pass(pass_tau_ustar_psurf, g%Domain)
759 endif
760 call cpu_clock_end(id_clock_pass)
761
762 if (associated(forces%p_surf)) p_surf => forces%p_surf
763 if (.not.associated(forces%p_surf)) cs%interp_p_surf = .false.
764 if (associated(cs%tv%p_surf) .and. associated(forces%p_surf)) then
765 do j=jsd,jed ; do i=isd,ied ; cs%tv%p_surf(i,j) = forces%p_surf(i,j) ; enddo ; enddo
766
767 if (allocated(cs%tv%SpV_avg) .and. associated(cs%tv%T)) then
768 ! The internal ocean state depends on the surface pressues, so update SpV_avg.
769 dynamics_stencil = min(3, g%Domain%nihalo, g%Domain%njhalo)
770 call calc_derived_thermo(cs%tv, h, g, gv, us, halo=dynamics_stencil, debug=cs%debug)
771 endif
772 endif
773
774 else
775 ! This step only updates the thermodynamics so setting timesteps is simpler.
776 n_max = 1
777 if ((time_interval > cs%dt_therm) .and. (cs%dt_therm > 0.0)) &
778 n_max = ceiling(time_interval/cs%dt_therm - 0.001)
779
780 dt = time_interval / real(n_max)
781 dt_therm = dt ; ntstep = 1
782
783 if (cs%UseWaves .and. associated(fluxes%ustar)) &
784 call pass_var(fluxes%ustar, g%Domain, clock=id_clock_pass, halo=1)
785 if (cs%UseWaves .and. associated(fluxes%tau_mag)) &
786 call pass_var(fluxes%tau_mag, g%Domain, clock=id_clock_pass, halo=1)
787
788 if (associated(fluxes%p_surf)) p_surf => fluxes%p_surf
789 if (associated(cs%tv%p_surf) .and. associated(fluxes%p_surf)) then
790 do j=js,je ; do i=is,ie ; cs%tv%p_surf(i,j) = fluxes%p_surf(i,j) ; enddo ; enddo
791 if (allocated(cs%tv%SpV_avg)) then
792 call pass_var(cs%tv%p_surf, g%Domain, clock=id_clock_pass)
793 ! The internal ocean state depends on the surface pressues, so update SpV_avg.
794 call extract_diabatic_member(cs%diabatic_CSp, diabatic_halo=halo_sz)
795 halo_sz = max(halo_sz, 1)
796 call calc_derived_thermo(cs%tv, h, g, gv, us, halo=halo_sz, debug=cs%debug)
797 endif
798 endif
799 endif
800
801 if (therm_reset) then
802 cs%time_in_thermo_cycle = 0.0
803 if (associated(cs%tv%frazil)) then
804 cs%tv%frazil(:,:) = 0.0
805 cs%tv%frazil_was_reset = .true.
806 endif
807 if (associated(cs%tv%salt_deficit)) cs%tv%salt_deficit(:,:) = 0.0
808 if (associated(cs%tv%TempxPmE)) cs%tv%TempxPmE(:,:) = 0.0
809 if (associated(cs%tv%internal_heat)) cs%tv%internal_heat(:,:) = 0.0
810 endif
811
812 if (cycle_start) then
813 cs%time_in_cycle = 0.0
814 do j=js,je ; do i=is,ie ; cs%ssh_rint(i,j) = 0.0 ; enddo ; enddo
815
816 if (cs%VarMix%use_variable_mixing) then
817 time_end_diag = time_start + real_to_time(cycle_time, unscale=us%T_to_s)
818 call enable_averages(cycle_time, time_end_diag, cs%diag)
819 call calc_resoln_function(h, cs%tv, g, gv, us, cs%VarMix, cs%MEKE, cs%OBC, dt)
820 call calc_depth_function(g, cs%VarMix)
821 call disable_averaging(cs%diag)
822 endif
823 endif
824 ! advance the random pattern if stochastic physics is active
825 if (cs%stoch_CS%do_sppt .OR. cs%stoch_CS%pert_epbl .OR. cs%stoch_CS%do_skeb) &
826 call update_stochastics(cs%stoch_CS)
827
828 if (do_dyn) then
829 if (nonblocking_p_surf_update) &
830 call complete_group_pass(pass_tau_ustar_psurf, g%Domain, clock=id_clock_pass)
831
832 if (cs%interp_p_surf) then
833 if (.not.associated(cs%p_surf_end)) allocate(cs%p_surf_end(isd:ied,jsd:jed))
834 if (.not.associated(cs%p_surf_begin)) allocate(cs%p_surf_begin(isd:ied,jsd:jed))
835 if (.not.cs%p_surf_prev_set) then
836 do j=jsd,jed ; do i=isd,ied
837 cs%p_surf_prev(i,j) = forces%p_surf(i,j)
838 enddo ; enddo
839 cs%p_surf_prev_set = .true.
840 endif
841 else
842 cs%p_surf_end => forces%p_surf
843 endif
844 if (cs%UseWaves) then
845 ! Update wave information, which is presently kept static over each call to step_mom
846 time_end_diag = time_start + real_to_time(time_interval, unscale=us%T_to_s)
847 call enable_averages(time_interval, time_end_diag, cs%diag)
848 call find_ustar(forces, cs%tv, u_star, g, gv, us, halo=1)
849 call thickness_to_dz(h, cs%tv, dz, g, gv, us, halo_size=1)
850 call update_stokes_drift(g, gv, us, waves, dz, u_star, time_interval, do_dyn)
851 call disable_averaging(cs%diag)
852 endif
853 else ! not do_dyn.
854 if (cs%UseWaves) then ! Diagnostics are not enabled in this call.
855 call find_ustar(fluxes, cs%tv, u_star, g, gv, us, halo=1)
856 call thickness_to_dz(h, cs%tv, dz, g, gv, us, halo_size=1)
857 call update_stokes_drift(g, gv, us, waves, dz, u_star, time_interval, do_dyn)
858 endif
859 endif
860
861 if (cs%debug) then
862 if (cycle_start) &
863 call mom_state_chksum("Before steps ", u, v, h, cs%uh, cs%vh, g, gv, us)
864 if (cycle_start .and. debug_redundant) &
865 call check_redundant("Before steps ", u, v, g, unscale=us%L_T_to_m_s)
866 if (do_dyn) call mom_mech_forcing_chksum("Before steps", forces, g, us, haloshift=0)
867 if (do_dyn .and. debug_redundant) &
868 call check_redundant("Before steps ", forces%taux, forces%tauy, g, &
869 unscale=us%RZ_T_to_kg_m2s*us%L_T_to_m_s)
870 endif
871 call cpu_clock_end(id_clock_other)
872
873 rel_time = 0.0
874 do n=1,n_max
875 rel_time = rel_time + dt ! The relative time at the end of the step.
876 ! Set the universally visible time to the middle of the time step.
877 cs%Time = time_start + real_to_time(rel_time - 0.5*dt, unscale=us%T_to_s)
878 ! Set the local time to the end of the time step.
879 time_local = time_start + real_to_time(rel_time, unscale=us%T_to_s)
880
881 if (showcalltree) call calltree_enter("DT cycles (step_MOM) n=",n)
882
883 ! Update the vertically extensive diagnostic grids so that they are
884 ! referenced to the beginning timestep
885 call diag_update_remap_grids(cs%diag, update_intensive = .false., update_extensive = .true. )
886
887 !===========================================================================
888 ! This is the first place where the diabatic processes and remapping could occur.
889 if (cs%diabatic_first .and. (cs%t_dyn_rel_adv==0.0) .and. do_thermo) then ! do thermodynamics.
890
891 if (.not.do_dyn) then
892 dtdia = dt
893 elseif (thermo_does_span_coupling) then
894 dtdia = dt_therm
895 if ((fluxes%dt_buoy_accum > 0.0) .and. (dtdia > time_interval) .and. &
896 (abs(fluxes%dt_buoy_accum - dtdia) > 1e-6*dtdia)) then
897 call mom_error(fatal, "step_MOM: Mismatch between long thermodynamic "//&
898 "timestep and time over which buoyancy fluxes have been accumulated.")
899 endif
900 call mom_error(fatal, "MOM is not yet set up to have restarts that work "//&
901 "with THERMO_SPANS_COUPLING and DIABATIC_FIRST.")
902 else
903 dtdia = dt*min(ntstep,n_max-(n-1))
904 endif
905
906 end_time_thermo = time_local
907 if (dtdia > dt) then
908 ! If necessary, temporarily reset CS%Time to the center of the period covered
909 ! by the call to step_MOM_thermo, noting that they begin at the same time.
910 cs%Time = cs%Time + real_to_time(0.5*(dtdia-dt), unscale=us%T_to_s)
911 ! The end-time of the diagnostic interval needs to be set ahead if there
912 ! are multiple dynamic time steps worth of thermodynamics applied here.
913 end_time_thermo = time_local + real_to_time(dtdia-dt, unscale=us%T_to_s)
914 endif
915
916 ! Apply diabatic forcing, do mixing, and regrid.
917 call step_mom_thermo(cs, g, gv, us, u, v, h, cs%tv, fluxes, dtdia, &
918 end_time_thermo, .true., waves=waves)
919 if ( cs%use_ALE_algorithm ) &
920 call ale_regridding_and_remapping(cs, g, gv, us, u, v, h, cs%tv, dtdia, time_local)
921 call post_diabatic_halo_updates(cs, g, gv, us, u, v, h, cs%tv)
922 cs%time_in_thermo_cycle = cs%time_in_thermo_cycle + dtdia
923
924 ! The diabatic processes are now ahead of the dynamics by dtdia.
925 cs%t_dyn_rel_thermo = -dtdia
926 if (showcalltree) call calltree_waypoint("finished diabatic_first (step_MOM)")
927
928 if (dtdia > dt) & ! Reset CS%Time to its previous value.
929 cs%Time = time_start + real_to_time(rel_time - 0.5*dt, unscale=us%T_to_s)
930 endif ! end of block "(CS%diabatic_first .and. (CS%t_dyn_rel_adv==0.0))"
931
932 if (do_dyn) then
933 ! Store pre-dynamics thicknesses for proper diagnostic remapping for transports or
934 ! advective tendencies. If there are more than one dynamics steps per advective
935 ! step (i.e DT_THERM > DT), this needs to be stored at the first dynamics call.
936 if (.not.cs%preadv_h_stored .and. (cs%t_dyn_rel_adv == 0.)) then
937 call diag_copy_diag_to_storage(cs%diag_pre_dyn, h, cs%diag)
938 cs%preadv_h_stored = .true.
939 endif
940
941 ! The pre-dynamics velocities might be stored for debugging truncations.
942 if (associated(cs%u_prev) .and. associated(cs%v_prev)) then
943 do k=1,nz ; do j=jsd,jed ; do i=isdb,iedb
944 cs%u_prev(i,j,k) = u(i,j,k)
945 enddo ; enddo ; enddo
946 do k=1,nz ; do j=jsdb,jedb ; do i=isd,ied
947 cs%v_prev(i,j,k) = v(i,j,k)
948 enddo ; enddo ; enddo
949 endif
950
951 if (cs%interface_filter_dt_bug) then
952 dt_tradv_here = dt_therm
953 if (do_thermo .and. do_dyn .and. .not.thermo_does_span_coupling) &
954 dt_tradv_here = dt*min(ntstep, n_max-n+1)
955 else
956 dt_tradv_here = dt_tr_adv
957 if (do_thermo .and. do_dyn .and. .not.tradv_does_span_coupling) &
958 dt_tradv_here = dt*min(ntstep, n_max-n+1)
959 endif
960
961 ! Indicate whether the bottom boundary layer properties need to be
962 ! recalculated, and if so for how long an interval they are valid.
963 bbl_time_int = 0.0
964 if (do_thermo) then
965 if ((cs%t_dyn_rel_adv == 0.0) .or. (n==1)) &
966 bbl_time_int = max(dt, min(dt_therm - cs%t_dyn_rel_adv, dt*(1+n_max-n)) )
967 else
968 if ((cs%t_dyn_rel_adv == 0.0) .or. ((n==1) .and. cycle_start)) &
969 bbl_time_int = min(dt_therm, cycle_time)
970 endif
971
972 if (cs%interp_p_surf) then
973 wt_end = real(n) / real(n_max)
974 wt_beg = real(n-1) / real(n_max)
975 do j=jsd,jed ; do i=isd,ied
976 cs%p_surf_end(i,j) = wt_end * forces%p_surf(i,j) + &
977 (1.0-wt_end) * cs%p_surf_prev(i,j)
978 cs%p_surf_begin(i,j) = wt_beg * forces%p_surf(i,j) + &
979 (1.0-wt_beg) * cs%p_surf_prev(i,j)
980 enddo ; enddo
981 endif
982
983 call step_mom_dynamics(forces, cs%p_surf_begin, cs%p_surf_end, dt, &
984 dt_tradv_here, bbl_time_int, cs, &
985 time_local, waves=waves)
986
987 !===========================================================================
988 ! This is the start of the tracer advection part of the algorithm.
989 if (tradv_does_span_coupling .or. .not.do_thermo) then
990 do_advection = ((cs%t_dyn_rel_adv + 0.5*dt > dt_tr_adv) .or. &
991 (cs%t_dyn_rel_thermo + 0.5*dt > dt_therm))
992 else
993 do_advection = ((mod(n,ntastep) == 0) .or. (n==n_max))
994 endif
995
996 if (do_advection) then ! Do advective transport and lateral tracer mixing.
997 call step_mom_tracer_dyn(cs, g, gv, us, h, time_local)
998 if (cs%diabatic_first .and. abs(cs%t_dyn_rel_thermo) > 1e-6*dt) call mom_error(fatal, &
999 "step_MOM: Mismatch between the dynamics and diabatic times "//&
1000 "with DIABATIC_FIRST.")
1001 endif
1002 endif ! end of (do_dyn)
1003
1004 !===========================================================================
1005 ! This is the second place where the diabatic processes and remapping could occur.
1006 if (thermo_does_span_coupling .or. .not.do_dyn) then
1007 do_diabatic = (do_thermo .and. (cs%t_dyn_rel_thermo + 0.5*dt > dt_therm))
1008 else
1009 do_diabatic = (do_thermo .and. ((mod(n,ntstep) == 0) .or. (n==n_max)))
1010 endif
1011 if ((cs%t_dyn_rel_adv==0.0) .and. (.not.cs%diabatic_first) .and. do_diabatic) then
1012
1013 dtdia = cs%t_dyn_rel_thermo
1014 ! If the MOM6 dynamic and thermodynamic time stepping is being orchestrated
1015 ! by the coupler, the value of diabatic_first does not matter.
1016 if ((cs%t_dyn_rel_thermo==0.0) .and. .not.do_dyn) dtdia = dt
1017
1018 if (cs%thermo_spans_coupling .and. (cs%dt_therm > 1.5*cycle_time) .and. &
1019 (abs(dt_therm - dtdia) > 1e-6*dt_therm)) then
1020 call mom_error(fatal, "step_MOM: Mismatch between dt_therm and dtdia "//&
1021 "before call to diabatic.")
1022 endif
1023
1024 ! If necessary, temporarily reset CS%Time to the center of the period covered
1025 ! by the call to step_MOM_thermo, noting that they end at the same time.
1026 if (dtdia > dt) &
1027 cs%Time = cs%Time - real_to_time(0.5*(dtdia-dt), unscale=us%T_to_s)
1028
1029 ! Apply diabatic forcing, do mixing, and regrid.
1030 call step_mom_thermo(cs, g, gv, us, u, v, h, cs%tv, fluxes, dtdia, &
1031 time_local, .false., waves=waves)
1032 if ( cs%use_ALE_algorithm ) &
1033 call ale_regridding_and_remapping(cs, g, gv, us, u, v, h, cs%tv, dtdia, time_local)
1034 call post_diabatic_halo_updates(cs, g, gv, us, u, v, h, cs%tv)
1035 cs%time_in_thermo_cycle = cs%time_in_thermo_cycle + dtdia
1036
1037 if ((cs%t_dyn_rel_thermo==0.0) .and. .not.do_dyn) then
1038 ! The diabatic processes are now ahead of the dynamics by dtdia.
1039 cs%t_dyn_rel_thermo = -dtdia
1040 else ! The diabatic processes and the dynamics are synchronized.
1041 cs%t_dyn_rel_thermo = 0.0
1042 endif
1043
1044 ! Reset CS%Time to its previous value.
1045 if (dtdia > dt) &
1046 cs%Time = time_start + real_to_time(rel_time - 0.5*dt, unscale=us%T_to_s)
1047 endif
1048
1049 if (do_dyn) then
1050 call cpu_clock_begin(id_clock_dynamics)
1051 ! Determining the time-average sea surface height is part of the algorithm.
1052 ! This may be eta_av if Boussinesq, or need to be diagnosed if not.
1053 cs%time_in_cycle = cs%time_in_cycle + dt
1054 call find_eta(h, cs%tv, g, gv, us, ssh, cs%eta_av_bc, dzref=g%Z_ref)
1055 do j=js,je ; do i=is,ie
1056 cs%ssh_rint(i,j) = cs%ssh_rint(i,j) + dt*ssh(i,j)
1057 enddo ; enddo
1058 if (cs%IDs%id_ssh_inst > 0) then
1059 call enable_averages(dt, time_local, cs%diag)
1060 call post_data(cs%IDs%id_ssh_inst, ssh, cs%diag)
1061 call disable_averaging(cs%diag)
1062 endif
1063 call cpu_clock_end(id_clock_dynamics)
1064 endif
1065
1066 !===========================================================================
1067 ! Calculate diagnostics at the end of the time step if the state is self-consistent.
1068 if (mom_state_is_synchronized(cs)) then
1069 !### Perhaps this should be if (CS%t_dyn_rel_thermo == 0.0)
1070 call cpu_clock_begin(id_clock_other) ; call cpu_clock_begin(id_clock_diagnostics)
1071 ! Diagnostics that require the complete state to be up-to-date can be calculated.
1072
1073 call enable_averages(cs%t_dyn_rel_diag, time_local, cs%diag)
1074 call calculate_diagnostic_fields(u, v, h, cs%uh, cs%vh, cs%tv, cs%ADp, &
1075 cs%CDp, p_surf, cs%t_dyn_rel_diag, cs%diag_pre_sync,&
1076 g, gv, us, cs%diagnostics_CSp)
1077 call post_tracer_diagnostics_at_sync(cs%Tracer_reg, h, cs%diag_pre_sync, cs%diag, g, gv, cs%t_dyn_rel_diag)
1078 call post_tracer_integral_diagnostics(g, gv, us, cs%Tracer_reg, h, cs%tv, cs%diag)
1079
1080 call diag_copy_diag_to_storage(cs%diag_pre_sync, h, cs%diag)
1081 if (showcalltree) call calltree_waypoint("finished calculate_diagnostic_fields (step_MOM)")
1082 call disable_averaging(cs%diag)
1083 cs%t_dyn_rel_diag = 0.0
1084
1085 call cpu_clock_end(id_clock_diagnostics) ; call cpu_clock_end(id_clock_other)
1086 endif
1087
1088 if (do_dyn .and. .not.cs%count_calls) cs%nstep_tot = cs%nstep_tot + 1
1089 if (showcalltree) call calltree_leave("DT cycles (step_MOM)")
1090
1091 enddo ! complete the n loop
1092
1093 if (cs%count_calls .and. cycle_start) cs%nstep_tot = cs%nstep_tot + 1
1094
1095 call cpu_clock_begin(id_clock_other)
1096
1097 if (cs%time_in_cycle > 0.0) then
1098 i_wt_ssh = 1.0/cs%time_in_cycle
1099 do j=js,je ; do i=is,ie
1100 ssh(i,j) = cs%ssh_rint(i,j)*i_wt_ssh
1101 cs%ave_ssh_ibc(i,j) = ssh(i,j)
1102 enddo ; enddo
1103 if (associated(cs%HA_CSp)) call ha_accum('ssh', ssh, time_local, g, cs%HA_CSp)
1104 if (do_dyn) then
1105 call adjust_ssh_for_p_atm(cs%tv, g, gv, us, cs%ave_ssh_ibc, forces%p_surf_SSH, &
1106 cs%calc_rho_for_sea_lev)
1107 elseif (do_thermo) then
1108 call adjust_ssh_for_p_atm(cs%tv, g, gv, us, cs%ave_ssh_ibc, fluxes%p_surf_SSH, &
1109 cs%calc_rho_for_sea_lev)
1110 endif
1111 endif
1112
1113 if (do_dyn .and. cs%interp_p_surf) then ; do j=jsd,jed ; do i=isd,ied
1114 cs%p_surf_prev(i,j) = forces%p_surf(i,j)
1115 enddo ; enddo ; endif
1116
1117 if (cs%ensemble_ocean) then
1118 ! store ensemble vector in odaCS
1119 call set_prior_tracer(cs%Time, g, gv, cs%h, cs%tv, cs%odaCS)
1120 ! call DA interface
1121 call oda(cs%Time,cs%odaCS)
1122 ! update the time for the next analysis step if needed
1123 call set_analysis_time(cs%Time,cs%odaCS)
1124 endif
1125
1126 if (showcalltree) call calltree_waypoint("calling extract_surface_state (step_MOM)")
1127 ! NOTE: sfc_state uses input indexing, since it is also used by drivers.
1128 call extract_surface_state(cs, sfc_state)
1129
1130 ! Do diagnostics that only occur at the end of a complete forcing step.
1131 if (cycle_end) then
1132 if (showcalltree) call calltree_waypoint("Do cycle end diagnostics (step_MOM)")
1133 if (cs%rotate_index) then
1134 allocate(sfc_state_diag)
1135 call rotate_surface_state(sfc_state, sfc_state_diag, g, turns)
1136 else
1137 sfc_state_diag => sfc_state
1138 endif
1139
1140 call cpu_clock_begin(id_clock_diagnostics)
1141 if (cs%time_in_cycle > 0.0) then
1142 call enable_averages(cs%time_in_cycle, time_local, cs%diag)
1143 call post_surface_dyn_diags(cs%sfc_IDs, g, cs%diag, sfc_state_diag, ssh)
1144 endif
1145 if (cs%time_in_thermo_cycle > 0.0) then
1146 call enable_averages(cs%time_in_thermo_cycle, time_local, cs%diag)
1147 call post_surface_thermo_diags(cs%sfc_IDs, g, gv, us, cs%diag, cs%time_in_thermo_cycle, &
1148 sfc_state_diag, cs%tv, ssh, cs%ave_ssh_ibc)
1149 endif
1150 call disable_averaging(cs%diag)
1151 call cpu_clock_end(id_clock_diagnostics)
1152 if (cs%rotate_index) then
1153 call deallocate_surface_state(sfc_state_diag)
1154 endif
1155 if (showcalltree) call calltree_waypoint("Done with end cycle diagnostics (step_MOM)")
1156 endif
1157
1158 ! Accumulate the surface fluxes for assessing conservation
1159 if (do_thermo .and. fluxes%fluxes_used) &
1160 call accumulate_net_input(fluxes, sfc_state, cs%tv, fluxes%dt_buoy_accum, &
1161 g, us, cs%sum_output_CSp)
1162
1163 if (mom_state_is_synchronized(cs)) &
1164 call write_energy(cs%u, cs%v, cs%h, cs%tv, time_local, cs%nstep_tot, &
1165 g, gv, us, cs%sum_output_CSp, cs%tracer_flow_CSp, &
1166 dt_forcing=real_to_time(time_interval, unscale=us%T_to_s) )
1167
1168 call cpu_clock_end(id_clock_other)
1169
1170 ! De-rotate fluxes and copy back to the input, since they can be changed.
1171 if (cs%rotate_index) then
1172 call rotate_forcing(fluxes, fluxes_in, -turns)
1173 call rotate_mech_forcing(forces, -turns, forces_in)
1174 call deallocate_mech_forcing(forces)
1175 deallocate(forces)
1176 call deallocate_forcing_type(fluxes)
1177 deallocate(fluxes)
1178 endif
1179
1180 if (showcalltree) call calltree_leave("step_MOM()")
1181 call cpu_clock_end(id_clock_ocean)
1182
1183end subroutine step_mom
1184
1185!> Time step the ocean dynamics, including the momentum and continuity equations
1186subroutine step_mom_dynamics(forces, p_surf_begin, p_surf_end, dt, dt_tr_adv, &
1187 bbl_time_int, CS, Time_local, Waves)
1188 type(mech_forcing), intent(in) :: forces !< A structure with the driving mechanical forces
1189 real, dimension(:,:), pointer :: p_surf_begin !< A pointer (perhaps NULL) to the surface
1190 !! pressure at the beginning of this dynamic
1191 !! step, intent in [R L2 T-2 ~> Pa].
1192 real, dimension(:,:), pointer :: p_surf_end !< A pointer (perhaps NULL) to the surface
1193 !! pressure at the end of this dynamic step,
1194 !! intent in [R L2 T-2 ~> Pa].
1195 real, intent(in) :: dt !< time interval covered by this call [T ~> s].
1196 real, intent(in) :: dt_tr_adv !< time interval covered by any updates that may
1197 !! span multiple dynamics steps [T ~> s].
1198 real, intent(in) :: bbl_time_int !< time interval over which updates to the
1199 !! bottom boundary layer properties will apply [T ~> s],
1200 !! or zero not to update the properties.
1201 type(mom_control_struct), intent(inout), target :: CS !< control structure from initialize_MOM
1202 type(time_type), intent(in) :: Time_local !< End time of a segment, as a time type
1203 type(wave_parameters_cs), &
1204 optional, pointer :: Waves !< Container for wave related parameters; the
1205 !! fields in Waves are intent in here.
1206
1207 ! local variables
1208 type(ocean_grid_type), pointer :: G => null() ! pointer to a structure containing
1209 ! metrics and related information
1210 type(verticalgrid_type), pointer :: GV => null() ! Pointer to the vertical grid structure
1211 type(unit_scale_type), pointer :: US => null() ! Pointer to a structure containing
1212 ! various unit conversion factors
1213 type(mom_diag_ids), pointer :: IDs => null() ! A structure with the diagnostic IDs.
1214 real, dimension(:,:,:), pointer :: &
1215 u => null(), & ! u : zonal velocity component [L T-1 ~> m s-1]
1216 v => null(), & ! v : meridional velocity component [L T-1 ~> m s-1]
1217 h => null() ! h : layer thickness [H ~> m or kg m-2]
1218
1219 type(time_type) :: Time_end_diag ! End time of a diagnostic segment, as a time type
1220 logical :: calc_dtbt ! Indicates whether the dynamically adjusted
1221 ! barotropic time step needs to be updated.
1222 logical :: showCallTree
1223
1224 integer :: i, j, k, is, ie, js, je, Isq, Ieq, Jsq, Jeq, nz
1225 integer :: isd, ied, jsd, jed, IsdB, IedB, JsdB, JedB
1226
1227 g => cs%G ; gv => cs%GV ; us => cs%US ; ids => cs%IDs
1228 is = g%isc ; ie = g%iec ; js = g%jsc ; je = g%jec ; nz = gv%ke
1229 isq = g%IscB ; ieq = g%IecB ; jsq = g%JscB ; jeq = g%JecB
1230 isd = g%isd ; ied = g%ied ; jsd = g%jsd ; jed = g%jed
1231 isdb = g%IsdB ; iedb = g%IedB ; jsdb = g%JsdB ; jedb = g%JedB
1232 u => cs%u ; v => cs%v ; h => cs%h
1233 showcalltree = calltree_showquery()
1234
1235 call cpu_clock_begin(id_clock_dynamics)
1236 call cpu_clock_begin(id_clock_stoch)
1237 if (cs%use_stochastic_EOS) call mom_stoch_eos_run(g, u, v, dt, time_local, cs%stoch_eos_CS)
1238 call cpu_clock_end(id_clock_stoch)
1239 call cpu_clock_begin(id_clock_vart)
1240 if (cs%use_stochastic_EOS) then
1241 call mom_calc_vart(g, gv, us, h, cs%tv, cs%stoch_eos_CS, dt)
1242 if (associated(cs%tv%varT)) call pass_var(cs%tv%varT, g%Domain, clock=id_clock_pass, halo=1)
1243 endif
1244 call cpu_clock_end(id_clock_vart)
1245
1246 if ((cs%t_dyn_rel_adv == 0.0) .and. cs%thickness_diffuse_first .and. &
1247 (cs%thickness_diffuse .or. cs%interface_filter)) then
1248
1249 time_end_diag = time_local + real_to_time(dt_tr_adv - dt, unscale=us%T_to_s)
1250 call enable_averages(dt_tr_adv, time_end_diag, cs%diag)
1251 if (cs%thickness_diffuse) then
1252 call cpu_clock_begin(id_clock_thick_diff)
1253 if (cs%VarMix%use_variable_mixing) &
1254 call calc_slope_functions(h, cs%tv, dt, g, gv, us, cs%VarMix, obc=cs%OBC)
1255 call thickness_diffuse(h, cs%uhtr, cs%vhtr, cs%tv, dt_tr_adv, g, gv, us, &
1256 cs%MEKE, cs%VarMix, cs%CDp, cs%thickness_diffuse_CSp, &
1257 cs%stoch_CS, u, v)
1258 call cpu_clock_end(id_clock_thick_diff)
1259 call pass_var(h, g%Domain, clock=id_clock_pass, halo=cs%dyn_h_stencil)
1260 if (showcalltree) call calltree_waypoint("finished thickness_diffuse_first (step_MOM)")
1261 endif
1262
1263 if (cs%interface_filter) then
1264 if (allocated(cs%tv%SpV_avg)) call pass_var(cs%tv%SpV_avg, g%Domain, clock=id_clock_pass)
1265 cs%tv%valid_SpV_halo = min(g%Domain%nihalo, g%Domain%njhalo)
1266 call cpu_clock_begin(id_clock_int_filter)
1267 call interface_filter(h, cs%uhtr, cs%vhtr, cs%tv, dt_tr_adv, g, gv, us, &
1268 cs%CDp, cs%interface_filter_CSp)
1269 call cpu_clock_end(id_clock_int_filter)
1270 call pass_var(h, g%Domain, clock=id_clock_pass, halo=cs%dyn_h_stencil)
1271 if (showcalltree) call calltree_waypoint("finished interface_filter_first (step_MOM)")
1272 endif
1273
1274 call disable_averaging(cs%diag)
1275 ! Whenever thickness changes let the diag manager know, target grids
1276 ! for vertical remapping may need to be regenerated.
1277 call diag_update_remap_grids(cs%diag)
1278 endif
1279
1280 ! Update porous barrier fractional cell metrics
1281 if (cs%use_porbar) then
1282 call enable_averages(dt, time_local, cs%diag)
1283 call porous_widths_layer(h, cs%tv, g, gv, us, cs%pbv, cs%por_bar_CS)
1284 call disable_averaging(cs%diag)
1285 call pass_vector(cs%pbv%por_face_areaU, cs%pbv%por_face_areaV, &
1286 g%Domain, direction=to_all+scalar_pair, clock=id_clock_pass, halo=cs%cont_stencil)
1287 endif
1288
1289 ! The bottom boundary layer properties need to be recalculated.
1290 if (bbl_time_int > 0.0) then
1291 time_end_diag = time_local + real_to_time(bbl_time_int - dt, unscale=us%T_to_s)
1292 call enable_averages(bbl_time_int, time_end_diag, cs%diag)
1293 ! Calculate the BBL properties and store them inside visc (u,h).
1294 call cpu_clock_begin(id_clock_bbl_visc)
1295 call set_viscous_bbl(cs%u, cs%v, cs%h, cs%tv, cs%visc, g, gv, us, cs%set_visc_CSp, cs%pbv)
1296 call cpu_clock_end(id_clock_bbl_visc)
1297 if (showcalltree) call calltree_waypoint("done with set_viscous_BBL (step_MOM)")
1298 call disable_averaging(cs%diag)
1299 endif
1300
1301 !OBC segment data update for some fields can be less frequent than others
1302 if (associated(cs%OBC)) then
1303 cs%OBC%update_OBC_seg_data = .false.
1304 if (cs%dt_obc_seg_period == 0.0) cs%OBC%update_OBC_seg_data = .true.
1305 if (cs%dt_obc_seg_period > 0.0) then
1306 if (time_local >= cs%dt_obc_seg_time) then
1307 cs%OBC%update_OBC_seg_data = .true.
1308 cs%dt_obc_seg_time = cs%dt_obc_seg_time + cs%dt_obc_seg_interval
1309 endif
1310 endif
1311 endif
1312 ! if (CS%debug_OBCs .and. associated(CS%OBC)) call chksum_OBC_segments(CS%OBC, G, GV, US, 3)
1313
1314 if (cs%do_dynamics .and. cs%split) then !--------------------------- start SPLIT
1315 ! This section uses a split time stepping scheme for the dynamic equations,
1316 ! basically the stacked shallow water equations with viscosity.
1317
1318 calc_dtbt = .false.
1319 if (cs%dtbt_reset_period == 0.0) calc_dtbt = .true.
1320 if (cs%dtbt_reset_period > 0.0) then
1321 if (time_local >= cs%dtbt_reset_time) then !### Change >= to > here.
1322 calc_dtbt = .true.
1323 cs%dtbt_reset_time = cs%dtbt_reset_time + cs%dtbt_reset_interval
1324 endif
1325 endif
1326
1327 if (cs%use_alt_split) then
1328 call step_mom_dyn_split_rk2b(u, v, h, cs%tv, cs%visc, time_local, dt, forces, &
1329 p_surf_begin, p_surf_end, cs%uh, cs%vh, cs%uhtr, cs%vhtr, &
1330 cs%eta_av_bc, g, gv, us, cs%dyn_split_RK2b_CSp, calc_dtbt, cs%VarMix, &
1331 cs%MEKE, cs%thickness_diffuse_CSp, cs%pbv, waves=waves)
1332 else
1333 call step_mom_dyn_split_rk2(u, v, h, cs%tv, cs%visc, time_local, dt, forces, &
1334 p_surf_begin, p_surf_end, cs%uh, cs%vh, cs%uhtr, cs%vhtr, &
1335 cs%eta_av_bc, g, gv, us, cs%dyn_split_RK2_CSp, calc_dtbt, cs%VarMix, &
1336 cs%MEKE, cs%thickness_diffuse_CSp, cs%pbv, cs%stoch_CS, waves=waves)
1337 endif
1338 if (showcalltree) call calltree_waypoint("finished step_MOM_dyn_split (step_MOM)")
1339
1340 elseif (cs%do_dynamics) then ! ------------------------------------ not SPLIT
1341 ! This section uses an unsplit stepping scheme for the dynamic
1342 ! equations; basically the stacked shallow water equations with viscosity.
1343 ! Because the time step is limited by CFL restrictions on the external
1344 ! gravity waves, the unsplit is usually much less efficient that the split
1345 ! approaches. But because of its simplicity, the unsplit method is very
1346 ! useful for debugging purposes.
1347
1348 if (cs%use_RK2) then
1349 call step_mom_dyn_unsplit_rk2(u, v, h, cs%tv, cs%visc, time_local, dt, forces, &
1350 p_surf_begin, p_surf_end, cs%uh, cs%vh, cs%uhtr, cs%vhtr, &
1351 cs%eta_av_bc, g, gv, us, cs%dyn_unsplit_RK2_CSp, cs%VarMix, cs%MEKE, cs%pbv, &
1352 cs%stoch_CS)
1353 else
1354 call step_mom_dyn_unsplit(u, v, h, cs%tv, cs%visc, time_local, dt, forces, &
1355 p_surf_begin, p_surf_end, cs%uh, cs%vh, cs%uhtr, cs%vhtr, &
1356 cs%eta_av_bc, g, gv, us, cs%dyn_unsplit_CSp, cs%VarMix, cs%MEKE, cs%pbv, &
1357 cs%stoch_CS, waves=waves)
1358 endif
1359 if (showcalltree) call calltree_waypoint("finished step_MOM_dyn_unsplit (step_MOM)")
1360
1361 endif ! -------------------------------------------------- end SPLIT
1362
1363 ! Accumulate resolved flux for tracer diagnostics
1364 if (cs%accumulate_resolved_flux) then
1365 !$OMP parallel do default(shared)
1366 do k=1,nz
1367 do j=js-2,je+2 ; do i=isq-2,ieq+2
1368 cs%uhtr_resolved(i,j,k) = cs%uhtr_resolved(i,j,k) + cs%uh(i,j,k)*dt
1369 enddo ; enddo
1370 do j=jsq-2,jeq+2 ; do i=is-2,ie+2
1371 cs%vhtr_resolved(i,j,k) = cs%vhtr_resolved(i,j,k) + cs%vh(i,j,k)*dt
1372 enddo ; enddo
1373 enddo
1374 endif
1375
1376 if (cs%use_particles .and. cs%do_dynamics .and. (.not. cs%use_uh_particles)) then
1377 if (cs%thickness_diffuse_first) call mom_error(warning,"particles_run: "//&
1378 "Thickness_diffuse_first is true and use_uh_particles is false. "//&
1379 "This is usually a bad combination.")
1380 !Run particles using unweighted velocity
1381 call particles_run(cs%particles, time_local, cs%u, cs%v, cs%h, &
1382 cs%tv, dt, cs%use_uh_particles)
1383 call particles_to_z_space(cs%particles, h)
1384 endif
1385
1386 ! Update the model's current to reflect wind-wave growth
1387 if (waves%Stokes_DDT .and. (.not.waves%Passive_Stokes_DDT)) then
1388 do j=jsq,jeq ; do i=is,ie
1389 v(i,j,:) = v(i,j,:) + waves%ddt_us_y(i,j,:)*dt
1390 enddo ; enddo
1391 do j=js,je ; do i=isq,ieq
1392 u(i,j,:) = u(i,j,:) + waves%ddt_us_x(i,j,:)*dt
1393 enddo ; enddo
1394 call pass_vector(u, v, g%Domain)
1395 endif
1396 ! Added an additional output to track Stokes drift time tendency.
1397 ! It is mostly for debugging, and perhaps doesn't need to hang
1398 ! around permanently.
1399 if (waves%Stokes_DDT .and. (waves%id_3dstokes_y_from_ddt>0)) then
1400 do j=jsq,jeq ; do i=is,ie
1401 waves%us_y_from_ddt(i,j,:) = waves%us_y_from_ddt(i,j,:) + waves%ddt_us_y(i,j,:)*dt
1402 enddo ; enddo
1403 endif
1404 if (waves%Stokes_DDT .and. (waves%id_3dstokes_x_from_ddt>0)) then
1405 do j=js,je ; do i=isq,ieq
1406 waves%us_x_from_ddt(i,j,:) = waves%us_x_from_ddt(i,j,:) + waves%ddt_us_x(i,j,:)*dt
1407 enddo ; enddo
1408 endif
1409
1410
1411 if ((cs%thickness_diffuse .or. cs%interface_filter) .and. &
1412 .not.cs%thickness_diffuse_first) then
1413
1414 if (cs%debug) call hchksum(h,"Pre-thickness_diffuse h", g%HI, haloshift=0, unscale=gv%H_to_MKS)
1415
1416 if (cs%thickness_diffuse) then
1417 call cpu_clock_begin(id_clock_thick_diff)
1418 if (cs%VarMix%use_variable_mixing) &
1419 call calc_slope_functions(h, cs%tv, dt, g, gv, us, cs%VarMix, obc=cs%OBC)
1420 call thickness_diffuse(h, cs%uhtr, cs%vhtr, cs%tv, dt, g, gv, us, &
1421 cs%MEKE, cs%VarMix, cs%CDp, cs%thickness_diffuse_CSp, &
1422 cs%stoch_CS, u, v)
1423 call cpu_clock_end(id_clock_thick_diff)
1424 call pass_var(h, g%Domain, clock=id_clock_pass, halo=cs%dyn_h_stencil)
1425 if (cs%debug) call hchksum(h,"Post-thickness_diffuse h", g%HI, haloshift=1, unscale=gv%H_to_MKS)
1426 if (showcalltree) call calltree_waypoint("finished thickness_diffuse (step_MOM)")
1427 endif
1428
1429 if (cs%interface_filter) then
1430 if (allocated(cs%tv%SpV_avg)) call pass_var(cs%tv%SpV_avg, g%Domain, clock=id_clock_pass)
1431 cs%tv%valid_SpV_halo = min(g%Domain%nihalo, g%Domain%njhalo)
1432 call cpu_clock_begin(id_clock_int_filter)
1433 if (cs%interface_filter_dt_bug) then
1434 call interface_filter(h, cs%uhtr, cs%vhtr, cs%tv, dt_tr_adv, g, gv, us, &
1435 cs%CDp, cs%interface_filter_CSp)
1436 else
1437 call interface_filter(h, cs%uhtr, cs%vhtr, cs%tv, dt, g, gv, us, &
1438 cs%CDp, cs%interface_filter_CSp)
1439 endif
1440 call cpu_clock_end(id_clock_int_filter)
1441 call pass_var(h, g%Domain, clock=id_clock_pass, halo=cs%dyn_h_stencil)
1442 if (showcalltree) call calltree_waypoint("finished interface_filter (step_MOM)")
1443 endif
1444 endif
1445
1446 ! apply the submesoscale mixed layer restratification parameterization
1447 if (cs%mixedlayer_restrat) then
1448 if (cs%debug) then
1449 call hchksum(h,"Pre-mixedlayer_restrat h", g%HI, haloshift=1, unscale=gv%H_to_MKS)
1450 call uvchksum("Pre-mixedlayer_restrat uhtr", &
1451 cs%uhtr, cs%vhtr, g%HI, haloshift=0, unscale=gv%H_to_MKS*us%L_to_m**2)
1452 endif
1453 call cpu_clock_begin(id_clock_ml_restrat)
1454 if (cs%wave_enhanced_ustar .and. cs%StokesMOST) then
1455 if (associated(cs%visc%Lam2)) then
1456 call mixedlayer_restrat(h, cs%uhtr, cs%vhtr, cs%tv, forces, dt, cs%visc%MLD, cs%visc%h_ML, &
1457 cs%visc%sfc_buoy_flx, cs%VarMix, g, gv, us, cs%mixedlayer_restrat_CSp, cs%visc%Lam2)
1458 else
1459 call mom_error(fatal,'step_MOM_dynamics:CS%visc%Lam2 not associated')
1460 endif
1461 else
1462 call mixedlayer_restrat(h, cs%uhtr, cs%vhtr, cs%tv, forces, dt, cs%visc%MLD, cs%visc%h_ML, &
1463 cs%visc%sfc_buoy_flx, cs%VarMix, g, gv, us, cs%mixedlayer_restrat_CSp)
1464 endif
1465 call cpu_clock_end(id_clock_ml_restrat)
1466 call pass_var(h, g%Domain, clock=id_clock_pass, halo=cs%dyn_h_stencil)
1467 if (cs%debug) then
1468 call hchksum(h,"Post-mixedlayer_restrat h", g%HI, haloshift=1, unscale=gv%H_to_MKS)
1469 call uvchksum("Post-mixedlayer_restrat [uv]htr", &
1470 cs%uhtr, cs%vhtr, g%HI, haloshift=0, unscale=gv%H_to_MKS*us%L_to_m**2)
1471 endif
1472 endif
1473
1474 ! Whenever thickness changes let the diag manager know, target grids
1475 ! for vertical remapping may need to be regenerated.
1476 call diag_update_remap_grids(cs%diag)
1477
1478 if (cs%useMEKE .and. cs%MEKE_in_dynamics) then
1479 call step_forward_meke(cs%MEKE, h, cs%VarMix%SN_u, cs%VarMix%SN_v, &
1480 cs%visc, dt, g, gv, us, cs%MEKE_CSp, cs%uhtr, cs%vhtr, &
1481 cs%u, cs%v, cs%tv, time_local)
1482 endif
1483 call disable_averaging(cs%diag)
1484
1485 ! Advance the dynamics time by dt.
1486 cs%t_dyn_rel_adv = cs%t_dyn_rel_adv + dt
1487
1488 if (cs%use_particles .and. cs%do_dynamics .and. cs%use_uh_particles .and. &
1489 cs%uh_particles_bug) then
1490 ! Run particles using thickness-weighted velocity
1491 call particles_run(cs%particles, time_local, cs%uhtr, cs%vhtr, cs%h, &
1492 cs%tv, cs%t_dyn_rel_adv, cs%use_uh_particles)
1493 endif
1494
1495 cs%n_dyn_steps_in_adv = cs%n_dyn_steps_in_adv + 1
1496 if (cs%alternate_first_direction) then
1497 call set_first_direction(g, modulo(g%first_direction+1,2))
1498 cs%first_dir_restart = real(g%first_direction)
1499 elseif (cs%use_particles .and. cs%do_dynamics .and. (.not.cs%use_uh_particles)) then
1500 call particles_to_k_space(cs%particles, h)
1501 endif
1502 cs%t_dyn_rel_thermo = cs%t_dyn_rel_thermo + dt
1503 if (abs(cs%t_dyn_rel_thermo) < 1e-6*dt) cs%t_dyn_rel_thermo = 0.0
1504 cs%t_dyn_rel_diag = cs%t_dyn_rel_diag + dt
1505
1506 call cpu_clock_end(id_clock_dynamics)
1507
1508 call cpu_clock_begin(id_clock_other) ; call cpu_clock_begin(id_clock_diagnostics)
1509 call enable_averages(dt, time_local, cs%diag)
1510 ! These diagnostics are available after every time dynamics step.
1511 if (ids%id_u > 0) call post_data(ids%id_u, u, cs%diag)
1512 if (ids%id_v > 0) call post_data(ids%id_v, v, cs%diag)
1513 if (ids%id_h > 0) call post_data(ids%id_h, h, cs%diag)
1514 if (cs%use_stochastic_EOS) call post_stoch_eos_diags(cs%stoch_eos_CS, cs%tv, cs%diag)
1515 call disable_averaging(cs%diag)
1516 call cpu_clock_end(id_clock_diagnostics) ; call cpu_clock_end(id_clock_other)
1517
1518end subroutine step_mom_dynamics
1519
1520!> step_MOM_tracer_dyn does tracer advection and lateral diffusion, bringing the
1521!! tracers up to date with the changes in state due to the dynamics. Surface
1522!! sources and sinks and remapping are handled via step_MOM_thermo.
1523subroutine step_mom_tracer_dyn(CS, G, GV, US, h, Time_local)
1524 type(mom_control_struct), intent(inout) :: CS !< control structure
1525 type(ocean_grid_type), intent(inout) :: G !< ocean grid structure
1526 type(verticalgrid_type), intent(in) :: GV !< ocean vertical grid structure
1527 type(unit_scale_type), intent(in) :: US !< A dimensional unit scaling type
1528 real, dimension(SZI_(G),SZJ_(G),SZK_(GV)), &
1529 intent(in) :: h !< layer thicknesses after the transports [H ~> m or kg m-2]
1530 type(time_type), intent(in) :: Time_local !< The model time at the end
1531 !! of the time step.
1532 type(group_pass_type) :: pass_T_S
1533 integer :: halo_sz ! The size of a halo where data must be valid.
1534 logical :: x_first ! If true, advect tracers first in the x-direction, then y.
1535 real, dimension(SZIB_(G),SZJ_(G),SZK_(GV)) :: &
1536 uhtr_tmp ! Temp. variable for advecting with alternate volume fluxes [H L2 ~> m3 or kg]
1537 real, dimension(SZI_(G),SZJB_(G),SZK_(GV)) :: &
1538 vhtr_tmp ! Temp. variable for advecting with alternate volume fluxes[H L2 ~> m3 or kg]
1539 integer :: i, j, k, m, is, ie, js, je, Isq, Ieq, Jsq, Jeq, nz
1540 integer :: IsdB, IedB, JsdB, JedB
1541 logical :: showCallTree
1542
1543 showcalltree = calltree_showquery()
1544
1545 is = g%isc ; ie = g%iec ; js = g%jsc ; je = g%jec ; nz = gv%ke
1546 isq = g%IscB ; ieq = g%IecB ; jsq = g%JscB ; jeq = g%JecB
1547
1548 if (cs%debug) then
1549 call cpu_clock_begin(id_clock_other)
1550 call hchksum(h,"Pre-advection h", g%HI, haloshift=1, unscale=gv%H_to_MKS)
1551 call uvchksum("Pre-advection uhtr", cs%uhtr, cs%vhtr, g%HI, &
1552 haloshift=0, unscale=gv%H_to_MKS*us%L_to_m**2)
1553 if (associated(cs%tv%T)) call hchksum(cs%tv%T, "Pre-advection T", g%HI, haloshift=1, unscale=us%C_to_degC)
1554 if (associated(cs%tv%S)) call hchksum(cs%tv%S, "Pre-advection S", g%HI, haloshift=1, unscale=us%S_to_ppt)
1555 if (associated(cs%tv%frazil)) call hchksum(cs%tv%frazil, "Pre-advection frazil", g%HI, haloshift=0, &
1556 unscale=us%Q_to_J_kg*us%RZ_to_kg_m2)
1557 if (associated(cs%tv%salt_deficit)) call hchksum(cs%tv%salt_deficit, &
1558 "Pre-advection salt deficit", g%HI, haloshift=0, unscale=us%S_to_ppt*us%RZ_to_kg_m2)
1559 ! call MOM_thermo_chksum("Pre-advection ", CS%tv, G, US)
1560 call cpu_clock_end(id_clock_other)
1561 endif
1562
1563 call cpu_clock_begin(id_clock_thermo) ; call cpu_clock_begin(id_clock_tracer)
1564 call enable_averages(cs%t_dyn_rel_adv, time_local, cs%diag)
1565
1566 if (cs%use_particles .and. cs%use_uh_particles .and. (.not. cs%uh_particles_bug)) then
1567 ! Run particles using thickness-weighted velocity
1568 call particles_run(cs%particles, time_local, cs%uhtr, cs%vhtr, cs%h, &
1569 cs%tv, cs%t_dyn_rel_adv, cs%use_uh_particles)
1570 endif
1571
1572 ! Tracer-step OBC path: active when DT_OBC_SEG_UPDATE_OBGC is ignored (i.e. DT_OBC_SEG_UPDATE_OBGC = DT_TRACER)
1573 ! or when the bug fix is enabled (OBC_TRACER_DZ_BUG=F). OBC_TRACER_DZ_BUG controls whether dz is recomputed
1574 ! from the current layer thicknesses before reading.
1575 if (associated(cs%OBC)) then
1576 if (cs%OBC%ignore_dt_obc_bgc .or. (.not. cs%OBC%tracer_dz_bug)) then
1577 if (cs%OBC%tracer_dz_bug) then
1578 call read_obc_tracer_data(g, gv, us, cs%OBC, time_local)
1579 else
1580 call read_obc_tracer_data(g, gv, us, cs%OBC, time_local, h=h, tv=cs%tv)
1581 endif
1582 call update_obc_tracer_data(cs%OBC)
1583 endif
1584 endif
1585
1586 if (cs%alternate_first_direction) then
1587 ! This calculation of the value of G%first_direction from the start of the accumulation of
1588 ! mass transports for use by the tracers is the equivalent to adding 2*n_dyn_steps before
1589 ! subtracting n_dyn_steps so that the mod will be taken of a non-negative number.
1590 x_first = (modulo(g%first_direction+cs%n_dyn_steps_in_adv,2) == 0)
1591 else
1592 x_first = (modulo(g%first_direction,2) == 0)
1593 endif
1594 if (cs%debug) call mom_tracer_chksum("Pre-advect ", cs%tracer_Reg, g)
1595 call advect_tracer(h, cs%uhtr, cs%vhtr, cs%OBC, cs%t_dyn_rel_adv, g, gv, us, &
1596 cs%tracer_adv_CSp, cs%tracer_Reg, x_first_in=x_first, flux_type=0)
1597
1598 if (cs%do_resolved_advection) then
1599 call advect_tracer(h, cs%uhtr_resolved, cs%vhtr_resolved, cs%OBC, cs%t_dyn_rel_adv, g, gv, us, &
1600 cs%tracer_adv_CSp, cs%tracer_Reg, x_first_in=x_first, flux_type=1)
1601 endif
1602
1603 if (cs%do_param_advection) then
1604 !$OMP parallel do default(shared)
1605 do k=1,nz
1606 do j=js-2,je+2 ; do i=isq-2,ieq+2
1607 uhtr_tmp(i,j,k) = cs%uhtr(i,j,k) - cs%uhtr_resolved(i,j,k)
1608 enddo ; enddo
1609 do j=jsq-2,jeq+2 ; do i=is-2,ie+2
1610 vhtr_tmp(i,j,k) = cs%vhtr(i,j,k) - cs%vhtr_resolved(i,j,k)
1611 enddo ; enddo
1612 enddo
1613 call advect_tracer(h, uhtr_tmp, vhtr_tmp, cs%OBC, cs%t_dyn_rel_adv, g, gv, us, &
1614 cs%tracer_adv_CSp, cs%tracer_Reg, x_first_in=x_first, flux_type=2)
1615 endif
1616
1617 if (cs%debug) call mom_tracer_chksum("Post-advect ", cs%tracer_Reg, g)
1618 call tracer_hordiff(h, cs%t_dyn_rel_adv, cs%MEKE, cs%VarMix, cs%visc, g, gv, us, &
1619 cs%tracer_diff_CSp, cs%tracer_Reg, cs%tv)
1620 if (cs%debug) call mom_tracer_chksum("Post-diffuse ", cs%tracer_Reg, g)
1621 if (showcalltree) call calltree_waypoint("finished tracer advection/diffusion (step_MOM)")
1622 if (associated(cs%OBC)) then
1623 call pass_vector(cs%uhtr, cs%vhtr, g%Domain)
1624 call update_segment_tracer_reservoirs(g, gv, cs%uhtr, cs%vhtr, h, cs%OBC, &
1625 cs%tracer_Reg)
1626 endif
1627 call cpu_clock_end(id_clock_tracer) ; call cpu_clock_end(id_clock_thermo)
1628
1629 call cpu_clock_begin(id_clock_other) ; call cpu_clock_begin(id_clock_diagnostics)
1630 call post_transport_diagnostics(g, gv, us, cs%uhtr, cs%vhtr, h, cs%transport_IDs, &
1631 cs%diag_pre_dyn, cs%diag, cs%t_dyn_rel_adv, cs%tracer_reg)
1632 ! Rebuild the remap grids now that we've posted the fields which rely on thicknesses
1633 ! from before the dynamics calls
1634 call diag_update_remap_grids(cs%diag)
1635
1636 call disable_averaging(cs%diag)
1637 call cpu_clock_end(id_clock_diagnostics) ; call cpu_clock_end(id_clock_other)
1638
1639 ! Reset the accumulated transports to 0 and record that the dynamics
1640 ! and advective times now agree.
1641 call cpu_clock_begin(id_clock_thermo) ; call cpu_clock_begin(id_clock_tracer)
1642 cs%uhtr(:,:,:) = 0.0
1643 cs%vhtr(:,:,:) = 0.0
1644 if (cs%accumulate_resolved_flux) then
1645 cs%uhtr_resolved(:,:,:) = 0.0
1646 cs%vhtr_resolved(:,:,:) = 0.0
1647 endif
1648 cs%n_dyn_steps_in_adv = 0
1649 cs%t_dyn_rel_adv = 0.0
1650 call cpu_clock_end(id_clock_tracer) ; call cpu_clock_end(id_clock_thermo)
1651
1652 if (cs%useMEKE .and. (.not. cs%MEKE_in_dynamics)) then
1653 call step_forward_meke(cs%MEKE, h, cs%VarMix%SN_u, cs%VarMix%SN_v, &
1654 cs%visc, cs%t_dyn_rel_adv, g, gv, us, cs%MEKE_CSp, cs%uhtr, cs%vhtr, &
1655 cs%u, cs%v, cs%tv, time_local)
1656 endif
1657
1658 if (associated(cs%tv%T)) then
1659 call extract_diabatic_member(cs%diabatic_CSp, diabatic_halo=halo_sz)
1660 ! The bottom boundary layer calculation may need halo values of SpV_avg, including the corners.
1661 if (allocated(cs%tv%SpV_avg)) halo_sz = max(halo_sz, 1)
1662 if (halo_sz > 0) then
1663 call create_group_pass(pass_t_s, cs%tv%T, g%Domain, to_all, halo=halo_sz)
1664 call create_group_pass(pass_t_s, cs%tv%S, g%Domain, to_all, halo=halo_sz)
1665 call do_group_pass(pass_t_s, g%Domain, clock=id_clock_pass)
1666 elseif (cs%diabatic_first) then
1667 ! Temperature and salinity need halo updates because they will be used
1668 ! in the dynamics before they are changed again.
1669 call create_group_pass(pass_t_s, cs%tv%T, g%Domain, to_all+omit_corners, halo=1)
1670 call create_group_pass(pass_t_s, cs%tv%S, g%Domain, to_all+omit_corners, halo=1)
1671 call do_group_pass(pass_t_s, g%Domain, clock=id_clock_pass)
1672 halo_sz = 1
1673 endif
1674
1675 ! Update derived thermodynamic quantities.
1676 if (allocated(cs%tv%SpV_avg)) then
1677 call calc_derived_thermo(cs%tv, h, g, gv, us, halo=halo_sz, debug=cs%debug)
1678 endif
1679 endif
1680
1681 cs%preadv_h_stored = .false.
1682
1683end subroutine step_mom_tracer_dyn
1684
1685!> MOM_step_thermo orchestrates the thermodynamic time stepping and vertical
1686!! remapping, via calls to diabatic (or adiabatic).
1687subroutine step_mom_thermo(CS, G, GV, US, u, v, h, tv, fluxes, dtdia, &
1688 Time_end_thermo, update_BBL, Waves)
1689 type(mom_control_struct), intent(inout) :: CS !< Master MOM control structure
1690 type(ocean_grid_type), intent(inout) :: G !< ocean grid structure
1691 type(verticalgrid_type), intent(inout) :: GV !< ocean vertical grid structure
1692 type(unit_scale_type), intent(in) :: US !< A dimensional unit scaling type
1693 real, dimension(SZIB_(G),SZJ_(G),SZK_(GV)), &
1694 intent(inout) :: u !< zonal velocity [L T-1 ~> m s-1]
1695 real, dimension(SZI_(G),SZJB_(G),SZK_(GV)), &
1696 intent(inout) :: v !< meridional velocity [L T-1 ~> m s-1]
1697 real, dimension(SZI_(G),SZJ_(G),SZK_(GV)), &
1698 intent(inout) :: h !< layer thickness [H ~> m or kg m-2]
1699 type(thermo_var_ptrs), intent(inout) :: tv !< A structure pointing to various thermodynamic variables
1700 type(forcing), intent(inout) :: fluxes !< pointers to forcing fields
1701 real, intent(in) :: dtdia !< The time interval over which to advance [T ~> s]
1702 type(time_type), intent(in) :: Time_end_thermo !< End of averaging interval for thermo diags
1703 logical, intent(in) :: update_BBL !< If true, calculate the bottom boundary layer properties.
1704 type(wave_parameters_cs), &
1705 optional, pointer :: Waves !< Container for wave related parameters
1706 !! the fields in Waves are intent in here.
1707
1708 logical :: debug_redundant ! If true, check redundant values on PE boundaries when debugging.
1709 logical :: showCallTree
1710 type(group_pass_type) :: pass_T_S
1711 integer :: dynamics_stencil ! The computational stencil for the calculations
1712 ! in the dynamic core.
1713 integer :: halo_sz ! The size of a halo where data must be valid.
1714
1715 showcalltree = calltree_showquery()
1716 if (showcalltree) call calltree_enter("step_MOM_thermo(), MOM.F90")
1717 if (cs%debug) call query_debugging_checks(do_redundant=debug_redundant)
1718
1719 call enable_averages(dtdia, time_end_thermo, cs%diag)
1720
1721 if (associated(cs%odaCS)) then
1722 if (cs%debug) then
1723 call mom_thermo_chksum("Pre-oda ", tv, g, us, haloshift=0)
1724 endif
1725 call apply_oda_tracer_increments(dtdia, time_end_thermo, g, gv, tv, h, cs%odaCS)
1726 if (cs%debug) then
1727 call mom_thermo_chksum("Post-oda ", tv, g, us, haloshift=0)
1728 endif
1729 endif
1730
1731 if (associated(fluxes%p_surf) .or. associated(fluxes%p_surf_full)) then
1732 call extract_diabatic_member(cs%diabatic_CSp, diabatic_halo=halo_sz)
1733 if (halo_sz > 0) then
1734 if (associated(fluxes%p_surf_full)) &
1735 call pass_var(fluxes%p_surf_full, g%Domain, &
1736 clock=id_clock_pass, halo=halo_sz, complete=.not.associated(fluxes%p_surf))
1737 call pass_var(fluxes%p_surf, g%Domain, clock=id_clock_pass, halo=halo_sz, complete=.true.)
1738 endif
1739 endif
1740
1741 if (update_bbl) then
1742 ! Calculate the BBL properties and store them inside visc (u,h).
1743 ! This is here so that CS%visc is updated before diabatic() when
1744 ! DIABATIC_FIRST=True. Otherwise diabatic() is called after the dynamics
1745 ! and set_viscous_BBL is called as a part of the dynamic stepping.
1746 call cpu_clock_begin(id_clock_bbl_visc)
1747 !update porous barrier fractional cell metrics
1748 if (cs%use_porbar) then
1749 call porous_widths_interface(h, cs%tv, g, gv, us, cs%pbv, cs%por_bar_CS)
1750 call pass_vector(cs%pbv%por_layer_widthU, cs%pbv%por_layer_widthV, &
1751 g%Domain, direction=to_all+scalar_pair, clock=id_clock_pass, halo=cs%cont_stencil)
1752 endif
1753 call set_viscous_bbl(u, v, h, tv, cs%visc, g, gv, us, cs%set_visc_CSp, cs%pbv)
1754 call cpu_clock_end(id_clock_bbl_visc)
1755 if (showcalltree) call calltree_waypoint("done with set_viscous_BBL (step_MOM_thermo)")
1756 endif
1757
1758 call cpu_clock_begin(id_clock_thermo)
1759 if (.not.cs%adiabatic) then
1760 if (cs%debug) then
1761 call uvchksum("Pre-diabatic [uv]", u, v, g%HI, haloshift=2, unscale=us%L_T_to_m_s)
1762 call hchksum(h,"Pre-diabatic h", g%HI, haloshift=1, unscale=gv%H_to_MKS)
1763 call uvchksum("Pre-diabatic [uv]h", cs%uhtr, cs%vhtr, g%HI, &
1764 haloshift=0, unscale=gv%H_to_MKS*us%L_to_m**2)
1765 ! call MOM_state_chksum("Pre-diabatic ", u, v, h, CS%uhtr, CS%vhtr, G, GV, vel_scale=1.0)
1766 call mom_thermo_chksum("Pre-diabatic ", tv, g, us, haloshift=0)
1767 if (debug_redundant) &
1768 call check_redundant("Pre-diabatic ", u, v, g, unscale=us%L_T_to_m_s)
1769 call mom_forcing_chksum("Pre-diabatic", fluxes, g, us, haloshift=0)
1770 endif
1771
1772 call cpu_clock_begin(id_clock_diabatic)
1773
1774 call diabatic(u, v, h, tv, cs%Hml, fluxes, cs%visc, cs%ADp, cs%CDp, dtdia, &
1775 time_end_thermo, g, gv, us, cs%diabatic_CSp, cs%stoch_CS, cs%OBC, waves)
1776 fluxes%fluxes_used = .true.
1777
1778 if (cs%stoch_CS%do_skeb) then
1779 call apply_skeb(g, gv, us, cs%stoch_CS, u, v, h, tv, dtdia, time_end_thermo)
1780 endif
1781
1782 if (showcalltree) call calltree_waypoint("finished diabatic (step_MOM_thermo)")
1783
1784 if (cs%debug) then
1785 call uvchksum("Post-diabatic u", u, v, g%HI, haloshift=2, unscale=us%L_T_to_m_s)
1786 call hchksum(h, "Post-diabatic h", g%HI, haloshift=1, unscale=gv%H_to_MKS)
1787 call uvchksum("Post-diabatic [uv]h", cs%uhtr, cs%vhtr, g%HI, &
1788 haloshift=0, unscale=gv%H_to_MKS*us%L_to_m**2)
1789 ! call MOM_state_chksum("Post-diabatic ", u, v, &
1790 ! h, CS%uhtr, CS%vhtr, G, GV, haloshift=1)
1791 if (associated(tv%T)) call hchksum(tv%T, "Post-diabatic T", g%HI, haloshift=1, unscale=us%C_to_degC)
1792 if (associated(tv%S)) call hchksum(tv%S, "Post-diabatic S", g%HI, haloshift=1, unscale=us%S_to_ppt)
1793 if (associated(tv%frazil)) call hchksum(tv%frazil, "Post-diabatic frazil", g%HI, haloshift=0, &
1794 unscale=us%Q_to_J_kg*us%RZ_to_kg_m2)
1795 if (associated(tv%salt_deficit)) call hchksum(tv%salt_deficit, &
1796 "Post-diabatic salt deficit", g%HI, haloshift=0, unscale=us%RZ_to_kg_m2)
1797 ! call MOM_thermo_chksum("Post-diabatic ", tv, G, US)
1798 if (debug_redundant) &
1799 call check_redundant("Post-diabatic ", u, v, g, unscale=us%L_T_to_m_s)
1800 endif
1801 call disable_averaging(cs%diag)
1802
1803 call cpu_clock_end(id_clock_diabatic)
1804 else ! complement of "if (.not.CS%adiabatic)"
1805
1806 call cpu_clock_begin(id_clock_adiabatic)
1807 call adiabatic(h, tv, fluxes, dtdia, g, gv, us, cs%diabatic_CSp)
1808 fluxes%fluxes_used = .true.
1809 call cpu_clock_end(id_clock_adiabatic)
1810
1811 if (associated(tv%T)) then
1812 dynamics_stencil = min(3, g%Domain%nihalo, g%Domain%njhalo)
1813 call create_group_pass(pass_t_s, tv%T, g%Domain, to_all+omit_corners, halo=dynamics_stencil)
1814 call create_group_pass(pass_t_s, tv%S, g%Domain, to_all+omit_corners, halo=dynamics_stencil)
1815 call do_group_pass(pass_t_s, g%Domain, clock=id_clock_pass)
1816 if (cs%debug) then
1817 if (associated(tv%T)) call hchksum(tv%T, "Post-diabatic T", g%HI, haloshift=1, unscale=us%C_to_degC)
1818 if (associated(tv%S)) call hchksum(tv%S, "Post-diabatic S", g%HI, haloshift=1, unscale=us%S_to_ppt)
1819 endif
1820
1821 ! Update derived thermodynamic quantities.
1822 if (allocated(tv%SpV_avg)) then
1823 call calc_derived_thermo(tv, h, g, gv, us, halo=dynamics_stencil, debug=cs%debug)
1824 endif
1825 endif
1826
1827 endif ! endif for the block "if (.not.CS%adiabatic)"
1828 call cpu_clock_end(id_clock_thermo)
1829
1830 call disable_averaging(cs%diag)
1831
1832! This works in general:
1833! if (associated(tv%T)) &
1834! call totalTandS(G%HI, h, G%areaT, tv%T, tv%S, "End of step_MOM", US, GV%H_to_mks)
1835! This works only if there is no rescaling being used:
1836! if (associated(tv%T)) &
1837! call totalTandS(G%HI, h, G%areaT, tv%T, tv%S, "End of step_MOM")
1838
1839 if (showcalltree) call calltree_leave("step_MOM_thermo(), MOM.F90")
1840
1841end subroutine step_mom_thermo
1842
1843!> ALE_regridding_and_remapping does regridding (the generation of a new grid) and remapping
1844!! (from the old grid to the new grid). This is done after the themrodynamic step.
1845subroutine ale_regridding_and_remapping(CS, G, GV, US, u, v, h, tv, dtdia, Time_end_thermo)
1846 type(mom_control_struct), intent(inout) :: CS !< Master MOM control structure
1847 type(ocean_grid_type), intent(inout) :: G !< ocean grid structure
1848 type(verticalgrid_type), intent(inout) :: GV !< ocean vertical grid structure
1849 type(unit_scale_type), intent(in) :: US !< A dimensional unit scaling type
1850 real, dimension(SZIB_(G),SZJ_(G),SZK_(GV)), &
1851 intent(inout) :: u !< zonal velocity [L T-1 ~> m s-1]
1852 real, dimension(SZI_(G),SZJB_(G),SZK_(GV)), &
1853 intent(inout) :: v !< meridional velocity [L T-1 ~> m s-1]
1854 real, dimension(SZI_(G),SZJ_(G),SZK_(GV)), &
1855 intent(inout) :: h !< layer thickness [H ~> m or kg m-2]
1856 type(thermo_var_ptrs), intent(inout) :: tv !< A structure pointing to various thermodynamic variables
1857 real, intent(in) :: dtdia !< The time interval over which to advance [T ~> s]
1858 type(time_type), intent(in) :: Time_end_thermo !< End of averaging interval for thermo diags
1859
1860 real :: h_new(SZI_(G),SZJ_(G),SZK_(GV)) ! Layer thicknesses after regridding [H ~> m or kg m-2]
1861 real :: dzRegrid(SZI_(G),SZJ_(G),SZK_(GV)+1) ! The change in grid interface positions due to regridding,
1862 ! in the same units as thicknesses [H ~> m or kg m-2]
1863 real :: h_old_u(SZIB_(G),SZJ_(G),SZK_(GV)) ! Source grid thickness at zonal
1864 ! velocity points [H ~> m or kg m-2]
1865 real :: h_old_v(SZI_(G),SZJB_(G),SZK_(GV)) ! Source grid thickness at meridional
1866 ! velocity points [H ~> m or kg m-2]
1867 real :: h_new_u(SZIB_(G),SZJ_(G),SZK_(GV)) ! Destination grid thickness at zonal
1868 ! velocity points [H ~> m or kg m-2]
1869 real :: h_new_v(SZI_(G),SZJB_(G),SZK_(GV)) ! Destination grid thickness at meridional
1870 ! velocity points [H ~> m or kg m-2]
1871 logical :: PCM_cell(SZI_(G),SZJ_(G),SZK_(GV)) ! If true, PCM remapping should be used in a cell.
1872 logical :: use_ice_shelf ! Needed for selecting the right ALE interface.
1873 logical :: debug_redundant ! If true, check redundant values on PE boundaries when debugging.
1874 logical :: showCallTree
1875 type(group_pass_type) :: pass_T_S_h
1876 integer :: i, j, k, is, ie, js, je, nz
1877
1878 is = g%isc ; ie = g%iec ; js = g%jsc ; je = g%jec ; nz = gv%ke
1879 use_ice_shelf = .false.
1880 if (associated(cs%frac_shelf_h)) use_ice_shelf = .true.
1881 showcalltree = calltree_showquery()
1882 if (showcalltree) call calltree_enter("ALE_regridding_and_remapping(), MOM.F90")
1883 if (cs%debug) call query_debugging_checks(do_redundant=debug_redundant)
1884
1885 call cpu_clock_begin(id_clock_remap)
1886
1887 ! Regridding/remapping is done here, at end of thermodynamics time step
1888 ! (that may comprise several dynamical time steps)
1889 ! The routine 'ALE_regrid' can be found in 'MOM_ALE.F90'.
1890 call enable_averages(dtdia, time_end_thermo, cs%diag)
1891
1892 call cpu_clock_begin(id_clock_pass)
1893 if (associated(tv%T)) &
1894 call create_group_pass(pass_t_s_h, tv%T, g%Domain, to_all+omit_corners, halo=1)
1895 if (associated(tv%S)) &
1896 call create_group_pass(pass_t_s_h, tv%S, g%Domain, to_all+omit_corners, halo=1)
1897 call create_group_pass(pass_t_s_h, h, g%Domain, to_all+omit_corners, halo=1)
1898 call do_group_pass(pass_t_s_h, g%Domain)
1899 call cpu_clock_end(id_clock_pass)
1900
1901 call preale_tracer_diagnostics(cs%tracer_Reg, g, gv)
1902
1903 if (cs%use_particles) then
1904 call particles_to_z_space(cs%particles, h)
1905 endif
1906
1907 if (cs%debug) then
1908 call mom_state_chksum("Pre-ALE ", u, v, h, cs%uh, cs%vh, g, gv, us, omit_corners=.true.)
1909 call hchksum(tv%T,"Pre-ALE T", g%HI, haloshift=1, omit_corners=.true., unscale=us%C_to_degC)
1910 call hchksum(tv%S,"Pre-ALE S", g%HI, haloshift=1, omit_corners=.true., unscale=us%S_to_ppt)
1911 if (debug_redundant) &
1912 call check_redundant("Pre-ALE ", u, v, g, unscale=us%L_T_to_m_s)
1913 endif
1914 call cpu_clock_begin(id_clock_ale)
1915
1916 call pre_ale_diagnostics(g, gv, us, h, u, v, tv, cs%ALE_CSp)
1917 call ale_update_regrid_weights(dtdia, cs%ALE_CSp)
1918 ! Do any necessary adjustments ot the state prior to remapping.
1919 call pre_ale_adjustments(g, gv, us, h, tv, cs%tracer_Reg, cs%ALE_CSp, u, v)
1920 ! Adjust the target grids for diagnostics, in case there have been thickness adjustments.
1921 call diag_update_remap_grids(cs%diag)
1922
1923 if (use_ice_shelf) then
1924 call ale_regrid(g, gv, us, h, h_new, dzregrid, tv, cs%ALE_CSp, cs%frac_shelf_h, pcm_cell)
1925 else
1926 call ale_regrid(g, gv, us, h, h_new, dzregrid, tv, cs%ALE_CSp, pcm_cell=pcm_cell)
1927 endif
1928
1929 if (showcalltree) call calltree_waypoint("new grid generated")
1930 ! Remap all variables from the old grid h onto the new grid h_new
1931 call ale_remap_tracers(cs%ALE_CSp, g, gv, h, h_new, cs%tracer_Reg, showcalltree, dtdia, pcm_cell)
1932
1933 ! Determine the old and new grid thicknesses at velocity points.
1934 call ale_remap_set_h_vel(cs%ALE_CSp, g, gv, h, h_old_u, h_old_v, cs%OBC, debug=showcalltree)
1935 if (cs%remap_uv_using_old_alg) then
1936 call ale_remap_set_h_vel_via_dz(cs%ALE_CSp, g, gv, h_new, h_new_u, h_new_v, cs%OBC, h, dzregrid, showcalltree)
1937 else
1938 call ale_remap_set_h_vel(cs%ALE_CSp, g, gv, h_new, h_new_u, h_new_v, cs%OBC, debug=showcalltree)
1939 endif
1940
1941 ! Remap the velocity components.
1942 call ale_remap_velocities(cs%ALE_CSp, g, gv, h_old_u, h_old_v, h_new_u, h_new_v, u, v, showcalltree, &
1943 dtdia, allow_preserve_variance=.true.)
1944
1945 if (allocated(tv%SpV_avg)) tv%valid_SpV_halo = -1 ! Record that SpV_avg is no longer valid.
1946
1947 if (cs%remap_aux_vars) then
1948 if (cs%split .and. cs%use_alt_split) then
1949 call remap_dyn_split_rk2b_aux_vars(g, gv, cs%dyn_split_RK2b_CSp, h_old_u, h_old_v, &
1950 h_new_u, h_new_v, cs%ALE_CSp)
1951 elseif (cs%split) then
1952 call remap_dyn_split_rk2_aux_vars(g, gv, cs%dyn_split_RK2_CSp, h_old_u, h_old_v, h_new_u, h_new_v, cs%ALE_CSp)
1953 endif
1954
1955 if (associated(cs%OBC) .or. associated(cs%visc%Kv_shear_Bu)) then
1956 call pass_var(h, g%Domain, complete=.false.)
1957 call pass_var(h_new, g%Domain, complete=.true.)
1958 endif
1959
1960 if (associated(cs%OBC)) &
1961 call remap_obc_fields(g, gv, h, h_new, cs%OBC, pcm_cell=pcm_cell)
1962
1963 call remap_vertvisc_aux_vars(g, gv, cs%visc, h, h_new, cs%ALE_CSp, cs%OBC)
1964 if (associated(cs%visc%Kv_shear)) &
1965 call pass_var(cs%visc%Kv_shear, g%Domain, to_all+omit_corners, clock=id_clock_pass, halo=1)
1966 endif
1967
1968 ! Replace the old grid with new one. All remapping must be done by this point in the code.
1969 !$OMP parallel do default(shared)
1970 do k=1,nz ; do j=js-1,je+1 ; do i=is-1,ie+1
1971 h(i,j,k) = h_new(i,j,k)
1972 enddo ; enddo ; enddo
1973
1974 if (showcalltree) call calltree_waypoint("finished ALE_regrid (ALE_regridding_and_remapping)")
1975 call cpu_clock_end(id_clock_ale)
1976
1977 ! Update derived thermodynamic quantities.
1978 if (allocated(cs%tv%SpV_avg)) then
1979 call calc_derived_thermo(cs%tv, cs%h, g, gv, us, halo=1, debug=cs%debug)
1980 endif
1981
1982 ! Whenever thickness changes let the diag manager know, target grids
1983 ! for vertical remapping may need to be regenerated. In non-Boussinesq mode,
1984 ! calc_derived_thermo needs to be called before diag_update_remap_grids.
1985 ! This needs to happen after the H update and before the next post_data.
1986 call diag_update_remap_grids(cs%diag)
1987
1988 call postale_tracer_diagnostics(cs%tracer_Reg, g, gv, cs%diag, dtdia)
1989
1990 if (cs%debug .and. cs%use_ALE_algorithm) then
1991 call mom_state_chksum("Post-ALE ", u, v, h, cs%uh, cs%vh, g, gv, us)
1992 call hchksum(tv%T, "Post-ALE T", g%HI, haloshift=1, unscale=us%C_to_degC)
1993 call hchksum(tv%S, "Post-ALE S", g%HI, haloshift=1, unscale=us%S_to_ppt)
1994 if (debug_redundant) &
1995 call check_redundant("Post-ALE ", u, v, g, unscale=us%L_T_to_m_s)
1996 endif
1997 if (cs%debug) then
1998 call uvchksum("Post-ALE, Post-diabatic u", u, v, g%HI, haloshift=2, unscale=us%L_T_to_m_s)
1999 call hchksum(h, "Post-ALE, Post-diabatic h", g%HI, haloshift=1, unscale=gv%H_to_MKS)
2000 call uvchksum("Post-ALE, Post-diabatic [uv]h", cs%uhtr, cs%vhtr, g%HI, &
2001 haloshift=0, unscale=gv%H_to_MKS*us%L_to_m**2)
2002 ! call MOM_state_chksum("Post-diabatic ", u, v, &
2003 ! h, CS%uhtr, CS%vhtr, G, GV, haloshift=1)
2004 if (associated(tv%T)) call hchksum(tv%T, "Post-ALE, Post-diabatic T", g%HI, haloshift=1, unscale=us%C_to_degC)
2005 if (associated(tv%S)) call hchksum(tv%S, "Post-ALE, Post-diabatic S", g%HI, haloshift=1, unscale=us%S_to_ppt)
2006 if (associated(tv%frazil)) call hchksum(tv%frazil, "Post-ALE, Post-diabatic frazil", g%HI, haloshift=0, &
2007 unscale=us%Q_to_J_kg*us%RZ_to_kg_m2)
2008 if (associated(tv%salt_deficit)) call hchksum(tv%salt_deficit, &
2009 "Post-ALE, Post-diabatic salt deficit", g%HI, haloshift=0, unscale=us%RZ_to_kg_m2)
2010 ! call MOM_thermo_chksum("Post-diabatic ", tv, G, US)
2011 if (debug_redundant) &
2012 call check_redundant("Post-ALE, Post-diabatic ", u, v, g, unscale=us%L_T_to_m_s)
2013 endif
2014 call disable_averaging(cs%diag)
2015
2016 call cpu_clock_end(id_clock_remap)
2017
2018 if (showcalltree) call calltree_leave("ALE_regridding_and_remapping(), MOM.F90")
2019
2020end subroutine ale_regridding_and_remapping
2021
2022!> post_diabatic_halo_updates does halo updates and calculates derived thermodynamic quantities
2023!! (e.g. specific volume). This must be done after the diabatic step regardless of is ALE
2024!! cooridinates are used or not.
2025subroutine post_diabatic_halo_updates(CS, G, GV, US, u, v, h, tv)
2026 type(mom_control_struct), intent(inout) :: CS !< Master MOM control structure
2027 type(ocean_grid_type), intent(inout) :: G !< ocean grid structure
2028 type(verticalgrid_type), intent(inout) :: GV !< ocean vertical grid structure
2029 type(unit_scale_type), intent(in) :: US !< A dimensional unit scaling type
2030 real, dimension(SZIB_(G),SZJ_(G),SZK_(GV)), &
2031 intent(inout) :: u !< zonal velocity [L T-1 ~> m s-1]
2032 real, dimension(SZI_(G),SZJB_(G),SZK_(GV)), &
2033 intent(inout) :: v !< meridional velocity [L T-1 ~> m s-1]
2034 real, dimension(SZI_(G),SZJ_(G),SZK_(GV)), &
2035 intent(inout) :: h !< layer thickness [H ~> m or kg m-2]
2036 type(thermo_var_ptrs), intent(inout) :: tv !< A structure pointing to various thermodynamic variables
2037
2038 logical :: debug_redundant ! If true, check redundant values on PE boundaries when debugging.
2039 logical :: showCallTree
2040 type(group_pass_type) :: pass_uv_T_S_h
2041 integer :: dynamics_stencil ! The computational stencil for the calculations
2042 ! in the dynamic core.
2043
2044 showcalltree = calltree_showquery()
2045 if (showcalltree) call calltree_enter("post_diabatic_halo_updates, MOM.F90")
2046 if (cs%debug) call query_debugging_checks(do_redundant=debug_redundant)
2047
2048 if (cs%use_particles) then
2049 call particles_to_k_space(cs%particles, h)
2050 endif
2051
2052 dynamics_stencil = min(3, g%Domain%nihalo, g%Domain%njhalo)
2053 call create_group_pass(pass_uv_t_s_h, u, v, g%Domain, halo=dynamics_stencil)
2054 if (associated(tv%T)) &
2055 call create_group_pass(pass_uv_t_s_h, tv%T, g%Domain, halo=dynamics_stencil)
2056 if (associated(tv%S)) &
2057 call create_group_pass(pass_uv_t_s_h, tv%S, g%Domain, halo=dynamics_stencil)
2058 call create_group_pass(pass_uv_t_s_h, h, g%Domain, halo=dynamics_stencil)
2059 call do_group_pass(pass_uv_t_s_h, g%Domain, clock=id_clock_pass)
2060
2061 if (associated(tv%frazil) .and. (.not.tv%frazil_was_reset) .and. cs%vertex_shear) &
2062 call pass_var(tv%frazil, g%Domain, halo=1)
2063
2064 ! Update derived thermodynamic quantities.
2065 if (allocated(tv%SpV_avg)) then
2066 call calc_derived_thermo(tv, h, g, gv, us, halo=dynamics_stencil, debug=cs%debug)
2067 endif
2068 if (showcalltree) call calltree_leave("post_diabatic_halo_updates, MOM.F90")
2069end subroutine post_diabatic_halo_updates
2070
2071!> step_offline is the main driver for running tracers offline in MOM6. This has been primarily
2072!! developed with ALE configurations in mind. Some work has been done in isopycnal configuration, but
2073!! the work is very preliminary. Some more detail about this capability along with some of the subroutines
2074!! called here can be found in tracers/MOM_offline_control.F90
2075subroutine step_offline(forces, fluxes, sfc_state, Time_start, time_interval, CS)
2076 type(mech_forcing), intent(in) :: forces !< A structure with the driving mechanical forces
2077 type(forcing), intent(inout) :: fluxes !< pointers to forcing fields
2078 type(surface), intent(inout) :: sfc_state !< surface ocean state
2079 type(time_type), intent(in) :: time_start !< starting time of a segment, as a time type
2080 real, intent(in) :: time_interval !< time interval [T ~> s]
2081 type(mom_control_struct), intent(inout) :: cs !< control structure from initialize_MOM
2082
2083 ! Local pointers
2084 type(ocean_grid_type), pointer :: g => null() ! Pointer to a structure containing
2085 ! metrics and related information
2086 type(verticalgrid_type), pointer :: gv => null() ! Pointer to structure containing information
2087 ! about the vertical grid
2088 type(unit_scale_type), pointer :: us => null() ! Pointer to a structure containing
2089 ! various unit conversion factors
2090
2091 logical :: first_iter !< True if this is the first time step_offline has been called in a given interval
2092 logical :: last_iter !< True if this is the last time step_tracer is to be called in an offline interval
2093 logical :: do_vertical !< If enough time has elapsed, do the diabatic tracer sources/sinks
2094 logical :: adv_converged !< True if all the horizontal fluxes have been used
2095
2096 real, allocatable, dimension(:,:,:) :: h_new ! Layer thicknesses after regridding [H ~> m or kg m-2]
2097 real, allocatable, dimension(:,:,:) :: dzregrid ! The change in grid interface positions due to regridding,
2098 ! in the same units as thicknesses [H ~> m or kg m-2]
2099 real :: dt_offline ! The offline timestep for advection [T ~> s]
2100 real :: dt_offline_vertical ! The offline timestep for vertical fluxes and remapping [T ~> s]
2101 logical :: skip_diffusion
2102
2103 type(time_type), pointer :: accumulated_time => null()
2104 type(time_type), pointer :: vertical_time => null()
2105 integer :: dynamics_stencil ! The computational stencil for the calculations
2106 ! in the dynamic core.
2107 integer :: i, j, k, is, ie, js, je, isd, ied, jsd, jed, nz
2108
2109 ! 3D pointers
2110 real, dimension(:,:,:), pointer :: &
2111 uhtr => null(), & ! Accumulated zonal thickness fluxes to advect tracers [H L2 ~> m3 or kg]
2112 vhtr => null(), & ! Accumulated meridional thickness fluxes to advect tracers [H L2 ~> m3 or kg]
2113 eatr => null(), & ! Layer entrainment rates across the interface above [H ~> m or kg m-2]
2114 ebtr => null(), & ! Layer entrainment rates across the interface below [H ~> m or kg m-2]
2115 h_end => null() ! Layer thicknesses at the end of a step [H ~> m or kg m-2]
2116
2117 type(time_type) :: time_end ! End time of a segment, as a time type
2118
2119 ! Grid-related pointer assignments
2120 g => cs%G ; gv => cs%GV ; us => cs%US
2121
2122 is = g%isc ; ie = g%iec ; js = g%jsc ; je = g%jec ; nz = gv%ke
2123 isd = g%isd ; ied = g%ied ; jsd = g%jsd ; jed = g%jed
2124
2125 call cpu_clock_begin(id_clock_offline_tracer)
2126 call extract_offline_main(cs%offline_CSp, uhtr, vhtr, eatr, ebtr, h_end, accumulated_time, &
2127 vertical_time, dt_offline, dt_offline_vertical, skip_diffusion)
2128 time_end = increment_date(time_start, seconds=floor(us%T_to_s*time_interval+0.001))
2129
2130 call enable_averages(time_interval, time_end, cs%diag)
2131
2132 ! Check to see if this is the first iteration of the offline interval
2133 first_iter = (accumulated_time == real_to_time(0.0))
2134
2135 ! Check to see if vertical tracer functions should be done
2136 do_vertical = (first_iter .or. (accumulated_time >= vertical_time))
2137 if (do_vertical) vertical_time = accumulated_time + real_to_time(dt_offline_vertical, unscale=us%T_to_s)
2138
2139 ! Increment the amount of time elapsed since last read and check if it's time to roll around
2140 accumulated_time = accumulated_time + real_to_time(time_interval, unscale=us%T_to_s)
2141
2142 last_iter = (accumulated_time >= real_to_time(dt_offline, unscale=us%T_to_s))
2143
2144 if (cs%use_ALE_algorithm) then
2145 ! If this is the first iteration in the offline timestep, then we need to read in fields and
2146 ! perform the main advection.
2147 if (first_iter) then
2148 call mom_mesg("Reading in new offline fields")
2149 ! Read in new transport and other fields
2150 ! call update_transport_from_files(G, GV, CS%offline_CSp, h_end, eatr, ebtr, uhtr, vhtr, &
2151 ! CS%tv%T, CS%tv%S, fluxes, CS%use_ALE_algorithm)
2152 ! call update_transport_from_arrays(CS%offline_CSp)
2153 call update_offline_fields(cs%offline_CSp, g, gv, us, cs%h, fluxes, cs%use_ALE_algorithm)
2154
2155 ! Apply any fluxes into the ocean
2156 call offline_fw_fluxes_into_ocean(g, gv, cs%offline_CSp, fluxes, cs%h)
2157
2158 if (.not.cs%diabatic_first) then
2159 call offline_advection_ale(fluxes, time_start, time_interval, g, gv, us, cs%offline_CSp, &
2160 id_clock_ale, cs%h, uhtr, vhtr, converged=adv_converged)
2161
2162 ! Redistribute any remaining transport
2163 call offline_redistribute_residual(cs%offline_CSp, g, gv, us, cs%h, uhtr, vhtr, adv_converged)
2164
2165 ! Perform offline diffusion if requested
2166 if (.not. skip_diffusion) then
2167 if (cs%VarMix%use_variable_mixing) then
2168 call pass_var(cs%h, g%Domain)
2169 call calc_resoln_function(cs%h, cs%tv, g, gv, us, cs%VarMix, cs%MEKE, cs%OBC, dt_offline)
2170 call calc_depth_function(g, cs%VarMix)
2171 call calc_slope_functions(cs%h, cs%tv, dt_offline, g, gv, us, cs%VarMix, obc=cs%OBC)
2172 endif
2173 call tracer_hordiff(cs%h, dt_offline, cs%MEKE, cs%VarMix, cs%visc, g, gv, us, &
2174 cs%tracer_diff_CSp, cs%tracer_Reg, cs%tv)
2175 endif
2176 endif
2177 endif
2178 ! The functions related to column physics of tracers is performed separately in ALE mode
2179 if (do_vertical) then
2180 call offline_diabatic_ale(fluxes, time_start, time_end, g, gv, us, cs%offline_CSp, &
2181 cs%h, cs%tv, eatr, ebtr)
2182 endif
2183
2184 ! Last thing that needs to be done is the final ALE remapping
2185 if (last_iter) then
2186 if (cs%diabatic_first) then
2187 call offline_advection_ale(fluxes, time_start, time_interval, g, gv, us, cs%offline_CSp, &
2188 id_clock_ale, cs%h, uhtr, vhtr, converged=adv_converged)
2189
2190 ! Redistribute any remaining transport and perform the remaining advection
2191 call offline_redistribute_residual(cs%offline_CSp, g, gv, us, cs%h, uhtr, vhtr, adv_converged)
2192 ! Perform offline diffusion if requested
2193 if (.not. skip_diffusion) then
2194 if (cs%VarMix%use_variable_mixing) then
2195 call pass_var(cs%h, g%Domain)
2196 call calc_resoln_function(cs%h, cs%tv, g, gv, us, cs%VarMix, cs%MEKE, cs%OBC, dt_offline)
2197 call calc_depth_function(g, cs%VarMix)
2198 call calc_slope_functions(cs%h, cs%tv, dt_offline, g, gv, us, cs%VarMix, obc=cs%OBC)
2199 endif
2200 call tracer_hordiff(cs%h, dt_offline, cs%MEKE, cs%VarMix, cs%visc, g, gv, us, &
2201 cs%tracer_diff_CSp, cs%tracer_Reg, cs%tv)
2202 endif
2203 endif
2204
2205 call mom_mesg("Last iteration of offline interval")
2206
2207 ! Apply freshwater fluxes out of the ocean
2208 call offline_fw_fluxes_out_ocean(g, gv, cs%offline_CSp, fluxes, cs%h)
2209 ! These diagnostic can be used to identify which grid points did not converge within
2210 ! the specified number of advection sub iterations
2211 call post_offline_convergence_diags(g, gv, cs%offline_CSp, cs%h, h_end, uhtr, vhtr)
2212
2213 ! Call ALE one last time to make sure that tracers are remapped onto the layer thicknesses
2214 ! stored from the forward run
2215 call cpu_clock_begin(id_clock_ale)
2216
2217 ! Do any necessary adjustments ot the state prior to remapping.
2218 call pre_ale_adjustments(g, gv, us, h_end, cs%tv, cs%tracer_Reg, cs%ALE_CSp)
2219
2220 allocate(h_new(isd:ied, jsd:jed, nz), source=0.0)
2221 allocate(dzregrid(isd:ied, jsd:jed, nz+1), source=0.0)
2222
2223 ! Generate the new grid based on the tracer grid at the end of the interval.
2224 call ale_regrid(g, gv, us, h_end, h_new, dzregrid, cs%tv, cs%ALE_CSp)
2225
2226 ! Remap the tracers from the previous tracer grid onto the new grid. The thicknesses that
2227 ! are used are intended to ensure that in the case where transports don't quite conserve,
2228 ! the offline layer thicknesses do not drift too far away from the online model.
2229 call ale_remap_tracers(cs%ALE_CSp, g, gv, cs%h, h_new, cs%tracer_Reg, debug=cs%debug)
2230 if (allocated(cs%tv%SpV_avg)) cs%tv%valid_SpV_halo = -1 ! Record that SpV_avg is no longer valid.
2231
2232 ! Update the tracer grid.
2233 do k=1,nz ; do j=js-1,je+1 ; do i=is-1,ie+1
2234 cs%h(i,j,k) = h_new(i,j,k)
2235 enddo ; enddo ; enddo
2236
2237 deallocate(h_new, dzregrid)
2238
2239 call cpu_clock_end(id_clock_ale)
2240 call pass_var(cs%h, g%Domain)
2241 endif
2242 else ! NON-ALE MODE...NOT WELL TESTED
2243 call mom_error(warning, &
2244 "Offline tracer mode in non-ALE configuration has not been thoroughly tested")
2245 ! Note that for the layer mode case, the calls to tracer sources and sinks is embedded in
2246 ! main_offline_advection_layer. Warning: this may not be appropriate for tracers that
2247 ! exchange with the atmosphere
2248 if (abs(time_interval - dt_offline) > 1.0e-6*us%s_to_T) then
2249 call mom_error(fatal, &
2250 "For offline tracer mode in a non-ALE configuration, dt_offline must equal time_interval")
2251 endif
2252 call update_offline_fields(cs%offline_CSp, g, gv, us, cs%h, fluxes, cs%use_ALE_algorithm)
2253 call offline_advection_layer(fluxes, time_start, time_interval, g, gv, us, cs%offline_CSp, &
2254 cs%h, eatr, ebtr, uhtr, vhtr)
2255 ! Perform offline diffusion if requested
2256 if (.not. skip_diffusion) then
2257 call tracer_hordiff(h_end, dt_offline, cs%MEKE, cs%VarMix, cs%visc, g, gv, us, &
2258 cs%tracer_diff_CSp, cs%tracer_Reg, cs%tv)
2259 endif
2260
2261 cs%h = h_end
2262
2263 call pass_var(cs%tv%T, g%Domain)
2264 call pass_var(cs%tv%S, g%Domain)
2265 call pass_var(cs%h, g%Domain)
2266
2267 endif
2268
2269 call adjust_ssh_for_p_atm(cs%tv, g, gv, us, cs%ave_ssh_ibc, forces%p_surf_SSH, &
2270 cs%calc_rho_for_sea_lev)
2271 call extract_surface_state(cs, sfc_state)
2272
2273 call disable_averaging(cs%diag)
2274 call pass_var(cs%tv%T, g%Domain)
2275 call pass_var(cs%tv%S, g%Domain)
2276 call pass_var(cs%h, g%Domain)
2277
2278 fluxes%fluxes_used = .true.
2279
2280 ! Update derived thermodynamic quantities.
2281 if (allocated(cs%tv%SpV_avg)) then
2282 dynamics_stencil = min(3, g%Domain%nihalo, g%Domain%njhalo)
2283 call calc_derived_thermo(cs%tv, cs%h, g, gv, us, halo=dynamics_stencil)
2284 endif
2285
2286 if (last_iter) then
2287 accumulated_time = real_to_time(0.0)
2288 endif
2289
2290 call cpu_clock_end(id_clock_offline_tracer)
2291
2292end subroutine step_offline
2293
2294!> Initialize MOM, including memory allocation, setting up parameters and diagnostics,
2295!! initializing the ocean state variables, and initializing subsidiary modules
2296subroutine initialize_mom(Time, Time_init, param_file, dirs, CS, &
2297 Time_in, offline_tracer_mode, input_restart_file, diag_ptr, &
2298 count_calls, tracer_flow_CSp, ice_shelf_CSp, waves_CSp, ensemble_num, &
2299 calve_ice_shelf_bergs)
2300 type(time_type), target, intent(inout) :: time !< model time, set in this routine
2301 type(time_type), intent(in) :: time_init !< The start time for the coupled model's calendar
2302 type(param_file_type), intent(out) :: param_file !< structure indicating parameter file to parse
2303 type(directories), intent(out) :: dirs !< structure with directory paths
2304 type(mom_control_struct), intent(inout), target :: cs !< pointer set in this routine to MOM control structure
2305 type(time_type), optional, intent(in) :: time_in !< time passed to MOM_initialize_state when
2306 !! model is not being started from a restart file
2307 logical, optional, intent(out) :: offline_tracer_mode !< True is returned if tracers are being run offline
2308 character(len=*),optional, intent(in) :: input_restart_file !< If present, name of restart file to read
2309 type(diag_ctrl), optional, pointer :: diag_ptr !< A pointer set in this routine to the diagnostic
2310 !! regulatory structure
2311 type(tracer_flow_control_cs), &
2312 optional, pointer :: tracer_flow_csp !< A pointer set in this routine to
2313 !! the tracer flow control structure.
2314 logical, optional, intent(in) :: count_calls !< If true, nstep_tot counts the number of
2315 !! calls to step_MOM instead of the number of
2316 !! dynamics timesteps.
2317 type(ice_shelf_cs), optional, pointer :: ice_shelf_csp !< A pointer to an ice shelf control structure
2318 type(wave_parameters_cs), &
2319 optional, pointer :: waves_csp !< An optional pointer to a wave property CS
2320 integer, optional :: ensemble_num !< Ensemble index provided by the cap (instead of FMS
2321 !! ensemble manager)
2322 logical, optional :: calve_ice_shelf_bergs !< If true, will add point iceberg calving variables to the ice
2323 !! shelf restart
2324 ! local variables
2325 type(ocean_grid_type), pointer :: g => null() ! A pointer to the metric grid use for the run
2326 type(ocean_grid_type), pointer :: g_in => null() ! Pointer to the input grid
2327 type(hor_index_type), pointer :: hi => null() ! A hor_index_type for array extents
2328 type(hor_index_type), target :: hi_in ! HI on the input grid
2329 type(hor_index_type) :: hi_in_unmasked ! HI on the unmasked input grid
2330 type(verticalgrid_type), pointer :: gv => null()
2331 type(dyn_horgrid_type), pointer :: dg => null(), test_dg => null()
2332 type(dyn_horgrid_type), pointer :: dg_in => null()
2333 type(dyn_horgrid_type), pointer :: dg_unmasked_in => null()
2334 type(diag_ctrl), pointer :: diag => null()
2335 type(unit_scale_type), pointer :: us => null()
2336 type(mom_restart_cs), pointer :: restart_csp => null()
2337 character(len=4), parameter :: vers_num = 'v2.0'
2338 integer :: turns ! Number of grid quarter-turns
2339 logical :: point_calving
2340
2341 ! Initial state on the input index map
2342 real, allocatable :: u_in(:,:,:) ! Initial zonal velocities [L T-1 ~> m s-1]
2343 real, allocatable :: v_in(:,:,:) ! Initial meridional velocities [L T-1 ~> m s-1]
2344 real, allocatable :: h_in(:,:,:) ! Initial layer thicknesses [H ~> m or kg m-2]
2345 real, allocatable, target :: frac_shelf_in(:,:) ! Initial fraction of the total cell area occupied
2346 ! by an ice shelf [nondim]
2347 real, allocatable, target :: mass_shelf_in(:,:) ! Initial mass of ice shelf contained within a grid cell
2348 ! [R Z ~> kg m-2]
2349 real, allocatable, target :: t_in(:,:,:) ! Initial temperatures [C ~> degC]
2350 real, allocatable, target :: s_in(:,:,:) ! Initial salinities [S ~> ppt]
2351
2352 type(ocean_obc_type), pointer :: obc_in => null()
2353 type(sponge_cs), pointer :: sponge_in_csp => null()
2354 type(ale_sponge_cs), pointer :: ale_sponge_in_csp => null()
2355 type(oda_incupd_cs),pointer :: oda_incupd_in_csp => null()
2356 ! This include declares and sets the variable "version".
2357# include "version_variable.h"
2358
2359 integer :: i, j, k, m, is, ie, js, je, isd, ied, jsd, jed, nz
2360 integer :: isdb, iedb, jsdb, jedb
2361 real :: dtbt ! If negative, this specifies the barotropic timestep as a fraction
2362 ! of the maximum stable value [nondim].
2363
2364 real, allocatable, dimension(:,:) :: eta ! free surface height or column mass [H ~> m or kg m-2]
2365 real, allocatable, dimension(:,:,:) :: h_new ! Layer thicknesses after regridding [H ~> m or kg m-2]
2366 real, allocatable, dimension(:,:,:) :: dzregrid ! The change in grid interface positions due to regridding,
2367 ! in the same units as thicknesses [H ~> m or kg m-2]
2368 real, allocatable, dimension(:,:,:) :: h_old_u ! Source grid thickness at zonal velocity points [H ~> m or kg m-2]
2369 real, allocatable, dimension(:,:,:) :: h_old_v ! Source grid thickness at meridional velocity
2370 ! points [H ~> m or kg m-2]
2371 real, allocatable, dimension(:,:,:) :: h_new_u ! Destination grid thickness at zonal
2372 ! velocity points [H ~> m or kg m-2]
2373 real, allocatable, dimension(:,:,:) :: h_new_v ! Destination grid thickness at meridional
2374 ! velocity points [H ~> m or kg m-2]
2375 logical, allocatable, dimension(:,:,:) :: pcm_cell ! If true, PCM remapping should be used in a cell.
2376 type(group_pass_type) :: tmp_pass_uv_t_s_h, pass_uv_t_s_h
2377
2378 real :: hmix_z, hmix_uv_z ! Temporary variables with averaging depths [Z ~> m]
2379 real :: hfrz_z ! Temporary variable with the melt potential depth [Z ~> m]
2380 real :: default_val ! The default value for DTBT_RESET_PERIOD [s]
2381 logical :: write_geom_files ! If true, write out the grid geometry files.
2382 logical :: new_sim ! If true, this has been determined to be a new simulation
2383 logical :: use_geothermal ! If true, apply geothermal heating.
2384 logical :: use_eos ! If true, density calculated from T & S using an equation of state.
2385 logical :: symmetric ! If true, use symmetric memory allocation.
2386 logical :: save_ic ! If true, save the initial conditions.
2387 logical :: do_unit_tests ! If true, call unit tests.
2388 logical :: fpmix ! Needed to decide if BLD should be passed to RK2.
2389 logical :: test_grid_copy = .false.
2390
2391 logical :: bulkmixedlayer ! If true, a refined bulk mixed layer scheme is used
2392 ! with nkml sublayers and nkbl buffer layer.
2393 logical :: use_temperature ! If true, temperature and salinity used as state variables.
2394 logical :: use_p_surf_in_eos ! If true, always include the surface pressure contributions
2395 ! in equation of state calculations.
2396 logical :: use_frazil ! If true, liquid seawater freezes if temp below freezing,
2397 ! with accumulated heat deficit returned to surface ocean.
2398 logical :: bound_salinity ! If true, salt is added to keep salinity above
2399 ! a minimum value, and the deficit is reported.
2400 integer :: default_answer_date ! The default setting for the various ANSWER_DATE flags.
2401 logical :: use_cont_abss ! If true, the prognostics T & S are conservative temperature
2402 ! and absolute salinity. Care should be taken to convert them
2403 ! to potential temperature and practical salinity before
2404 ! exchanging them with the coupler and/or reporting T&S diagnostics.
2405 logical :: advect_ts ! If false, then no horizontal advection of temperature
2406 ! and salnity is performed
2407 logical :: use_ice_shelf ! Needed for ALE
2408 logical :: global_indexing ! If true use global horizontal index values instead
2409 ! of having the data domain on each processor start at 1.
2410 logical :: bathy_at_vel ! If true, also define bathymetric fields at the
2411 ! the velocity points.
2412 logical :: calc_dtbt ! Indicates whether the dynamically adjusted barotropic
2413 ! time step needs to be updated before it is used.
2414 logical :: debug_truncations ! If true, turn on diagnostics useful for debugging truncations.
2415 integer :: first_direction ! An integer that indicates which direction is to be
2416 ! updated first in directionally split parts of the
2417 ! calculation.
2418 logical :: enable_bugs ! If true, the defaults for certain recently added bug-fix flags are
2419 ! set to recreate the bugs so that the code can be moved forward
2420 ! without changing answers for existing configurations. When this is
2421 ! false, bugs are only used if they are actively selected.
2422 logical :: non_bous ! If true, this run is fully non-Boussinesq
2423 logical :: boussinesq ! If true, this run is fully Boussinesq
2424 logical :: semi_boussinesq ! If true, this run is partially non-Boussinesq
2425 logical :: use_kpp ! If true, diabatic is using KPP vertical mixing
2426 logical :: mle_use_pbl_mld ! If true, use stored boundary layer depths for submesoscale restratification.
2427 logical :: obc_reservoir_init_bug
2428 logical :: obc_bgc_time_ref_bug ! If true, use the start of the current run (not the overall
2429 ! start time) as the reference for OBC BGC tracer update schedule.
2430 integer :: nkml, nkbl, verbosity, write_geom, number_of_obc_segments
2431 integer :: dynamics_stencil ! The computational stencil for the calculations
2432 ! in the dynamic core.
2433 real :: salin_underflow ! A tiny value of salinity below which the it is set to 0 [S ~> ppt]
2434 real :: temp_underflow ! A tiny magnitude of temperatures below which they are set to 0 [C ~> degC]
2435 real :: conv2watt ! A conversion factor from temperature fluxes to heat
2436 ! fluxes [J m-2 H-1 C-1 ~> J m-3 degC-1 or J kg-1 degC-1]
2437 real :: conv2salt ! A conversion factor for salt fluxes [m H-1 ~> 1] or [kg m-2 H-1 ~> 1]
2438 character(len=48) :: s_flux_units
2439
2440 type(vardesc) :: vd_t, vd_s ! Structures describing temperature and salinity variables.
2441 type(time_type) :: start_time
2442 type(ocean_internal_state) :: mom_internal_state
2443 type(mom_domain_type), pointer :: mom_dom_unmasked => null() ! Unmasked MOM domain instance
2444 ! (To be used for writing out ocean geometry)
2445 character(len=240) :: geom_file ! Name of the ocean geometry file
2446
2447 cs%Time => time
2448
2449 id_clock_ocean = cpu_clock_id('Ocean', grain=clock_component)
2450 id_clock_init = cpu_clock_id('Ocean Initialization', grain=clock_subcomponent)
2451 call cpu_clock_begin(id_clock_ocean) ; call cpu_clock_begin(id_clock_init)
2452
2453 start_time = time ; if (present(time_in)) start_time = time_in
2454
2455 ! Read paths and filenames from namelist and store in "dirs".
2456 ! Also open the parsed input parameter file(s) and setup param_file.
2457 call get_mom_input(param_file, dirs, default_input_filename=input_restart_file, ensemble_num=ensemble_num)
2458
2459 verbosity = 2 ; call read_param(param_file, "VERBOSITY", verbosity)
2460 call mom_set_verbosity(verbosity, .true.)
2461 call calltree_enter("initialize_MOM(), MOM.F90")
2462
2463 call find_obsolete_params(param_file)
2464
2465 ! Determining the internal unit scaling factors for this run.
2466 call unit_scaling_init(param_file, cs%US)
2467 us => cs%US
2468
2469 ! Read relevant parameters and write them to the model log.
2470 call log_version(param_file, "MOM", version, "", log_to_all=.true., layout=.true., debugging=.true.)
2471 call get_param(param_file, "MOM", "VERBOSITY", verbosity, &
2472 "Integer controlling level of messaging\n" // &
2473 "\t0 = Only FATAL messages\n" // &
2474 "\t2 = Only FATAL, WARNING, NOTE [default]\n" // &
2475 "\t6 = Above plus call tree messages\n" //&
2476 "\t9 = All)", default=2, debuggingparam=.true.)
2477 call get_param(param_file, "MOM", "DO_UNIT_TESTS", do_unit_tests, &
2478 "If True, exercises unit tests at model start up.", &
2479 default=.false., debuggingparam=.true.)
2480 if (do_unit_tests) then
2481 id_clock_unit_tests = cpu_clock_id('(Ocean unit tests)', grain=clock_module)
2482 call cpu_clock_begin(id_clock_unit_tests)
2483 call unit_tests(verbosity)
2484 call cpu_clock_end(id_clock_unit_tests)
2485 endif
2486
2487 call get_param(param_file, "MOM", "SPLIT", cs%split, &
2488 "Use the split time stepping if true.", default=.true.)
2489 call get_param(param_file, "MOM", "SPLIT_RK2B", cs%use_alt_split, &
2490 "If true, use a version of the split explicit time stepping scheme that "//&
2491 "exchanges velocities with step_MOM that have the average barotropic phase over "//&
2492 "a baroclinic timestep rather than the instantaneous barotropic phase.", &
2493 default=.false., do_not_log=.not.cs%split)
2494 if (cs%split) then
2495 cs%use_RK2 = .false.
2496 else
2497 call get_param(param_file, "MOM", "USE_RK2", cs%use_RK2, &
2498 "If true, use RK2 instead of RK3 in the unsplit time stepping.", &
2499 default=.false.)
2500 endif
2501
2502 ! FPMIX is needed to decide if boundary layer depth should be passed to RK2
2503 call get_param(param_file, '', "FPMIX", fpmix, &
2504 "If true, add non-local momentum flux increments and diffuse down the Eulerian gradient.", &
2505 default=.false., do_not_log=.true.)
2506 if (fpmix .and. .not. cs%split) then
2507 call mom_error(fatal, "initialize_MOM: "//&
2508 "FPMIX=True only works when SPLIT=True.")
2509 endif
2510 call openparameterblock(param_file, 'KPP', do_not_log=.true.)
2511 call get_param(param_file, '', 'STOKES_MOST', cs%StokesMOST, &
2512 'If True, use Stokes Similarity package.', &
2513 default=.false., do_not_log=.true.)
2514 call closeparameterblock(param_file)
2515 call openparameterblock(param_file,'MLE', do_not_log=.true.)
2516 call get_param(param_file, '', "WAVE_ENHANCED_USTAR", cs%wave_enhanced_ustar, &
2517 "If true, enhance ustar in Bodner23.", default=.false., do_not_log=.true.)
2518 call closeparameterblock(param_file)
2519 call get_param(param_file, "MOM", "BOUSSINESQ", boussinesq, &
2520 "If true, make the Boussinesq approximation.", default=.true., do_not_log=.true.)
2521 call get_param(param_file, "MOM", "SEMI_BOUSSINESQ", semi_boussinesq, &
2522 "If true, do non-Boussinesq pressure force calculations and use mass-based "//&
2523 "thicknesses, but use RHO_0 to convert layer thicknesses into certain "//&
2524 "height changes. This only applies if BOUSSINESQ is false.", &
2525 default=.true., do_not_log=.true.)
2526 non_bous = .not.(boussinesq .or. semi_boussinesq)
2527 call get_param(param_file, "MOM", "CALC_RHO_FOR_SEA_LEVEL", cs%calc_rho_for_sea_lev, &
2528 "If true, the in-situ density is used to calculate the "//&
2529 "effective sea level that is returned to the coupler. If false, "//&
2530 "the Boussinesq parameter RHO_0 is used.", default=non_bous)
2531 call get_param(param_file, "MOM", "ENABLE_THERMODYNAMICS", use_temperature, &
2532 "If true, Temperature and salinity are used as state "//&
2533 "variables.", default=.true.)
2534 call get_param(param_file, "MOM", "USE_EOS", use_eos, &
2535 "If true, density is calculated from temperature and "//&
2536 "salinity with an equation of state. If USE_EOS is "//&
2537 "true, ENABLE_THERMODYNAMICS must be true as well.", &
2538 default=use_temperature)
2539 call get_param(param_file, "MOM", "DIABATIC_FIRST", cs%diabatic_first, &
2540 "If true, apply diabatic and thermodynamic processes, "//&
2541 "including buoyancy forcing and mass gain or loss, "//&
2542 "before stepping the dynamics forward.", default=.false.)
2543 call get_param(param_file, "MOM", "USE_CONTEMP_ABSSAL", use_cont_abss, &
2544 "If true, the prognostics T&S are the conservative temperature "//&
2545 "and absolute salinity. Care should be taken to convert them "//&
2546 "to potential temperature and practical salinity before "//&
2547 "exchanging them with the coupler and/or reporting T&S diagnostics.", &
2548 default=.false.)
2549 cs%tv%T_is_conT = use_cont_abss ; cs%tv%S_is_absS = use_cont_abss
2550 call get_param(param_file, "MOM", "ADIABATIC", cs%adiabatic, &
2551 "There are no diapycnal mass fluxes if ADIABATIC is true. "//&
2552 "This assumes that KD = 0.0 and that there is no buoyancy forcing, "//&
2553 "but makes the model faster by eliminating subroutine calls.", default=.false.)
2554 call get_param(param_file, "MOM", "DO_DYNAMICS", cs%do_dynamics, &
2555 "If False, skips the dynamics calls that update u & v, as well as "//&
2556 "the gravity wave adjustment to h. This may be a fragile feature, "//&
2557 "but can be useful during development", default=.true.)
2558 call get_param(param_file, "MOM", "ADVECT_TS", advect_ts, &
2559 "If True, advect temperature and salinity horizontally "//&
2560 "If False, T/S are registered for advection. "//&
2561 "This is intended only to be used in offline tracer mode "//&
2562 "and is by default false in that case.", &
2563 do_not_log=.true., default=.true.)
2564 if (present(offline_tracer_mode)) then ! Only read this parameter in enabled modes
2565 call get_param(param_file, "MOM", "OFFLINE_TRACER_MODE", cs%offline_tracer_mode, &
2566 "If true, barotropic and baroclinic dynamics, thermodynamics "//&
2567 "are all bypassed with all the fields necessary to integrate "//&
2568 "the tracer advection and diffusion equation are read in from "//&
2569 "files stored from a previous integration of the prognostic model. "//&
2570 "NOTE: This option only used in the ocean_solo_driver.", default=.false.)
2571 if (cs%offline_tracer_mode) then
2572 call get_param(param_file, "MOM", "ADVECT_TS", advect_ts, &
2573 "If True, advect temperature and salinity horizontally "//&
2574 "If False, T/S are registered for advection. "//&
2575 "This is intended only to be used in offline tracer mode, "//&
2576 "and is by default false in that case", &
2577 default=.false. )
2578 endif
2579 endif
2580 call get_param(param_file, "MOM", "USE_REGRIDDING", cs%use_ALE_algorithm, &
2581 "If True, use the ALE algorithm (regridding/remapping). "//&
2582 "If False, use the layered isopycnal algorithm.", default=.false. )
2583 call get_param(param_file, "MOM", "REMAP_UV_USING_OLD_ALG", cs%remap_uv_using_old_alg, &
2584 "If true, uses the old remapping-via-a-delta-z method for "//&
2585 "remapping u and v. If false, uses the new method that remaps "//&
2586 "between grids described by an old and new thickness.", &
2587 default=.false., do_not_log=.not.cs%use_ALE_algorithm)
2588 call get_param(param_file, "MOM", "REMAP_AUXILIARY_VARS", cs%remap_aux_vars, &
2589 "If true, apply ALE remapping to all of the auxiliary 3-dimensional "//&
2590 "variables that are needed to reproduce across restarts, similarly to "//&
2591 "what is already being done with the primary state variables. "//&
2592 "The default should be changed to true.", default=.false., &
2593 do_not_log=.not.cs%use_ALE_algorithm)
2594 call get_param(param_file, "MOM", "BULKMIXEDLAYER", bulkmixedlayer, &
2595 "If true, use a Kraus-Turner-like bulk mixed layer "//&
2596 "with transitional buffer layers. Layers 1 through "//&
2597 "NKML+NKBL have variable densities. There must be at "//&
2598 "least NKML+NKBL+1 layers if BULKMIXEDLAYER is true. "//&
2599 "BULKMIXEDLAYER can not be used with USE_REGRIDDING. "//&
2600 "The default is influenced by ENABLE_THERMODYNAMICS.", &
2601 default=use_temperature .and. .not.cs%use_ALE_algorithm)
2602 call get_param(param_file, "MOM", "USE_POROUS_BARRIER", cs%use_porbar, &
2603 "If true, use porous barrier to constrain the widths "//&
2604 "and face areas at the edges of the grid cells. ", &
2605 default=.false.)
2606 call get_param(param_file, "MOM", "BATHYMETRY_AT_VEL", bathy_at_vel, &
2607 "If true, there are separate values for the basin depths "//&
2608 "at velocity points. Otherwise the effects of topography "//&
2609 "are entirely determined from thickness points.", &
2610 default=.false.)
2611 call get_param(param_file, "MOM", "USE_WAVES", cs%UseWaves, default=.false., &
2612 do_not_log=.true.)
2613
2614 call get_param(param_file, "MOM", "DEBUG", cs%debug, &
2615 "If true, write out verbose debugging data.", &
2616 default=.false., debuggingparam=.true.)
2617 call get_param(param_file, "MOM", "DEBUG_TRUNCATIONS", debug_truncations, &
2618 "If true, calculate all diagnostics that are useful for "//&
2619 "debugging truncations.", default=.false., debuggingparam=.true.)
2620 call get_param(param_file, "MOM", "OBC_NUMBER_OF_SEGMENTS", number_of_obc_segments, &
2621 default=0, do_not_log=.true.)
2622 call get_param(param_file, "MOM", "DEBUG_OBCS", cs%debug_OBCs, &
2623 "If true, write out verbose debugging data about OBCs.", &
2624 default=.false., debuggingparam=.true., do_not_log=(number_of_obc_segments<=0))
2625 call get_param(param_file, "MOM", "ENABLE_BUGS_BY_DEFAULT", enable_bugs, &
2626 "If true, the defaults for certain recently added bug-fix flags are set to "//&
2627 "recreate the bugs so that the code can be moved forward without changing "//&
2628 "answers for existing configurations. The defaults for groups of bug-fix "//&
2629 "flags are periodically changed to correct the bugs, at which point this "//&
2630 "parameter will no longer be used to set their default. Setting this to false "//&
2631 "means that bugs are only used if they are actively selected, but it also "//&
2632 "means that answers may change when code is updated due to newly found bugs.", &
2633 default=.true.)
2634
2635 call get_param(param_file, "MOM", "DT", cs%dt, &
2636 "The (baroclinic) dynamics time step. The time-step that "//&
2637 "is actually used will be an integer fraction of the "//&
2638 "forcing time-step (DT_FORCING in ocean-only mode or the "//&
2639 "coupling timestep in coupled mode.)", units="s", scale=us%s_to_T, &
2640 fail_if_missing=.true.)
2641 call get_param(param_file, "MOM", "DT_THERM", cs%dt_therm, &
2642 "The thermodynamic time step. Ideally DT_THERM should be an "//&
2643 "integer multiple of DT and of DT_TRACER_ADVECT "//&
2644 "and less than the forcing or coupling time-step. However, if "//&
2645 "THERMO_SPANS_COUPLING is true, DT_THERM can be an integer multiple "//&
2646 "of the coupling timestep. By default DT_THERM is set to DT.", &
2647 units="s", scale=us%s_to_T, default=us%T_to_s*cs%dt)
2648 call get_param(param_file, "MOM", "THERMO_SPANS_COUPLING", cs%thermo_spans_coupling, &
2649 "If true, the MOM will take thermodynamic "//&
2650 "timesteps that can be longer than the coupling timestep. "//&
2651 "The actual thermodynamic timestep that is used in this "//&
2652 "case is the largest integer multiple of the coupling "//&
2653 "timestep that is less than or equal to DT_THERM.", default=.false.)
2654 call get_param(param_file, "MOM", "DT_TRACER_ADVECT", cs%dt_tr_adv, &
2655 "The tracer advection time step. Ideally DT_TRACER_ADVECT should be an "//&
2656 "integer multiple of DT, less than DT_THERM, and less than the forcing "//&
2657 "or coupling time-step. However, if TRADV_SPANS_COUPLING is true, "//&
2658 "DT_TRACER_ADVECT can be longer than the coupling timestep. By "//&
2659 "default DT_TRACER_ADVECT is set to DT_THERM.", &
2660 units="s", scale=us%s_to_T, default=us%T_to_s*cs%dt_therm)
2661 call get_param(param_file, "MOM", "TRADV_SPANS_COUPLING", cs%tradv_spans_coupling, &
2662 "If true, the MOM will take tracer advection "//&
2663 "timesteps that can be longer than the coupling timestep. "//&
2664 "The actual tracer advection timestep that is used in this "//&
2665 "case is the largest integer multiple of the coupling "//&
2666 "timestep that is less than or equal to DT_TRACER_ADVECT.", &
2667 default=cs%thermo_spans_coupling)
2668 if ( cs%diabatic_first .and. (cs%dt_tr_adv /= cs%dt_therm) ) then
2669 call mom_error(fatal,"MOM: If using DIABATIC_FIRST, DT_TRACER_ADVECT must equal DT_THERM.")
2670 endif
2671 call get_param(param_file, "MOM", "THICKNESSDIFFUSE", cs%thickness_diffuse, &
2672 "If true, isopycnal surfaces are diffused with a Laplacian "//&
2673 "coefficient of KHTH.", default=.false.)
2674 call get_param(param_file, "MOM", "APPLY_INTERFACE_FILTER", cs%interface_filter, &
2675 "If true, model interface heights are subjected to a grid-scale "//&
2676 "dependent spatial smoothing, often with biharmonic filter.", default=.false.)
2677 call get_param(param_file, "MOM", "THICKNESSDIFFUSE_FIRST", cs%thickness_diffuse_first, &
2678 "If true, do thickness diffusion or interface height smoothing before dynamics. "//&
2679 "This is only used if THICKNESSDIFFUSE or APPLY_INTERFACE_FILTER is true.", &
2680 default=.false., do_not_log=.not.(cs%thickness_diffuse.or.cs%interface_filter))
2681 cs%interface_filter_dt_bug = .false.
2682 if ((.not.cs%thickness_diffuse_first .and. cs%interface_filter) .or. &
2683 (cs%thickness_diffuse_first .and. (cs%thickness_diffuse .or. cs%interface_filter) &
2684 .and. (cs%dt_tr_adv /= cs%dt_therm))) then
2685 call get_param(param_file, "MOM", "INTERFACE_FILTER_DT_BUG", cs%interface_filter_dt_bug, &
2686 "If true, uses the wrong time interval in calls to interface_filter "//&
2687 "and thickness_diffuse. Has no effect when THICKNESSDIFFUSE_FIRST is "//&
2688 "true and DT_TRACER_ADVECT = DT_THERMO or when THICKNESSDIFFUSE_FIRST "//&
2689 "is false and APPLY_INTERFACE_FILTER is false. ", default=.false.)
2690 endif
2691
2692 if (bulkmixedlayer) then
2693 cs%Hmix = -1.0 ; cs%Hmix_UV = -1.0
2694 else
2695 call get_param(param_file, "MOM", "HMIX_SFC_PROP", hmix_z, &
2696 "If BULKMIXEDLAYER is false, HMIX_SFC_PROP is the depth "//&
2697 "over which to average to find surface properties like "//&
2698 "SST and SSS or density (but not surface velocities).", &
2699 units="m", default=1.0, scale=us%m_to_Z)
2700 call get_param(param_file, "MOM", "HMIX_UV_SFC_PROP", hmix_uv_z, &
2701 "If BULKMIXEDLAYER is false, HMIX_UV_SFC_PROP is the depth "//&
2702 "over which to average to find surface flow properties, "//&
2703 "SSU, SSV. A non-positive value indicates no averaging.", &
2704 units="m", default=0.0, scale=us%m_to_Z)
2705 endif
2706 call get_param(param_file, "MOM", "HFREEZE", hfrz_z, &
2707 "If HFREEZE > 0, melt potential will be computed. The actual depth "//&
2708 "over which melt potential is computed will be min(HFREEZE, OBLD), "//&
2709 "where OBLD is the boundary layer depth. If HFREEZE <= 0 (default), "//&
2710 "melt potential will not be computed.", &
2711 units="m", default=-1.0, scale=us%m_to_Z)
2712 call get_param(param_file, "MOM", "INTERPOLATE_P_SURF", cs%interp_p_surf, &
2713 "If true, linearly interpolate the surface pressure "//&
2714 "over the coupling time step, using the specified value "//&
2715 "at the end of the step.", default=.false.)
2716
2717 if (cs%split) then
2718 call get_param(param_file, "MOM", "DTBT", dtbt, units="s or nondim", default=-0.98)
2719 default_val = us%T_to_s*cs%dt_therm ; if (dtbt > 0.0) default_val = -1.0
2720 cs%dtbt_reset_period = -1.0
2721 call get_param(param_file, "MOM", "DTBT_RESET_PERIOD", cs%dtbt_reset_period, &
2722 "The period between recalculations of DTBT (if DTBT <= 0). If "//&
2723 "DTBT_RESET_PERIOD is negative, DTBT is set based only on information "//&
2724 "available at initialization. If 0, DTBT will be set every dynamics time "//&
2725 "step. Values between 0 and DT are treated as 0. The default is set by "//&
2726 "DT_THERM. This is only used if SPLIT is true.", &
2727 units="s", default=default_val, scale=us%s_to_T, do_not_read=(dtbt > 0.0))
2728 endif
2729
2730 ! This is here in case these values are used inappropriately.
2731 use_frazil = .false. ; bound_salinity = .false. ; use_p_surf_in_eos = .false.
2732 cs%tv%P_Ref = 2.0e7*us%Pa_to_RL2_T2
2733 if (use_temperature) then
2734 call get_param(param_file, "MOM", "FRAZIL", use_frazil, &
2735 "If true, water freezes if it gets too cold, and the "//&
2736 "accumulated heat deficit is returned in the "//&
2737 "surface state. FRAZIL is only used if "//&
2738 "ENABLE_THERMODYNAMICS is true.", default=.false.)
2739 call get_param(param_file, "MOM", "DO_GEOTHERMAL", use_geothermal, &
2740 "If true, apply geothermal heating.", default=.false.)
2741 call get_param(param_file, "MOM", "BOUND_SALINITY", bound_salinity, &
2742 "If true, limit salinity to being positive. (The sea-ice "//&
2743 "model may ask for more salt than is available and "//&
2744 "drive the salinity negative otherwise.)", default=.false.)
2745 call get_param(param_file, "MOM", "MIN_SALINITY", cs%tv%min_salinity, &
2746 "The minimum value of salinity when BOUND_SALINITY=True.", &
2747 units="PPT", default=0.0, scale=us%ppt_to_S, do_not_log=.not.bound_salinity)
2748 call get_param(param_file, "MOM", "SALINITY_UNDERFLOW", salin_underflow, &
2749 "A tiny value of salinity below which the it is set to 0. For reference, "//&
2750 "one molecule of salt per square meter of ocean is of order 1e-29 ppt.", &
2751 units="PPT", default=0.0, scale=us%ppt_to_S)
2752 call get_param(param_file, "MOM", "TEMPERATURE_UNDERFLOW", temp_underflow, &
2753 "A tiny magnitude of temperatures below which they are set to 0.", &
2754 units="degC", default=0.0, scale=us%degC_to_C)
2755 call get_param(param_file, "MOM", "C_P", cs%tv%C_p, &
2756 "The heat capacity of sea water, approximated as a constant. "//&
2757 "This is only used if ENABLE_THERMODYNAMICS is true. The default "//&
2758 "value is from the TEOS-10 definition of conservative temperature.", &
2759 units="J kg-1 K-1", default=3991.86795711963, scale=us%J_kg_to_Q*us%C_to_degC)
2760 call get_param(param_file, "MOM", "USE_PSURF_IN_EOS", use_p_surf_in_eos, &
2761 "If true, always include the surface pressure contributions "//&
2762 "in equation of state calculations.", default=.true.)
2763 endif
2764 if (use_eos) call get_param(param_file, "MOM", "P_REF", cs%tv%P_Ref, &
2765 "The pressure that is used for calculating the coordinate "//&
2766 "density. (1 Pa = 1e4 dbar, so 2e7 is commonly used.) "//&
2767 "This is only used if USE_EOS and ENABLE_THERMODYNAMICS are true.", &
2768 units="Pa", default=2.0e7, scale=us%Pa_to_RL2_T2)
2769
2770 if (bulkmixedlayer) then
2771 call get_param(param_file, "MOM", "NKML", nkml, &
2772 "The number of sublayers within the mixed layer if "//&
2773 "BULKMIXEDLAYER is true.", units="nondim", default=2)
2774 call get_param(param_file, "MOM", "NKBL", nkbl, &
2775 "The number of layers that are used as variable density buffer "//&
2776 "layers if BULKMIXEDLAYER is true.", units="nondim", default=2)
2777 endif
2778
2779 call get_param(param_file, "MOM", "GLOBAL_INDEXING", global_indexing, &
2780 "If true, use a global lateral indexing convention, so "//&
2781 "that corresponding points on different processors have "//&
2782 "the same index. This does not work with static memory.", &
2783 default=.false., layoutparam=.true.)
2784#ifdef STATIC_MEMORY_
2785 if (global_indexing) call mom_error(fatal, "initialize_MOM: "//&
2786 "GLOBAL_INDEXING can not be true with STATIC_MEMORY.")
2787#endif
2788 call get_param(param_file, "MOM", "FIRST_DIRECTION", first_direction, &
2789 "An integer that indicates which direction goes first "//&
2790 "in parts of the code that use directionally split "//&
2791 "updates, with even numbers (or 0) used for x- first "//&
2792 "and odd numbers used for y-first.", default=0)
2793 call get_param(param_file, "MOM", "ALTERNATE_FIRST_DIRECTION", cs%alternate_first_direction, &
2794 "If true, after every dynamic timestep alternate whether the x- or y- "//&
2795 "direction updates occur first in directionally split parts of the calculation. "//&
2796 "If this is true, FIRST_DIRECTION applies at the start of a new run or if "//&
2797 "the next first direction can not be found in the restart file.", default=.false.)
2798 call get_param(param_file, "MOM", "CHECK_BAD_SURFACE_VALS", cs%check_bad_sfc_vals, &
2799 "If true, check the surface state for ridiculous values.", &
2800 default=.false.)
2801 if (cs%check_bad_sfc_vals) then
2802 call get_param(param_file, "MOM", "BAD_VAL_SSH_MAX", cs%bad_val_ssh_max, &
2803 "The value of SSH above which a bad value message is "//&
2804 "triggered, if CHECK_BAD_SURFACE_VALS is true.", &
2805 units="m", default=20.0, scale=us%m_to_Z)
2806 call get_param(param_file, "MOM", "BAD_VAL_SSS_MAX", cs%bad_val_sss_max, &
2807 "The value of SSS above which a bad value message is "//&
2808 "triggered, if CHECK_BAD_SURFACE_VALS is true.", &
2809 units="PPT", default=45.0, scale=us%ppt_to_S)
2810 call get_param(param_file, "MOM", "BAD_VAL_SST_MAX", cs%bad_val_sst_max, &
2811 "The value of SST above which a bad value message is "//&
2812 "triggered, if CHECK_BAD_SURFACE_VALS is true.", &
2813 units="deg C", default=45.0, scale=us%degC_to_C)
2814 call get_param(param_file, "MOM", "BAD_VAL_SST_MIN", cs%bad_val_sst_min, &
2815 "The value of SST below which a bad value message is "//&
2816 "triggered, if CHECK_BAD_SURFACE_VALS is true.", &
2817 units="deg C", default=-2.1, scale=us%degC_to_C)
2818 call get_param(param_file, "MOM", "BAD_VAL_COLUMN_THICKNESS", cs%bad_val_col_thick, &
2819 "The value of column thickness below which a bad value message is "//&
2820 "triggered, if CHECK_BAD_SURFACE_VALS is true.", &
2821 units="m", default=0.0, scale=us%m_to_Z)
2822 endif
2823 call get_param(param_file, "MOM", "DEFAULT_ANSWER_DATE", default_answer_date, &
2824 "This sets the default value for the various _ANSWER_DATE parameters.", &
2825 default=99991231)
2826 call get_param(param_file, "MOM", "SURFACE_ANSWER_DATE", cs%answer_date, &
2827 "The vintage of the expressions for the surface properties. Values below "//&
2828 "20190101 recover the answers from the end of 2018, while higher values "//&
2829 "use updated and more robust forms of the same expressions.", &
2830 default=default_answer_date, do_not_log=non_bous)
2831 if (non_bous) cs%answer_date = 99991231
2832
2833 call get_param(param_file, "MOM", "SAVE_INITIAL_CONDS", save_ic, &
2834 "If true, write the initial conditions to a file given "//&
2835 "by IC_OUTPUT_FILE.", default=.false.)
2836 call get_param(param_file, "MOM", "IC_OUTPUT_FILE", cs%IC_file, &
2837 "The file into which to write the initial conditions.", &
2838 default="MOM_IC")
2839 call get_param(param_file, "MOM", "WRITE_GEOM", write_geom, &
2840 "If =0, never write the geometry and vertical grid files. "//&
2841 "If =1, write the geometry and vertical grid files only for "//&
2842 "a new simulation. If =2, always write the geometry and "//&
2843 "vertical grid files. Other values are invalid.", default=1)
2844 if (write_geom<0 .or. write_geom>2) call mom_error(fatal,"MOM: "//&
2845 "WRITE_GEOM must be equal to 0, 1 or 2.")
2846 call get_param(param_file, "MOM", "GEOM_FILE", geom_file, &
2847 "The file into which to write the ocean geometry.", &
2848 default="ocean_geometry")
2849 call get_param(param_file, "MOM", "USE_DBCLIENT", cs%use_dbclient, &
2850 "If true, initialize a client to a remote database that can "//&
2851 "be used for online analysis and machine-learning inference.",&
2852 default=.false.)
2853
2854 ! Check for inconsistent parameter settings.
2855 if (cs%use_ALE_algorithm .and. bulkmixedlayer) call mom_error(fatal, &
2856 "MOM: BULKMIXEDLAYER can not currently be used with the ALE algorithm.")
2857 if (cs%use_ALE_algorithm .and. .not.use_temperature) call mom_error(fatal, &
2858 "MOM: At this time, USE_EOS should be True when using the ALE algorithm.")
2859 if (cs%adiabatic .and. use_temperature) call mom_error(warning, &
2860 "MOM: ADIABATIC and ENABLE_THERMODYNAMICS both defined is usually unwise.")
2861 if (use_eos .and. .not.use_temperature) call mom_error(fatal, &
2862 "MOM: ENABLE_THERMODYNAMICS must be defined to use USE_EOS.")
2863 if (cs%adiabatic .and. bulkmixedlayer) call mom_error(fatal, &
2864 "MOM: ADIABATIC and BULKMIXEDLAYER can not both be defined.")
2865 if (bulkmixedlayer .and. .not.use_eos) call mom_error(fatal, &
2866 "initialize_MOM: A bulk mixed layer can only be used with T & S as "//&
2867 "state variables. Add USE_EOS = True to MOM_input.")
2868
2869 use_ice_shelf = .false.
2870 if (present(ice_shelf_csp)) then
2871 call get_param(param_file, "MOM", "ICE_SHELF", use_ice_shelf, &
2872 "If true, enables the ice shelf model.", default=.false.)
2873 endif
2874
2875 call get_param(param_file, "MOM", "USE_PARTICLES", cs%use_particles, &
2876 "If true, use the particles package.", default=.false.)
2877 call get_param(param_file, "MOM", "USE_UH_PARTICLES", cs%use_uh_particles, &
2878 "If true, use the uh velocity in the particles package.", &
2879 default=.false., do_not_log=.not.cs%use_particles)
2880 call get_param(param_file, "MOM", "UH_PARTICLES_BUG", cs%uh_particles_bug, &
2881 "If true, use a bug in which the particles are advected inconsistently"//&
2882 "with the dynamics timestep instead of the tracer timestep.", &
2883 default=enable_bugs, do_not_log=.not.cs%use_uh_particles)
2884 cs%ensemble_ocean=.false.
2885 call get_param(param_file, "MOM", "ENSEMBLE_OCEAN", cs%ensemble_ocean, &
2886 "If False, The model is being run in serial mode as a single realization. "//&
2887 "If True, The current model realization is part of a larger ensemble "//&
2888 "and at the end of step MOM, we will perform a gather of the ensemble "//&
2889 "members for statistical evaluation and/or data assimilation.", default=.false.)
2890
2891 call calltree_waypoint("MOM parameters read (initialize_MOM)")
2892
2893 call get_param(param_file, "MOM", "HOMOGENIZE_FORCINGS", cs%homogenize_forcings, &
2894 "If True, homogenize the forces and fluxes.", default=.false.)
2895 call get_param(param_file, "MOM", "UPDATE_USTAR",cs%update_ustar, &
2896 "If True, update ustar from homogenized tau when using the "//&
2897 "HOMOGENIZE_FORCINGS option. Note that this will not work "//&
2898 "with a non-zero gustiness factor.", default=.false., &
2899 do_not_log=.not.cs%homogenize_forcings)
2900
2901 ! Grid rotation test
2902 call get_param(param_file, "MOM", "ROTATE_INDEX", cs%rotate_index, &
2903 "Enable rotation of the horizontal indices.", default=.false., &
2904 debuggingparam=.true.)
2905 if (cs%rotate_index) then
2906 ! TODO: Index rotation currently only works when index rotation does not
2907 ! change the MPI rank of each domain. Resolving this will require a
2908 ! modification to FMS PE assignment.
2909 ! For now, we only permit single-core runs.
2910
2911 if (num_pes() /= 1) &
2912 call mom_error(fatal, "Index rotation is only supported on one PE.")
2913
2914 ! Alternate_first_direction is not permitted with index rotation.
2915 ! This feature can be added later in the future if needed.
2916 if (cs%alternate_first_direction) &
2917 call mom_error(fatal, "Alternating_first_direction is not compatible with index rotation.")
2918
2919 call get_param(param_file, "MOM", "INDEX_TURNS", turns, &
2920 "Number of counterclockwise quarter-turn index rotations.", &
2921 default=1, debuggingparam=.true.)
2922 else
2923 turns = 0
2924 endif
2925
2926 ! Set up the model domain and grids.
2927#ifdef SYMMETRIC_MEMORY_
2928 symmetric = .true.
2929#else
2930 symmetric = .false.
2931#endif
2932 g_in => cs%G_in
2933#ifdef STATIC_MEMORY_
2934 call mom_domains_init(g_in%domain, param_file, symmetric=symmetric, &
2935 static_memory=.true., nihalo=nihalo_, njhalo=njhalo_, &
2936 niglobal=niglobal_, njglobal=njglobal_, niproc=niproc_, &
2937 njproc=njproc_, us=us, mom_dom_unmasked=mom_dom_unmasked)
2938#else
2939 call mom_domains_init(g_in%domain, param_file, symmetric=symmetric, &
2940 domain_name="MOM_in", us=us, mom_dom_unmasked=mom_dom_unmasked)
2941#endif
2942
2943 ! Copy input grid (G_in) domain to active grid G
2944 ! Swap axes for quarter and 3-quarter turns
2945 if (cs%rotate_index) then
2946 allocate(cs%G)
2947 call clone_mom_domain(g_in%Domain, cs%G%Domain, turns=turns, domain_name="MOM_rot")
2948 else
2949 cs%G => g_in
2950 endif
2951
2952 ! TODO: It is unlikely that test_grid_copy and rotate_index would work at the
2953 ! same time. It may be possible to enable both but for now we prevent it.
2954 if (test_grid_copy .and. cs%rotate_index) &
2955 call mom_error(fatal, "Grid cannot be copied during index rotation.")
2956
2957 if (test_grid_copy) then ; allocate(g)
2958 else ; g => cs%G ; endif
2959
2960 call calltree_waypoint("domains initialized (initialize_MOM)")
2961
2962 call mom_debugging_init(param_file)
2963 call diag_mediator_infrastructure_init()
2964 call mom_io_init(param_file)
2965
2966 ! Create HI and dG on the input index map.
2967 call hor_index_init(g_in%Domain, hi_in, param_file, &
2968 local_indexing=.not.global_indexing)
2969 call create_dyn_horgrid(dg_in, hi_in, bathymetry_at_vel=bathy_at_vel)
2970 call clone_mom_domain(g_in%Domain, dg_in%Domain)
2971 ! Also allocate the input ocean_grid_type type at this point based on the same information.
2972 call mom_grid_init(g_in, param_file, us, hi_in, bathymetry_at_vel=bathy_at_vel)
2973
2974 ! Allocate initialize time-invariant MOM variables.
2975 call mom_initialize_fixed(dg_in, us, obc_in, param_file)
2976
2977 call get_param(param_file, "MOM", "DT_OBC_SEG_UPDATE_OBGC", cs%dt_obc_seg_period, &
2978 "The time between OBC segment data updates for OBGC tracers. This must be an "//&
2979 "integer multiple of DT and DT_THERM. The default is set to DT.", units="s", &
2980 default=us%T_to_s*cs%dt, scale=us%s_to_T, do_not_log=.not.associated(obc_in))
2981 call get_param(param_file, "MOM", "OBC_BGC_TIME_REF_BUG", obc_bgc_time_ref_bug, &
2982 "If true, recover a bug that the BGC OBC segment update schedule is "//&
2983 "referenced to the start of the current run rather than the overall start "//&
2984 "time, which can lead to restart reproducibility failures.", &
2985 default=enable_bugs, do_not_log=.not.associated(obc_in))
2986
2987 ! Copy the grid metrics and bathymetry to the ocean_grid_type
2988 call copy_dyngrid_to_mom_grid(dg_in, g_in, us)
2989
2990 call calltree_waypoint("returned from MOM_initialize_fixed() (initialize_MOM)")
2991
2992 call verticalgridinit( param_file, cs%GV, us )
2993 gv => cs%GV
2994
2995 ! Now that the vertical grid has been initialized, rescale parameters that depend on factors
2996 ! that are set with the vertical grid to their desired units. This added rescaling step would
2997 ! be unnecessary if the vertical grid were initialized earlier in this routine.
2998 if (.not.bulkmixedlayer) then
2999 cs%Hmix = (us%Z_to_m * gv%m_to_H) * hmix_z
3000 cs%Hmix_UV = (us%Z_to_m * gv%m_to_H) * hmix_uv_z
3001 endif
3002 cs%HFrz = (us%Z_to_m * gv%m_to_H) * hfrz_z
3003
3004 ! Shift from using the temporary dynamic grid type to using the final (potentially static)
3005 ! and properly rotated ocean-specific grid type and horizontal index type.
3006 if (cs%rotate_index) then
3007 allocate(hi)
3008 call rotate_hor_index(hi_in, turns, hi)
3009 ! NOTE: If indices are rotated, then G and G_in must both be initialized separately, and
3010 ! the dynamic grid must be created to handle the grid rotation. G%domain has already been
3011 ! initialized above.
3012 call mom_grid_init(g, param_file, us, hi, bathymetry_at_vel=bathy_at_vel)
3013 call create_dyn_horgrid(dg, hi, bathymetry_at_vel=bathy_at_vel)
3014 call clone_mom_domain(g%Domain, dg%Domain)
3015 call rotate_dyn_horgrid(dg_in, dg, us, turns)
3016 call copy_dyngrid_to_mom_grid(dg, g, us)
3017
3018 if (associated(obc_in)) then
3019 allocate(cs%OBC)
3020 call rotate_obc_config(obc_in, dg_in, cs%OBC, dg, turns)
3021 endif
3022
3023 call destroy_dyn_horgrid(dg)
3024 else
3025 ! If not rotated, then G_in and G are the same grid.
3026 hi => hi_in
3027 g => g_in
3028 cs%OBC => obc_in
3029 endif
3030 ! dG_in is retained for now so that it can be used with write_ocean_geometry_file() below.
3031
3032 if (is_root_pe()) call check_mom6_scaling_factors(cs%GV, us)
3033
3034 call calltree_waypoint("grids initialized (initialize_MOM)")
3035
3036 call mom_timing_init(cs)
3037
3038 call tracer_registry_init(param_file, cs%tracer_Reg)
3039
3040 ! Allocate and initialize space for the primary time-varying MOM variables.
3041 is = hi%isc ; ie = hi%iec ; js = hi%jsc ; je = hi%jec ; nz = gv%ke
3042 isd = hi%isd ; ied = hi%ied ; jsd = hi%jsd ; jed = hi%jed
3043 isdb = hi%IsdB ; iedb = hi%IedB ; jsdb = hi%JsdB ; jedb = hi%JedB
3044 alloc_(cs%u(isdb:iedb,jsd:jed,nz)) ; cs%u(:,:,:) = 0.0
3045 alloc_(cs%v(isd:ied,jsdb:jedb,nz)) ; cs%v(:,:,:) = 0.0
3046 alloc_(cs%h(isd:ied,jsd:jed,nz)) ; cs%h(:,:,:) = gv%Angstrom_H
3047 alloc_(cs%uh(isdb:iedb,jsd:jed,nz)) ; cs%uh(:,:,:) = 0.0
3048 alloc_(cs%vh(isd:ied,jsdb:jedb,nz)) ; cs%vh(:,:,:) = 0.0
3049 if (use_temperature) then
3050 alloc_(cs%T(isd:ied,jsd:jed,nz)) ; cs%T(:,:,:) = 0.0
3051 alloc_(cs%S(isd:ied,jsd:jed,nz)) ; cs%S(:,:,:) = 0.0
3052 cs%tv%T => cs%T ; cs%tv%S => cs%S
3053 if (cs%tv%T_is_conT) then
3054 vd_t = var_desc(name="contemp", units="Celsius", longname="Conservative Temperature", &
3055 cmor_field_name="bigthetao", cmor_longname="Sea Water Conservative Temperature", &
3056 conversion=us%C_to_degC)
3057 else
3058 vd_t = var_desc(name="temp", units="degC", longname="Potential Temperature", &
3059 cmor_field_name="thetao", cmor_longname="Sea Water Potential Temperature", &
3060 conversion=us%C_to_degC)
3061 endif
3062 if (cs%tv%S_is_absS) then
3063 vd_s = var_desc(name="abssalt", units="g kg-1", longname="Absolute Salinity", &
3064 cmor_field_name="absso", cmor_longname="Sea Water Absolute Salinity", &
3065 conversion=us%S_to_ppt)
3066 else
3067 vd_s = var_desc(name="salt", units="psu", longname="Salinity", &
3068 cmor_field_name="so", cmor_longname="Sea Water Salinity", &
3069 conversion=us%S_to_ppt)
3070 endif
3071
3072 if (advect_ts) then
3073 s_flux_units = get_tr_flux_units(gv, "psu") ! Could change to "kg m-2 s-1"?
3074 conv2watt = gv%H_to_kg_m2 * us%Q_to_J_kg*cs%tv%C_p
3075 if (gv%Boussinesq) then
3076 conv2salt = us%S_to_ppt*gv%H_to_m ! Could change to US%S_to_ppt*GV%H_to_kg_m2 * 0.001?
3077 else
3078 conv2salt = us%S_to_ppt*gv%H_to_kg_m2
3079 endif
3080 call register_tracer(cs%tv%T, cs%tracer_Reg, param_file, hi, gv, &
3081 tr_desc=vd_t, registry_diags=.true., conc_scale=us%C_to_degC, &
3082 flux_nameroot='T', flux_units='W', flux_longname='Heat', &
3083 net_surfflux_name='KPP_QminusSW', nlt_budget_name='KPP_NLT_temp_budget', &
3084 net_surfflux_longname='Net temperature flux ignoring short-wave, as used by [CVMix] KPP', &
3085 flux_scale=conv2watt, convergence_units='W m-2', &
3086 convergence_scale=conv2watt, cmor_tendprefix="opottemp", &
3087 diag_form=2, underflow_conc=temp_underflow, tr_out=cs%tv%tr_T)
3088 call register_tracer(cs%tv%S, cs%tracer_Reg, param_file, hi, gv, &
3089 tr_desc=vd_s, registry_diags=.true., conc_scale=us%S_to_ppt, &
3090 flux_nameroot='S', flux_units=s_flux_units, flux_longname='Salt', &
3091 net_surfflux_name='KPP_netSalt', nlt_budget_name='KPP_NLT_saln_budget', &
3092 flux_scale=conv2salt, convergence_units='kg m-2 s-1', &
3093 convergence_scale=0.001*us%S_to_ppt*gv%H_to_kg_m2, cmor_tendprefix="osalt", &
3094 diag_form=2, underflow_conc=salin_underflow, tr_out=cs%tv%tr_S)
3095 endif
3096 endif
3097
3098 if (use_p_surf_in_eos) allocate(cs%tv%p_surf(isd:ied,jsd:jed), source=0.0)
3099 if (use_frazil) then
3100 allocate(cs%tv%frazil(isd:ied,jsd:jed), source=0.0)
3101 cs%tv%frazil_was_reset = .true.
3102 endif
3103 if (bound_salinity) allocate(cs%tv%salt_deficit(isd:ied,jsd:jed), source=0.0)
3104
3105 allocate(cs%Hml(isd:ied,jsd:jed), source=0.0)
3106
3107 if (bulkmixedlayer) then
3108 gv%nkml = nkml ; gv%nk_rho_varies = nkml + nkbl
3109 else
3110 gv%nkml = 0 ; gv%nk_rho_varies = 0
3111 endif
3112 if (cs%use_ALE_algorithm) then
3113 call get_param(param_file, "MOM", "NK_RHO_VARIES", gv%nk_rho_varies, default=0) ! Will default to nz later... -AJA
3114 endif
3115
3116 alloc_(cs%uhtr(isdb:iedb,jsd:jed,nz)) ; cs%uhtr(:,:,:) = 0.0
3117 alloc_(cs%vhtr(isd:ied,jsdb:jedb,nz)) ; cs%vhtr(:,:,:) = 0.0
3118 cs%t_dyn_rel_adv = 0.0 ; cs%t_dyn_rel_thermo = 0.0 ; cs%t_dyn_rel_diag = 0.0
3119 cs%n_dyn_steps_in_adv = 0
3120
3121 if (debug_truncations) then
3122 allocate(cs%u_prev(isdb:iedb,jsd:jed,nz), source=0.0)
3123 allocate(cs%v_prev(isd:ied,jsdb:jedb,nz), source=0.0)
3124 mom_internal_state%u_prev => cs%u_prev
3125 mom_internal_state%v_prev => cs%v_prev
3126 call safe_alloc_ptr(cs%ADp%du_dt_visc,isdb,iedb,jsd,jed,nz)
3127 call safe_alloc_ptr(cs%ADp%dv_dt_visc,isd,ied,jsdb,jedb,nz)
3128 if (.not.cs%adiabatic) then
3129 call safe_alloc_ptr(cs%ADp%du_dt_dia,isdb,iedb,jsd,jed,nz)
3130 call safe_alloc_ptr(cs%ADp%dv_dt_dia,isd,ied,jsdb,jedb,nz)
3131 endif
3132 endif
3133
3134 mom_internal_state%u => cs%u ; mom_internal_state%v => cs%v
3135 mom_internal_state%h => cs%h
3136 mom_internal_state%uh => cs%uh ; mom_internal_state%vh => cs%vh
3137 if (use_temperature) then
3138 mom_internal_state%T => cs%T ; mom_internal_state%S => cs%S
3139 endif
3140
3141 cs%CDp%uh => cs%uh ; cs%CDp%vh => cs%vh
3142
3143 if (cs%interp_p_surf) allocate(cs%p_surf_prev(isd:ied,jsd:jed), source=0.0)
3144
3145 alloc_(cs%ssh_rint(isd:ied,jsd:jed)) ; cs%ssh_rint(:,:) = 0.0
3146 alloc_(cs%ave_ssh_ibc(isd:ied,jsd:jed)) ; cs%ave_ssh_ibc(:,:) = 0.0
3147 alloc_(cs%eta_av_bc(isd:ied,jsd:jed)) ; cs%eta_av_bc(:,:) = 0.0 ! -G%Z_ref
3148 cs%time_in_cycle = 0.0 ; cs%time_in_thermo_cycle = 0.0
3149
3150 !allocate porous topography variables
3151 allocate(cs%pbv%por_face_areaU(isdb:iedb,jsd:jed,nz), source=1.0)
3152 allocate(cs%pbv%por_face_areaV(isd:ied,jsdb:jedb,nz), source=1.0)
3153 allocate(cs%pbv%por_layer_widthU(isdb:iedb,jsd:jed,nz+1), source=1.0)
3154 allocate(cs%pbv%por_layer_widthV(isd:ied,jsdb:jedb,nz+1), source=1.0)
3155
3156 ! Use the Wright equation of state by default, unless otherwise specified
3157 ! Note: this line and the following block ought to be in a separate
3158 ! initialization routine for tv.
3159 if (use_eos) then
3160 allocate(cs%tv%eqn_of_state)
3161 call eos_init(param_file, cs%tv%eqn_of_state, us, use_cont_abss)
3162 endif
3163 if (use_temperature) then
3164 allocate(cs%tv%TempxPmE(isd:ied,jsd:jed), source=0.0)
3165 if (use_geothermal) then
3166 allocate(cs%tv%internal_heat(isd:ied,jsd:jed), source=0.0)
3167 endif
3168 endif
3169 call calltree_waypoint("state variables allocated (initialize_MOM)")
3170
3171 ! Set the fields that are needed for bitwise identical restarting
3172 ! the time stepping scheme.
3173 call restart_init(param_file, cs%restart_CS)
3174 restart_csp => cs%restart_CS
3175
3176 call set_restart_fields(gv, us, param_file, cs, restart_csp)
3177 if (cs%split .and. cs%use_alt_split) then
3178 call register_restarts_dyn_split_rk2b(hi, gv, us, param_file, &
3179 cs%dyn_split_RK2b_CSp, restart_csp, cs%uh, cs%vh)
3180 elseif (cs%split) then
3181 call register_restarts_dyn_split_rk2(hi, gv, us, param_file, &
3182 cs%dyn_split_RK2_CSp, restart_csp, cs%uh, cs%vh)
3183 elseif (cs%use_RK2) then
3184 call register_restarts_dyn_unsplit_rk2(hi, gv, param_file, &
3185 cs%dyn_unsplit_RK2_CSp)
3186 else
3187 call register_restarts_dyn_unsplit(hi, gv, param_file, &
3188 cs%dyn_unsplit_CSp)
3189 endif
3190
3191 ! This subroutine calls user-specified tracer registration routines.
3192 ! Additional calls can be added to MOM_tracer_flow_control.F90.
3193 call call_tracer_register(g, gv, us, param_file, cs%tracer_flow_CSp, &
3194 cs%tracer_Reg, restart_csp)
3195
3196 call meke_alloc_register_restart(hi, us, param_file, cs%MEKE, restart_csp)
3197 call set_visc_register_restarts(hi, g, gv, us, param_file, cs%visc, restart_csp, use_ice_shelf)
3198 call mixedlayer_restrat_register_restarts(hi, gv, us, param_file, &
3199 cs%mixedlayer_restrat_CSp, restart_csp)
3200
3201 if (associated(cs%OBC)) then
3202 ! This call initializes the relevant vertical remapping structures.
3203 call open_boundary_setup_vert(gv, us, cs%OBC)
3204
3205 ! Set up remaining information about open boundary conditions that is needed for OBCs.
3206 ! Package specific changes to OBCs occur here.
3207 call call_obc_register(g, gv, us, param_file, cs%update_OBC_CSp, cs%OBC, cs%tracer_Reg)
3208
3209 ! This is the equivalent to 2 calls to register_segment_tracer (per segment), which
3210 ! could occur with the call to update_OBC_data or after the main initialization.
3211 if (use_temperature) &
3212 call register_temp_salt_segments(gv, us, cs%OBC, cs%tracer_Reg, param_file)
3213 ! This is the equivalent call to register_temp_salt_segments for external tracers with OBC
3214 call call_tracer_register_obc_segments(gv, param_file, cs%tracer_flow_CSp, cs%tracer_Reg, cs%OBC)
3215
3216 ! Set up the thickness reservoirs if using them.
3217 if (cs%OBC%use_h_res) &
3218 call segment_thickness_reservoir_init(gv, us, cs%OBC, param_file)
3219
3220 ! This needs the number of tracers and to have called any code that sets whether
3221 ! reservoirs are used.
3222 call open_boundary_register_restarts(hi, gv, us, cs%OBC, cs%tracer_Reg, &
3223 param_file, restart_csp, use_temperature)
3224
3225 ! This call allocates the arrays on the segments for open boundary data, but it must occur
3226 ! after any calls to call_tracer_register_obc_segments.
3227 call initialize_segment_data(gv, us, cs%OBC, param_file, turns, use_temperature)
3228
3229 if (cs%debug_OBCs) call write_obc_info(cs%OBC, g, gv, us)
3230 endif
3231
3232 if (present(waves_csp)) then
3233 call waves_register_restarts(waves_csp, hi, gv, us, param_file, restart_csp)
3234 endif
3235
3236 if (use_temperature) then
3237 call stoch_eos_register_restarts(hi, param_file, cs%stoch_eos_CS, restart_csp)
3238 endif
3239
3240 if (.not. cs%adiabatic) then
3241 call register_diabatic_restarts(g, gv, us, param_file, cs%int_tide_CSp, restart_csp, cs%diabatic_CSp)
3242 endif
3243
3244 call calltree_waypoint("restart registration complete (initialize_MOM)")
3245 call restart_registry_lock(restart_csp)
3246
3247 ! Write out all of the grid data used by this run.
3248 new_sim = determine_is_new_run(dirs%input_filename, dirs%restart_input_dir, g_in, restart_csp)
3249 write_geom_files = ((write_geom==2) .or. ((write_geom==1) .and. new_sim))
3250 if (write_geom_files) then
3251 if (associated(mom_dom_unmasked)) then
3252 call hor_index_init(mom_dom_unmasked, hi_in_unmasked, param_file, &
3253 local_indexing=.not.global_indexing)
3254 call create_dyn_horgrid(dg_unmasked_in, hi_in_unmasked, bathymetry_at_vel=bathy_at_vel)
3255 call clone_mom_domain(mom_dom_unmasked, dg_unmasked_in%Domain)
3256 call mom_initialize_fixed(dg_unmasked_in, us, obc_in, param_file)
3257 call write_ocean_geometry_file(dg_unmasked_in, param_file, dirs%output_directory, us=us, geom_file=geom_file)
3258 call deallocate_mom_domain(mom_dom_unmasked)
3259 call destroy_dyn_horgrid(dg_unmasked_in)
3260 else
3261 call write_ocean_geometry_file(dg_in, param_file, dirs%output_directory, us=us, geom_file=geom_file)
3262 endif
3263 endif
3264 call destroy_dyn_horgrid(dg_in)
3265
3266 ! Initialize dynamically evolving fields, perhaps from restart files.
3267 call cpu_clock_begin(id_clock_mom_init)
3268 call mom_initialize_coord(gv, us, param_file, cs%tv, g%max_depth)
3269 call calltree_waypoint("returned from MOM_initialize_coord() (initialize_MOM)")
3270
3271 if (cs%use_ALE_algorithm) then
3272 call ale_init(param_file, g, gv, us, g%max_depth, cs%ALE_CSp)
3273 call calltree_waypoint("returned from ALE_init() (initialize_MOM)")
3274 endif
3275
3276 ! Set a few remaining fields that are specific to the ocean grid type.
3277 if (cs%rotate_index) then
3278 call set_first_direction(g, modulo(first_direction + turns, 2))
3279 else
3280 call set_first_direction(g, modulo(first_direction, 2))
3281 endif
3282 ! Allocate the auxiliary non-symmetric domain for debugging or I/O purposes.
3283 if (cs%debug .or. g%symmetric) then
3284 call clone_mom_domain(g%Domain, g%Domain_aux, symmetric=.false.)
3285 else ; g%Domain_aux => g%Domain ; endif
3286 ! Copy common variables from the vertical grid to the horizontal grid.
3287 ! Consider removing this later?
3288 g%ke = gv%ke
3289
3290 if (use_ice_shelf) then
3291 point_calving = .false. ; if (present(calve_ice_shelf_bergs)) point_calving = calve_ice_shelf_bergs
3292 endif
3293
3294 if (cs%rotate_index) then
3295 g_in%ke = gv%ke
3296
3297 ! Allocate the auxiliary non-symmetric domain for debugging or I/O purposes.
3298 if (cs%debug .or. g_in%symmetric) then
3299 call clone_mom_domain(g_in%Domain, g_in%Domain_aux, symmetric=.false.)
3300 else ; g_in%Domain_aux => g_in%Domain ; endif
3301
3302 allocate(u_in(g_in%IsdB:g_in%IedB, g_in%jsd:g_in%jed, nz), source=0.0)
3303 allocate(v_in(g_in%isd:g_in%ied, g_in%JsdB:g_in%JedB, nz), source=0.0)
3304 allocate(h_in(g_in%isd:g_in%ied, g_in%jsd:g_in%jed, nz), source=gv%Angstrom_H)
3305
3306 if (use_temperature) then
3307 allocate(t_in(g_in%isd:g_in%ied, g_in%jsd:g_in%jed, nz), source=0.0)
3308 allocate(s_in(g_in%isd:g_in%ied, g_in%jsd:g_in%jed, nz), source=0.0)
3309
3310 cs%tv%T => t_in
3311 cs%tv%S => s_in
3312
3313 if (associated(cs%OBC)) then
3314 ! Log this parameter in MOM_initialize_state
3315 call get_param(param_file, "MOM", "OBC_RESERVOIR_INIT_BUG", obc_reservoir_init_bug, &
3316 "If true, set the OBC tracer reservoirs at the startup of a new run from the "//&
3317 "interior tracer concentrations regardless of properties that may be explicitly "//&
3318 "specified for the reservoir concentrations.", default=enable_bugs, do_not_log=.true.)
3319 if (obc_reservoir_init_bug .and. (allocated(cs%OBC%tres_x) .or. allocated(cs%OBC%tres_y))) &
3320 call mom_error(fatal, "OBC_RESERVOIR_INIT_BUG can not be set to true with grid rotation.")
3321 endif
3322 endif
3323
3324 if (use_ice_shelf) then
3325 ! These arrays are not initialized in most solo cases, but are needed
3326 ! when using an ice shelf. Passing the ice shelf diagnostics CS from MOM
3327 ! for legacy reasons. The actual ice shelf diag CS is internal to the ice shelf
3328 call initialize_ice_shelf(param_file, g, time, ice_shelf_csp, diag_ptr, &
3329 time_init, dirs%output_directory, calve_ice_shelf_bergs=point_calving)
3330 allocate(frac_shelf_in(g_in%isd:g_in%ied, g_in%jsd:g_in%jed), source=0.0)
3331 allocate(mass_shelf_in(g_in%isd:g_in%ied, g_in%jsd:g_in%jed), source=0.0)
3332 allocate(cs%frac_shelf_h(isd:ied, jsd:jed), source=0.0)
3333 allocate(cs%mass_shelf(isd:ied, jsd:jed), source=0.0)
3334 call ice_shelf_query(ice_shelf_csp, g, cs%frac_shelf_h, cs%mass_shelf)
3335 ! MOM_initialize_state is using the unrotated metric
3336 call rotate_array(cs%frac_shelf_h, -turns, frac_shelf_in)
3337 call rotate_array(cs%mass_shelf, -turns, mass_shelf_in)
3338 call mom_initialize_state(u_in, v_in, h_in, cs%tv, time, g_in, gv, us, &
3339 param_file, dirs, restart_csp, cs%ALE_CSp, cs%tracer_Reg, &
3340 sponge_in_csp, ale_sponge_in_csp, oda_incupd_in_csp, obc_in, time_in, &
3341 frac_shelf_h=frac_shelf_in, mass_shelf=mass_shelf_in)
3342 else
3343 call mom_initialize_state(u_in, v_in, h_in, cs%tv, time, g_in, gv, us, &
3344 param_file, dirs, restart_csp, cs%ALE_CSp, cs%tracer_Reg, &
3345 sponge_in_csp, ale_sponge_in_csp, oda_incupd_in_csp, obc_in, time_in)
3346 endif
3347
3348 if (use_temperature) then
3349 cs%tv%T => cs%T
3350 cs%tv%S => cs%S
3351 endif
3352
3353 ! Reset the first direction if it was found in a restart file
3354 if (cs%first_dir_restart > -1.0) then
3355 call set_first_direction(g, modulo(nint(cs%first_dir_restart) + turns, 2))
3356 else
3357 cs%first_dir_restart = real(modulo(first_direction, 2))
3358 endif
3359
3360 call rotate_initial_state(u_in, v_in, h_in, t_in, s_in, use_temperature, &
3361 turns, cs%u, cs%v, cs%h, cs%T, cs%S)
3362
3363 if (associated(sponge_in_csp)) then
3364 ! TODO: Implementation and testing of non-ALE sponge rotation
3365 call mom_error(fatal, "Index rotation of non-ALE sponge is not yet implemented.")
3366 endif
3367
3368 if (associated(ale_sponge_in_csp)) then
3369 call rotate_ale_sponge(ale_sponge_in_csp, g_in, cs%ALE_sponge_CSp, g, gv, us, turns, param_file)
3370 call update_ale_sponge_field(cs%ALE_sponge_CSp, t_in, g, gv, cs%T)
3371 call update_ale_sponge_field(cs%ALE_sponge_CSp, s_in, g, gv, cs%S)
3372 endif
3373
3374 ! Deallocate the unrotated arrays and types that are no longer needed.
3375 deallocate(u_in)
3376 deallocate(v_in)
3377 deallocate(h_in)
3378 if (use_temperature) then
3379 deallocate(t_in)
3380 deallocate(s_in)
3381 endif
3382 if (use_ice_shelf) deallocate(frac_shelf_in, mass_shelf_in)
3383 if (associated(obc_in)) call open_boundary_end(obc_in)
3384
3385 else ! The model is being run without grid rotation. This is true of all production runs.
3386 if (use_ice_shelf) then
3387 call initialize_ice_shelf(param_file, g, time, ice_shelf_csp, diag_ptr, time_init, &
3388 dirs%output_directory, calve_ice_shelf_bergs=point_calving)
3389 allocate(cs%frac_shelf_h(isd:ied, jsd:jed), source=0.0)
3390 allocate(cs%mass_shelf(isd:ied, jsd:jed), source=0.0)
3391 call ice_shelf_query(ice_shelf_csp,g,cs%frac_shelf_h, cs%mass_shelf)
3392 call mom_initialize_state(cs%u, cs%v, cs%h, cs%tv, time, g, gv, us, &
3393 param_file, dirs, restart_csp, cs%ALE_CSp, cs%tracer_Reg, &
3394 cs%sponge_CSp, cs%ALE_sponge_CSp, cs%oda_incupd_CSp, cs%OBC, time_in, &
3395 frac_shelf_h=cs%frac_shelf_h, mass_shelf=cs%mass_shelf, obc_for_bug=cs%OBC)
3396 else
3397 call mom_initialize_state(cs%u, cs%v, cs%h, cs%tv, time, g, gv, us, &
3398 param_file, dirs, restart_csp, cs%ALE_CSp, cs%tracer_Reg, &
3399 cs%sponge_CSp, cs%ALE_sponge_CSp, cs%oda_incupd_CSp, cs%OBC, time_in, obc_for_bug=cs%OBC)
3400 endif
3401
3402 ! Reset the first direction if it was found in a restart file.
3403 if (cs%first_dir_restart > -1.0) then
3404 call set_first_direction(g, nint(cs%first_dir_restart))
3405 else
3406 cs%first_dir_restart = real(modulo(first_direction, 2))
3407 endif
3408 endif
3409
3410 ! Allocate any derived densities or other equation of state derived fields.
3411 if (.not.(gv%Boussinesq .or. gv%semi_Boussinesq)) then
3412 allocate(cs%tv%SpV_avg(isd:ied,jsd:jed,nz), source=0.0)
3413 cs%tv%valid_SpV_halo = -1 ! This array does not yet have any valid data.
3414 endif
3415
3416 if (associated(cs%OBC)) then
3417 call mom_initialize_obcs(cs%h, cs%tv, cs%OBC, time, g, gv, us, param_file, restart_csp, cs%tracer_Reg)
3418
3419 if (use_temperature) then
3420 call pass_var(cs%tv%T, g%Domain, complete=.false.)
3421 call pass_var(cs%tv%S, g%Domain, complete=.true.)
3422 endif
3423 call calc_derived_thermo(cs%tv, cs%h, g, gv, us)
3424
3425 ! Call this during initialization to fill boundary arrays from fixed values
3426 call read_obc_dynamics_data(g, gv, us, cs%OBC, cs%tv, cs%h, time)
3427 call update_obc_dynamics_data(g, gv, us, cs%OBC, cs%h, time)
3428 ! BGC data is not read/updated at initialization since OBC%update_OBC_seg_data is false.
3429 call read_obc_tracer_data(g, gv, us, cs%OBC, time, include_bgc=.false.)
3430 call update_obc_tracer_data(cs%OBC, include_bgc=.false.)
3431 call initialize_obc_segment_reservoirs(gv, cs%OBC)
3432 endif
3433
3434 if (use_ice_shelf .and. cs%debug) then
3435 call hchksum(cs%frac_shelf_h, "MOM:frac_shelf_h", g%HI, haloshift=0)
3436 call hchksum(cs%mass_shelf, "MOM:mass_shelf", g%HI, haloshift=0, unscale=us%RZ_to_kg_m2)
3437 endif
3438
3439 call cpu_clock_end(id_clock_mom_init)
3440 call calltree_waypoint("returned from MOM_initialize_state() (initialize_MOM)")
3441
3442 ! From this point, there may be pointers being set, so the final grid type
3443 ! that will persist throughout the run has to be used.
3444
3445 if (test_grid_copy) then
3446 ! Copy the data from the temporary grid to the dyn_hor_grid to CS%G.
3447 call create_dyn_horgrid(test_dg, g%HI)
3448 call clone_mom_domain(g%Domain, test_dg%Domain)
3449
3450 call clone_mom_domain(g%Domain, cs%G%Domain)
3451 call mom_grid_init(cs%G, param_file, us)
3452
3453 call copy_mom_grid_to_dyngrid(g, test_dg, us)
3454 call copy_dyngrid_to_mom_grid(test_dg, cs%G, us)
3455
3456 call destroy_dyn_horgrid(test_dg)
3457 call mom_grid_end(g) ; deallocate(g)
3458
3459 g => cs%G
3460 if (cs%debug .or. cs%G%symmetric) then
3461 call clone_mom_domain(cs%G%Domain, cs%G%Domain_aux, symmetric=.false.)
3462 else ; cs%G%Domain_aux => cs%G%Domain ; endif
3463 g%ke = gv%ke
3464 endif
3465
3466 ! At this point, all user-modified initialization code has been called. The
3467 ! remainder of this subroutine is controlled by the parameters that have
3468 ! have already been set.
3469
3470 if (ale_remap_init_conds(cs%ALE_CSp) .and. .not. query_initialized(cs%h,"h",restart_csp)) then
3471 ! This block is controlled by the ALE parameter REMAP_AFTER_INITIALIZATION.
3472 ! \todo This block exists for legacy reasons and we should phase it out of all examples. !###
3473 if (cs%debug) then
3474 call uvchksum("Pre ALE adjust init cond [uv]", cs%u, cs%v, g%HI, haloshift=1, unscale=us%L_T_to_m_s)
3475 call hchksum(cs%h,"Pre ALE adjust init cond h", g%HI, haloshift=1, unscale=gv%H_to_MKS)
3476 endif
3477 call calltree_waypoint("Calling adjustGridForIntegrity() to remap initial conditions (initialize_MOM)")
3478 call adjustgridforintegrity(cs%ALE_CSp, g, gv, cs%h )
3479 if (allocated(cs%tv%SpV_avg)) call calc_derived_thermo(cs%tv, cs%h, g, gv, us, halo=1)
3480 call pre_ale_adjustments(g, gv, us, cs%h, cs%tv, cs%tracer_Reg, cs%ALE_CSp, cs%u, cs%v)
3481
3482 call calltree_waypoint("Calling ALE_regrid() to remap initial conditions (initialize_MOM)")
3483 allocate(h_new(isd:ied, jsd:jed, nz), source=0.0)
3484 allocate(dzregrid(isd:ied, jsd:jed, nz+1), source=0.0)
3485 allocate(pcm_cell(isd:ied, jsd:jed, nz), source=.false.)
3486 allocate(h_old_u(isdb:iedb, jsd:jed, nz), source=0.0)
3487 allocate(h_new_u(isdb:iedb, jsd:jed, nz), source=0.0)
3488 allocate(h_old_v(isd:ied, jsdb:jedb, nz), source=0.0)
3489 allocate(h_new_v(isd:ied, jsdb:jedb, nz), source=0.0)
3490 if (use_ice_shelf) then
3491 call ale_regrid(g, gv, us, cs%h, h_new, dzregrid, cs%tv, cs%ALE_CSp, cs%frac_shelf_h, pcm_cell)
3492 else
3493 call ale_regrid(g, gv, us, cs%h, h_new, dzregrid, cs%tv, cs%ALE_CSp, pcm_cell=pcm_cell)
3494 endif
3495
3496 if (calltree_showquery()) call calltree_waypoint("new grid generated")
3497 ! Remap all variables from the old grid h onto the new grid h_new
3498 call ale_remap_tracers(cs%ALE_CSp, g, gv, cs%h, h_new, cs%tracer_Reg, cs%debug, pcm_cell=pcm_cell)
3499
3500 ! Determine the old and new grid thicknesses at velocity points.
3501 call ale_remap_set_h_vel(cs%ALE_CSp, g, gv, cs%h, h_old_u, h_old_v, cs%OBC, debug=cs%debug)
3502 if (cs%remap_uv_using_old_alg) then
3503 call ale_remap_set_h_vel_via_dz(cs%ALE_CSp, g, gv, h_new, h_new_u, h_new_v, cs%OBC, cs%h, dzregrid, cs%debug)
3504 else
3505 call ale_remap_set_h_vel(cs%ALE_CSp, g, gv, h_new, h_new_u, h_new_v, cs%OBC, debug=cs%debug)
3506 endif
3507
3508 ! Remap the velocity components.
3509 call ale_remap_velocities(cs%ALE_CSp, g, gv, h_old_u, h_old_v, h_new_u, h_new_v, cs%u, cs%v, cs%debug)
3510
3511 if (allocated(cs%tv%SpV_avg)) cs%tv%valid_SpV_halo = -1 ! Record that SpV_avg is no longer valid.
3512
3513 ! Replace the old grid with new one. All remapping must be done at this point.
3514 !$OMP parallel do default(shared)
3515 do k=1,nz ; do j=js-1,je+1 ; do i=is-1,ie+1
3516 cs%h(i,j,k) = h_new(i,j,k)
3517 enddo ; enddo ; enddo
3518
3519 deallocate(h_new, dzregrid, pcm_cell, h_old_u, h_new_u, h_old_v, h_new_v)
3520
3521 call cpu_clock_begin(id_clock_pass_init)
3522 call create_group_pass(tmp_pass_uv_t_s_h, cs%u, cs%v, g%Domain)
3523 if (use_temperature) then
3524 call create_group_pass(tmp_pass_uv_t_s_h, cs%tv%T, g%Domain)
3525 call create_group_pass(tmp_pass_uv_t_s_h, cs%tv%S, g%Domain)
3526 endif
3527 call create_group_pass(tmp_pass_uv_t_s_h, cs%h, g%Domain)
3528 call do_group_pass(tmp_pass_uv_t_s_h, g%Domain)
3529 call cpu_clock_end(id_clock_pass_init)
3530
3531 if (cs%debug) then
3532 call uvchksum("Post ALE adjust init cond [uv]", cs%u, cs%v, g%HI, haloshift=1, unscale=us%L_T_to_m_s)
3533 call hchksum(cs%h, "Post ALE adjust init cond h", g%HI, haloshift=2, unscale=gv%H_to_MKS)
3534 if (use_temperature) then
3535 call hchksum(cs%tv%T, "Post ALE adjust init cond T", g%HI, haloshift=2, unscale=us%C_to_degC)
3536 call hchksum(cs%tv%S, "Post ALE adjust init cond S", g%HI, haloshift=2, unscale=us%S_to_ppt)
3537 endif
3538 endif
3539 endif
3540 if ( cs%use_ALE_algorithm ) then
3541 call ale_set_extrap_boundaries (param_file, cs%ALE_CSp)
3542 call calltree_waypoint("returned from ALE_init() (initialize_MOM)")
3543 call ale_updateverticalgridtype( cs%ALE_CSp, gv )
3544 endif
3545 ! The basic state variables have now been fully initialized, so update their halos and
3546 ! calculate any derived thermodynmics quantities.
3547
3548 !--- set up group pass for u,v,T,S and h. pass_uv_T_S_h also is used in step_MOM
3549 call cpu_clock_begin(id_clock_pass_init)
3550 dynamics_stencil = min(3, g%Domain%nihalo, g%Domain%njhalo)
3551 call create_group_pass(pass_uv_t_s_h, cs%u, cs%v, g%Domain, halo=dynamics_stencil)
3552 if (use_temperature) then
3553 call create_group_pass(pass_uv_t_s_h, cs%tv%T, g%Domain, halo=dynamics_stencil)
3554 call create_group_pass(pass_uv_t_s_h, cs%tv%S, g%Domain, halo=dynamics_stencil)
3555 endif
3556 call create_group_pass(pass_uv_t_s_h, cs%h, g%Domain, halo=dynamics_stencil)
3557
3558 call do_group_pass(pass_uv_t_s_h, g%Domain)
3559 if (associated(cs%tv%p_surf)) call pass_var(cs%tv%p_surf, g%Domain, halo=dynamics_stencil)
3560 call cpu_clock_end(id_clock_pass_init)
3561
3562 ! Update derived thermodynamic quantities.
3563 if (allocated(cs%tv%SpV_avg)) then
3564 call calc_derived_thermo(cs%tv, cs%h, g, gv, us, halo=dynamics_stencil, debug=cs%debug)
3565 endif
3566
3567
3568 diag => cs%diag
3569 ! Initialize the diag mediator.
3570 call diag_mediator_init(g, gv, us, gv%ke, param_file, diag, doc_file_dir=dirs%output_directory)
3571 if (associated(cs%OBC)) then
3572 call diag_mediator_set_obc_info(g, cs%OBC%segnum_u, cs%OBC%segnum_v, diag)
3573 endif
3574 if (present(diag_ptr)) diag_ptr => cs%diag
3575
3576 ! Initialize the diagnostics masks for native arrays.
3577 ! This step has to be done after call to MOM_initialize_state
3578 ! and before MOM_diagnostics_init
3579 call diag_masks_set(g, gv%ke, diag)
3580
3581 ! Set up pointers within diag mediator control structure,
3582 ! this needs to occur _after_ CS%h etc. have been allocated.
3583 call diag_set_state_ptrs(cs%h, cs%tv, diag)
3584
3585 ! This call sets up the diagnostic axes. These are needed,
3586 ! e.g. to generate the target grids below.
3587 call set_axes_info(g, gv, us, param_file, diag)
3588
3589 ! Whenever thickness/T/S changes let the diag manager know, target grids
3590 ! for vertical remapping may need to be regenerated. In non-Boussinesq mode,
3591 ! calc_derived_thermo needs to be called before diag_update_remap_grids.
3592 call diag_update_remap_grids(diag)
3593
3594 ! Setup the diagnostic grid storage types
3595 call diag_grid_storage_init(cs%diag_pre_sync, g, gv, diag)
3596 call diag_grid_storage_init(cs%diag_pre_dyn, g, gv, diag)
3597
3598 ! Calculate masks for diagnostics arrays in non-native coordinates
3599 ! This step has to be done after set_axes_info() because the axes needed
3600 ! to be configured, and after diag_update_remap_grids() because the grids
3601 ! must be defined.
3602 call set_masks_for_axes(g, diag)
3603
3604 ! Register the volume cell measure (must be one of first diagnostics)
3605 call register_cell_measure(g, cs%diag, time)
3606
3607 call cpu_clock_begin(id_clock_mom_init)
3608 ! Diagnose static fields AND associate areas/volumes with axes
3609 call write_static_fields(g, gv, us, cs%tv, cs%diag)
3610 call calltree_waypoint("static fields written (initialize_MOM)")
3611
3612 if (cs%use_ALE_algorithm) then
3613 call ale_writecoordinatefile( cs%ALE_CSp, gv, dirs%output_directory )
3614 call calltree_waypoint("ALE initialized (initialize_MOM)")
3615 elseif (write_geom_files) then
3616 call write_vertgrid_file(gv, us, param_file, dirs%output_directory)
3617 endif
3618 call cpu_clock_end(id_clock_mom_init)
3619
3620 if (cs%use_dbclient) call database_comms_init(param_file, cs%dbcomms_CS)
3621 cs%useMEKE = meke_init(time, g, gv, us, param_file, diag, cs%dbcomms_CS, cs%MEKE_CSp, cs%MEKE, &
3622 restart_csp, cs%MEKE_in_dynamics)
3623
3624 call varmix_init(time, g, gv, us, param_file, diag, cs%VarMix)
3625 call set_visc_init(time, g, gv, us, param_file, diag, cs%visc, cs%set_visc_CSp, restart_csp, cs%OBC)
3626 call thickness_diffuse_init(time, g, gv, us, param_file, diag, cs%CDp, cs%thickness_diffuse_CSp)
3627 if (cs%interface_filter) &
3628 call interface_filter_init(time, g, gv, us, param_file, diag, cs%CDp, cs%interface_filter_CSp)
3629
3630 new_sim = is_new_run(restart_csp)
3631 if (use_temperature) then
3632 cs%use_stochastic_EOS = mom_stoch_eos_init(time, g, gv, us, param_file, diag, cs%stoch_eos_CS, restart_csp)
3633 else
3634 cs%use_stochastic_EOS = .false.
3635 endif
3636
3637 if (cs%use_porbar) &
3638 call porous_barriers_init(time, gv, us, param_file, diag, cs%por_bar_CS)
3639
3640 if (cs%split) then
3641 allocate(eta(szi_(g),szj_(g)), source=0.0)
3642 if (cs%use_alt_split) then
3643 call initialize_dyn_split_rk2b(cs%u, cs%v, cs%h, cs%tv, cs%uh, cs%vh, eta, time, &
3644 g, gv, us, param_file, diag, cs%dyn_split_RK2b_CSp, cs%HA_CSp, restart_csp, &
3645 cs%dt, cs%ADp, cs%CDp, mom_internal_state, cs%VarMix, cs%MEKE, &
3646 cs%thickness_diffuse_CSp, cs%OBC, cs%update_OBC_CSp, cs%ALE_CSp, cs%set_visc_CSp, &
3647 cs%visc, dirs, cs%ntrunc, cs%pbv, calc_dtbt=calc_dtbt, &
3648 cont_stencil=cs%cont_stencil, dyn_h_stencil=cs%dyn_h_stencil)
3649 else
3650 call initialize_dyn_split_rk2(cs%u, cs%v, cs%h, cs%tv, cs%uh, cs%vh, eta, time, &
3651 g, gv, us, param_file, diag, cs%dyn_split_RK2_CSp, cs%HA_CSp, restart_csp, &
3652 cs%dt, cs%ADp, cs%CDp, mom_internal_state, cs%VarMix, cs%MEKE, &
3653 cs%thickness_diffuse_CSp, cs%OBC, cs%update_OBC_CSp, cs%ALE_CSp, cs%set_visc_CSp, &
3654 cs%visc, dirs, cs%ntrunc, cs%pbv, calc_dtbt=calc_dtbt, &
3655 cont_stencil=cs%cont_stencil, dyn_h_stencil=cs%dyn_h_stencil)
3656 endif
3657 ! A reset period no longer than dt is equivalent to recalculating every step.
3658 if (cs%dtbt_reset_period > 0.0 .and. cs%dtbt_reset_period <= cs%dt) &
3659 cs%dtbt_reset_period = 0.0
3660 if (cs%dtbt_reset_period > 0.0) then
3661 cs%dtbt_reset_interval = real_to_time(cs%dtbt_reset_period, unscale=us%T_to_s)
3662 if (calc_dtbt) then
3663 ! No restart DTBT (not found or new run) or DTBT_RESTART_BUG=True: set to the most recent
3664 ! multiple of the interval before or equal to current time, so the set_dtbt is called on
3665 ! the first step.
3666 cs%dtbt_reset_time = time_init + cs%dtbt_reset_interval * &
3667 ((time - time_init) / cs%dtbt_reset_interval)
3668 else
3669 ! Restart DTBT available: defer to the next multiple after current time so the first step
3670 ! uses the restart value unless a reset is naturally due.
3671 cs%dtbt_reset_time = time_init + cs%dtbt_reset_interval * &
3672 ((time - time_init) / cs%dtbt_reset_interval + 1)
3673 endif
3674 endif
3675 elseif (cs%use_RK2) then
3676 call initialize_dyn_unsplit_rk2(cs%u, cs%v, cs%h, cs%tv, time, g, gv, &
3677 us, param_file, diag, cs%dyn_unsplit_RK2_CSp, &
3678 cs%ADp, cs%CDp, mom_internal_state, cs%OBC, &
3679 cs%update_OBC_CSp, cs%ALE_CSp, cs%set_visc_CSp, cs%visc, dirs, &
3680 cs%ntrunc, cont_stencil=cs%cont_stencil, dyn_h_stencil=cs%dyn_h_stencil)
3681 else
3682 call initialize_dyn_unsplit(cs%u, cs%v, cs%h, cs%tv, time, g, gv, &
3683 us, param_file, diag, cs%dyn_unsplit_CSp, &
3684 cs%ADp, cs%CDp, mom_internal_state, cs%OBC, &
3685 cs%update_OBC_CSp, cs%ALE_CSp, cs%set_visc_CSp, cs%visc, dirs, &
3686 cs%ntrunc, cont_stencil=cs%cont_stencil, dyn_h_stencil=cs%dyn_h_stencil)
3687 endif
3688 cs%dyn_h_stencil = max(2, cs%dyn_h_stencil)
3689
3690 ! When IGNORE_DT_OBC_SEG_UPDATE_OBGC is true, BGC OBC updates happen every tracer advection step.
3691 if (associated(cs%OBC)) then
3692 if (cs%OBC%ignore_dt_obc_bgc) cs%dt_obc_seg_period = 0.0
3693 endif
3694
3695 ! Set the next time to update OBC segment BGC tracer data
3696 if (associated(cs%OBC) .and. (cs%dt_obc_seg_period > 0.0)) then
3697 if (cs%dt_obc_seg_period > cs%dt_tr_adv) then
3698 if (new_sim) then
3699 call mom_error(warning, "DT_OBC_SEG_UPDATE_OBGC > DT_TRACER_ADVECT: this run will "//&
3700 "proceed normally, but any restart from it will fail with a FATAL error because "//&
3701 "BGC OBC external data is not saved in restart files. "//&
3702 "Set DT_OBC_SEG_UPDATE_OBGC = DT_TRACER_ADVECT or 0 until this is fixed.")
3703 else
3704 call mom_error(fatal, "DT_OBC_SEG_UPDATE_OBGC > DT_TRACER_ADVECT is not supported "//&
3705 "for restart runs: BGC OBC external data is not saved in restart files, so the "//&
3706 "first tracer advection step after restart may use incorrect boundary data. "//&
3707 "Set DT_OBC_SEG_UPDATE_OBGC = DT_TRACER_ADVECT or 0 until this is fixed.")
3708 endif
3709 endif
3710 cs%dt_obc_seg_interval = real_to_time(cs%dt_obc_seg_period, unscale=us%T_to_s)
3711 if (obc_bgc_time_ref_bug) then
3712 cs%dt_obc_seg_time = time + cs%dt_obc_seg_interval
3713 else
3714 ! Set to the next update point after current time, so that %t read from initialization is
3715 ! not overwritten. Note that even though this line by itself is correct, there are still
3716 ! issue with restart runs, as external data %t is not saved in restart files.
3717 cs%dt_obc_seg_time = time_init + cs%dt_obc_seg_interval * &
3718 ((time - time_init) / cs%dt_obc_seg_interval + 1)
3719 endif
3720 endif
3721
3722 call calltree_waypoint("dynamics initialized (initialize_MOM)")
3723
3724 cs%mixedlayer_restrat = mixedlayer_restrat_init(time, g, gv, us, param_file, diag, &
3725 cs%mixedlayer_restrat_CSp, restart_csp)
3726
3727 if (gv%Boussinesq .and. associated(cs%visc%h_ML)) then
3728 ! This is here to allow for a transition of restart files between model versions.
3729 call get_param(param_file, "MOM", "MLE_USE_PBL_MLD", mle_use_pbl_mld, &
3730 default=.false., do_not_log=.true.)
3731 if (mle_use_pbl_mld .and. .not.query_initialized(cs%visc%h_ML, "h_ML", restart_csp) .and. &
3732 associated(cs%visc%MLD)) then
3733 do j=js,je ; do i=is,ie ; cs%visc%h_ML(i,j) = gv%Z_to_H * cs%visc%MLD(i,j) ; enddo ; enddo
3734 endif
3735 endif
3736
3737 if (cs%mixedlayer_restrat) then
3738 if (.not.(bulkmixedlayer .or. cs%use_ALE_algorithm)) &
3739 call mom_error(fatal, "MOM: MIXEDLAYER_RESTRAT true requires a boundary layer scheme.")
3740 ! When DIABATIC_FIRST=False and using CS%visc%ML in mixedlayer_restrat we need to update after a restart
3741 if (.not. cs%diabatic_first .and. associated(cs%visc%MLD)) &
3742 call pass_var(cs%visc%MLD, g%domain, halo=1)
3743 if (.not. cs%diabatic_first .and. associated(cs%visc%h_ML)) &
3744 call pass_var(cs%visc%h_ML, g%domain, halo=1)
3745 endif
3746
3747 call mom_diagnostics_init(mom_internal_state, cs%ADp, cs%CDp, time, g, gv, us, &
3748 param_file, diag, cs%diagnostics_CSp, cs%tv)
3749 call diag_copy_diag_to_storage(cs%diag_pre_sync, cs%h, cs%diag)
3750
3751
3752 if (cs%adiabatic) then
3753 call adiabatic_driver_init(time, g, param_file, diag, cs%diabatic_CSp, &
3754 cs%tracer_flow_CSp)
3755 else
3756 call diabatic_driver_init(time, g, gv, us, param_file, cs%use_ALE_algorithm, diag, &
3757 cs%ADp, cs%CDp, cs%diabatic_CSp, cs%tracer_flow_CSp, &
3758 cs%sponge_CSp, cs%ALE_sponge_CSp, cs%oda_incupd_CSp, cs%int_tide_CSp)
3759 endif
3760
3761 cs%vertex_shear = kappa_shear_at_vertex(param_file)
3762
3763 ! GMM, the following is needed to get BLDs into the dynamics module
3764 if (cs%split .and. fpmix) then
3765 call init_dyn_split_rk2_diabatic(cs%diabatic_CSp, cs%dyn_split_RK2_CSp)
3766 endif
3767
3768 if (associated(cs%sponge_CSp)) &
3769 call init_sponge_diags(time, g, gv, us, diag, cs%sponge_CSp)
3770
3771 if (associated(cs%oda_incupd_CSp)) &
3772 call init_oda_incupd_diags(time, g, gv, diag, cs%oda_incupd_CSp, us)
3773
3774 call tracer_advect_init(time, g, us, param_file, diag, cs%tracer_adv_CSp)
3775 call tracer_hor_diff_init(time, g, gv, us, param_file, diag, cs%tv%eqn_of_state, cs%diabatic_CSp, &
3776 cs%tracer_diff_CSp)
3777
3778 call lock_tracer_registry(cs%tracer_Reg)
3779 call calltree_waypoint("tracer registry now locked (initialize_MOM)")
3780
3781 ! now register some diagnostics since the tracer registry is now locked
3782 call register_surface_diags(time, g, us, cs%sfc_IDs, cs%diag, cs%tv)
3783 call register_diags(time, g, gv, us, cs%IDs, cs%diag)
3784 call register_transport_diags(time, g, gv, us, cs%transport_IDs, cs%diag)
3785 call extract_diabatic_member(cs%diabatic_CSp, use_kpp=use_kpp)
3786 call register_tracer_diagnostics(cs%tracer_Reg, cs%h, time, diag, g, gv, us, &
3787 cs%use_ALE_algorithm, use_kpp)
3788 if (cs%use_ALE_algorithm) then
3789 call ale_register_diags(time, g, gv, us, diag, cs%ALE_CSp)
3790 endif
3791
3792 ! determine if we need to accumulate resolved transports for tracer advection diagnostics
3793 do m = 1,cs%tracer_Reg%ntr
3794 if (cs%tracer_Reg%Tr(m)%id_adx_resolved > 0 .or. &
3795 cs%tracer_Reg%Tr(m)%id_ady_resolved > 0) then
3796 cs%accumulate_resolved_flux = .true.
3797 cs%do_resolved_advection = .true.
3798 endif
3799 if (cs%tracer_Reg%Tr(m)%id_adx_param > 0 .or. &
3800 cs%tracer_Reg%Tr(m)%id_ady_param > 0) then
3801 cs%accumulate_resolved_flux = .true.
3802 cs%do_param_advection = .true.
3803 endif
3804 enddo
3805 if (cs%accumulate_resolved_flux) then
3806 allocate(cs%uhtr_resolved(isdb:iedb,jsd:jed,nz), source=0.0)
3807 allocate(cs%vhtr_resolved(isd:ied,jsdb:jedb,nz), source=0.0)
3808 endif
3809
3810
3811 ! Do any necessary halo updates on any auxiliary variables that have been initialized.
3812 call cpu_clock_begin(id_clock_pass_init)
3813 if (associated(cs%visc%Kv_shear)) &
3814 call pass_var(cs%visc%Kv_shear, g%Domain, to_all+omit_corners, halo=1)
3815
3816 if (associated(cs%visc%Kv_slow)) &
3817 call pass_var(cs%visc%Kv_slow, g%Domain, to_all+omit_corners, halo=1)
3818 call cpu_clock_end(id_clock_pass_init)
3819
3820 ! This subroutine initializes any tracer packages.
3821 call tracer_flow_control_init(.not.new_sim, time, g, gv, us, cs%h, param_file, &
3822 cs%diag, cs%OBC, cs%tracer_flow_CSp, cs%sponge_CSp, &
3823 cs%ALE_sponge_CSp, cs%tv)
3824 if (present(tracer_flow_csp)) tracer_flow_csp => cs%tracer_flow_CSp
3825
3826 if (associated(cs%ALE_sponge_CSp)) &
3827 call init_ale_sponge_diags(time, g, diag, cs%ALE_sponge_CSp, us)
3828
3829 ! If running in offline tracer mode, initialize the necessary control structure and
3830 ! parameters
3831 if (present(offline_tracer_mode)) offline_tracer_mode=cs%offline_tracer_mode
3832
3833 if (cs%offline_tracer_mode) then
3834 ! Setup some initial parameterizations and also assign some of the subtypes
3835 call offline_transport_init(param_file, cs%offline_CSp, cs%diabatic_CSp, g, gv, us)
3836 call insert_offline_main( cs=cs%offline_CSp, ale_csp=cs%ALE_CSp, diabatic_csp=cs%diabatic_CSp, &
3837 diag=cs%diag, obc=cs%OBC, tracer_adv_csp=cs%tracer_adv_CSp, &
3838 tracer_flow_csp=cs%tracer_flow_CSp, tracer_reg=cs%tracer_Reg, &
3839 tv=cs%tv, x_before_y=(modulo(first_direction,2)==0), debug=cs%debug )
3840 call register_diags_offline_transport(time, cs%diag, cs%offline_CSp, gv, us)
3841 endif
3842
3843 if (associated(cs%OBC)) then
3844 ! At this point any information related to the tracer reservoirs has either been read from
3845 ! the restart file or has been specified in the segments. Initialize the tracer reservoir
3846 ! values from the segments if they have not been set via the restart file.
3847 call setup_obc_tracer_reservoirs(g, gv, cs%OBC, restart_csp)
3848 call setup_obc_thickness_reservoirs(g, gv, cs%OBC, restart_csp)
3849 call open_boundary_halo_update(g, cs%OBC)
3850 call copy_obc_radiation_coefs(cs%OBC)
3851 if (.not. (cs%OBC%reservoir_init_bug .and. new_sim .and. cs%diabatic_first)) &
3852 ! The if-guard is needed to preserve old answers with OBC_RESERVOIR_INIT_BUG=True, in which case
3853 ! segment T/S reservoir %tres and global restart arrays OBC%tres_x/y have diverged at this point.
3854 call copy_obc_tracer_reservoirs(cs%OBC)
3855 call copy_obc_thickness_reservoirs(cs%OBC, g, gv)
3856 endif
3857
3858 call register_obsolete_diagnostics(param_file, cs%diag)
3859
3860 if (use_frazil) then
3861 if (.not.query_initialized(cs%tv%frazil, "frazil", restart_csp)) then
3862 cs%tv%frazil(:,:) = 0.0
3863 call set_initialized(cs%tv%frazil, "frazil", restart_csp)
3864 endif
3865 endif
3866
3867 if (cs%interp_p_surf) then
3868 cs%p_surf_prev_set = query_initialized(cs%p_surf_prev, "p_surf_prev", restart_csp)
3869
3870 if (cs%p_surf_prev_set) then
3871 call pass_var(cs%p_surf_prev, g%domain)
3872 endif
3873 endif
3874
3875 if (.not.query_initialized(cs%ave_ssh_ibc, "ave_ssh", restart_csp)) then
3876 if (cs%split) then
3877 call find_eta(cs%h, cs%tv, g, gv, us, cs%ave_ssh_ibc, eta, dzref=g%Z_ref)
3878 else
3879 call find_eta(cs%h, cs%tv, g, gv, us, cs%ave_ssh_ibc, dzref=g%Z_ref)
3880 endif
3881 call set_initialized(cs%ave_ssh_ibc, "ave_ssh", restart_csp)
3882 endif
3883 if (cs%split) deallocate(eta)
3884
3885 cs%nstep_tot = 0
3886 if (present(count_calls)) cs%count_calls = count_calls
3887 call mom_sum_output_init(g_in, gv, us, param_file, dirs%output_directory, &
3888 cs%ntrunc, time_init, cs%sum_output_CSp)
3889
3890 ! Flag whether to save initial conditions in finish_MOM_initialization() or not.
3891 cs%write_IC = save_ic .and. &
3892 .not.((dirs%input_filename(1:1) == 'r') .and. &
3893 (len_trim(dirs%input_filename) == 1))
3894
3895 if (cs%ensemble_ocean) then
3896 call init_oda(time, g, gv, us, cs%diag, cs%odaCS)
3897 endif
3898
3899 ! initialize stochastic physics
3900 call stochastics_init(cs%dt_therm, cs%G, cs%GV, us, cs%stoch_CS, param_file, diag, time)
3901
3902 call calltree_leave("initialize_MOM()")
3903 call cpu_clock_end(id_clock_init) ; call cpu_clock_end(id_clock_ocean)
3904
3905end subroutine initialize_mom
3906
3907!> Finishes initializing MOM and writes out the initial conditions.
3908subroutine finish_mom_initialization(Time, dirs, CS)
3909 type(time_type), intent(in) :: time !< model time, used in this routine
3910 type(directories), intent(in) :: dirs !< structure with directory paths
3911 type(mom_control_struct), intent(inout) :: cs !< MOM control structure
3912
3913 type(ocean_grid_type), pointer :: g => null() ! pointer to a structure containing
3914 ! metrics and related information
3915 type(verticalgrid_type), pointer :: gv => null() ! Pointer to the vertical grid structure
3916 type(unit_scale_type), pointer :: us => null() ! Pointer to a structure containing
3917 ! various unit conversion factors
3918 type(mom_restart_cs), pointer :: restart_csp_tmp => null()
3919 real, allocatable :: z_interface(:,:,:) ! Interface heights [Z ~> m]
3920
3921 call cpu_clock_begin(id_clock_init)
3922 call calltree_enter("finish_MOM_initialization()")
3923
3924 ! Pointers for convenience
3925 g => cs%G ; gv => cs%GV ; us => cs%US
3926
3927 if (cs%use_particles) then
3928 call particles_init(cs%particles, g, cs%Time, cs%dt_therm, cs%u, cs%v, cs%h)
3929 endif
3930
3931 ! Write initial conditions
3932 if (cs%write_IC) then
3933 allocate(restart_csp_tmp)
3934 restart_csp_tmp = cs%restart_CS
3935 call restart_registry_lock(restart_csp_tmp, unlocked=.true.)
3936 allocate(z_interface(szi_(g),szj_(g),szk_(gv)+1))
3937 call find_eta(cs%h, cs%tv, g, gv, us, z_interface, dzref=g%Z_ref)
3938 call register_restart_field(z_interface, "eta", .true., restart_csp_tmp, &
3939 "Interface heights", "meter", z_grid='i', conversion=us%Z_to_m)
3940 ! NOTE: write_ic=.true. routes routine to fms2 IO write_initial_conditions interface
3941 call save_restart(dirs%output_directory, time, cs%G_in, &
3942 restart_csp_tmp, filename=cs%IC_file, gv=gv, write_ic=.true.)
3943 deallocate(z_interface)
3944 deallocate(restart_csp_tmp)
3945 endif
3946
3947 call write_energy(cs%u, cs%v, cs%h, cs%tv, time, 0, g, gv, us, &
3948 cs%sum_output_CSp, cs%tracer_flow_CSp)
3949
3950 call calltree_leave("finish_MOM_initialization()")
3951 call cpu_clock_end(id_clock_init)
3952
3953end subroutine finish_mom_initialization
3954
3955!> Register certain diagnostics
3956subroutine register_diags(Time, G, GV, US, IDs, diag)
3957 type(time_type), intent(in) :: Time !< current model time
3958 type(ocean_grid_type), intent(in) :: G !< ocean grid structure
3959 type(verticalgrid_type), intent(in) :: GV !< ocean vertical grid structure
3960 type(unit_scale_type), intent(inout) :: US !< A dimensional unit scaling type
3961 type(mom_diag_ids), intent(inout) :: IDs !< A structure with the diagnostic IDs.
3962 type(diag_ctrl), intent(inout) :: diag !< regulates diagnostic output
3963
3964 character(len=48) :: thickness_units
3965
3966 thickness_units = get_thickness_units(gv)
3967
3968 ! Diagnostics of the rapidly varying dynamic state
3969 ids%id_u = register_diag_field('ocean_model', 'u_dyn', diag%axesCuL, time, &
3970 'Zonal velocity after the dynamics update', 'm s-1', conversion=us%L_T_to_m_s)
3971 ids%id_v = register_diag_field('ocean_model', 'v_dyn', diag%axesCvL, time, &
3972 'Meridional velocity after the dynamics update', 'm s-1', conversion=us%L_T_to_m_s)
3973 ids%id_h = register_diag_field('ocean_model', 'h_dyn', diag%axesTL, time, &
3974 'Layer Thickness after the dynamics update', thickness_units, conversion=gv%H_to_MKS, &
3975 v_extensive=.true.)
3976 ids%id_ssh_inst = register_diag_field('ocean_model', 'SSH_inst', diag%axesT1, &
3977 time, 'Instantaneous Sea Surface Height', 'm', conversion=us%Z_to_m)
3978
3979end subroutine register_diags
3980
3981!> Set up CPU clock IDs for timing various subroutines.
3982subroutine mom_timing_init(CS)
3983 type(mom_control_struct), intent(in) :: CS !< control structure set up by initialize_MOM.
3984
3985 id_clock_dynamics = cpu_clock_id('Ocean dynamics', grain=clock_subcomponent)
3986 id_clock_thermo = cpu_clock_id('Ocean thermodynamics and tracers', grain=clock_subcomponent)
3987 id_clock_remap = cpu_clock_id('Ocean grid generation and remapping', grain=clock_subcomponent)
3988 id_clock_other = cpu_clock_id('Ocean Other', grain=clock_subcomponent)
3989 id_clock_mom_end = cpu_clock_id('Ocean MOM_end', grain=clock_subcomponent)
3990 id_clock_tracer = cpu_clock_id('(Ocean tracer advection)', grain=clock_module_driver)
3991 if (.not.cs%adiabatic) then
3992 id_clock_diabatic = cpu_clock_id('(Ocean diabatic driver)', grain=clock_module_driver)
3993 else
3994 id_clock_adiabatic = cpu_clock_id('(Ocean adiabatic driver)', grain=clock_module_driver)
3995 endif
3996
3997 id_clock_continuity = cpu_clock_id('(Ocean continuity equation *)', grain=clock_module)
3998 id_clock_bbl_visc = cpu_clock_id('(Ocean set BBL viscosity)', grain=clock_module)
3999 id_clock_pass = cpu_clock_id('(Ocean message passing *)', grain=clock_module)
4000 id_clock_mom_init = cpu_clock_id('(Ocean MOM_initialize_state)', grain=clock_module)
4001 id_clock_pass_init = cpu_clock_id('(Ocean init message passing *)', grain=clock_routine)
4002 if (cs%thickness_diffuse) &
4003 id_clock_thick_diff = cpu_clock_id('(Ocean thickness diffusion *)', grain=clock_module)
4004 if (cs%interface_filter) &
4005 id_clock_int_filter = cpu_clock_id('(Ocean interface height filter *)', grain=clock_module)
4006 !if (CS%mixedlayer_restrat) &
4007 id_clock_ml_restrat = cpu_clock_id('(Ocean mixed layer restrat)', grain=clock_module)
4008 id_clock_diagnostics = cpu_clock_id('(Ocean collective diagnostics)', grain=clock_module)
4009 id_clock_z_diag = cpu_clock_id('(Ocean Z-space diagnostics)', grain=clock_module)
4010 id_clock_ale = cpu_clock_id('(Ocean ALE)', grain=clock_module)
4011 if (cs%offline_tracer_mode) then
4012 id_clock_offline_tracer = cpu_clock_id('Ocean offline tracers', grain=clock_subcomponent)
4013 endif
4014 id_clock_stoch = cpu_clock_id('(Stochastic EOS)', grain=clock_module)
4015 id_clock_vart = cpu_clock_id('(SGS Temperature Variance)', grain=clock_module)
4016
4017 id_clock_save_restart = cpu_clock_id('(Ocean MOM save_restart)', grain=clock_module)
4018
4019end subroutine mom_timing_init
4020
4021!> Set the fields that are needed for bitwise identical restarting
4022!! the time stepping scheme. In addition to those specified here
4023!! directly, there may be fields related to the forcing or to the
4024!! barotropic solver that are needed; these are specified in sub-
4025!! routines that are called from this one.
4026!!
4027!! This routine should be altered if there are any changes to the
4028!! time stepping scheme. The CHECK_RESTART facility may be used to
4029!! confirm that all needed restart fields have been included.
4030subroutine set_restart_fields(GV, US, param_file, CS, restart_CSp)
4031 type(verticalgrid_type), intent(inout) :: GV !< ocean vertical grid structure
4032 type(unit_scale_type), intent(inout) :: US !< A dimensional unit scaling type
4033 type(param_file_type), intent(in) :: param_file !< opened file for parsing to get parameters
4034 type(mom_control_struct), intent(in) :: CS !< control structure set up by initialize_MOM
4035 type(mom_restart_cs), pointer :: restart_CSp !< pointer to the restart control
4036 !! structure that will be used for MOM.
4037 ! Local variables
4038 logical :: use_ice_shelf ! Needed to determine whether to add CS%Hml to restarts
4039 character(len=48) :: thickness_units, flux_units
4040 type(vardesc) :: u_desc, v_desc
4041
4042 thickness_units = get_thickness_units(gv)
4043 flux_units = get_flux_units(gv)
4044
4045 if (associated(cs%tv%T)) &
4046 call register_restart_field(cs%tv%T, "Temp", .true., restart_csp, &
4047 "Potential Temperature", "degC", conversion=us%C_to_degC)
4048 if (associated(cs%tv%S)) &
4049 call register_restart_field(cs%tv%S, "Salt", .true., restart_csp, &
4050 "Salinity", "PPT", conversion=us%S_to_ppt)
4051
4052 call register_restart_field(cs%h, "h", .true., restart_csp, &
4053 "Layer Thickness", thickness_units, conversion=gv%H_to_MKS)
4054
4055 u_desc = var_desc("u", "m s-1", "Zonal velocity", hor_grid='Cu')
4056 v_desc = var_desc("v", "m s-1", "Meridional velocity", hor_grid='Cv')
4057 call register_restart_pair(cs%u, cs%v, u_desc, v_desc, .true., restart_csp, conversion=us%L_T_to_m_s)
4058
4059 if (associated(cs%tv%frazil)) &
4060 call register_restart_field(cs%tv%frazil, "frazil", .false., restart_csp, &
4061 "Frazil heat flux into ocean", &
4062 "J m-2", conversion=us%Q_to_J_kg*us%RZ_to_kg_m2)
4063
4064 if (cs%interp_p_surf) then
4065 call register_restart_field(cs%p_surf_prev, "p_surf_prev", .false., restart_csp, &
4066 "Previous ocean surface pressure", "Pa", conversion=us%RL2_T2_to_Pa)
4067 endif
4068
4069 if (associated(cs%tv%p_surf)) &
4070 call register_restart_field(cs%tv%p_surf, "p_surf_EOS", .false., restart_csp, &
4071 "Ocean surface pressure used in EoS", "Pa", conversion=us%RL2_T2_to_Pa)
4072
4073 call register_restart_field(cs%ave_ssh_ibc, "ave_ssh", .false., restart_csp, &
4074 "Time average sea surface height", "meter", conversion=us%Z_to_m)
4075
4076 ! hML is needed when using the ice shelf module
4077 call get_param(param_file, '', "ICE_SHELF", use_ice_shelf, default=.false., &
4078 do_not_log=.true.)
4079 if (use_ice_shelf .and. associated(cs%Hml)) then
4080 call register_restart_field(cs%Hml, "hML", .false., restart_csp, &
4081 "Mixed layer thickness", "m", conversion=us%Z_to_m)
4082 endif
4083
4084 ! Register scalar unit conversion factors.
4085 call register_restart_field(cs%first_dir_restart, "First_direction", .false., restart_csp, &
4086 "Indicator of the first direction in split calculations.", "nondim")
4087
4088end subroutine set_restart_fields
4089
4090!> Apply a correction to the sea surface height to compensate
4091!! for the atmospheric pressure (the inverse barometer).
4092subroutine adjust_ssh_for_p_atm(tv, G, GV, US, ssh, p_atm, use_EOS)
4093 type(thermo_var_ptrs), intent(in) :: tv !< A structure pointing to various thermodynamic variables
4094 type(ocean_grid_type), intent(in) :: G !< ocean grid structure
4095 type(verticalgrid_type), intent(in) :: GV !< ocean vertical grid structure
4096 type(unit_scale_type), intent(in) :: US !< A dimensional unit scaling type
4097 real, dimension(SZI_(G),SZJ_(G)), intent(inout) :: ssh !< time mean surface height [Z ~> m]
4098 real, dimension(:,:), pointer :: p_atm !< Ocean surface pressure [R L2 T-2 ~> Pa]
4099 logical, intent(in) :: use_EOS !< If true, calculate the density for
4100 !! the SSH correction using the equation of state.
4101
4102 real :: Rho_conv(SZI_(G)) ! The density used to convert surface pressure to
4103 ! a corrected effective SSH [R ~> kg m-3].
4104 real :: IgR0 ! The SSH conversion factor from R L2 T-2 to Z [Z T2 R-1 L-2 ~> m Pa-1].
4105 logical :: calc_rho
4106 integer, dimension(2) :: EOSdom ! The i-computational domain for the equation of state
4107 integer :: i, j, is, ie, js, je
4108
4109 is = g%isc ; ie = g%iec ; js = g%jsc ; je = g%jec
4110 eosdom(:) = eos_domain(g%HI)
4111 if (associated(p_atm)) then
4112 calc_rho = use_eos .and. associated(tv%eqn_of_state)
4113 ! Correct the output sea surface height for the contribution from the ice pressure.
4114 do j=js,je
4115 if (calc_rho) then
4116 call calculate_density(tv%T(:,j,1), tv%S(:,j,1), 0.5*p_atm(:,j), rho_conv, &
4117 tv%eqn_of_state, eosdom)
4118 do i=is,ie
4119 igr0 = 1.0 / (rho_conv(i) * gv%g_Earth)
4120 ssh(i,j) = ssh(i,j) + p_atm(i,j) * igr0
4121 enddo
4122 else
4123 igr0 = 1.0 / (gv%Rho0 * gv%g_Earth)
4124 do i=is,ie
4125 ssh(i,j) = ssh(i,j) + p_atm(i,j) * igr0
4126 enddo
4127 endif
4128 enddo
4129 endif
4130
4131end subroutine adjust_ssh_for_p_atm
4132
4133!> Set the surface (return) properties of the ocean model by
4134!! setting the appropriate fields in sfc_state. Unused fields
4135!! are set to NULL or are unallocated.
4136subroutine extract_surface_state(CS, sfc_state_in)
4137 type(mom_control_struct), intent(inout), target :: cs !< Master MOM control structure
4138 type(surface), target, intent(inout) :: sfc_state_in !< transparent ocean surface state
4139 !! structure shared with the calling routine
4140 !! data in this structure is intent out.
4141
4142 ! Local variables
4143 real :: hu, hv ! Thicknesses interpolated to velocity points [H ~> m or kg m-2]
4144 type(ocean_grid_type), pointer :: g => null() !< pointer to a structure containing
4145 !! metrics and related information
4146 type(ocean_grid_type), pointer :: g_in => null() !< Input grid metric
4147 type(verticalgrid_type), pointer :: gv => null() !< structure containing vertical grid info
4148 type(unit_scale_type), pointer :: us => null() !< structure containing various unit conversion factors
4149 type(surface), pointer :: sfc_state => null() ! surface state on the model grid
4150 real, dimension(:,:,:), pointer :: h => null() !< h : layer thickness [H ~> m or kg m-2]
4151 real :: depth(szi_(cs%g)) !< Distance from the surface in depth units [Z ~> m] or [H ~> m or kg m-2]
4152 real :: depth_ml !< Depth over which to average to determine mixed
4153 !! layer properties [Z ~> m] or [H ~> m or kg m-2]
4154 real :: dh !< Thickness of a layer within the mixed layer [Z ~> m] or [H ~> m or kg m-2]
4155 real :: mass !< Mass per unit area of a layer [R Z ~> kg m-2]
4156 real :: i_depth !< The inverse of depth [Z-1 ~> m-1] or [H-1 ~> m-1 or m2 kg-1]
4157 real :: missing_depth !< The portion of depth_ml that can not be found in a column [H ~> m or kg m-2]
4158 real :: h_rescale !< A conversion factor from thickness units to the units used in the
4159 !! calculation of properties of the uppermost ocean [nondim] or [Z H-1 ~> 1 or m3 kg-1]
4160 ! After the ANSWERS_2018 flag has been obsoleted, H_rescale will be 1.
4161 real :: t_freeze(szi_(cs%g)) !< freezing temperature [C ~> degC]
4162 real :: pres(szi_(cs%g)) !< Pressure to use for the freezing temperature calculation [R L2 T-2 ~> Pa]
4163 real :: delt(szi_(cs%g)) !< Depth integral of T-T_freeze [H C ~> m degC or degC kg m-2]
4164 logical :: use_temperature !< If true, temperature and salinity are used as state variables.
4165 integer :: i, j, k, is, ie, js, je, nz, numberoferrors, ig, jg
4166 integer :: isd, ied, jsd, jed
4167 integer :: iscb, iecb, jscb, jecb, isdb, iedb, jsdb, jedb
4168 logical :: localerror
4169 logical :: use_iceshelves
4170 character(240) :: msg
4171 integer :: turns ! Number of quarter turns
4172
4173 call calltree_enter("extract_surface_state(), MOM.F90")
4174 g => cs%G ; g_in => cs%G_in ; gv => cs%GV ; us => cs%US
4175 is = g%isc ; ie = g%iec ; js = g%jsc ; je = g%jec ; nz = gv%ke
4176 isd = g%isd ; ied = g%ied ; jsd = g%jsd ; jed = g%jed
4177 iscb = g%iscB ; iecb = g%iecB ; jscb = g%jscB ; jecb = g%jecB
4178 isdb = g%isdB ; iedb = g%iedB ; jsdb = g%jsdB ; jedb = g%jedB
4179 h => cs%h
4180
4181 use_temperature = associated(cs%tv%T)
4182
4183 use_iceshelves=.false.
4184 if (associated(cs%frac_shelf_h)) use_iceshelves = .true.
4185
4186 turns = 0
4187 if (cs%rotate_index) &
4188 turns = g%HI%turns
4189
4190 if (.not.sfc_state_in%arrays_allocated) then
4191 ! Consider using a run-time flag to determine whether to do the vertical
4192 ! integrals, since the 3-d sums are not negligible in cost.
4193 call allocate_surface_state(sfc_state_in, g_in, use_temperature, &
4194 do_integrals=.true., omit_frazil=.not.associated(cs%tv%frazil),&
4195 use_iceshelves=use_iceshelves)
4196 endif
4197
4198 if (cs%rotate_index) then
4199 allocate(sfc_state)
4200 call allocate_surface_state(sfc_state, g, use_temperature, &
4201 do_integrals=.true., omit_frazil=.not.associated(cs%tv%frazil),&
4202 use_iceshelves=use_iceshelves, sfc_state_in=sfc_state_in, turns=turns)
4203 else
4204 sfc_state => sfc_state_in
4205 endif
4206
4207 sfc_state%T_is_conT = cs%tv%T_is_conT
4208 sfc_state%S_is_absS = cs%tv%S_is_absS
4209
4210 do j=js,je ; do i=is,ie
4211 sfc_state%sea_lev(i,j) = cs%ave_ssh_ibc(i,j)
4212 enddo ; enddo
4213
4214 if (allocated(sfc_state%frazil) .and. associated(cs%tv%frazil)) then ; do j=js,je ; do i=is,ie
4215 sfc_state%frazil(i,j) = cs%tv%frazil(i,j)
4216 enddo ; enddo ; endif
4217
4218 ! copy Hml into sfc_state, so that caps can access it
4219 do j=js,je ; do i=is,ie
4220 sfc_state%Hml(i,j) = cs%Hml(i,j)
4221 enddo ; enddo
4222
4223 if (cs%Hmix < 0.0) then ! A bulk mixed layer is in use, so layer 1 has the properties
4224 if (use_temperature) then ; do j=js,je ; do i=is,ie
4225 sfc_state%SST(i,j) = cs%tv%T(i,j,1)
4226 sfc_state%SSS(i,j) = cs%tv%S(i,j,1)
4227 enddo ; enddo ; endif
4228 do j=js,je ; do i=is-1,ie
4229 sfc_state%u(i,j) = cs%u(i,j,1)
4230 enddo ; enddo
4231 do j=js-1,je ; do i=is,ie
4232 sfc_state%v(i,j) = cs%v(i,j,1)
4233 enddo ; enddo
4234
4235 else ! (CS%Hmix >= 0.0)
4236 h_rescale = 1.0
4237 depth_ml = cs%Hmix
4238 if (cs%answer_date < 20190101) then
4239 h_rescale = gv%H_to_Z
4240 depth_ml = gv%H_to_Z*cs%Hmix
4241 endif
4242 ! Determine the mean tracer properties of the uppermost depth_ml fluid.
4243
4244 !$OMP parallel do default(shared) private(depth,dh)
4245 do j=js,je
4246 do i=is,ie
4247 depth(i) = 0.0
4248 if (use_temperature) then
4249 sfc_state%SST(i,j) = 0.0 ; sfc_state%SSS(i,j) = 0.0
4250 else
4251 sfc_state%sfc_density(i,j) = 0.0
4252 endif
4253 enddo
4254
4255 do k=1,nz ; do i=is,ie
4256 if (depth(i) + h(i,j,k)*h_rescale < depth_ml) then
4257 dh = h(i,j,k)*h_rescale
4258 elseif (depth(i) < depth_ml) then
4259 dh = depth_ml - depth(i)
4260 else
4261 dh = 0.0
4262 endif
4263 if (use_temperature) then
4264 sfc_state%SST(i,j) = sfc_state%SST(i,j) + dh * cs%tv%T(i,j,k)
4265 sfc_state%SSS(i,j) = sfc_state%SSS(i,j) + dh * cs%tv%S(i,j,k)
4266 else
4267 sfc_state%sfc_density(i,j) = sfc_state%sfc_density(i,j) + dh * gv%Rlay(k)
4268 endif
4269 depth(i) = depth(i) + dh
4270 enddo ; enddo
4271 ! Calculate the average properties of the mixed layer depth.
4272 do i=is,ie
4273 if (cs%answer_date < 20190101) then
4274 if (depth(i) < gv%H_subroundoff*h_rescale) &
4275 depth(i) = gv%H_subroundoff*h_rescale
4276 if (use_temperature) then
4277 sfc_state%SST(i,j) = sfc_state%SST(i,j) / depth(i)
4278 sfc_state%SSS(i,j) = sfc_state%SSS(i,j) / depth(i)
4279 else
4280 sfc_state%sfc_density(i,j) = sfc_state%sfc_density(i,j) / depth(i)
4281 endif
4282 else
4283 if (depth(i) < gv%H_subroundoff*h_rescale) then
4284 i_depth = 1.0 / (gv%H_subroundoff*h_rescale)
4285 missing_depth = gv%H_subroundoff*h_rescale - depth(i)
4286 if (use_temperature) then
4287 sfc_state%SST(i,j) = (sfc_state%SST(i,j) + missing_depth*cs%tv%T(i,j,1)) * i_depth
4288 sfc_state%SSS(i,j) = (sfc_state%SSS(i,j) + missing_depth*cs%tv%S(i,j,1)) * i_depth
4289 else
4290 sfc_state%sfc_density(i,j) = (sfc_state%sfc_density(i,j) + &
4291 missing_depth*gv%Rlay(1)) * i_depth
4292 endif
4293 else
4294 i_depth = 1.0 / depth(i)
4295 if (use_temperature) then
4296 sfc_state%SST(i,j) = sfc_state%SST(i,j) * i_depth
4297 sfc_state%SSS(i,j) = sfc_state%SSS(i,j) * i_depth
4298 else
4299 sfc_state%sfc_density(i,j) = sfc_state%sfc_density(i,j) * i_depth
4300 endif
4301 endif
4302 endif
4303 enddo
4304 enddo ! end of j loop
4305
4306! Determine the mean velocities in the uppermost depth_ml fluid.
4307 ! NOTE: Velocity loops start on `[ij]s-1` in order to update halo values
4308 ! required by the speed diagnostic on the non-symmetric grid.
4309 ! This assumes that u and v halos have already been updated.
4310 if (cs%Hmix_UV>0.) then
4311 depth_ml = cs%Hmix_UV
4312 if (cs%answer_date < 20190101) depth_ml = gv%H_to_Z*cs%Hmix_UV
4313 !$OMP parallel do default(shared) private(depth,dh,hv)
4314 do j=js-1,je
4315 do i=is,ie
4316 depth(i) = 0.0
4317 sfc_state%v(i,j) = 0.0
4318 enddo
4319 do k=1,nz ; do i=is,ie
4320 hv = 0.5 * (h(i,j,k) + h(i,j+1,k)) * h_rescale
4321 if (depth(i) + hv < depth_ml) then
4322 dh = hv
4323 elseif (depth(i) < depth_ml) then
4324 dh = depth_ml - depth(i)
4325 else
4326 dh = 0.0
4327 endif
4328 sfc_state%v(i,j) = sfc_state%v(i,j) + dh * cs%v(i,j,k)
4329 depth(i) = depth(i) + dh
4330 enddo ; enddo
4331 ! Calculate the average properties of the mixed layer depth.
4332 do i=is,ie
4333 sfc_state%v(i,j) = sfc_state%v(i,j) / max(depth(i), gv%H_subroundoff*h_rescale)
4334 enddo
4335 enddo ! end of j loop
4336
4337 !$OMP parallel do default(shared) private(depth,dh,hu)
4338 do j=js,je
4339 do i=is-1,ie
4340 depth(i) = 0.0
4341 sfc_state%u(i,j) = 0.0
4342 enddo
4343 do k=1,nz ; do i=is-1,ie
4344 hu = 0.5 * (h(i,j,k) + h(i+1,j,k)) * h_rescale
4345 if (depth(i) + hu < depth_ml) then
4346 dh = hu
4347 elseif (depth(i) < depth_ml) then
4348 dh = depth_ml - depth(i)
4349 else
4350 dh = 0.0
4351 endif
4352 sfc_state%u(i,j) = sfc_state%u(i,j) + dh * cs%u(i,j,k)
4353 depth(i) = depth(i) + dh
4354 enddo ; enddo
4355 ! Calculate the average properties of the mixed layer depth.
4356 do i=is-1,ie
4357 sfc_state%u(i,j) = sfc_state%u(i,j) / max(depth(i), gv%H_subroundoff*h_rescale)
4358 enddo
4359 enddo ! end of j loop
4360 else ! Hmix_UV<=0.
4361 do j=js,je ; do i=is-1,ie
4362 sfc_state%u(i,j) = cs%u(i,j,1)
4363 enddo ; enddo
4364 do j=js-1,je ; do i=is,ie
4365 sfc_state%v(i,j) = cs%v(i,j,1)
4366 enddo ; enddo
4367 endif
4368 endif ! (CS%Hmix >= 0.0)
4369
4370
4371 if (allocated(sfc_state%melt_potential)) then
4372 !$OMP parallel do default(shared) private(depth_ml, dh, T_freeze, depth, pres, delT)
4373 do j=js,je
4374 do i=is,ie
4375 depth(i) = 0.0
4376 delt(i) = 0.0
4377 pres(i) = 0.0
4378 ! Here it is assumed that p=0 is OK, since HFrz ~ 10 to 20m, but under ice-shelves this
4379 ! can be a very bad assumption. ###To fix this, uncomment the following...
4380 ! pres(i) = p_surface(i) + 0.5*(GV%g_Earth*GV%H_to_RZ)*h(i,j,1)
4381 enddo
4382
4383 do k=1,nz
4384 call calculate_tfreeze(cs%tv%S(is:ie,j,k), pres(is:ie), t_freeze(is:ie), cs%tv%eqn_of_state)
4385 do i=is,ie
4386 depth_ml = min(cs%HFrz, cs%visc%h_ML(i,j))
4387 if (depth(i) + h(i,j,k) < depth_ml) then
4388 dh = h(i,j,k)
4389 elseif (depth(i) < depth_ml) then
4390 dh = depth_ml - depth(i)
4391 else
4392 dh = 0.0
4393 endif
4394
4395 depth(i) = depth(i) + dh
4396 delt(i) = delt(i) + dh * (cs%tv%T(i,j,k) - t_freeze(i))
4397 enddo
4398 ! If there is a pressure-dependent freezing point calculation uncomment the following.
4399 ! if (k<nz) then ; do i=is,ie
4400 ! pres(i) = pres(i) + 0.5*(GV%g_Earth*GV%H_to_RZ) * (h(i,j,k) + h(i,j,k+1))
4401 ! enddo ; endif
4402 enddo
4403
4404 do i=is,ie
4405 ! set melt_potential to zero to avoid passing previous values
4406 sfc_state%melt_potential(i,j) = 0.0
4407
4408 if (g%mask2dT(i,j)>0.) then
4409 ! instantaneous melt_potential [Q R Z ~> J m-2]
4410 sfc_state%melt_potential(i,j) = cs%tv%C_p * gv%H_to_RZ * delt(i)
4411 endif
4412 enddo
4413 enddo ! end of j loop
4414 endif ! melt_potential
4415
4416 if (allocated(sfc_state%taux_shelf) .and. allocated(cs%visc%taux_shelf)) then
4417 !$OMP parallel do default(shared)
4418 do j=js,je ; do i=is-1,ie
4419 sfc_state%taux_shelf(i,j) = cs%visc%taux_shelf(i,j)
4420 enddo ; enddo
4421 endif
4422 if (allocated(sfc_state%tauy_shelf) .and. allocated(cs%visc%tauy_shelf)) then
4423 !$OMP parallel do default(shared)
4424 do j=js-1,je ; do i=is,ie
4425 sfc_state%tauy_shelf(i,j) = cs%visc%tauy_shelf(i,j)
4426 enddo ; enddo
4427 endif
4428
4429 if (allocated(sfc_state%ocean_mass) .and. allocated(sfc_state%ocean_heat) .and. &
4430 allocated(sfc_state%ocean_salt)) then
4431 !$OMP parallel do default(shared)
4432 do j=js,je ; do i=is,ie
4433 sfc_state%ocean_mass(i,j) = 0.0
4434 sfc_state%ocean_heat(i,j) = 0.0 ; sfc_state%ocean_salt(i,j) = 0.0
4435 enddo ; enddo
4436 !$OMP parallel do default(shared) private(mass)
4437 do j=js,je ; do k=1,nz ; do i=is,ie
4438 mass = gv%H_to_RZ*h(i,j,k)
4439 sfc_state%ocean_mass(i,j) = sfc_state%ocean_mass(i,j) + mass
4440 sfc_state%ocean_heat(i,j) = sfc_state%ocean_heat(i,j) + mass * cs%tv%T(i,j,k)
4441 sfc_state%ocean_salt(i,j) = sfc_state%ocean_salt(i,j) + mass * (1.0e-3*cs%tv%S(i,j,k))
4442 enddo ; enddo ; enddo
4443 else
4444 if (allocated(sfc_state%ocean_mass)) then
4445 !$OMP parallel do default(shared)
4446 do j=js,je ; do i=is,ie ; sfc_state%ocean_mass(i,j) = 0.0 ; enddo ; enddo
4447 !$OMP parallel do default(shared)
4448 do j=js,je ; do k=1,nz ; do i=is,ie
4449 sfc_state%ocean_mass(i,j) = sfc_state%ocean_mass(i,j) + gv%H_to_RZ*h(i,j,k)
4450 enddo ; enddo ; enddo
4451 endif
4452 if (allocated(sfc_state%ocean_heat)) then
4453 !$OMP parallel do default(shared)
4454 do j=js,je ; do i=is,ie ; sfc_state%ocean_heat(i,j) = 0.0 ; enddo ; enddo
4455 !$OMP parallel do default(shared) private(mass)
4456 do j=js,je ; do k=1,nz ; do i=is,ie
4457 mass = gv%H_to_RZ*h(i,j,k)
4458 sfc_state%ocean_heat(i,j) = sfc_state%ocean_heat(i,j) + mass * cs%tv%T(i,j,k)
4459 enddo ; enddo ; enddo
4460 endif
4461 if (allocated(sfc_state%ocean_salt)) then
4462 !$OMP parallel do default(shared)
4463 do j=js,je ; do i=is,ie ; sfc_state%ocean_salt(i,j) = 0.0 ; enddo ; enddo
4464 !$OMP parallel do default(shared) private(mass)
4465 do j=js,je ; do k=1,nz ; do i=is,ie
4466 mass = gv%H_to_RZ*h(i,j,k)
4467 sfc_state%ocean_salt(i,j) = sfc_state%ocean_salt(i,j) + mass * (1.0e-3*cs%tv%S(i,j,k))
4468 enddo ; enddo ; enddo
4469 endif
4470 endif
4471
4472 if (associated(cs%tracer_flow_CSp)) then
4473 call call_tracer_surface_state(sfc_state, h, g, gv, us, cs%tracer_flow_CSp)
4474 endif
4475
4476 if (cs%check_bad_sfc_vals) then
4477 numberoferrors=0 ! count number of errors
4478 do j=js,je ; do i=is,ie
4479 if (g%mask2dT(i,j)>0.) then
4480 localerror = sfc_state%sea_lev(i,j) < -g%bathyT(i,j) - g%Z_ref &
4481 .or. sfc_state%sea_lev(i,j) >= cs%bad_val_ssh_max + (g%meanSL(i,j) - g%Z_ref) &
4482 .or. sfc_state%sea_lev(i,j) <= -cs%bad_val_ssh_max + (g%meanSL(i,j) - g%Z_ref) &
4483 .or. sfc_state%sea_lev(i,j) + g%bathyT(i,j) + g%Z_ref < cs%bad_val_col_thick
4484 if (use_temperature) localerror = localerror &
4485 .or. sfc_state%SSS(i,j)<0. &
4486 .or. sfc_state%SSS(i,j)>=cs%bad_val_sss_max &
4487 .or. sfc_state%SST(i,j)< cs%bad_val_sst_min &
4488 .or. sfc_state%SST(i,j)>=cs%bad_val_sst_max
4489 if (localerror) then
4490 numberoferrors=numberoferrors+1
4491 if (numberoferrors<9) then ! Only report details for the first few errors
4492 ig = i + g%HI%idg_offset ! Global i-index
4493 jg = j + g%HI%jdg_offset ! Global j-index
4494 if (use_temperature) then
4495 write(msg(1:240),'(2(a,I0,1x),4(a,f8.3,1x),8(a,es11.4,1x))') &
4496 'Extreme surface sfc_state detected: i=',ig,'j=',jg, &
4497 'lon=',g%geoLonT(i,j), 'lat=',g%geoLatT(i,j), &
4498 'x=',g%gridLonT(ig), 'y=',g%gridLatT(jg), &
4499 'D=',us%Z_to_m*(g%bathyT(i,j)+g%Z_ref), 'SSH=',us%Z_to_m*sfc_state%sea_lev(i,j), &
4500 'SST=',us%C_to_degC*sfc_state%SST(i,j), 'SSS=',us%S_to_ppt*sfc_state%SSS(i,j), &
4501 'U-=',us%L_T_to_m_s*sfc_state%u(i-1,j), 'U+=',us%L_T_to_m_s*sfc_state%u(i,j), &
4502 'V-=',us%L_T_to_m_s*sfc_state%v(i,j-1), 'V+=',us%L_T_to_m_s*sfc_state%v(i,j)
4503 else
4504 write(msg(1:240),'(2(a,I0,1x),4(a,f8.3,1x),6(a,es11.4))') &
4505 'Extreme surface sfc_state detected: i=',ig,'j=',jg, &
4506 'lon=',g%geoLonT(i,j), 'lat=',g%geoLatT(i,j), &
4507 'x=',g%gridLonT(ig), 'y=',g%gridLatT(jg), &
4508 'D=',us%Z_to_m*(g%bathyT(i,j)+g%Z_ref), 'SSH=',us%Z_to_m*sfc_state%sea_lev(i,j), &
4509 'U-=',us%L_T_to_m_s*sfc_state%u(i-1,j), 'U+=',us%L_T_to_m_s*sfc_state%u(i,j), &
4510 'V-=',us%L_T_to_m_s*sfc_state%v(i,j-1), 'V+=',us%L_T_to_m_s*sfc_state%v(i,j)
4511 endif
4512 call mom_error(warning, trim(msg), all_print=.true.)
4513 elseif (numberoferrors==9) then ! Indicate once that there are more errors
4514 call mom_error(warning, 'There were more unreported extreme events!', all_print=.true.)
4515 endif ! numberOfErrors
4516 endif ! localError
4517 endif ! mask2dT
4518 enddo ; enddo
4519 call sum_across_pes(numberoferrors)
4520 if (numberoferrors>0) then
4521 write(msg(1:240),'(a,i0,a)') 'There were a total of ',numberoferrors, &
4522 ' locations detected with extreme surface values!'
4523 call mom_error(fatal, trim(msg))
4524 endif
4525 endif
4526
4527 if (cs%debug) call mom_surface_chksum("Post extract_sfc", sfc_state, g, us, haloshift=0, symmetric=.true.)
4528
4529 ! Rotate sfc_state back onto the input grid, sfc_state_in
4530 if (cs%rotate_index) then
4531 call rotate_surface_state(sfc_state, sfc_state_in, g_in, -turns)
4532 call deallocate_surface_state(sfc_state)
4533 endif
4534
4535 call calltree_leave("extract_surface_sfc_state()")
4536end subroutine extract_surface_state
4537
4538!> Rotate initialization fields from input to rotated arrays.
4539subroutine rotate_initial_state(u_in, v_in, h_in, T_in, S_in, &
4540 use_temperature, turns, u, v, h, T, S)
4541 real, dimension(:,:,:), intent(in) :: u_in !< Zonal velocity on the initial grid [L T-1 ~> m s-1]
4542 real, dimension(:,:,:), intent(in) :: v_in !< Meridional velocity on the initial grid [L T-1 ~> m s-1]
4543 real, dimension(:,:,:), intent(in) :: h_in !< Layer thickness on the initial grid [H ~> m or kg m-2]
4544 real, dimension(:,:,:), intent(in) :: T_in !< Temperature on the initial grid [C ~> degC]
4545 real, dimension(:,:,:), intent(in) :: S_in !< Salinity on the initial grid [S ~> ppt]
4546 logical, intent(in) :: use_temperature !< If true, temperature and salinity are active
4547 integer, intent(in) :: turns !< The number quarter-turns to apply
4548 real, dimension(:,:,:), intent(out) :: u !< Zonal velocity on the rotated grid [L T-1 ~> m s-1]
4549 real, dimension(:,:,:), intent(out) :: v !< Meridional velocity on the rotated grid [L T-1 ~> m s-1]
4550 real, dimension(:,:,:), intent(out) :: h !< Layer thickness on the rotated grid [H ~> m or kg m-2]
4551 real, dimension(:,:,:), intent(out) :: T !< Temperature on the rotated grid [C ~> degC]
4552 real, dimension(:,:,:), intent(out) :: S !< Salinity on the rotated grid [S ~> ppt]
4553
4554 call rotate_vector(u_in, v_in, turns, u, v)
4555 call rotate_array(h_in, turns, h)
4556 if (use_temperature) then
4557 call rotate_array(t_in, turns, t)
4558 call rotate_array(s_in, turns, s)
4559 endif
4560end subroutine rotate_initial_state
4561
4562!> Return true if all phases of step_MOM are at the same point in time.
4563function mom_state_is_synchronized(CS, adv_dyn) result(in_synch)
4564 type(mom_control_struct), intent(inout) :: cs !< MOM control structure
4565 logical, optional, intent(in) :: adv_dyn !< If present and true, only check
4566 !! whether the advection is up-to-date with
4567 !! the dynamics.
4568 logical :: in_synch !< True if all phases of the update are synchronized.
4569
4570 logical :: adv_only
4571
4572 adv_only = .false. ; if (present(adv_dyn)) adv_only = adv_dyn
4573
4574 if (adv_only) then
4575 in_synch = (cs%t_dyn_rel_adv == 0.0)
4576 else
4577 in_synch = ((cs%t_dyn_rel_adv == 0.0) .and. (cs%t_dyn_rel_thermo == 0.0))
4578 endif
4579
4580end function mom_state_is_synchronized
4581
4582!> This subroutine offers access to values or pointers to other types from within
4583!! the MOM_control_struct, allowing the MOM_control_struct to be opaque.
4584subroutine get_mom_state_elements(CS, G, GV, US, C_p, C_p_scaled, use_temp)
4585 type(mom_control_struct), intent(inout), target :: cs !< MOM control structure
4586 type(ocean_grid_type), optional, pointer :: g !< structure containing metrics and grid info
4587 type(verticalgrid_type), optional, pointer :: gv !< structure containing vertical grid info
4588 type(unit_scale_type), optional, pointer :: us !< A dimensional unit scaling type
4589 real, optional, intent(out) :: c_p !< The heat capacity [J kg degC-1]
4590 real, optional, intent(out) :: c_p_scaled !< The heat capacity in scaled
4591 !! units [Q C-1 ~> J kg-1 degC-1]
4592 logical, optional, intent(out) :: use_temp !< True if temperature is a state variable
4593
4594 if (present(g)) g => cs%G_in
4595 if (present(gv)) gv => cs%GV
4596 if (present(us)) us => cs%US
4597 if (present(c_p)) c_p = cs%US%Q_to_J_kg*us%degC_to_C * cs%tv%C_p
4598 if (present(c_p_scaled)) c_p_scaled = cs%tv%C_p
4599 if (present(use_temp)) use_temp = associated(cs%tv%T)
4600end subroutine get_mom_state_elements
4601
4602!> Find the global integrals of various quantities.
4603subroutine get_ocean_stocks(CS, mass, heat, salt, on_PE_only)
4604 type(mom_control_struct), intent(inout) :: cs !< MOM control structure
4605 real, optional, intent(out) :: heat !< The globally integrated integrated ocean heat [J].
4606 real, optional, intent(out) :: salt !< The globally integrated integrated ocean salt [kg].
4607 real, optional, intent(out) :: mass !< The globally integrated integrated ocean mass [kg].
4608 logical, optional, intent(in) :: on_pe_only !< If present and true, only sum on the local PE.
4609
4610 if (present(mass)) &
4611 mass = global_mass_integral(cs%h, cs%G, cs%GV, on_pe_only=on_pe_only)
4612 if (present(heat)) &
4613 heat = cs%US%Q_to_J_kg*cs%US%RZL2_to_kg * cs%tv%C_p * &
4614 global_mass_integral(cs%h, cs%G, cs%GV, cs%tv%T, on_pe_only=on_pe_only, tmp_scale=cs%US%C_to_degC)
4615 if (present(salt)) &
4616 salt = 1.0e-3 * global_mass_integral(cs%h, cs%G, cs%GV, cs%tv%S, on_pe_only=on_pe_only, unscale=cs%US%S_to_ppt)
4617
4618end subroutine get_ocean_stocks
4619
4620
4621!> Save restart/pickup files required to initialize the MOM6 internal state.
4622subroutine save_mom_restart(CS, directory, time, G, time_stamped, filename, &
4623 GV, num_rest_files, write_IC)
4624 type(mom_control_struct), intent(inout) :: cs
4625 !< MOM control structure
4626 character(len=*), intent(in) :: directory
4627 !< The directory where the restart files are to be written
4628 type(time_type), intent(in) :: time
4629 !< The current model time
4630 type(ocean_grid_type), intent(inout) :: g
4631 !< The ocean's grid structure
4632 logical, optional, intent(in) :: time_stamped
4633 !< If present and true, add time-stamp to the restart file names
4634 character(len=*), optional, intent(in) :: filename
4635 !< A filename that overrides the name in CS%restartfile
4636 type(verticalgrid_type), optional, intent(in) :: gv
4637 !< The ocean's vertical grid structure
4638 integer, optional, intent(out) :: num_rest_files
4639 !< number of restart files written
4640 logical, optional, intent(in) :: write_ic
4641 !< If present and true, initial conditions are being written
4642
4643 logical :: showcalltree
4644 showcalltree = calltree_showquery()
4645
4646 call cpu_clock_begin(id_clock_ocean) ; call cpu_clock_begin(id_clock_save_restart)
4647 if (showcalltree) call calltree_waypoint("About to call save_restart (step_MOM)")
4648 call save_restart(directory, time, g, cs%restart_CS, &
4649 time_stamped=time_stamped, filename=filename, gv=gv, &
4650 num_rest_files=num_rest_files, write_ic=write_ic)
4651 if (showcalltree) call calltree_waypoint("Done with call to save_restart (step_MOM)")
4652
4653 if (cs%use_particles) call particles_save_restart(cs%particles, cs%h, directory, time, time_stamped)
4654 call cpu_clock_end(id_clock_save_restart) ; call cpu_clock_end(id_clock_ocean)
4655end subroutine save_mom_restart
4656
4657
4658!> End of ocean model, including memory deallocation
4659subroutine mom_end(CS)
4660 type(mom_control_struct), intent(inout) :: cs !< MOM control structure
4661
4662 call cpu_clock_begin(id_clock_ocean) ; call cpu_clock_begin(id_clock_mom_end)
4663
4664 call mom_sum_output_end(cs%sum_output_CSp)
4665
4666 if (cs%use_ALE_algorithm) call ale_end(cs%ALE_CSp)
4667
4668 !deallocate porous topography variables
4669 deallocate(cs%pbv%por_face_areaU) ; deallocate(cs%pbv%por_face_areaV)
4670 deallocate(cs%pbv%por_layer_widthU) ; deallocate(cs%pbv%por_layer_widthV)
4671
4672 ! NOTE: Allocated in PressureForce_FV_Bouss
4673 if (associated(cs%tv%varT)) deallocate(cs%tv%varT)
4674
4675 call tracer_advect_end(cs%tracer_adv_CSp)
4676 call tracer_hor_diff_end(cs%tracer_diff_CSp)
4677 call tracer_registry_end(cs%tracer_Reg)
4678 call tracer_flow_control_end(cs%tracer_flow_CSp)
4679
4680 if (.not. cs%adiabatic) then
4681 call diabatic_driver_end(cs%diabatic_CSp)
4682 deallocate(cs%diabatic_CSp)
4683 endif
4684
4685 call mom_diagnostics_end(cs%diagnostics_CSp, cs%ADp, cs%CDp)
4686
4687 if (cs%offline_tracer_mode) call offline_transport_end(cs%offline_CSp)
4688
4689 if (cs%split .and. cs%use_alt_split) then
4690 call end_dyn_split_rk2b(cs%dyn_split_RK2b_CSp)
4691 elseif (cs%split) then
4692 call end_dyn_split_rk2(cs%dyn_split_RK2_CSp)
4693 elseif (cs%use_RK2) then
4694 call end_dyn_unsplit_rk2(cs%dyn_unsplit_RK2_CSp)
4695 else
4696 call end_dyn_unsplit(cs%dyn_unsplit_CSp)
4697 endif
4698
4699 if (cs%use_particles) then
4700 call particles_end(cs%particles, cs%h)
4701 deallocate(cs%particles)
4702 endif
4703
4704 call thickness_diffuse_end(cs%thickness_diffuse_CSp, cs%CDp)
4705 if (cs%interface_filter) call interface_filter_end(cs%interface_filter_CSp, cs%CDp)
4706 call varmix_end(cs%VarMix)
4707 call set_visc_end(cs%visc, cs%set_visc_CSp)
4708 call meke_end(cs%MEKE)
4709
4710 if (associated(cs%tv%internal_heat)) deallocate(cs%tv%internal_heat)
4711 if (associated(cs%tv%TempxPmE)) deallocate(cs%tv%TempxPmE)
4712
4713 dealloc_(cs%ave_ssh_ibc) ; dealloc_(cs%ssh_rint) ; dealloc_(cs%eta_av_bc)
4714
4715 ! TODO: debug_truncations deallocation
4716
4717 dealloc_(cs%uhtr) ; dealloc_(cs%vhtr)
4718
4719 if (allocated(cs%uhtr_resolved)) deallocate(cs%uhtr_resolved)
4720 if (allocated(cs%vhtr_resolved)) deallocate(cs%vhtr_resolved)
4721
4722 if (associated(cs%Hml)) deallocate(cs%Hml)
4723 if (associated(cs%tv%salt_deficit)) deallocate(cs%tv%salt_deficit)
4724 if (associated(cs%tv%frazil)) deallocate(cs%tv%frazil)
4725 if (allocated(cs%tv%SpV_avg)) deallocate(cs%tv%SpV_avg)
4726
4727 if (associated(cs%tv%T)) then
4728 dealloc_(cs%T) ; cs%tv%T => null() ; dealloc_(cs%S) ; cs%tv%S => null()
4729 endif
4730
4731 dealloc_(cs%u) ; dealloc_(cs%v) ; dealloc_(cs%h)
4732 dealloc_(cs%uh) ; dealloc_(cs%vh)
4733
4734 if (associated(cs%update_OBC_CSp)) call obc_register_end(cs%update_OBC_CSp)
4735 if (associated(cs%OBC)) call open_boundary_end(cs%OBC)
4736
4737 call verticalgridend(cs%GV)
4738 call mom_grid_end(cs%G)
4739
4740 if (cs%debug .or. cs%G%symmetric) &
4741 call deallocate_mom_domain(cs%G%Domain_aux)
4742
4743 if (cs%rotate_index) &
4744 call deallocate_mom_domain(cs%G%Domain)
4745
4746 ! The MPP domains may be needed by an external coupler, so use `cursory`.
4747 ! TODO: This may create a domain memory leak, and needs investigation.
4748 call deallocate_mom_domain(cs%G_in%domain, cursory=.true.)
4749
4750 call unit_scaling_end(cs%US)
4751
4752 call cpu_clock_end(id_clock_mom_end) ; call cpu_clock_end(id_clock_ocean)
4753
4754end subroutine mom_end
4755
4756!> \namespace mom
4757!!
4758!! Modular Ocean Model (MOM) Version 6.0 (MOM6)
4759!!
4760!! \authors Alistair Adcroft, Robert Hallberg, and Stephen Griffies
4761!!
4762!! Additional contributions from:
4763!! * Whit Anderson
4764!! * Brian Arbic
4765!! * Will Cooke
4766!! * Anand Gnanadesikan
4767!! * Matthew Harrison
4768!! * Mehmet Ilicak
4769!! * Laura Jackson
4770!! * Jasmine John
4771!! * John Krasting
4772!! * Zhi Liang
4773!! * Bonnie Samuels
4774!! * Harper Simmons
4775!! * Laurent White
4776!! * Niki Zadeh
4777!!
4778!! MOM ice-shelf code was developed by
4779!! * Daniel Goldberg
4780!! * Robert Hallberg
4781!! * Chris Little
4782!! * Olga Sergienko
4783!!
4784!! \section section_overview Overview of MOM
4785!!
4786!! This program (MOM) simulates the ocean by numerically solving
4787!! the hydrostatic primitive equations in generalized Lagrangian
4788!! vertical coordinates, typically tracking stretched pressure (p*)
4789!! surfaces or following isopycnals in the ocean's interior, and
4790!! general orthogonal horizontal coordinates. Unlike earlier versions
4791!! of MOM, in MOM6 these equations are horizontally discretized on an
4792!! Arakawa C-grid. (It remains to be seen whether a B-grid dynamic
4793!! core will be revived in MOM6 at a later date; for now applications
4794!! requiring a B-grid discretization should use MOM5.1.) MOM6 offers
4795!! a range of options for the physical parameterizations, from those
4796!! most appropriate to highly idealized models for geophysical fluid
4797!! dynamics studies to a rich suite of processes appropriate for
4798!! realistic ocean simulations. The thermodynamic options typically
4799!! use conservative temperature and preformed salinity as conservative
4800!! state variables and a full nonlinear equation of state, but there
4801!! are also idealized adiabatic configurations of the model that use
4802!! fixed density layers. Version 6.0 of MOM continues in the long
4803!! tradition of a commitment to climate-quality ocean simulations
4804!! embodied in previous versions of MOM, even as it draws extensively
4805!! on the lessons learned in the development of the Generalized Ocean
4806!! Layered Dynamics (GOLD) ocean model, which was also primarily
4807!! developed at NOAA/GFDL. MOM has also benefited tremendously from
4808!! the FMS infrastructure, which it utilizes and shares with other
4809!! component models developed at NOAA/GFDL.
4810!!
4811!! When run is isopycnal-coordinate mode, the uppermost few layers
4812!! are often used to describe a bulk mixed layer, including the
4813!! effects of penetrating shortwave radiation. Either a split-
4814!! explicit time stepping scheme or a non-split scheme may be used
4815!! for the dynamics, while the time stepping may be split (and use
4816!! different numbers of steps to cover the same interval) for the
4817!! forcing, the thermodynamics, and for the dynamics. Most of the
4818!! numerics are second order accurate in space. MOM can run with an
4819!! absurdly thin minimum layer thickness. A variety of non-isopycnal
4820!! vertical coordinate options are under development, but all exploit
4821!! the advantages of a Lagrangian vertical coordinate, as discussed
4822!! in detail by Adcroft and Hallberg (Ocean Modelling, 2006).
4823!!
4824!! Details of the numerics and physical parameterizations are
4825!! provided in the appropriate source files. All of the available
4826!! options are selected at run-time by parsing the input files,
4827!! usually MOM_input and MOM_override, and the options choices are
4828!! then documented for each run in MOM_param_docs.
4829!!
4830!! MOM6 integrates the equations forward in time in three distinct
4831!! phases. In one phase, the dynamic equations for the velocities
4832!! and layer thicknesses are advanced, capturing the propagation of
4833!! external and internal inertia-gravity waves, Rossby waves, and
4834!! other strictly adiabatic processes, including lateral stresses,
4835!! vertical viscosity and momentum forcing, and interface height
4836!! diffusion (commonly called Gent-McWilliams diffusion in depth-
4837!! coordinate models). In the second phase, all tracers are advected
4838!! and diffused along the layers. The third phase applies diabatic
4839!! processes, vertical mixing of water properties, and perhaps
4840!! vertical remapping to cause the layers to track the desired
4841!! vertical coordinate.
4842!!
4843!! The present file (MOM.F90) orchestrates the main time stepping
4844!! loops. One time integration option for the dynamics uses a split
4845!! explicit time stepping scheme to rapidly step the barotropic
4846!! pressure and velocity fields. The barotropic velocities are
4847!! averaged over the baroclinic time step before they are used to
4848!! advect thickness and determine the baroclinic accelerations. As
4849!! described in Hallberg and Adcroft (2009), a barotropic correction
4850!! is applied to the time-mean layer velocities to ensure that the
4851!! sum of the layer transports agrees with the time-mean barotropic
4852!! transport, thereby ensuring that the estimates of the free surface
4853!! from the sum of the layer thicknesses agrees with the final free
4854!! surface height as calculated by the barotropic solver. The
4855!! barotropic and baroclinic velocities are kept consistent by
4856!! recalculating the barotropic velocities from the baroclinic
4857!! transports each time step. This scheme is described in Hallberg,
4858!! 1997, J. Comp. Phys. 135, 54-65 and in Hallberg and Adcroft, 2009,
4859!! Ocean Modelling, 29, 15-26.
4860!!
4861!! The other time integration options use non-split time stepping
4862!! schemes based on the 3-step third order Runge-Kutta scheme
4863!! described in Matsuno, 1966, J. Met. Soc. Japan, 44, 85-88, or on
4864!! a two-step quasi-2nd order Runge-Kutta scheme. These are much
4865!! slower than the split time-stepping scheme, but they are useful
4866!! for providing a more robust solution for debugging cases where the
4867!! more complicated split time-stepping scheme may be giving suspect
4868!! solutions.
4869!!
4870!! There are a range of closure options available. Horizontal
4871!! velocities are subject to a combination of horizontal biharmonic
4872!! and Laplacian friction (based on a stress tensor formalism) and a
4873!! vertical Fickian viscosity (perhaps using the kinematic viscosity
4874!! of water). The horizontal viscosities may be constant, spatially
4875!! varying or may be dynamically calculated using Smagorinsky's
4876!! approach. A diapycnal diffusion of density and thermodynamic
4877!! quantities is also allowed, but not required, as is horizontal
4878!! diffusion of interface heights (akin to the Gent-McWilliams
4879!! closure of geopotential coordinate models). The diapycnal mixing
4880!! may use a fixed diffusivity or it may use the shear Richardson
4881!! number dependent closure, like that described in Jackson et al.
4882!! (JPO, 2008). When there is diapycnal diffusion, it applies to
4883!! momentum as well. As this is in addition to the vertical viscosity,
4884!! the vertical Prandtl always exceeds 1. A refined bulk-mixed layer
4885!! is often used to describe the planetary boundary layer in realistic
4886!! ocean simulations.
4887!!
4888!! MOM has a number of noteworthy debugging capabilities.
4889!! Excessively large velocities are truncated and MOM will stop
4890!! itself after a number of such instances to keep the model from
4891!! crashing altogether. This is useful in diagnosing failures,
4892!! or (by accepting some truncations) it may be useful for getting
4893!! the model past the adjustment from an ill-balanced initial
4894!! condition. In addition, all of the accelerations in the columns
4895!! with excessively large velocities may be directed to a text file.
4896!! Parallelization errors may be diagnosed using the DEBUG option,
4897!! which causes extensive checksums to be written out along with
4898!! comments indicating where in the algorithm the sums originate and
4899!! what variable is being summed. The point where these checksums
4900!! differ between runs is usually a good indication of where in the
4901!! code the problem lies. All of the test cases provided with MOM
4902!! are routinely tested to ensure that they give bitwise identical
4903!! results regardless of the domain decomposition, or whether they
4904!! use static or dynamic memory allocation.
4905!!
4906!! \section section_structure Structure of MOM
4907!!
4908!! About 115 other files of source code and 4 header files comprise
4909!! the MOM code, although there are several hundred more files that
4910!! make up the FMS infrastructure upon which MOM is built. Each of
4911!! the MOM files contains comments documenting what it does, and
4912!! most of the file names are fairly self-evident. In addition, all
4913!! subroutines and data types are referenced via a module use, only
4914!! statement, and the module names are consistent with the file names,
4915!! so it is not too hard to find the source file for a subroutine.
4916!!
4917!! The typical MOM directory tree is as follows:
4918!!
4919!! \verbatim
4920!! ../MOM
4921!! |-- ac
4922!! |-- config_src
4923!! | |-- drivers
4924!! | ! |-- FMS_cap
4925!! | ! |-- ice_solo_driver
4926!! | ! |-- mct_cap
4927!! | ! |-- nuopc_cap
4928!! | ! |-- solo_driver
4929!! | ! `-- unit_drivers
4930!! | |-- external
4931!! | ! |-- drifters
4932!! | ! |-- GFDL_ocean_BGC
4933!! | ! `-- ODA_hooks
4934!! | |-- infra
4935!! | ! |-- FMS1
4936!! | ! `-- FMS2
4937!! | `-- memory
4938!! | ! |-- dynamic_nonsymmetric
4939!! | ! `-- dynamic_symmetric
4940!! |-- docs
4941!! |-- pkg
4942!! | |-- CVMix-src
4943!! | |-- ...
4944!! | `-- MOM6_DA_hooks
4945!! `-- src
4946!! |-- ALE
4947!! |-- core
4948!! |-- diagnostics
4949!! |-- equation_of_state
4950!! |-- framework
4951!! |-- ice_shelf
4952!! |-- initialization
4953!! |-- ocean_data_assim
4954!! |-- parameterizations
4955!! | |-- CVMix
4956!! | |-- lateral
4957!! | `-- vertical
4958!! |-- tracer
4959!! `-- user
4960!! \endverbatim
4961!!
4962!! Rather than describing each file here, selected directory contents
4963!! will be described to give a broad overview of the MOM code
4964!! structure.
4965!!
4966!! The directories under config_src contain files that are used for
4967!! configuring the code, for instance for coupled or ocean-only runs.
4968!! Only one or two of these directories are used in compiling any,
4969!! particular run.
4970!!
4971!! * config_src/drivers/FMS-cap:
4972!! The files here are used to couple MOM as a component in a larger
4973!! run driven by the FMS coupler. This includes code that converts
4974!! various forcing fields into the code structures and flux and unit
4975!! conventions used by MOM, and converts the MOM surface fields
4976!! back to the forms used by other FMS components.
4977!!
4978!! * config_src/drivers/nuopc-cap:
4979!! The files here are used to couple MOM as a component in a larger
4980!! run driven by the NUOPC coupler. This includes code that converts
4981!! various forcing fields into the code structures and flux and unit
4982!! conventions used by MOM, and converts the MOM surface fields
4983!! back to the forms used by other NUOPC components.
4984!!
4985!! * config_src/drivers/solo_driver:
4986!! The files here are include the _main driver that is used when
4987!! MOM is configured as an ocean-only model, as well as the files
4988!! that specify the surface forcing in this configuration.
4989!!
4990!! * config_src/external:
4991!! The files here are mostly just stubs, so that MOM6 can compile
4992!! with calls to the public interfaces external packages, but
4993!! without actually requiring those packages themselves. In more
4994!! elaborate configurations, would be linked to the actual code for
4995!! those external packages rather than these simple stubs.
4996!!
4997!! * config_src/memory/dynamic-symmetric:
4998!! The only file here is the version of MOM_memory.h that is used
4999!! for dynamic memory configurations of MOM.
5000!!
5001!! The directories under src contain most of the MOM files. These
5002!! files are used in every configuration using MOM.
5003!!
5004!! * src/core:
5005!! The files here constitute the MOM dynamic core. This directory
5006!! also includes files with the types that describe the model's
5007!! lateral grid and have defined types that are shared across
5008!! various MOM modules to allow for more succinct and flexible
5009!! subroutine argument lists.
5010!!
5011!! * src/diagnostics:
5012!! The files here calculate various diagnostics that are ancilliary
5013!! to the model itself. While most of these diagnostics do not
5014!! directly affect the model's solution, there are some, like the
5015!! calculation of the deformation radius, that are used in some
5016!! of the process parameterizations.
5017!!
5018!! * src/equation_of_state:
5019!! These files describe the physical properties of sea-water,
5020!! including both the equation of state and when it freezes.
5021!!
5022!! * src/framework:
5023!! These files provide infrastructure utilities for MOM. Many are
5024!! simply wrappers for capabilities provided by FMS, although others
5025!! provide capabilities (like the file_parser) that are unique to
5026!! MOM. When MOM is adapted to use a modeling infrastructure
5027!! distinct from FMS, most of the required changes are in this
5028!! directory.
5029!!
5030!! * src/initialization:
5031!! These are the files that are used to initialize the MOM grid
5032!! or provide the initial physical state for MOM. These files are
5033!! not intended to be modified, but provide a means for calling
5034!! user-specific initialization code like the examples in src/user.
5035!!
5036!! * src/parameterizations/lateral:
5037!! These files implement a number of quasi-lateral (along-layer)
5038!! process parameterizations, including lateral viscosities,
5039!! parameterizations of eddy effects, and the calculation of tidal
5040!! forcing.
5041!!
5042!! * src/parameterizations/vertical:
5043!! These files implement a number of vertical mixing or diabatic
5044!! processes, including the effects of vertical viscosity and
5045!! code to parameterize the planetary boundary layer. There is a
5046!! separate driver that orchestrates this portion of the algorithm,
5047!! and there is a diversity of parameterizations to be found here.
5048!!
5049!! * src/tracer:
5050!! These files handle the lateral transport and diffusion of
5051!! tracers, or are the code to implement various passive tracer
5052!! packages. Additional tracer packages are readily accommodated.
5053!!
5054!! * src/user:
5055!! These are either stub routines that a user could use to change
5056!! the model's initial conditions or forcing, or are examples that
5057!! implement specific test cases. These files can easily be hand
5058!! edited to create new analytically specified configurations.
5059!!
5060!!
5061!! Most simulations can be set up by modifying only the files
5062!! MOM_input, and possibly one or two of the files in src/user.
5063!! In addition, the diag_table (MOM_diag_table) will commonly be
5064!! modified to tailor the output to the needs of the question at
5065!! hand. The FMS utility mkmf works with a file called path_names
5066!! to build an appropriate makefile, and path_names should be edited
5067!! to reflect the actual location of the desired source code.
5068!!
5069!! The separate MOM-examples git repository provides a large number
5070!! of working configurations of MOM, along with reference solutions for several
5071!! different compilers on GFDL's latest large computer. The versions
5072!! of MOM_memory.h in these directories need not be used if dynamic
5073!! memory allocation is desired, and the answers should be unchanged.
5074!!
5075!!
5076!! There are 3 publicly visible subroutines in this file (MOM.F90).
5077!! * step_MOM steps MOM over a specified interval of time.
5078!! * MOM_initialize calls initialize and does other initialization
5079!! that does not warrant user modification.
5080!! * extract_surface_state determines the surface (bulk mixed layer
5081!! if traditional isopycnal vertical coordinate) properties of the
5082!! current model state and packages pointers to these fields into an
5083!! exported structure.
5084!!
5085!! The remaining subroutines in this file (src/core/MOM.F90) are:
5086!! * find_total_transport determines the barotropic mass transport.
5087!! * register_diags registers many diagnostic fields for the dynamic
5088!! solver, or of the main model variables.
5089!! * MOM_timing_init initializes various CPU time clocks.
5090!! * write_static_fields writes out various time-invariant fields.
5091!! * set_restart_fields is used to specify those fields that are
5092!! written to and read from the restart file.
5093!!
5094!! \section section_heat_budget Diagnosing MOM heat budget
5095!!
5096!! Here are some example heat budgets for the ALE version of MOM6.
5097!!
5098!! \subsection subsection_2d_heat_budget Depth integrated heat budget
5099!!
5100!! Depth integrated heat budget diagnostic for MOM.
5101!!
5102!! * OPOTTEMPTEND_2d = T_ADVECTION_XY_2d + OPOTTEMPPMDIFF_2d + HFDS + HFGEOU
5103!!
5104!! * T_ADVECTION_XY_2d = horizontal advection
5105!! * OPOTTEMPPMDIFF_2d = neutral diffusion
5106!! * HFDS = net surface boundary heat flux
5107!! * HFGEOU = geothermal heat flux
5108!!
5109!! * HFDS = net surface boundary heat flux entering the ocean
5110!! = rsntds + rlntds + hfls + hfss + heat_pme + hfsifrazil
5111!!
5112!! * More heat flux cross-checks
5113!! * hfds = net_heat_coupler + hfsifrazil + heat_pme
5114!! * heat_pme = heat_content_surfwater
5115!! = heat_content_massin + heat_content_massout
5116!! = heat_content_fprec + heat_content_cond + heat_content_vprec
5117!! + hfrunoffds + hfevapds + hfrainds
5118!!
5119!! \subsection subsection_3d_heat_budget Depth integrated heat budget
5120!!
5121!! Here is an example 3d heat budget diagnostic for MOM.
5122!!
5123!! * OPOTTEMPTEND = T_ADVECTION_XY + TH_TENDENCY_VERT_REMAP + OPOTTEMPDIFF + OPOTTEMPPMDIFF
5124!! + BOUNDARY_FORCING_HEAT_TENDENCY + FRAZIL_HEAT_TENDENCY
5125!!
5126!! * OPOTTEMPTEND = net tendency of heat as diagnosed in MOM.F90
5127!! * T_ADVECTION_XY = heating of a cell from lateral advection
5128!! * TH_TENDENCY_VERT_REMAP = heating of a cell from vertical remapping
5129!! * OPOTTEMPDIFF = heating of a cell from diabatic diffusion
5130!! * OPOTTEMPPMDIFF = heating of a cell from neutral diffusion
5131!! * BOUNDARY_FORCING_HEAT_TENDENCY = heating of cell from boundary fluxes
5132!! * FRAZIL_HEAT_TENDENCY = heating of cell from frazil
5133!!
5134!! * TH_TENDENCY_VERT_REMAP has zero vertical sum, as it redistributes heat in vertical.
5135!!
5136!! * OPOTTEMPDIFF has zero vertical sum, as it redistributes heat in the vertical.
5137!!
5138!! * BOUNDARY_FORCING_HEAT_TENDENCY generally has 3d structure, with k > 1 contributions from
5139!! penetrative shortwave, and from other fluxes for the case when layers are tiny, in which
5140!! case MOM6 partitions tendencies into k > 1 layers.
5141!!
5142!! * FRAZIL_HEAT_TENDENCY generally has 3d structure, since MOM6 frazil calculation checks the
5143!! full ocean column.
5144!!
5145!! * FRAZIL_HEAT_TENDENCY[k=\@sum] = HFSIFRAZIL = column integrated frazil heating.
5146!!
5147!! * HFDS = FRAZIL_HEAT_TENDENCY[k=\@sum] + BOUNDARY_FORCING_HEAT_TENDENCY[k=\@sum]
5148!!
5149!! Here is an example 2d heat budget (depth summed) diagnostic for MOM.
5150!!
5151!! * OPOTTEMPTEND_2d = T_ADVECTION_XY_2d + OPOTTEMPPMDIFF_2d + HFDS
5152!!
5153!!
5154!! Here is an example 3d salt budget diagnostic for MOM.
5155!!
5156!! * OSALTTEND = S_ADVECTION_XY + SH_TENDENCY_VERT_REMAP + OSALTDIFF + OSALTPMDIFF
5157!! + BOUNDARY_FORCING_SALT_TENDENCY
5158!!
5159!! * OSALTTEND = net tendency of salt as diagnosed in MOM.F90
5160!! * S_ADVECTION_XY = salt convergence to cell from lateral advection
5161!! * SH_TENDENCY_VERT_REMAP = salt convergence to cell from vertical remapping
5162!! * OSALTDIFF = salt convergence to cell from diabatic diffusion
5163!! * OSALTPMDIFF = salt convergence to cell from neutral diffusion
5164!! * BOUNDARY_FORCING_SALT_TENDENCY = salt convergence to cell from boundary fluxes
5165!!
5166!! * SH_TENDENCY_VERT_REMAP has zero vertical sum, as it redistributes salt in vertical.
5167!!
5168!! * OSALTDIFF has zero vertical sum, as it redistributes salt in the vertical.
5169!!
5170!! * BOUNDARY_FORCING_SALT_TENDENCY generally has 3d structure, with k > 1 contributions from
5171!! the case when layers are tiny, in which case MOM6 partitions tendencies into k > 1 layers.
5172!!
5173!! * SFDSI = BOUNDARY_FORCING_SALT_TENDENCY[k=\@sum]
5174!!
5175!! Here is an example 2d salt budget (depth summed) diagnostic for MOM.
5176!!
5177!! * OSALTTEND_2d = S_ADVECTION_XY_2d + OSALTPMDIFF_2d + SFDSI (+ SALT_FLUX_RESTORE)
5178!!
5179!!
5180!!
5181end module mom