MOM6
MOM_bulk_mixed_layer.F90
1 !> Build mixed layer parameterization
3 
4 ! This file is part of MOM6. See LICENSE.md for the license.
5 
6 use mom_cpu_clock, only : cpu_clock_id, cpu_clock_begin, cpu_clock_end, clock_routine
7 use mom_diag_mediator, only : post_data, register_diag_field, safe_alloc_alloc
8 use mom_diag_mediator, only : time_type, diag_ctrl, diag_update_remap_grids
9 use mom_domains, only : create_group_pass, do_group_pass, group_pass_type
10 use mom_error_handler, only : mom_error, fatal, warning
12 use mom_forcing_type, only : extractfluxes1d, forcing
13 use mom_grid, only : ocean_grid_type
14 use mom_opacity, only : absorbremainingsw, optics_type, extract_optics_slice
19 
20 implicit none ; private
21 
22 #include <MOM_memory.h>
23 
24 public bulkmixedlayer, bulkmixedlayer_init
25 
26 ! A note on unit descriptions in comments: MOM6 uses units that can be rescaled for dimensional
27 ! consistency testing. These are noted in comments with units like Z, H, L, and T, along with
28 ! their mks counterparts with notation like "a velocity [Z T-1 ~> m s-1]". If the units
29 ! vary with the Boussinesq approximation, the Boussinesq variant is given first.
30 
31 !> The control structure with parameters for the MOM_bulk_mixed_layer module
32 type, public :: bulkmixedlayer_cs ; private
33  integer :: nkml !< The number of layers in the mixed layer.
34  integer :: nkbl !< The number of buffer layers.
35  integer :: nsw !< The number of bands of penetrating shortwave radiation.
36  real :: mstar !< The ratio of the friction velocity cubed to the
37  !! TKE input to the mixed layer, nondimensional.
38  real :: nstar !< The fraction of the TKE input to the mixed layer
39  !! available to drive entrainment [nondim].
40  real :: nstar2 !< The fraction of potential energy released by
41  !! convective adjustment that drives entrainment [nondim].
42  logical :: absorb_all_sw !< If true, all shortwave radiation is absorbed by the
43  !! ocean, instead of passing through to the bottom mud.
44  real :: tke_decay !< The ratio of the natural Ekman depth to the TKE
45  !! decay scale, nondimensional.
46  real :: bulk_ri_ml !< The efficiency with which mean kinetic energy
47  !! released by mechanically forced entrainment of
48  !! the mixed layer is converted to TKE [nondim].
49  real :: bulk_ri_convective !< The efficiency with which convectively
50  !! released mean kinetic energy becomes TKE [nondim].
51  real :: hmix_min !< The minimum mixed layer thickness [H ~> m or kg m-2].
52  real :: h_limit_fluxes !< When the total ocean depth is less than this
53  !! value [H ~> m or kg m-2], scale away all surface forcing to
54  !! avoid boiling the ocean.
55  real :: ustar_min !< A minimum value of ustar to avoid numerical problems [Z T-1 ~> m s-1].
56  !! If the value is small enough, this should not affect the solution.
57  real :: omega !< The Earth's rotation rate [T-1 ~> s-1].
58  real :: dt_ds_wt !< When forced to extrapolate T & S to match the
59  !! layer densities, this factor (in degC / ppt) is
60  !! combined with the derivatives of density with T & S
61  !! to determines what direction is orthogonal to
62  !! density contours. It should be a typical value of
63  !! (dR/dS) / (dR/dT) in oceanic profiles.
64  !! 6 degC ppt-1 might be reasonable.
65  real :: hbuffer_min !< The minimum buffer layer thickness when the mixed layer
66  !! is very large [H ~> m or kg m-2].
67  real :: hbuffer_rel_min !< The minimum buffer layer thickness relative to the combined
68  !! mixed and buffer layer thicknesses when they are thin [nondim]
69  real :: bl_detrain_time !< A timescale that characterizes buffer layer detrainment
70  !! events [T ~> s].
71  real :: bl_extrap_lim !< A limit on the density range over which
72  !! extrapolation can occur when detraining from the
73  !! buffer layers, relative to the density range
74  !! within the mixed and buffer layers, when the
75  !! detrainment is going into the lightest interior
76  !! layer [nondim].
77  real :: bl_split_rho_tol !< The fractional tolerance for matching layer target densities
78  !! when splitting layers to deal with massive interior layers
79  !! that are lighter than one of the mixed or buffer layers [nondim].
80  logical :: ml_resort !< If true, resort the layers by density, rather than
81  !! doing convective adjustment.
82  integer :: ml_presort_nz_conv_adj !< If ML_resort is true, do convective
83  !! adjustment on this many layers (starting from the
84  !! top) before sorting the remaining layers.
85  real :: omega_frac !< When setting the decay scale for turbulence, use
86  !! this fraction of the absolute rotation rate blended
87  !! with the local value of f, as sqrt((1-of)*f^2 + of*4*omega^2).
88  logical :: correct_absorption !< If true, the depth at which penetrating
89  !! shortwave radiation is absorbed is corrected by
90  !! moving some of the heating upward in the water
91  !! column. The default is false.
92  logical :: resolve_ekman !< If true, the nkml layers in the mixed layer are
93  !! chosen to optimally represent the impact of the
94  !! Ekman transport on the mixed layer TKE budget.
95  type(time_type), pointer :: time => null() !< A pointer to the ocean model's clock.
96  logical :: tke_diagnostics = .false. !< If true, calculate extensive diagnostics of the TKE budget
97  logical :: do_rivermix = .false. !< Provide additional TKE to mix river runoff
98  !! at the river mouths to rivermix_depth
99  real :: rivermix_depth = 0.0 !< The depth of mixing if do_rivermix is true [Z ~> m].
100  logical :: limit_det !< If true, limit the extent of buffer layer
101  !! detrainment to be consistent with neighbors.
102  real :: lim_det_dh_sfc !< The fractional limit in the change between grid
103  !! points of the surface region (mixed & buffer
104  !! layer) thickness [nondim]. 0.5 by default.
105  real :: lim_det_dh_bathy !< The fraction of the total depth by which the
106  !! thickness of the surface region (mixed & buffer
107  !! layer) is allowed to change between grid points.
108  !! Nondimensional, 0.2 by default.
109  logical :: use_river_heat_content !< If true, use the fluxes%runoff_Hflx field
110  !! to set the heat carried by runoff, instead of
111  !! using SST for temperature of liq_runoff
112  logical :: use_calving_heat_content !< Use SST for temperature of froz_runoff
113  logical :: salt_reject_below_ml !< It true, add salt below mixed layer (layer mode only)
114 
115  type(diag_ctrl), pointer :: diag => null() !< A structure that is used to regulate the
116  !! timing of diagnostic output.
117  real :: allowed_t_chg !< The amount by which temperature is allowed
118  !! to exceed previous values during detrainment, K.
119  real :: allowed_s_chg !< The amount by which salinity is allowed
120  !! to exceed previous values during detrainment, ppt.
121 
122  ! These are terms in the mixed layer TKE budget, all in [Z m2 T-3 ~> m3 s-3] except as noted.
123  real, allocatable, dimension(:,:) :: &
124  ml_depth, & !< The mixed layer depth [H ~> m or kg m-2].
125  diag_tke_wind, & !< The wind source of TKE.
126  diag_tke_ribulk, & !< The resolved KE source of TKE.
127  diag_tke_conv, & !< The convective source of TKE.
128  diag_tke_pen_sw, & !< The TKE sink required to mix penetrating shortwave heating.
129  diag_tke_mech_decay, & !< The decay of mechanical TKE.
130  diag_tke_conv_decay, & !< The decay of convective TKE.
131  diag_tke_mixing, & !< The work done by TKE to deepen the mixed layer.
132  diag_tke_conv_s2, & !< The convective source of TKE due to to mixing in sigma2.
133  diag_pe_detrain, & !< The spurious source of potential energy due to mixed layer
134  !! detrainment [kg T-3 Z m-1 ~> W m-2].
135  diag_pe_detrain2 !< The spurious source of potential energy due to mixed layer only
136  !! detrainment [kg T-3 Z m-1 ~> W m-2].
137  logical :: allow_clocks_in_omp_loops !< If true, clocks can be called from inside loops that can
138  !! be threaded. To run with multiple threads, set to False.
139  type(group_pass_type) :: pass_h_sum_hmbl_prev !< For group halo pass
140 
141  !>@{ Diagnostic IDs
142  integer :: id_ml_depth = -1, id_tke_wind = -1, id_tke_mixing = -1
143  integer :: id_tke_ribulk = -1, id_tke_conv = -1, id_tke_pen_sw = -1
144  integer :: id_tke_mech_decay = -1, id_tke_conv_decay = -1, id_tke_conv_s2 = -1
145  integer :: id_pe_detrain = -1, id_pe_detrain2 = -1, id_h_mismatch = -1
146  integer :: id_hsfc_used = -1, id_hsfc_max = -1, id_hsfc_min = -1
147  !!@}
148 end type bulkmixedlayer_cs
149 
150 !>@{ CPU clock IDs
151 integer :: id_clock_detrain=0, id_clock_mech=0, id_clock_conv=0, id_clock_adjustment=0
152 integer :: id_clock_eos=0, id_clock_resort=0, id_clock_pass=0
153 !!@}
154 
155 contains
156 
157 !> This subroutine partially steps the bulk mixed layer model.
158 !! The following processes are executed, in the order listed.
159 !! 1. Undergo convective adjustment into mixed layer.
160 !! 2. Apply surface heating and cooling.
161 !! 3. Starting from the top, entrain whatever fluid the TKE budget
162 !! permits. Penetrating shortwave radiation is also applied at
163 !! this point.
164 !! 4. If there is any unentrained fluid that was formerly in the
165 !! mixed layer, detrain this fluid into the buffer layer. This
166 !! is equivalent to the mixed layer detraining to the Monin-
167 !! Obukhov depth.
168 !! 5. Divide the fluid in the mixed layer evenly into CS%nkml pieces.
169 !! 6. Split the buffer layer if appropriate.
170 !! Layers 1 to nkml are the mixed layer, nkml+1 to nkml+nkbl are the
171 !! buffer layers. The results of this subroutine are mathematically
172 !! identical if there are multiple pieces of the mixed layer with
173 !! the same density or if there is just a single layer. There is no
174 !! stability limit on the time step.
175 !!
176 !! The key parameters for the mixed layer are found in the control structure.
177 !! These include mstar, nstar, nstar2, pen_SW_frac, pen_SW_scale, and TKE_decay.
178 !! For the Oberhuber (1993) mixed layer, the values of these are:
179 !! pen_SW_frac = 0.42, pen_SW_scale = 15.0 m, mstar = 1.25,
180 !! nstar = 1, TKE_decay = 2.5, conv_decay = 0.5
181 !! TKE_decay is 1/kappa in eq. 28 of Oberhuber (1993), while conv_decay is 1/mu.
182 !! Conv_decay has been eliminated in favor of the well-calibrated form for the
183 !! efficiency of penetrating convection from Wang (2003).
184 !! For a traditional Kraus-Turner mixed layer, the values are:
185 !! pen_SW_frac = 0.0, pen_SW_scale = 0.0 m, mstar = 1.25,
186 !! nstar = 0.4, TKE_decay = 0.0, conv_decay = 0.0
187 subroutine bulkmixedlayer(h_3d, u_3d, v_3d, tv, fluxes, dt_in_T, ea, eb, G, GV, US, CS, &
188  optics, Hml, aggregate_FW_forcing, dt_diag, last_call)
189  type(ocean_grid_type), intent(inout) :: g !< The ocean's grid structure.
190  type(verticalgrid_type), intent(in) :: gv !< The ocean's vertical grid structure.
191  type(unit_scale_type), intent(in) :: us !< A dimensional unit scaling type
192  real, dimension(SZI_(G),SZJ_(G),SZK_(GV)), &
193  intent(inout) :: h_3d !< Layer thickness [H ~> m or kg m-2].
194  real, dimension(SZI_(G),SZJ_(G),SZK_(GV)), &
195  intent(in) :: u_3d !< Zonal velocities interpolated to h points
196  !! [m s-1].
197  real, dimension(SZI_(G),SZJ_(G),SZK_(GV)), &
198  intent(in) :: v_3d !< Zonal velocities interpolated to h points
199  !! [m s-1].
200  type(thermo_var_ptrs), intent(inout) :: tv !< A structure containing pointers to any
201  !! available thermodynamic fields. Absent
202  !! fields have NULL ptrs.
203  type(forcing), intent(inout) :: fluxes !< A structure containing pointers to any
204  !! possible forcing fields. Unused fields
205  !! have NULL ptrs.
206  real, intent(in) :: dt_in_t !< Time increment [T ~> s].
207  real, dimension(SZI_(G),SZJ_(G),SZK_(GV)), &
208  intent(inout) :: ea !< The amount of fluid moved downward into a
209  !! layer; this should be increased due to
210  !! mixed layer detrainment [H ~> m or kg m-2].
211  real, dimension(SZI_(G),SZJ_(G),SZK_(GV)), &
212  intent(inout) :: eb !< The amount of fluid moved upward into a
213  !! layer; this should be increased due to
214  !! mixed layer entrainment [H ~> m or kg m-2].
215  type(bulkmixedlayer_cs), pointer :: cs !< The control structure returned by a
216  !! previous call to mixedlayer_init.
217  type(optics_type), pointer :: optics !< The structure containing the inverse of the
218  !! vertical absorption decay scale for
219  !! penetrating shortwave radiation [m-1].
220  real, dimension(:,:), pointer :: hml !< Active mixed layer depth [m].
221  logical, intent(in) :: aggregate_fw_forcing !< If true, the net incoming and
222  !! outgoing surface freshwater fluxes are
223  !! combined before being applied, instead of
224  !! being applied separately.
225  real, optional, intent(in) :: dt_diag !< The diagnostic time step,
226  !! which may be less than dt if there are
227  !! two callse to mixedlayer [T ~> s].
228  logical, optional, intent(in) :: last_call !< if true, this is the last call
229  !! to mixedlayer in the current time step, so
230  !! diagnostics will be written. The default is
231  !! .true.
232 
233  ! Local variables
234  real, dimension(SZI_(G),SZK_(GV)) :: &
235  eaml, & ! The amount of fluid moved downward into a layer due to mixed
236  ! layer detrainment [H ~> m or kg m-2]. (I.e. entrainment from above.)
237  ebml ! The amount of fluid moved upward into a layer due to mixed
238  ! layer detrainment [H ~> m or kg m-2]. (I.e. entrainment from below.)
239 
240  ! If there is resorting, the vertical coordinate for these variables is the
241  ! new, sorted index space. Here layer 0 is an initially massless layer that
242  ! will be used to hold the new mixed layer properties.
243  real, dimension(SZI_(G),SZK0_(GV)) :: &
244  h, & ! The layer thickness [H ~> m or kg m-2].
245  t, & ! The layer temperatures [degC].
246  s, & ! The layer salinities [ppt].
247  r0, & ! The potential density referenced to the surface [kg m-3].
248  rcv ! The coordinate variable potential density [kg m-3].
249  real, dimension(SZI_(G),SZK_(GV)) :: &
250  u, & ! The zonal velocity [m s-1].
251  v, & ! The meridional velocity [m s-1].
252  h_orig, & ! The original thickness [H ~> m or kg m-2].
253  d_eb, & ! The downward increase across a layer in the entrainment from
254  ! below [H ~> m or kg m-2]. The sign convention is that positive values of
255  ! d_eb correspond to a gain in mass by a layer by upward motion.
256  d_ea, & ! The upward increase across a layer in the entrainment from
257  ! above [H ~> m or kg m-2]. The sign convention is that positive values of
258  ! d_ea mean a net gain in mass by a layer from downward motion.
259  eps ! The (small) thickness that must remain in a layer [H ~> m or kg m-2].
260  integer, dimension(SZI_(G),SZK_(GV)) :: &
261  ksort ! The sorted k-index that each original layer goes to.
262  real, dimension(SZI_(G),SZJ_(G)) :: &
263  h_miss ! The summed absolute mismatch [Z ~> m].
264  real, dimension(SZI_(G)) :: &
265  tke, & ! The turbulent kinetic energy available for mixing over a
266  ! time step [Z m2 T-2 ~> m3 s-2].
267  conv_en, & ! The turbulent kinetic energy source due to mixing down to
268  ! the depth of free convection [Z m2 T-2 ~> m3 s-2].
269  htot, & ! The total depth of the layers being considered for
270  ! entrainment [H ~> m or kg m-2].
271  r0_tot, & ! The integrated potential density referenced to the surface
272  ! of the layers which are fully entrained [H kg m-3 ~> kg m-2 or kg2 m-5].
273  rcv_tot, & ! The integrated coordinate value potential density of the
274  ! layers that are fully entrained [H kg m-3 ~> kg m-2 or kg2 m-5].
275  ttot, & ! The integrated temperature of layers which are fully
276  ! entrained [degC H ~> degC m or degC kg m-2].
277  stot, & ! The integrated salt of layers which are fully entrained
278  ! [H ppt ~> m ppt or ppt kg m-2].
279  uhtot, & ! The depth integrated zonal and meridional velocities in the
280  vhtot, & ! mixed layer [H m s-1 ~> m2 s-1 or kg m-1 s-1].
281 
282  netmassinout, & ! The net mass flux (if non-Boussinsq) or volume flux (if
283  ! Boussinesq - i.e. the fresh water flux (P+R-E)) into the
284  ! ocean over a time step [H ~> m or kg m-2].
285  netmassout, & ! The mass flux (if non-Boussinesq) or volume flux (if Boussinesq)
286  ! over a time step from evaporating fresh water [H ~> m or kg m-2]
287  net_heat, & ! The net heating at the surface over a time step [degC H ~> degC m or degC kg m-2].
288  ! Any penetrating shortwave radiation is not included in Net_heat.
289  net_salt, & ! The surface salt flux into the ocean over a time step, ppt H.
290  idecay_len_tke, & ! The inverse of a turbulence decay length scale [H-1 ~> m-1 or m2 kg-1].
291  p_ref, & ! Reference pressure for the potential density governing mixed
292  ! layer dynamics, almost always 0 (or 1e5) Pa.
293  p_ref_cv, & ! Reference pressure for the potential density which defines
294  ! the coordinate variable, set to P_Ref [Pa].
295  dr0_dt, & ! Partial derivative of the mixed layer potential density with
296  ! temperature [kg m-3 degC-1].
297  drcv_dt, & ! Partial derivative of the coordinate variable potential
298  ! density in the mixed layer with temperature [kg m-3 degC-1].
299  dr0_ds, & ! Partial derivative of the mixed layer potential density with
300  ! salinity [kg m-3 ppt-1].
301  drcv_ds, & ! Partial derivative of the coordinate variable potential
302  ! density in the mixed layer with salinity [kg m-3 ppt-1].
303  tke_river ! The source of turbulent kinetic energy available for mixing
304  ! at rivermouths [Z m2 T-3 ~> m3 s-3].
305 
306  real, dimension(max(CS%nsw,1),SZI_(G)) :: &
307  pen_sw_bnd ! The penetrating fraction of the shortwave heating integrated
308  ! over a time step in each band [degC H ~> degC m or degC kg m-2].
309  real, dimension(max(CS%nsw,1),SZI_(G),SZK_(GV)) :: &
310  opacity_band ! The opacity in each band [H-1 ~> m-1 or m2 kg-1]. The indicies are band, i, k.
311 
312  real :: cmke(2,szi_(g)) ! Coefficients of HpE and HpE^2 used in calculating the
313  ! denominator of MKE_rate; the two elements have differing
314  ! units of [H-1 ~> m-1 or m2 kg-1] and [H-2 ~> m-2 or m4 kg-2].
315  real :: irho0 ! 1.0 / rho_0 [m3 kg-1]
316  real :: inkml, inkmlm1! 1.0 / REAL(nkml) and 1.0 / REAL(nkml-1)
317  real :: ih ! The inverse of a thickness [H-1 ~> m-1 or m2 kg-1].
318  real :: idt_diag ! The inverse of the timestep used for diagnostics [T-1 ~> s-1].
319  real :: rmixconst
320 
321  real, dimension(SZI_(G)) :: &
322  dke_fc, & ! The change in mean kinetic energy due to free convection
323  ! [Z m2 T-2 ~> m3 s-2].
324  h_ca ! The depth to which convective adjustment has gone [H ~> m or kg m-2].
325  real, dimension(SZI_(G),SZK_(GV)) :: &
326  dke_ca, & ! The change in mean kinetic energy due to convective
327  ! adjustment [Z m2 T-2 ~> m3 s-2].
328  ctke ! The turbulent kinetic energy source due to convective
329  ! adjustment [Z m2 T-2 ~> m3 s-2].
330  real, dimension(SZI_(G),SZJ_(G)) :: &
331  hsfc_max, & ! The thickness of the surface region (mixed and buffer layers)
332  ! after entrainment but before any buffer layer detrainment [Z ~> m].
333  hsfc_used, & ! The thickness of the surface region after buffer layer
334  ! detrainment [Z ~> m].
335  hsfc_min, & ! The minimum thickness of the surface region based on the
336  ! new mixed layer depth and the previous thickness of the
337  ! neighboring water columns [Z ~> m].
338  h_sum, & ! The total thickness of the water column [H ~> m or kg m-2].
339  hmbl_prev ! The previous thickness of the mixed and buffer layers [H ~> m or kg m-2].
340  real, dimension(SZI_(G)) :: &
341  hsfc, & ! The thickness of the surface region (mixed and buffer
342  ! layers before detrainment in to the interior [H ~> m or kg m-2].
343  max_bl_det ! If non-negative, the maximum amount of entrainment from
344  ! the buffer layers that will be allowed this time step [H ~> m or kg m-2].
345  real :: dhsfc, dhd ! Local copies of nondimensional parameters.
346  real :: h_nbr ! A minimum thickness based on neighboring thicknesses [H ~> m or kg m-2].
347 
348  real :: absf_x_h ! The absolute value of f times the mixed layer thickness [Z T-1 ~> m s-1].
349  real :: ku_star ! Ustar times the Von Karmen constant [Z T-1 ~> m s-1].
350 ! real :: dt_in_T ! Time increment in time units [T ~> s].
351  real :: dt__diag ! A recaled copy of dt_diag (if present) or dt [T ~> s].
352  logical :: write_diags ! If true, write out diagnostics with this step.
353  logical :: reset_diags ! If true, zero out the accumulated diagnostics.
354  integer :: i, j, k, is, ie, js, je, nz, nkmb, n
355  integer :: nsw ! The number of bands of penetrating shortwave radiation.
356 
357  is = g%isc ; ie = g%iec ; js = g%jsc ; je = g%jec ; nz = gv%ke
358 
359  if (.not. associated(cs)) call mom_error(fatal, "MOM_mixed_layer: "//&
360  "Module must be initialized before it is used.")
361  if (gv%nkml < 1) return
362 
363  if (.not. associated(tv%eqn_of_state)) call mom_error(fatal, &
364  "MOM_mixed_layer: Temperature, salinity and an equation of state "//&
365  "must now be used.")
366  if (.NOT. associated(fluxes%ustar)) call mom_error(fatal, &
367  "MOM_mixed_layer: No surface TKE fluxes (ustar) defined in mixedlayer!")
368 
369  nkmb = cs%nkml+cs%nkbl
370  inkml = 1.0 / real(cs%nkml)
371  if (cs%nkml > 1) inkmlm1 = 1.0 / real(cs%nkml-1)
372 
373 ! dt_in_T = dt * US%s_to_T
374 
375  irho0 = 1.0 / gv%Rho0
376  dt__diag = dt_in_t ; if (present(dt_diag)) dt__diag = dt_diag
377  idt_diag = 1.0 / (dt__diag)
378  write_diags = .true. ; if (present(last_call)) write_diags = last_call
379 
380  p_ref(:) = 0.0 ; p_ref_cv(:) = tv%P_Ref
381 
382  nsw = cs%nsw
383 
384  if (cs%limit_det .or. (cs%id_Hsfc_min > 0)) then
385  !$OMP parallel do default(shared)
386  do j=js-1,je+1 ; do i=is-1,ie+1
387  h_sum(i,j) = 0.0 ; hmbl_prev(i,j) = 0.0
388  enddo ; enddo
389  !$OMP parallel do default(shared)
390  do j=js-1,je+1
391  do k=1,nkmb ; do i=is-1,ie+1
392  h_sum(i,j) = h_sum(i,j) + h_3d(i,j,k)
393  hmbl_prev(i,j) = hmbl_prev(i,j) + h_3d(i,j,k)
394  enddo ; enddo
395  do k=nkmb+1,nz ; do i=is-1,ie+1
396  h_sum(i,j) = h_sum(i,j) + h_3d(i,j,k)
397  enddo ; enddo
398  enddo
399 
400  call cpu_clock_begin(id_clock_pass)
401  call create_group_pass(cs%pass_h_sum_hmbl_prev, h_sum,g%Domain)
402  call create_group_pass(cs%pass_h_sum_hmbl_prev, hmbl_prev,g%Domain)
403  call do_group_pass(cs%pass_h_sum_hmbl_prev, g%Domain)
404  call cpu_clock_end(id_clock_pass)
405  endif
406 
407  ! Determine whether to zero out diagnostics before accumulation.
408  reset_diags = .true.
409  if (present(dt_diag) .and. write_diags .and. (dt__diag > dt_in_t)) &
410  reset_diags = .false. ! This is the second call to mixedlayer.
411 
412  if (reset_diags) then
413  if (cs%TKE_diagnostics) then
414  !$OMP parallel do default(shared)
415  do j=js,je ; do i=is,ie
416  cs%diag_TKE_wind(i,j) = 0.0 ; cs%diag_TKE_RiBulk(i,j) = 0.0
417  cs%diag_TKE_conv(i,j) = 0.0 ; cs%diag_TKE_pen_SW(i,j) = 0.0
418  cs%diag_TKE_mixing(i,j) = 0.0 ; cs%diag_TKE_mech_decay(i,j) = 0.0
419  cs%diag_TKE_conv_decay(i,j) = 0.0 ; cs%diag_TKE_conv_s2(i,j) = 0.0
420  enddo ; enddo
421  endif
422  if (allocated(cs%diag_PE_detrain)) then
423  !$OMP parallel do default(shared)
424  do j=js,je ; do i=is,ie
425  cs%diag_PE_detrain(i,j) = 0.0
426  enddo ; enddo
427  endif
428  if (allocated(cs%diag_PE_detrain2)) then
429  !$OMP parallel do default(shared)
430  do j=js,je ; do i=is,ie
431  cs%diag_PE_detrain2(i,j) = 0.0
432  enddo ; enddo
433  endif
434  endif
435 
436  if (cs%ML_resort) then
437  do i=is,ie ; h_ca(i) = 0.0 ; enddo
438  do k=1,nz ; do i=is,ie ; dke_ca(i,k) = 0.0 ; ctke(i,k) = 0.0 ; enddo ; enddo
439  endif
440  max_bl_det(:) = -1
441 
442  !$OMP parallel default(shared) firstprivate(dKE_CA,cTKE,h_CA,max_BL_det,p_ref,p_ref_cv) &
443  !$OMP private(h,u,v,h_orig,eps,T,S,opacity_band,d_ea,d_eb,R0,Rcv,ksort, &
444  !$OMP dR0_dT,dR0_dS,dRcv_dT,dRcv_dS,htot,Ttot,Stot,TKE,Conv_en, &
445  !$OMP RmixConst,TKE_river,Pen_SW_bnd,netMassInOut,NetMassOut, &
446  !$OMP Net_heat,Net_salt,uhtot,vhtot,R0_tot,Rcv_tot,dKE_FC, &
447  !$OMP Idecay_len_TKE,cMKE,Hsfc,dHsfc,dHD,H_nbr,kU_Star, &
448  !$OMP absf_x_H,ebml,eaml)
449  !$OMP do
450  do j=js,je
451  ! Copy the thicknesses and other fields to 2-d arrays.
452  do k=1,nz ; do i=is,ie
453  h(i,k) = h_3d(i,j,k) ; u(i,k) = u_3d(i,j,k) ; v(i,k) = v_3d(i,j,k)
454  h_orig(i,k) = h_3d(i,j,k)
455  eps(i,k) = 0.0 ; if (k > nkmb) eps(i,k) = gv%Angstrom_H
456  t(i,k) = tv%T(i,j,k) ; s(i,k) = tv%S(i,j,k)
457  enddo ; enddo
458  if (nsw>0) call extract_optics_slice(optics, j, g, gv, opacity=opacity_band, opacity_scale=gv%H_to_m)
459 
460  do k=1,nz ; do i=is,ie
461  d_ea(i,k) = 0.0 ; d_eb(i,k) = 0.0
462  enddo ; enddo
463 
464  if (id_clock_eos>0) call cpu_clock_begin(id_clock_eos)
465  ! Calculate an estimate of the mid-mixed layer pressure [Pa]
466  do i=is,ie ; p_ref(i) = 0.0 ; enddo
467  do k=1,cs%nkml ; do i=is,ie
468  p_ref(i) = p_ref(i) + 0.5*gv%H_to_Pa*h(i,k)
469  enddo ; enddo
470  call calculate_density_derivs(t(:,1), s(:,1), p_ref, dr0_dt, dr0_ds, &
471  is, ie-is+1, tv%eqn_of_state)
472  call calculate_density_derivs(t(:,1), s(:,1), p_ref_cv, drcv_dt, drcv_ds, &
473  is, ie-is+1, tv%eqn_of_state)
474  do k=1,nz
475  call calculate_density(t(:,k), s(:,k), p_ref, r0(:,k), is, ie-is+1, &
476  tv%eqn_of_state)
477  call calculate_density(t(:,k), s(:,k), p_ref_cv, rcv(:,k), is, &
478  ie-is+1, tv%eqn_of_state)
479  enddo
480  if (id_clock_eos>0) call cpu_clock_end(id_clock_eos)
481 
482  if (cs%ML_resort) then
483  if (id_clock_resort>0) call cpu_clock_begin(id_clock_resort)
484  if (cs%ML_presort_nz_conv_adj > 0) &
485  call convective_adjustment(h(:,1:), u, v, r0(:,1:), rcv(:,1:), t(:,1:), &
486  s(:,1:), eps, d_eb, dke_ca, ctke, j, g, gv, us, cs, &
487  cs%ML_presort_nz_conv_adj)
488 
489  call sort_ml(h(:,1:), r0(:,1:), eps, g, gv, cs, ksort)
490  if (id_clock_resort>0) call cpu_clock_end(id_clock_resort)
491  else
492  do k=1,nz ; do i=is,ie ; ksort(i,k) = k ; enddo ; enddo
493 
494  if (id_clock_adjustment>0) call cpu_clock_begin(id_clock_adjustment)
495  ! Undergo instantaneous entrainment into the buffer layers and mixed layers
496  ! to remove hydrostatic instabilities. Any water that is lighter than
497  ! currently in the mixed or buffer layer is entrained.
498  call convective_adjustment(h(:,1:), u, v, r0(:,1:), rcv(:,1:), t(:,1:), &
499  s(:,1:), eps, d_eb, dke_ca, ctke, j, g, gv, us, cs)
500  do i=is,ie ; h_ca(i) = h(i,1) ; enddo
501 
502  if (id_clock_adjustment>0) call cpu_clock_end(id_clock_adjustment)
503  endif
504 
505  if (associated(fluxes%lrunoff) .and. cs%do_rivermix) then
506 
507  ! Here we add an additional source of TKE to the mixed layer where river
508  ! is present to simulate unresolved estuaries. The TKE input is diagnosed
509  ! as follows:
510  ! TKE_river[m3 s-3] = 0.5*rivermix_depth*g*Irho0*drho_ds*
511  ! River*(Samb - Sriver) = CS%mstar*U_star^3
512  ! where River is in units of [m s-1].
513  ! Samb = Ambient salinity at the mouth of the estuary
514  ! rivermix_depth = The prescribed depth over which to mix river inflow
515  ! drho_ds = The gradient of density wrt salt at the ambient surface salinity.
516  ! Sriver = 0 (i.e. rivers are assumed to be pure freshwater)
517  rmixconst = 0.5*cs%rivermix_depth * (us%L_to_m**2*gv%g_Earth*us%m_to_Z) * irho0**2
518  do i=is,ie
519  tke_river(i) = max(0.0, rmixconst*dr0_ds(i)* &
520  us%T_to_s*(fluxes%lrunoff(i,j) + fluxes%frunoff(i,j)) * s(i,1))
521  enddo
522  else
523  do i=is,ie ; tke_river(i) = 0.0 ; enddo
524  endif
525 
526 
527  if (id_clock_conv>0) call cpu_clock_begin(id_clock_conv)
528 
529  ! The surface forcing is contained in the fluxes type.
530  ! We aggregate the thermodynamic forcing for a time step into the following:
531  ! netMassInOut = water [H ~> m or kg m-2] added/removed via surface fluxes
532  ! netMassOut = water [H ~> m or kg m-2] removed via evaporating surface fluxes
533  ! net_heat = heat via surface fluxes [degC H ~> degC m or degC kg m-2]
534  ! net_salt = salt via surface fluxes [ppt H ~> dppt m or gSalt m-2]
535  ! Pen_SW_bnd = components to penetrative shortwave radiation
536  call extractfluxes1d(g, gv, fluxes, optics, nsw, j, us%T_to_s*dt_in_t, &
537  cs%H_limit_fluxes, cs%use_river_heat_content, cs%use_calving_heat_content, &
538  h(:,1:), t(:,1:), netmassinout, netmassout, net_heat, net_salt, pen_sw_bnd,&
539  tv, aggregate_fw_forcing)
540 
541  ! This subroutine causes the mixed layer to entrain to depth of free convection.
542  call mixedlayer_convection(h(:,1:), d_eb, htot, ttot, stot, uhtot, vhtot, &
543  r0_tot, rcv_tot, u, v, t(:,1:), s(:,1:), &
544  r0(:,1:), rcv(:,1:), eps, &
545  dr0_dt, drcv_dt, dr0_ds, drcv_ds, &
546  netmassinout, netmassout, net_heat, net_salt, &
547  nsw, pen_sw_bnd, opacity_band, conv_en, &
548  dke_fc, j, ksort, g, gv, us, cs, tv, fluxes, dt_in_t, &
549  aggregate_fw_forcing)
550 
551  if (id_clock_conv>0) call cpu_clock_end(id_clock_conv)
552 
553  ! Now the mixed layer undergoes mechanically forced entrainment.
554  ! The mixed layer may entrain down to the Monin-Obukhov depth if the
555  ! surface is becoming lighter, and is effecti1336vely detraining.
556 
557  ! First the TKE at the depth of free convection that is available
558  ! to drive mixing is calculated.
559  if (id_clock_mech>0) call cpu_clock_begin(id_clock_mech)
560 
561  call find_starting_tke(htot, h_ca, fluxes, conv_en, ctke, dke_fc, dke_ca, &
562  tke, tke_river, idecay_len_tke, cmke, dt_in_t, idt_diag, &
563  j, ksort, g, gv, us, cs)
564 
565  ! Here the mechanically driven entrainment occurs.
566  call mechanical_entrainment(h(:,1:), d_eb, htot, ttot, stot, uhtot, vhtot, &
567  r0_tot, rcv_tot, u, v, t(:,1:), s(:,1:), r0(:,1:), rcv(:,1:), eps, dr0_dt, drcv_dt, &
568  cmke, idt_diag, nsw, pen_sw_bnd, opacity_band, tke, &
569  idecay_len_tke, j, ksort, g, gv, us, cs)
570 
571  call absorbremainingsw(g, gv, us, h(:,1:), opacity_band, nsw, optics, j, dt_in_t, &
572  cs%H_limit_fluxes, cs%correct_absorption, cs%absorb_all_SW, &
573  t(:,1:), pen_sw_bnd, eps, ksort, htot, ttot)
574 
575  if (cs%TKE_diagnostics) then ; do i=is,ie
576  cs%diag_TKE_mech_decay(i,j) = cs%diag_TKE_mech_decay(i,j) - idt_diag*tke(i)
577  enddo ; endif
578  if (id_clock_mech>0) call cpu_clock_end(id_clock_mech)
579 
580  ! Calculate the homogeneous mixed layer properties and store them in layer 0.
581  do i=is,ie ; if (htot(i) > 0.0) then
582  ih = 1.0 / htot(i)
583  r0(i,0) = r0_tot(i) * ih ; rcv(i,0) = rcv_tot(i) * ih
584  t(i,0) = ttot(i) * ih ; s(i,0) = stot(i) * ih
585  h(i,0) = htot(i)
586  else ! This may not ever be needed?
587  t(i,0) = t(i,1) ; s(i,0) = s(i,1) ; r0(i,0) = r0(i,1) ; rcv(i,0) = rcv(i,1)
588  h(i,0) = htot(i)
589  endif ; enddo
590  if (write_diags .and. allocated(cs%ML_depth)) then ; do i=is,ie
591  cs%ML_depth(i,j) = h(i,0) * gv%H_to_m ! Rescale the diagnostic.
592  enddo ; endif
593  if (associated(hml)) then ; do i=is,ie
594  hml(i,j) = g%mask2dT(i,j) * (h(i,0) * gv%H_to_m) ! Rescale the diagnostic for output.
595  enddo ; endif
596 
597 ! At this point, return water to the original layers, but constrained to
598 ! still be sorted. After this point, all the water that is in massive
599 ! interior layers will be denser than water remaining in the mixed- and
600 ! buffer-layers. To achieve this, some of these variable density layers
601 ! might be split between two isopycnal layers that are denser than new
602 ! mixed layer or any remaining water from the old mixed- or buffer-layers.
603 ! Alternately, if there are fewer than nkbl of the old buffer or mixed layers
604 ! with any mass, relatively light interior layers might be transferred to
605 ! these unused layers (but not currently in the code).
606 
607  if (cs%ML_resort) then
608  if (id_clock_resort>0) call cpu_clock_begin(id_clock_resort)
609  call resort_ml(h(:,0:), t(:,0:), s(:,0:), r0(:,0:), rcv(:,0:), gv%Rlay, eps, &
610  d_ea, d_eb, ksort, g, gv, cs, dr0_dt, dr0_ds, drcv_dt, drcv_ds)
611  if (id_clock_resort>0) call cpu_clock_end(id_clock_resort)
612  endif
613 
614  if (cs%limit_det .or. (cs%id_Hsfc_max > 0) .or. (cs%id_Hsfc_min > 0)) then
615  do i=is,ie ; hsfc(i) = h(i,0) ; enddo
616  do k=1,nkmb ; do i=is,ie ; hsfc(i) = hsfc(i) + h(i,k) ; enddo ; enddo
617 
618  if (cs%limit_det .or. (cs%id_Hsfc_min > 0)) then
619  dhsfc = cs%lim_det_dH_sfc ; dhd = cs%lim_det_dH_bathy
620  do i=is,ie
621  h_nbr = min(dhsfc*max(hmbl_prev(i-1,j), hmbl_prev(i+1,j), &
622  hmbl_prev(i,j-1), hmbl_prev(i,j+1)), &
623  max(hmbl_prev(i-1,j) - dhd*min(h_sum(i,j),h_sum(i-1,j)), &
624  hmbl_prev(i+1,j) - dhd*min(h_sum(i,j),h_sum(i+1,j)), &
625  hmbl_prev(i,j-1) - dhd*min(h_sum(i,j),h_sum(i,j-1)), &
626  hmbl_prev(i,j+1) - dhd*min(h_sum(i,j),h_sum(i,j+1))) )
627 
628  hsfc_min(i,j) = gv%H_to_Z * max(h(i,0), min(hsfc(i), h_nbr))
629 
630  if (cs%limit_det) max_bl_det(i) = max(0.0, hsfc(i)-h_nbr)
631  enddo
632  endif
633 
634  if (cs%id_Hsfc_max > 0) then ; do i=is,ie
635  hsfc_max(i,j) = gv%H_to_Z * hsfc(i)
636  enddo ; endif
637  endif
638 
639 ! Move water left in the former mixed layer into the buffer layer and
640 ! from the buffer layer into the interior. These steps might best be
641 ! treated in conjuction.
642  if (id_clock_detrain>0) call cpu_clock_begin(id_clock_detrain)
643  if (cs%nkbl == 1) then
644  call mixedlayer_detrain_1(h(:,0:), t(:,0:), s(:,0:), r0(:,0:), rcv(:,0:), &
645  gv%Rlay, dt_in_t, dt__diag, d_ea, d_eb, j, g, gv, us, cs, &
646  drcv_dt, drcv_ds, max_bl_det)
647  elseif (cs%nkbl == 2) then
648  call mixedlayer_detrain_2(h(:,0:), t(:,0:), s(:,0:), r0(:,0:), rcv(:,0:), &
649  gv%Rlay, dt_in_t, dt__diag, d_ea, j, g, gv, us, cs, &
650  dr0_dt, dr0_ds, drcv_dt, drcv_ds, max_bl_det)
651  else ! CS%nkbl not = 1 or 2
652  ! This code only works with 1 or 2 buffer layers.
653  call mom_error(fatal, "MOM_mixed_layer: CS%nkbl must be 1 or 2 for now.")
654  endif
655  if (id_clock_detrain>0) call cpu_clock_end(id_clock_detrain)
656 
657 
658  if (cs%id_Hsfc_used > 0) then
659  do i=is,ie ; hsfc_used(i,j) = gv%H_to_Z * h(i,0) ; enddo
660  do k=cs%nkml+1,nkmb ; do i=is,ie
661  hsfc_used(i,j) = hsfc_used(i,j) + gv%H_to_Z * h(i,k)
662  enddo ; enddo
663  endif
664 
665 ! Now set the properties of the layers in the mixed layer in the original
666 ! 3-d variables.
667  if (cs%Resolve_Ekman .and. (cs%nkml>1)) then
668  ! The thickness of the topmost piece of the mixed layer is given by
669  ! h_1 = H / (3 + sqrt(|f|*H^2/2*nu_max)), which asymptotes to the Ekman
670  ! layer depth and 1/3 of the mixed layer depth. This curve has been
671  ! determined to maximize the impact of the Ekman transport in the mixed
672  ! layer TKE budget with nkml=2. With nkml=3, this should also be used,
673  ! as the third piece will then optimally describe mixed layer
674  ! restratification. For nkml>=4 the whole strategy should be revisited.
675  do i=is,ie
676  ku_star = 0.41*fluxes%ustar(i,j) ! Maybe could be replaced with u*+w*?
677  if (associated(fluxes%ustar_shelf) .and. &
678  associated(fluxes%frac_shelf_h)) then
679  if (fluxes%frac_shelf_h(i,j) > 0.0) &
680  ku_star = (1.0 - fluxes%frac_shelf_h(i,j)) * ku_star + &
681  fluxes%frac_shelf_h(i,j) * (0.41*fluxes%ustar_shelf(i,j))
682  endif
683  absf_x_h = 0.25 * gv%H_to_Z * h(i,0) * &
684  ((abs(g%CoriolisBu(i,j)) + abs(g%CoriolisBu(i-1,j-1))) + &
685  (abs(g%CoriolisBu(i,j-1)) + abs(g%CoriolisBu(i-1,j))))
686  ! If the mixed layer vertical viscosity specification is changed in
687  ! MOM_vert_friction.F90, this line will have to be modified accordingly.
688  h_3d(i,j,1) = h(i,0) / (3.0 + sqrt(absf_x_h*(absf_x_h + 2.0*ku_star) / ku_star**2))
689  do k=2,cs%nkml
690  ! The other layers are evenly distributed through the mixed layer.
691  h_3d(i,j,k) = (h(i,0)-h_3d(i,j,1)) * inkmlm1
692  d_ea(i,k) = d_ea(i,k) + h_3d(i,j,k)
693  d_ea(i,1) = d_ea(i,1) - h_3d(i,j,k)
694  enddo
695  enddo
696  else
697  do i=is,ie
698  h_3d(i,j,1) = h(i,0) * inkml
699  enddo
700  do k=2,cs%nkml ; do i=is,ie
701  h_3d(i,j,k) = h(i,0) * inkml
702  d_ea(i,k) = d_ea(i,k) + h_3d(i,j,k)
703  d_ea(i,1) = d_ea(i,1) - h_3d(i,j,k)
704  enddo ; enddo
705  endif
706  do i=is,ie ; h(i,0) = 0.0 ; enddo
707  do k=1,cs%nkml ; do i=is,ie
708  tv%T(i,j,k) = t(i,0) ; tv%S(i,j,k) = s(i,0)
709  enddo ; enddo
710 
711  ! These sum needs to be done in the original layer space.
712 
713  ! The treatment of layer 1 is atypical because evaporation shows up as
714  ! negative ea(i,1), and because all precipitation goes straight into layer 1.
715  ! The code is ordered so that any roundoff errors in ea are lost the surface.
716 ! do i=is,ie ; eaml(i,1) = 0.0 ; enddo
717 ! do k=2,nz ; do i=is,ie ; eaml(i,k) = eaml(i,k-1) - d_ea(i,k-1) ; enddo ; enddo
718 ! do i=is,ie ; eaml(i,1) = netMassInOut(i) ; enddo
719 
720 
721  do i=is,ie
722 ! eaml(i,nz) is derived from h(i,nz) - h_orig(i,nz) = eaml(i,nz) - ebml(i,nz-1)
723  ebml(i,nz) = 0.0
724  eaml(i,nz) = (h(i,nz) - h_orig(i,nz)) - d_eb(i,nz)
725  enddo
726  do k=nz-1,1,-1 ; do i=is,ie
727  ebml(i,k) = ebml(i,k+1) - d_eb(i,k+1)
728  eaml(i,k) = eaml(i,k+1) + d_ea(i,k)
729  enddo ; enddo
730  do i=is,ie ; eaml(i,1) = netmassinout(i) ; enddo
731 
732  ! Copy the interior thicknesses and other fields back to the 3-d arrays.
733  do k=cs%nkml+1,nz ; do i=is,ie
734  h_3d(i,j,k) = h(i,k); tv%T(i,j,k) = t(i,k) ; tv%S(i,j,k) = s(i,k)
735  enddo ; enddo
736 
737  do k=1,nz ; do i=is,ie
738  ea(i,j,k) = ea(i,j,k) + eaml(i,k)
739  eb(i,j,k) = eb(i,j,k) + ebml(i,k)
740  enddo ; enddo
741 
742  if (cs%id_h_mismatch > 0) then
743  do i=is,ie
744  h_miss(i,j) = gv%H_to_Z * abs(h_3d(i,j,1) - (h_orig(i,1) + &
745  (eaml(i,1) + (ebml(i,1) - eaml(i,1+1)))))
746  enddo
747  do k=2,nz-1 ; do i=is,ie
748  h_miss(i,j) = h_miss(i,j) + gv%H_to_Z * abs(h_3d(i,j,k) - (h_orig(i,k) + &
749  ((eaml(i,k) - ebml(i,k-1)) + (ebml(i,k) - eaml(i,k+1)))))
750  enddo ; enddo
751  do i=is,ie
752  h_miss(i,j) = h_miss(i,j) + gv%H_to_Z * abs(h_3d(i,j,nz) - (h_orig(i,nz) + &
753  ((eaml(i,nz) - ebml(i,nz-1)) + ebml(i,nz))))
754  enddo
755  endif
756 
757  enddo ! j loop
758  !$OMP end parallel
759 
760  ! Whenever thickness changes let the diag manager know, target grids
761  ! for vertical remapping may need to be regenerated.
762  ! This needs to happen after the H update and before the next post_data.
763  call diag_update_remap_grids(cs%diag)
764 
765 
766  if (write_diags) then
767  if (cs%id_ML_depth > 0) &
768  call post_data(cs%id_ML_depth, cs%ML_depth, cs%diag)
769  if (cs%id_TKE_wind > 0) &
770  call post_data(cs%id_TKE_wind, cs%diag_TKE_wind, cs%diag)
771  if (cs%id_TKE_RiBulk > 0) &
772  call post_data(cs%id_TKE_RiBulk, cs%diag_TKE_RiBulk, cs%diag)
773  if (cs%id_TKE_conv > 0) &
774  call post_data(cs%id_TKE_conv, cs%diag_TKE_conv, cs%diag)
775  if (cs%id_TKE_pen_SW > 0) &
776  call post_data(cs%id_TKE_pen_SW, cs%diag_TKE_pen_SW, cs%diag)
777  if (cs%id_TKE_mixing > 0) &
778  call post_data(cs%id_TKE_mixing, cs%diag_TKE_mixing, cs%diag)
779  if (cs%id_TKE_mech_decay > 0) &
780  call post_data(cs%id_TKE_mech_decay, cs%diag_TKE_mech_decay, cs%diag)
781  if (cs%id_TKE_conv_decay > 0) &
782  call post_data(cs%id_TKE_conv_decay, cs%diag_TKE_conv_decay, cs%diag)
783  if (cs%id_TKE_conv_s2 > 0) &
784  call post_data(cs%id_TKE_conv_s2, cs%diag_TKE_conv_s2, cs%diag)
785  if (cs%id_PE_detrain > 0) &
786  call post_data(cs%id_PE_detrain, cs%diag_PE_detrain, cs%diag)
787  if (cs%id_PE_detrain2 > 0) &
788  call post_data(cs%id_PE_detrain2, cs%diag_PE_detrain2, cs%diag)
789  if (cs%id_h_mismatch > 0) &
790  call post_data(cs%id_h_mismatch, h_miss, cs%diag)
791  if (cs%id_Hsfc_used > 0) &
792  call post_data(cs%id_Hsfc_used, hsfc_used, cs%diag)
793  if (cs%id_Hsfc_max > 0) &
794  call post_data(cs%id_Hsfc_max, hsfc_max, cs%diag)
795  if (cs%id_Hsfc_min > 0) &
796  call post_data(cs%id_Hsfc_min, hsfc_min, cs%diag)
797  endif
798 
799 end subroutine bulkmixedlayer
800 
801 !> This subroutine does instantaneous convective entrainment into the buffer
802 !! layers and mixed layers to remove hydrostatic instabilities. Any water that
803 !! is lighter than currently in the mixed- or buffer- layer is entrained.
804 subroutine convective_adjustment(h, u, v, R0, Rcv, T, S, eps, d_eb, &
805  dKE_CA, cTKE, j, G, GV, US, CS, nz_conv)
806  type(ocean_grid_type), intent(in) :: G !< The ocean's grid structure.
807  type(verticalgrid_type), intent(in) :: GV !< The ocean's vertical grid structure.
808  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: h !< Layer thickness [H ~> m or kg m-2].
809  !! The units of h are referred to as H below.
810  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: u !< Zonal velocities interpolated to h
811  !! points, m s-1.
812  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: v !< Zonal velocities interpolated to h
813  !! points, m s-1.
814  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: T !< Layer temperatures [degC].
815  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: S !< Layer salinities [ppt].
816  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: R0 !< Potential density referenced to
817  !! surface pressure [kg m-3].
818  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: Rcv !< The coordinate defining potential
819  !! density [kg m-3].
820  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: d_eb !< The downward increase across a layer
821  !! in the entrainment from below [H ~> m or kg m-2].
822  !! Positive values go with mass gain by
823  !! a layer.
824  real, dimension(SZI_(G),SZK_(GV)), intent(in) :: eps !< The negligibly small amount of water
825  !! that will be left in each layer [H ~> m or kg m-2].
826  real, dimension(SZI_(G),SZK_(GV)), intent(out) :: dKE_CA !< The vertically integrated change in
827  !! kinetic energy due to convective
828  !! adjustment [Z m2 T-2 ~> m3 s-2].
829  real, dimension(SZI_(G),SZK_(GV)), intent(out) :: cTKE !< The buoyant turbulent kinetic energy
830  !! source due to convective adjustment
831  !! [Z m2 T-2 ~> m3 s-2].
832  integer, intent(in) :: j !< The j-index to work on.
833  type(unit_scale_type), intent(in) :: US !< A dimensional unit scaling type
834  type(bulkmixedlayer_cs), pointer :: CS !< The control structure for this module.
835  integer, optional, intent(in) :: nz_conv !< If present, the number of layers
836  !! over which to do convective adjustment
837  !! (perhaps CS%nkml).
838 
839 ! This subroutine does instantaneous convective entrainment into the buffer
840 ! layers and mixed layers to remove hydrostatic instabilities. Any water that
841 ! is lighter than currently in the mixed- or buffer- layer is entrained.
842 
843  ! Local variables
844  real, dimension(SZI_(G)) :: &
845  htot, & ! The total depth of the layers being considered for
846  ! entrainment [H ~> m or kg m-2].
847  r0_tot, & ! The integrated potential density referenced to the surface
848  ! of the layers which are fully entrained [H kg m-3 ~> kg m-2 or kg2 m-5].
849  rcv_tot, & ! The integrated coordinate value potential density of the
850  ! layers that are fully entrained [H kg m-3 ~> kg m-2 or kg2 m-5].
851  ttot, & ! The integrated temperature of layers which are fully
852  ! entrained [degC H ~> degC m or degC kg m-2].
853  stot, & ! The integrated salt of layers which are fully entrained
854  ! [H ppt ~> m ppt or ppt kg m-2].
855  uhtot, & ! The depth integrated zonal and meridional velocities in
856  vhtot, & ! the mixed layer [H m s-1 ~> m2 s-1 or kg m-1 s-1].
857  ke_orig, & ! The total mean kinetic energy in the mixed layer before
858  ! convection, H m2 s-2.
859  h_orig_k1 ! The depth of layer k1 before convective adjustment [H ~> m or kg m-2].
860  real :: h_ent ! The thickness from a layer that is entrained [H ~> m or kg m-2].
861  real :: Ih ! The inverse of a thickness [H-1 ~> m-1 or m2 kg-1].
862  real :: g_H2_2Rho0 ! Half the gravitational acceleration times the square of
863  ! the conversion from H to Z divided by the mean density,
864  ! in [m5 Z T-2 H-2 kg-1 ~> m4 s-2 kg-1 or m10 s-2 kg-3].
865  integer :: is, ie, nz, i, k, k1, nzc, nkmb
866 
867  is = g%isc ; ie = g%iec ; nz = gv%ke
868  g_h2_2rho0 = (us%L_to_m**2*gv%g_Earth * gv%H_to_Z**2) / (2.0 * gv%Rho0)
869  nzc = nz ; if (present(nz_conv)) nzc = nz_conv
870  nkmb = cs%nkml+cs%nkbl
871 
872 ! Undergo instantaneous entrainment into the buffer layers and mixed layers
873 ! to remove hydrostatic instabilities. Any water that is lighter than currently
874 ! in the layer is entrained.
875  do k1=min(nzc-1,nkmb),1,-1
876  do i=is,ie
877  h_orig_k1(i) = h(i,k1)
878  ke_orig(i) = 0.5*h(i,k1)*(u(i,k1)**2 + v(i,k1)**2)
879  uhtot(i) = h(i,k1)*u(i,k1) ; vhtot(i) = h(i,k1)*v(i,k1)
880  r0_tot(i) = r0(i,k1) * h(i,k1)
881  ctke(i,k1) = 0.0 ; dke_ca(i,k1) = 0.0
882 
883  rcv_tot(i) = rcv(i,k1) * h(i,k1)
884  ttot(i) = t(i,k1) * h(i,k1) ; stot(i) = s(i,k1) * h(i,k1)
885  enddo
886  do k=k1+1,nzc
887  do i=is,ie
888  if ((h(i,k) > eps(i,k)) .and. (r0_tot(i) > h(i,k1)*r0(i,k))) then
889  h_ent = h(i,k)-eps(i,k)
890  ctke(i,k1) = ctke(i,k1) + h_ent * g_h2_2rho0 * &
891  (r0_tot(i) - h(i,k1)*r0(i,k)) * cs%nstar2
892  if (k < nkmb) then
893  ctke(i,k1) = ctke(i,k1) + ctke(i,k)
894  dke_ca(i,k1) = dke_ca(i,k1) + dke_ca(i,k)
895  endif
896  r0_tot(i) = r0_tot(i) + h_ent * r0(i,k)
897  ke_orig(i) = ke_orig(i) + 0.5*h_ent* &
898  (u(i,k)*u(i,k) + v(i,k)*v(i,k))
899  uhtot(i) = uhtot(i) + h_ent*u(i,k)
900  vhtot(i) = vhtot(i) + h_ent*v(i,k)
901 
902  rcv_tot(i) = rcv_tot(i) + h_ent * rcv(i,k)
903  ttot(i) = ttot(i) + h_ent * t(i,k)
904  stot(i) = stot(i) + h_ent * s(i,k)
905  h(i,k1) = h(i,k1) + h_ent ; h(i,k) = eps(i,k)
906 
907  d_eb(i,k) = d_eb(i,k) - h_ent
908  d_eb(i,k1) = d_eb(i,k1) + h_ent
909  endif
910  enddo
911  enddo
912 ! Determine the temperature, salinity, and velocities of the mixed or buffer
913 ! layer in question, if it has entrained.
914  do i=is,ie ; if (h(i,k1) > h_orig_k1(i)) then
915  ih = 1.0 / h(i,k1)
916  r0(i,k1) = r0_tot(i) * ih
917  u(i,k1) = uhtot(i) * ih ; v(i,k1) = vhtot(i) * ih
918  dke_ca(i,k1) = dke_ca(i,k1) + gv%H_to_Z * us%T_to_s**2*(cs%bulk_Ri_convective * &
919  (ke_orig(i) - 0.5*h(i,k1)*(u(i,k1)**2 + v(i,k1)**2)))
920  rcv(i,k1) = rcv_tot(i) * ih
921  t(i,k1) = ttot(i) * ih ; s(i,k1) = stot(i) * ih
922  endif ; enddo
923  enddo
924 ! If lower mixed or buffer layers are massless, give them the properties of the
925 ! layer above.
926  do k=2,min(nzc,nkmb) ; do i=is,ie ; if (h(i,k) == 0.0) then
927  r0(i,k) = r0(i,k-1)
928  rcv(i,k) = rcv(i,k-1) ; t(i,k) = t(i,k-1) ; s(i,k) = s(i,k-1)
929  endif ; enddo ; enddo
930 
931 end subroutine convective_adjustment
932 
933 !> This subroutine causes the mixed layer to entrain to the depth of free
934 !! convection. The depth of free convection is the shallowest depth at which the
935 !! fluid is denser than the average of the fluid above.
936 subroutine mixedlayer_convection(h, d_eb, htot, Ttot, Stot, uhtot, vhtot, &
937  R0_tot, Rcv_tot, u, v, T, S, R0, Rcv, eps, &
938  dR0_dT, dRcv_dT, dR0_dS, dRcv_dS, &
939  netMassInOut, netMassOut, Net_heat, Net_salt, &
940  nsw, Pen_SW_bnd, opacity_band, Conv_en, &
941  dKE_FC, j, ksort, G, GV, US, CS, tv, fluxes, dt_in_T, &
942  aggregate_FW_forcing)
943  type(ocean_grid_type), intent(in) :: G !< The ocean's grid structure.
944  type(verticalgrid_type), intent(in) :: GV !< The ocean's vertical grid structure.
945  real, dimension(SZI_(G),SZK_(GV)), &
946  intent(inout) :: h !< Layer thickness [H ~> m or kg m-2].
947  !! The units of h are referred to as H below.
948  real, dimension(SZI_(G),SZK_(GV)), &
949  intent(inout) :: d_eb !< The downward increase across a layer in the
950  !! layer in the entrainment from below [H ~> m or kg m-2].
951  !! Positive values go with mass gain by a layer.
952  real, dimension(SZI_(G)), intent(out) :: htot !< The accumulated mixed layer thickness [H ~> m or kg m-2].
953  real, dimension(SZI_(G)), intent(out) :: Ttot !< The depth integrated mixed layer temperature
954  !! [degC H ~> degC m or degC kg m-2].
955  real, dimension(SZI_(G)), intent(out) :: Stot !< The depth integrated mixed layer salinity
956  !! [ppt H ~> ppt m or ppt kg m-2].
957  real, dimension(SZI_(G)), intent(out) :: uhtot !< The depth integrated mixed layer zonal
958  !! velocity, H m s-1.
959  real, dimension(SZI_(G)), intent(out) :: vhtot !< The integrated mixed layer meridional
960  !! velocity, H m s-1.
961  real, dimension(SZI_(G)), intent(out) :: R0_tot !< The integrated mixed layer potential density referenced
962  !! to 0 pressure [H kg m-2 ~> kg m-1 or kg2 m-4].
963  real, dimension(SZI_(G)), intent(out) :: Rcv_tot !< The integrated mixed layer coordinate
964  !! variable potential density [H kg m-2 ~> kg m-1 or kg2 m-4].
965  real, dimension(SZI_(G),SZK_(GV)), &
966  intent(in) :: u !< Zonal velocities interpolated to h points, m s-1.
967  real, dimension(SZI_(G),SZK_(GV)), &
968  intent(in) :: v !< Zonal velocities interpolated to h points, m s-1.
969  real, dimension(SZI_(G),SZK_(GV)), &
970  intent(in) :: T !< Layer temperatures [degC].
971  real, dimension(SZI_(G),SZK_(GV)), &
972  intent(in) :: S !< Layer salinities [ppt].
973  real, dimension(SZI_(G),SZK_(GV)), &
974  intent(in) :: R0 !< Potential density referenced to
975  !! surface pressure [kg m-3].
976  real, dimension(SZI_(G),SZK_(GV)), &
977  intent(in) :: Rcv !< The coordinate defining potential
978  !! density [kg m-3].
979  real, dimension(SZI_(G),SZK_(GV)), &
980  intent(in) :: eps !< The negligibly small amount of water
981  !! that will be left in each layer [H ~> m or kg m-2].
982  real, dimension(SZI_(G)), intent(in) :: dR0_dT !< The partial derivative of R0 with respect to
983  !! temperature [kg m-3 degC-1].
984  real, dimension(SZI_(G)), intent(in) :: dRcv_dT !< The partial derivative of Rcv with respect to
985  !! temperature [kg m-3 degC-1].
986  real, dimension(SZI_(G)), intent(in) :: dR0_dS !< The partial derivative of R0 with respect to
987  !! salinity [kg m-3 ppt-1].
988  real, dimension(SZI_(G)), intent(in) :: dRcv_dS !< The partial derivative of Rcv with respect to
989  !! salinity [kg m-3 ppt-1].
990  real, dimension(SZI_(G)), intent(in) :: netMassInOut !< The net mass flux (if non-Boussinesq)
991  !! or volume flux (if Boussinesq) into the ocean
992  !! within a time step [H ~> m or kg m-2]. (I.e. P+R-E.)
993  real, dimension(SZI_(G)), intent(in) :: netMassOut !< The mass or volume flux out of the ocean
994  !! within a time step [H ~> m or kg m-2].
995  real, dimension(SZI_(G)), intent(in) :: Net_heat !< The net heating at the surface over a time
996  !! step [degC H ~> degC m or degC kg m-2]. Any penetrating
997  !! shortwave radiation is not included in Net_heat.
998  real, dimension(SZI_(G)), intent(in) :: Net_salt !< The net surface salt flux into the ocean
999  !! over a time step [ppt H ~> ppt m or ppt kg m-2].
1000  integer, intent(in) :: nsw !< The number of bands of penetrating
1001  !! shortwave radiation.
1002  real, dimension(max(nsw,1),SZI_(G)), intent(inout) :: Pen_SW_bnd !< The penetrating shortwave
1003  !! heating at the sea surface in each penetrating
1004  !! band [degC H ~> degC m or degC kg m-2].
1005  real, dimension(max(nsw,1),SZI_(G),SZK_(GV)), intent(in) :: opacity_band !< The opacity in each band of
1006  !! penetrating shortwave radiation [H-1 ~> m-1 or m2 kg-1].
1007  real, dimension(SZI_(G)), intent(out) :: Conv_en !< The buoyant turbulent kinetic energy source
1008  !! due to free convection [Z m2 T-2 ~> m3 s-2].
1009  real, dimension(SZI_(G)), intent(out) :: dKE_FC !< The vertically integrated change in kinetic
1010  !! energy due to free convection [Z m2 T-2 ~> m3 s-2].
1011  integer, intent(in) :: j !< The j-index to work on.
1012  integer, dimension(SZI_(G),SZK_(GV)), &
1013  intent(in) :: ksort !< The density-sorted k-indices.
1014  type(unit_scale_type), intent(in) :: US !< A dimensional unit scaling type
1015  type(bulkmixedlayer_cs), pointer :: CS !< The control structure for this module.
1016  type(thermo_var_ptrs), intent(inout) :: tv !< A structure containing pointers to any
1017  !! available thermodynamic fields. Absent
1018  !! fields have NULL ptrs.
1019  type(forcing), intent(inout) :: fluxes !< A structure containing pointers to any
1020  !! possible forcing fields. Unused fields
1021  !! have NULL ptrs.
1022  real, intent(in) :: dt_in_T !< Time increment [T ~> s].
1023  logical, intent(in) :: aggregate_FW_forcing !< If true, the net incoming and
1024  !! outgoing surface freshwater fluxes are
1025  !! combined before being applied, instead of
1026  !! being applied separately.
1027 
1028 ! This subroutine causes the mixed layer to entrain to the depth of free
1029 ! convection. The depth of free convection is the shallowest depth at which the
1030 ! fluid is denser than the average of the fluid above.
1031 
1032  ! Local variables
1033  real, dimension(SZI_(G)) :: &
1034  massOutRem, & ! Evaporation that remains to be supplied [H ~> m or kg m-2].
1035  netMassIn ! mass entering through ocean surface [H ~> m or kg m-2]
1036  real :: SW_trans ! The fraction of shortwave radiation
1037  ! that is not absorbed in a layer [nondim].
1038  real :: Pen_absorbed ! The amount of penetrative shortwave radiation
1039  ! that is absorbed in a layer [degC H ~> degC m or degC kg m-2].
1040  real :: h_avail ! The thickness in a layer available for
1041  ! entrainment [H ~> m or kg m-2].
1042  real :: h_ent ! The thickness from a layer that is entrained [H ~> m or kg m-2].
1043  real :: T_precip ! The temperature of the precipitation [degC].
1044  real :: C1_3, C1_6 ! 1/3 and 1/6.
1045  real :: En_fn, Frac, x1 ! Nondimensional temporary variables.
1046  real :: dr, dr0 ! Temporary variables [kg m-3 H ~> kg m-2 or kg2 m-5].
1047  real :: dr_ent, dr_comp ! Temporary variables [kg m-3 H ~> kg m-2 or kg2 m-5].
1048  real :: dr_dh ! The partial derivative of dr_ent with h_ent [kg m-3].
1049  real :: h_min, h_max ! The minimum, maximum, and previous estimates for
1050  real :: h_prev ! h_ent [H ~> m or kg m-2].
1051  real :: h_evap ! The thickness that is evaporated [H ~> m or kg m-2].
1052  real :: dh_Newt ! The Newton's method estimate of the change in
1053  ! h_ent between iterations [H ~> m or kg m-2].
1054  real :: g_H2_2Rho0 ! Half the gravitational acceleration times the square of
1055  ! the conversion from H to Z divided by the mean density,
1056  ! [m7 T-2 Z-1 H-2 kg-1 ~> m4 s-2 kg-1 or m10 s-2 kg-3].
1057  real :: Angstrom ! The minimum layer thickness [H ~> m or kg m-2].
1058  real :: opacity ! The opacity converted to inverse thickness units [H-1 ~> m-1 or m2 kg-1]
1059  real :: sum_Pen_En ! The potential energy change due to penetrating
1060  ! shortwave radiation, integrated over a layer
1061  ! [H kg m-3 ~> kg m-2 or kg2 m-5].
1062  real :: Idt ! 1.0/dt [T-1 ~> s-1]
1063  real :: netHeatOut ! accumulated heat content of mass leaving ocean
1064  integer :: is, ie, nz, i, k, ks, itt, n
1065  real, dimension(max(nsw,1)) :: &
1066  C2, & ! Temporary variable [kg m-3 H-1 ~> kg m-4 or m-1].
1067  r_SW_top ! Temporary variables [H kg m-3 ~> kg m-2 or kg2 m-5].
1068 
1069  angstrom = gv%Angstrom_H
1070  c1_3 = 1.0/3.0 ; c1_6 = 1.0/6.0
1071  g_h2_2rho0 = (us%L_to_m**2*gv%g_Earth * gv%H_to_Z**2) / (2.0 * gv%Rho0)
1072  idt = 1.0 / dt_in_t
1073  is = g%isc ; ie = g%iec ; nz = gv%ke
1074 
1075  do i=is,ie ; if (ksort(i,1) > 0) then
1076  k = ksort(i,1)
1077 
1078  if (aggregate_fw_forcing) then
1079  massoutrem(i) = 0.0
1080  if (netmassinout(i) < 0.0) massoutrem(i) = -netmassinout(i)
1081  netmassin(i) = netmassinout(i) + massoutrem(i)
1082  else
1083  massoutrem(i) = -netmassout(i)
1084  netmassin(i) = netmassinout(i) - netmassout(i)
1085  endif
1086 
1087  ! htot is an Angstrom (taken from layer 1) plus any net precipitation.
1088  h_ent = max(min(angstrom,h(i,k)-eps(i,k)),0.0)
1089  htot(i) = h_ent + netmassin(i)
1090  h(i,k) = h(i,k) - h_ent
1091  d_eb(i,k) = d_eb(i,k) - h_ent
1092 
1093  pen_absorbed = 0.0
1094  do n=1,nsw ; if (pen_sw_bnd(n,i) > 0.0) then
1095  sw_trans = exp(-htot(i)*opacity_band(n,i,k))
1096  pen_absorbed = pen_absorbed + pen_sw_bnd(n,i) * (1.0-sw_trans)
1097  pen_sw_bnd(n,i) = pen_sw_bnd(n,i) * sw_trans
1098  endif ; enddo
1099 
1100  ! Precipitation is assumed to have the same temperature and velocity
1101  ! as layer 1. Because layer 1 might not be the topmost layer, this
1102  ! involves multiple terms.
1103  t_precip = t(i,1)
1104  ttot(i) = (net_heat(i) + (netmassin(i) * t_precip + h_ent * t(i,k))) + &
1105  pen_absorbed
1106  ! Net_heat contains both heat fluxes and the heat content of mass fluxes.
1107  !! Ttot(i) = netMassIn(i) * T_precip + h_ent * T(i,k)
1108  !! Ttot(i) = Net_heat(i) + Ttot(i)
1109  !! Ttot(i) = Ttot(i) + Pen_absorbed
1110  ! smg:
1111  ! Ttot(i) = (Net_heat(i) + (h_ent * T(i,k))) + Pen_absorbed
1112  stot(i) = h_ent*s(i,k) + net_salt(i)
1113  uhtot(i) = u(i,1)*netmassin(i) + u(i,k)*h_ent
1114  vhtot(i) = v(i,1)*netmassin(i) + v(i,k)*h_ent
1115  r0_tot(i) = (h_ent*r0(i,k) + netmassin(i)*r0(i,1)) + &
1116 ! dR0_dT(i)*netMassIn(i)*(T_precip - T(i,1)) + &
1117  (dr0_dt(i)*(net_heat(i) + pen_absorbed) - &
1118  dr0_ds(i) * (netmassin(i) * s(i,1) - net_salt(i)))
1119  rcv_tot(i) = (h_ent*rcv(i,k) + netmassin(i)*rcv(i,1)) + &
1120 ! dRcv_dT(i)*netMassIn(i)*(T_precip - T(i,1)) + &
1121  (drcv_dt(i)*(net_heat(i) + pen_absorbed) - &
1122  drcv_ds(i) * (netmassin(i) * s(i,1) - net_salt(i)))
1123  conv_en(i) = 0.0 ; dke_fc(i) = 0.0
1124  if (associated(fluxes%heat_content_massin)) &
1125  fluxes%heat_content_massin(i,j) = fluxes%heat_content_massin(i,j) + us%s_to_T * &
1126  t_precip * netmassin(i) * gv%H_to_kg_m2 * fluxes%C_p * idt
1127  if (associated(tv%TempxPmE)) tv%TempxPmE(i,j) = tv%TempxPmE(i,j) + &
1128  t_precip * netmassin(i) * gv%H_to_kg_m2
1129  endif ; enddo
1130 
1131  ! Now do netMassOut case in this block.
1132  ! At this point htot contains an Angstrom of fluid from layer 0 plus netMassIn.
1133  do ks=1,nz
1134  do i=is,ie ; if (ksort(i,ks) > 0) then
1135  k = ksort(i,ks)
1136 
1137  if ((htot(i) < angstrom) .and. (h(i,k) > eps(i,k))) then
1138  ! If less than an Angstrom was available from the layers above plus
1139  ! any precipitation, add more fluid from this layer.
1140  h_ent = min(angstrom-htot(i), h(i,k)-eps(i,k))
1141  htot(i) = htot(i) + h_ent
1142  h(i,k) = h(i,k) - h_ent
1143  d_eb(i,k) = d_eb(i,k) - h_ent
1144 
1145  r0_tot(i) = r0_tot(i) + h_ent*r0(i,k)
1146  uhtot(i) = uhtot(i) + h_ent*u(i,k)
1147  vhtot(i) = vhtot(i) + h_ent*v(i,k)
1148 
1149  rcv_tot(i) = rcv_tot(i) + h_ent*rcv(i,k)
1150  ttot(i) = ttot(i) + h_ent*t(i,k)
1151  stot(i) = stot(i) + h_ent*s(i,k)
1152  endif
1153 
1154  ! Water is removed from the topmost layers with any mass.
1155  ! We may lose layers if they are thin enough.
1156  ! The salt that is left behind goes into Stot.
1157  if ((massoutrem(i) > 0.0) .and. (h(i,k) > eps(i,k))) then
1158  if (massoutrem(i) > (h(i,k) - eps(i,k))) then
1159  h_evap = h(i,k) - eps(i,k)
1160  h(i,k) = eps(i,k)
1161  massoutrem(i) = massoutrem(i) - h_evap
1162  else
1163  h_evap = massoutrem(i)
1164  h(i,k) = h(i,k) - h_evap
1165  massoutrem(i) = 0.0
1166  endif
1167 
1168  stot(i) = stot(i) + h_evap*s(i,k)
1169  r0_tot(i) = r0_tot(i) + dr0_ds(i)*h_evap*s(i,k)
1170  rcv_tot(i) = rcv_tot(i) + drcv_ds(i)*h_evap*s(i,k)
1171  d_eb(i,k) = d_eb(i,k) - h_evap
1172 
1173  ! smg: when resolve the A=B code, we will set
1174  ! heat_content_massout = heat_content_massout - T(i,k)*h_evap*GV%H_to_kg_m2*fluxes%C_p*Idt
1175  ! by uncommenting the lines here.
1176  ! we will also then completely remove TempXpme from the model.
1177  if (associated(fluxes%heat_content_massout)) &
1178  fluxes%heat_content_massout(i,j) = fluxes%heat_content_massout(i,j) - us%s_to_T * &
1179  t(i,k)*h_evap*gv%H_to_kg_m2 * fluxes%C_p * idt
1180  if (associated(tv%TempxPmE)) tv%TempxPmE(i,j) = tv%TempxPmE(i,j) - &
1181  t(i,k)*h_evap*gv%H_to_kg_m2
1182 
1183  endif
1184 
1185  ! The following section calculates how much fluid will be entrained.
1186  h_avail = h(i,k) - eps(i,k)
1187  if (h_avail > 0.0) then
1188  dr = r0_tot(i) - htot(i)*r0(i,k)
1189  h_ent = 0.0
1190 
1191  dr0 = dr
1192  do n=1,nsw ; if (pen_sw_bnd(n,i) > 0.0) then
1193  dr0 = dr0 - (dr0_dt(i)*pen_sw_bnd(n,i)) * &
1194  opacity_band(n,i,k)*htot(i)
1195  endif ; enddo
1196 
1197  ! Some entrainment will occur from this layer.
1198  if (dr0 > 0.0) then
1199  dr_comp = dr
1200  do n=1,nsw ; if (pen_sw_bnd(n,i) > 0.0) then
1201  ! Compare the density at the bottom of a layer with the
1202  ! density averaged over the mixed layer and that layer.
1203  opacity = opacity_band(n,i,k)
1204  sw_trans = exp(-h_avail*opacity)
1205  dr_comp = dr_comp + (dr0_dt(i)*pen_sw_bnd(n,i)) * &
1206  ((1.0 - sw_trans) - opacity*(htot(i)+h_avail)*sw_trans)
1207  endif ; enddo
1208  if (dr_comp >= 0.0) then
1209  ! The entire layer is entrained.
1210  h_ent = h_avail
1211  else
1212  ! The layer is partially entrained. Iterate to determine how much
1213  ! entrainment occurs. Solve for the h_ent at which dr_ent = 0.
1214 
1215  ! Instead of assuming that the curve is linear between the two end
1216  ! points, assume that the change is concentrated near small values
1217  ! of entrainment. On average, this saves about 1 iteration.
1218  frac = dr0 / (dr0 - dr_comp)
1219  h_ent = h_avail * frac*frac
1220  h_min = 0.0 ; h_max = h_avail
1221 
1222  do n=1,nsw
1223  r_sw_top(n) = dr0_dt(i) * pen_sw_bnd(n,i)
1224  c2(n) = r_sw_top(n) * opacity_band(n,i,k)**2
1225  enddo
1226  do itt=1,10
1227  dr_ent = dr ; dr_dh = 0.0
1228  do n=1,nsw
1229  opacity = opacity_band(n,i,k)
1230  sw_trans = exp(-h_ent*opacity)
1231  dr_ent = dr_ent + r_sw_top(n) * ((1.0 - sw_trans) - &
1232  opacity*(htot(i)+h_ent)*sw_trans)
1233  dr_dh = dr_dh + c2(n) * (htot(i)+h_ent) * sw_trans
1234  enddo
1235 
1236  if (dr_ent > 0.0) then
1237  h_min = h_ent
1238  else
1239  h_max = h_ent
1240  endif
1241 
1242  dh_newt = -dr_ent / dr_dh
1243  h_prev = h_ent ; h_ent = h_prev+dh_newt
1244  if (h_ent > h_max) then
1245  h_ent = 0.5*(h_prev+h_max)
1246  elseif (h_ent < h_min) then
1247  h_ent = 0.5*(h_prev+h_min)
1248  endif
1249 
1250  if (abs(dh_newt) < 0.2*angstrom) exit
1251  enddo
1252 
1253  endif
1254 
1255  ! Now that the amount of entrainment (h_ent) has been determined,
1256  ! calculate changes in various terms.
1257  sum_pen_en = 0.0 ; pen_absorbed = 0.0
1258  do n=1,nsw ; if (pen_sw_bnd(n,i) > 0.0) then
1259  opacity = opacity_band(n,i,k)
1260  sw_trans = exp(-h_ent*opacity)
1261 
1262  x1 = h_ent*opacity
1263  if (x1 < 2.0e-5) then
1264  en_fn = (opacity*htot(i)*(1.0 - 0.5*(x1 - c1_3*x1)) + &
1265  x1*x1*c1_6)
1266  else
1267  en_fn = ((opacity*htot(i) + 2.0) * &
1268  ((1.0-sw_trans) / x1) - 1.0 + sw_trans)
1269  endif
1270  sum_pen_en = sum_pen_en - (dr0_dt(i)*pen_sw_bnd(n,i)) * en_fn
1271 
1272  pen_absorbed = pen_absorbed + pen_sw_bnd(n,i) * (1.0 - sw_trans)
1273  pen_sw_bnd(n,i) = pen_sw_bnd(n,i) * sw_trans
1274  endif ; enddo
1275 
1276  conv_en(i) = conv_en(i) + g_h2_2rho0 * h_ent * &
1277  ( (r0_tot(i) - r0(i,k)*htot(i)) + sum_pen_en )
1278 
1279  r0_tot(i) = r0_tot(i) + (h_ent * r0(i,k) + pen_absorbed*dr0_dt(i))
1280  stot(i) = stot(i) + h_ent * s(i,k)
1281  ttot(i) = ttot(i) + (h_ent * t(i,k) + pen_absorbed)
1282  rcv_tot(i) = rcv_tot(i) + (h_ent * rcv(i,k) + pen_absorbed*drcv_dt(i))
1283  endif ! dr0 > 0.0
1284 
1285  if (h_ent > 0.0) then
1286  if (htot(i) > 0.0) &
1287  dke_fc(i) = dke_fc(i) + cs%bulk_Ri_convective * 0.5 * &
1288  ((gv%H_to_Z*h_ent) / (htot(i)*(h_ent+htot(i)))) * &
1289  us%T_to_s**2*((uhtot(i)-u(i,k)*htot(i))**2 + (vhtot(i)-v(i,k)*htot(i))**2)
1290 
1291  htot(i) = htot(i) + h_ent
1292  h(i,k) = h(i,k) - h_ent
1293  d_eb(i,k) = d_eb(i,k) - h_ent
1294  uhtot(i) = u(i,k)*h_ent ; vhtot(i) = v(i,k)*h_ent
1295  endif
1296 
1297 
1298  endif ! h_avail>0
1299  endif ; enddo ! i loop
1300  enddo ! k loop
1301 
1302 end subroutine mixedlayer_convection
1303 
1304 !> This subroutine determines the TKE available at the depth of free
1305 !! convection to drive mechanical entrainment.
1306 subroutine find_starting_tke(htot, h_CA, fluxes, Conv_En, cTKE, dKE_FC, dKE_CA, &
1307  TKE, TKE_river, Idecay_len_TKE, cMKE, dt_in_T, Idt_diag, &
1308  j, ksort, G, GV, US, CS)
1309  type(ocean_grid_type), intent(in) :: G !< The ocean's grid structure.
1310  type(verticalgrid_type), intent(in) :: GV !< The ocean's vertical grid structure.
1311  type(unit_scale_type), intent(in) :: US !< A dimensional unit scaling type
1312  real, dimension(SZI_(G)), intent(in) :: htot !< The accumulated mixed layer thickness
1313  !! [H ~> m or kg m-2]
1314  real, dimension(SZI_(G)), intent(in) :: h_CA !< The mixed layer depth after convective
1315  !! adjustment [H ~> m or kg m-2].
1316  type(forcing), intent(in) :: fluxes !< A structure containing pointers to any
1317  !! possible forcing fields. Unused fields
1318  !! have NULL ptrs.
1319  real, dimension(SZI_(G)), intent(inout) :: Conv_En !< The buoyant turbulent kinetic energy source
1320  !! due to free convection [Z m2 T-2 ~> m3 s-2].
1321  real, dimension(SZI_(G)), intent(in) :: dKE_FC !< The vertically integrated change in
1322  !! kinetic energy due to free convection
1323  !! [Z m2 T-2 ~> m3 s-2].
1324  real, dimension(SZI_(G),SZK_(GV)), &
1325  intent(in) :: cTKE !< The buoyant turbulent kinetic energy
1326  !! source due to convective adjustment
1327  !! [Z m2 T-2 ~> m3 s-2].
1328  real, dimension(SZI_(G),SZK_(GV)), &
1329  intent(in) :: dKE_CA !< The vertically integrated change in
1330  !! kinetic energy due to convective
1331  !! adjustment [Z m2 T-2 ~> m3 s-2].
1332  real, dimension(SZI_(G)), intent(out) :: TKE !< The turbulent kinetic energy available for
1333  !! mixing over a time step [Z m2 T-2 ~> m3 s-2].
1334  real, dimension(SZI_(G)), intent(out) :: Idecay_len_TKE !< The inverse of the vertical decay
1335  !! scale for TKE [H-1 ~> m-1 or m2 kg-1].
1336  real, dimension(SZI_(G)), intent(in) :: TKE_river !< The source of turbulent kinetic energy
1337  !! available for driving mixing at river mouths
1338  !! [Z m2 T-3 ~> m3 s-3].
1339  real, dimension(2,SZI_(G)), intent(out) :: cMKE !< Coefficients of HpE and HpE^2 in
1340  !! calculating the denominator of MKE_rate,
1341  !! [H-1 ~> m-1 or m2 kg-1] and [H-2 ~> m-2 or m4 kg-2].
1342  real, intent(in) :: dt_in_T !< The time step [T ~> s].
1343  real, intent(in) :: Idt_diag !< The inverse of the accumulated diagnostic
1344  !! time interval [T-1 ~> s-1].
1345  integer, intent(in) :: j !< The j-index to work on.
1346  integer, dimension(SZI_(G),SZK_(GV)), &
1347  intent(in) :: ksort !< The density-sorted k-indicies.
1348  type(bulkmixedlayer_cs), pointer :: CS !< The control structure for this module.
1349 
1350 ! This subroutine determines the TKE available at the depth of free
1351 ! convection to drive mechanical entrainment.
1352 
1353  ! Local variables
1354  real :: dKE_conv ! The change in mean kinetic energy due to all convection [Z m2 T-2 ~> m3 s-2].
1355  real :: nstar_FC ! The effective efficiency with which the energy released by
1356  ! free convection is converted to TKE, often ~0.2 [nondim].
1357  real :: nstar_CA ! The effective efficiency with which the energy released by
1358  ! convective adjustment is converted to TKE, often ~0.2 [nondim].
1359  real :: TKE_CA ! The potential energy released by convective adjustment if
1360  ! that release is positive [Z m2 T-2 ~> m3 s-2].
1361  real :: MKE_rate_CA ! MKE_rate for convective adjustment [nondim], 0 to 1.
1362  real :: MKE_rate_FC ! MKE_rate for free convection [nondim], 0 to 1.
1363  real :: totEn_Z ! The total potential energy released by convection, [Z3 T-2 ~> m3 s-2].
1364  real :: Ih ! The inverse of a thickness [H-1 ~> m-1 or m2 kg-1].
1365  real :: exp_kh ! The nondimensional decay of TKE across a layer [nondim].
1366  real :: absf ! The absolute value of f averaged to thickness points [T-1 ~> s-1].
1367  real :: U_star ! The friction velocity [Z T-1 ~> m s-1].
1368  real :: absf_Ustar ! The absolute value of f divided by U_star [Z-1 ~> m-1].
1369  real :: wind_TKE_src ! The surface wind source of TKE [Z m2 T-3 ~> m3 s-3].
1370  real :: diag_wt ! The ratio of the current timestep to the diagnostic
1371  ! timestep (which may include 2 calls) [nondim].
1372  integer :: is, ie, nz, i
1373 
1374  is = g%isc ; ie = g%iec ; nz = gv%ke
1375  diag_wt = dt_in_t * idt_diag
1376 
1377  if (cs%omega_frac >= 1.0) absf = 2.0*cs%omega
1378  do i=is,ie
1379  u_star = fluxes%ustar(i,j)
1380  if (associated(fluxes%ustar_shelf) .and. associated(fluxes%frac_shelf_h)) then
1381  if (fluxes%frac_shelf_h(i,j) > 0.0) &
1382  u_star = (1.0 - fluxes%frac_shelf_h(i,j)) * u_star + &
1383  fluxes%frac_shelf_h(i,j) * fluxes%ustar_shelf(i,j)
1384  endif
1385 
1386  if (u_star < cs%ustar_min) u_star = cs%ustar_min
1387  if (cs%omega_frac < 1.0) then
1388  absf = 0.25*((abs(g%CoriolisBu(i,j)) + abs(g%CoriolisBu(i-1,j-1))) + &
1389  (abs(g%CoriolisBu(i,j-1)) + abs(g%CoriolisBu(i-1,j))))
1390  if (cs%omega_frac > 0.0) &
1391  absf = sqrt(cs%omega_frac*4.0*cs%omega**2 + (1.0-cs%omega_frac)*absf**2)
1392  endif
1393  absf_ustar = absf / u_star
1394  idecay_len_tke(i) = (absf_ustar * cs%TKE_decay) * gv%H_to_Z
1395 
1396 ! The first number in the denominator could be anywhere up to 16. The
1397 ! value of 3 was chosen to minimize the time-step dependence of the amount
1398 ! of shear-driven mixing in 10 days of a 1-degree global model, emphasizing
1399 ! the equatorial areas. Although it is not cast as a parameter, it should
1400 ! be considered an empirical parameter, and it might depend strongly on the
1401 ! number of sublayers in the mixed layer and their locations.
1402 ! The 0.41 is VonKarman's constant. This equation assumes that small & large
1403 ! scales contribute to mixed layer deepening at similar rates, even though
1404 ! small scales are dissipated more rapidly (implying they are less efficient).
1405 ! Ih = 1.0/(16.0*0.41*U_star*dt)
1406  ih = gv%H_to_Z/(3.0*0.41*u_star*dt_in_t)
1407  cmke(1,i) = 4.0 * ih ; cmke(2,i) = (absf_ustar*gv%H_to_Z) * ih
1408 
1409  if (idecay_len_tke(i) > 0.0) then
1410  exp_kh = exp(-htot(i)*idecay_len_tke(i))
1411  else
1412  exp_kh = 1.0
1413  endif
1414 
1415 ! Here nstar is a function of the natural Rossby number 0.2/(1+0.2/Ro), based
1416 ! on a curve fit from the data of Wang (GRL, 2003).
1417 ! Note: Ro = 1.0/sqrt(0.5 * dt * (absf*htot(i))**3 / totEn)
1418  if (conv_en(i) < 0.0) conv_en(i) = 0.0
1419  if (ctke(i,1) > 0.0) then ; tke_ca = ctke(i,1) ; else ; tke_ca = 0.0 ; endif
1420  if ((htot(i) >= h_ca(i)) .or. (tke_ca == 0.0)) then
1421  toten_z = us%m_to_Z**2 * (conv_en(i) + tke_ca)
1422 
1423  if (toten_z > 0.0) then
1424  nstar_fc = cs%nstar * toten_z / (toten_z + 0.2 * &
1425  sqrt(0.5 * dt_in_t * (absf*(htot(i)*gv%H_to_Z))**3 * toten_z))
1426  else
1427  nstar_fc = cs%nstar
1428  endif
1429  nstar_ca = nstar_fc
1430  else
1431  ! This reconstructs the Buoyancy flux within the topmost htot of water.
1432  if (conv_en(i) > 0.0) then
1433  toten_z = us%m_to_Z**2 * (conv_en(i) + tke_ca * (htot(i) / h_ca(i)) )
1434  nstar_fc = cs%nstar * toten_z / (toten_z + 0.2 * &
1435  sqrt(0.5 * dt_in_t * (absf*(htot(i)*gv%H_to_Z))**3 * toten_z))
1436  else
1437  nstar_fc = cs%nstar
1438  endif
1439 
1440  toten_z = us%m_to_Z**2 * (conv_en(i) + tke_ca)
1441  if (tke_ca > 0.0) then
1442  nstar_ca = cs%nstar * toten_z / (toten_z + 0.2 * &
1443  sqrt(0.5 * dt_in_t * (absf*(h_ca(i)*gv%H_to_Z))**3 * toten_z))
1444  else
1445  nstar_ca = cs%nstar
1446  endif
1447  endif
1448 
1449  if (dke_fc(i) + dke_ca(i,1) > 0.0) then
1450  if (htot(i) >= h_ca(i)) then
1451  mke_rate_fc = 1.0 / (1.0 + htot(i)*(cmke(1,i) + cmke(2,i)*htot(i)) )
1452  mke_rate_ca = mke_rate_fc
1453  else
1454  mke_rate_fc = 1.0 / (1.0 + htot(i)*(cmke(1,i) + cmke(2,i)*htot(i)) )
1455  mke_rate_ca = 1.0 / (1.0 + h_ca(i)*(cmke(1,i) + cmke(2,i)*h_ca(i)) )
1456  endif
1457  else
1458  ! This branch just saves unnecessary calculations.
1459  mke_rate_fc = 1.0 ; mke_rate_ca = 1.0
1460  endif
1461 
1462  dke_conv = dke_ca(i,1) * mke_rate_ca + dke_fc(i) * mke_rate_fc
1463 ! At this point, it is assumed that cTKE is positive and stored in TKE_CA!
1464 ! Note: Removed factor of 2 in u*^3 terms.
1465  tke(i) = (dt_in_t*cs%mstar)*((us%Z_to_m**2*(u_star*u_star*u_star))*exp_kh) + &
1466  (exp_kh * dke_conv + nstar_fc*conv_en(i) + nstar_ca * tke_ca)
1467 
1468  if (cs%do_rivermix) then ! Add additional TKE at river mouths
1469  tke(i) = tke(i) + tke_river(i)*dt_in_t*exp_kh
1470  endif
1471 
1472  if (cs%TKE_diagnostics) then
1473  wind_tke_src = cs%mstar*(us%Z_to_m**2*u_star*u_star*u_star) * diag_wt
1474  cs%diag_TKE_wind(i,j) = cs%diag_TKE_wind(i,j) + &
1475  ( wind_tke_src + tke_river(i) * diag_wt )
1476  cs%diag_TKE_RiBulk(i,j) = cs%diag_TKE_RiBulk(i,j) + dke_conv*idt_diag
1477  cs%diag_TKE_mech_decay(i,j) = cs%diag_TKE_mech_decay(i,j) + &
1478  (exp_kh-1.0)*(wind_tke_src + dke_conv*idt_diag)
1479  cs%diag_TKE_conv(i,j) = cs%diag_TKE_conv(i,j) + &
1480  idt_diag * (nstar_fc*conv_en(i) + nstar_ca*tke_ca)
1481  cs%diag_TKE_conv_decay(i,j) = cs%diag_TKE_conv_decay(i,j) + &
1482  idt_diag * ((cs%nstar-nstar_fc)*conv_en(i) + (cs%nstar-nstar_ca)*tke_ca)
1483  cs%diag_TKE_conv_s2(i,j) = cs%diag_TKE_conv_s2(i,j) + &
1484  idt_diag * (ctke(i,1)-tke_ca)
1485  endif
1486  enddo
1487 
1488 end subroutine find_starting_tke
1489 
1490 !> This subroutine calculates mechanically driven entrainment.
1491 subroutine mechanical_entrainment(h, d_eb, htot, Ttot, Stot, uhtot, vhtot, &
1492  R0_tot, Rcv_tot, u, v, T, S, R0, Rcv, eps, &
1493  dR0_dT, dRcv_dT, cMKE, Idt_diag, nsw, &
1494  Pen_SW_bnd, opacity_band, TKE, &
1495  Idecay_len_TKE, j, ksort, G, GV, US, CS)
1496  type(ocean_grid_type), intent(in) :: G !< The ocean's grid structure.
1497  type(verticalgrid_type), intent(in) :: GV !< The ocean's vertical grid structure.
1498  type(unit_scale_type), intent(in) :: US !< A dimensional unit scaling type
1499  real, dimension(SZI_(G),SZK_(GV)), &
1500  intent(inout) :: h !< Layer thickness [H ~> m or kg m-2].
1501  real, dimension(SZI_(G),SZK_(GV)), &
1502  intent(inout) :: d_eb !< The downward increase across a layer in the
1503  !! layer in the entrainment from below [H ~> m or kg m-2].
1504  !! Positive values go with mass gain by a layer.
1505  real, dimension(SZI_(G)), intent(inout) :: htot !< The accumlated mixed layer thickness [H ~> m or kg m-2].
1506  real, dimension(SZI_(G)), intent(inout) :: Ttot !< The depth integrated mixed layer temperature
1507  !! [degC H ~> degC m or degC kg m-2].
1508  real, dimension(SZI_(G)), intent(inout) :: Stot !< The depth integrated mixed layer salinity
1509  !! [ppt H ~> ppt m or ppt kg m-2].
1510  real, dimension(SZI_(G)), intent(inout) :: uhtot !< The depth integrated mixed layer zonal
1511  !! velocity, H m s-1.
1512  real, dimension(SZI_(G)), intent(inout) :: vhtot !< The integrated mixed layer meridional
1513  !! velocity, H m s-1.
1514  real, dimension(SZI_(G)), intent(inout) :: R0_tot !< The integrated mixed layer potential density
1515  !! referenced to 0 pressure [H kg m-3 ~> kg m-2 or kg2 m-5].
1516  real, dimension(SZI_(G)), intent(inout) :: Rcv_tot !< The integrated mixed layer coordinate variable
1517  !! potential density [H kg m-3 ~> kg m-2 or kg2 m-5].
1518  real, dimension(SZI_(G),SZK_(GV)), &
1519  intent(in) :: u !< Zonal velocities interpolated to h points, m s-1.
1520  real, dimension(SZI_(G),SZK_(GV)), &
1521  intent(in) :: v !< Zonal velocities interpolated to h points, m s-1.
1522  real, dimension(SZI_(G),SZK_(GV)), &
1523  intent(in) :: T !< Layer temperatures [degC].
1524  real, dimension(SZI_(G),SZK_(GV)), &
1525  intent(in) :: S !< Layer salinities [ppt].
1526  real, dimension(SZI_(G),SZK_(GV)), &
1527  intent(in) :: R0 !< Potential density referenced to
1528  !! surface pressure [kg m-3].
1529  real, dimension(SZI_(G),SZK_(GV)), &
1530  intent(in) :: Rcv !< The coordinate defining potential
1531  !! density [kg m-3].
1532  real, dimension(SZI_(G),SZK_(GV)), &
1533  intent(in) :: eps !< The negligibly small amount of water
1534  !! that will be left in each layer [H ~> m or kg m-2].
1535  real, dimension(SZI_(G)), intent(in) :: dR0_dT !< The partial derivative of R0 with respect to
1536  !! temperature [kg m-3 degC-1].
1537  real, dimension(SZI_(G)), intent(in) :: dRcv_dT !< The partial derivative of Rcv with respect to
1538  !! temperature [kg m-3 degC-1].
1539  real, dimension(2,SZI_(G)), intent(in) :: cMKE !< Coefficients of HpE and HpE^2 used in calculating the
1540  !! denominator of MKE_rate; the two elements have differing
1541  !! units of [H-1 ~> m-1 or m2 kg-1] and [H-2 ~> m-2 or m4 kg-2].
1542  real, intent(in) :: Idt_diag !< The inverse of the accumulated diagnostic
1543  !! time interval [T-1 ~> s-1].
1544  integer, intent(in) :: nsw !< The number of bands of penetrating
1545  !! shortwave radiation.
1546  real, dimension(max(nsw,1),SZI_(G)), intent(inout) :: Pen_SW_bnd !< The penetrating shortwave
1547  !! heating at the sea surface in each penetrating
1548  !! band [degC H ~> degC m or degC kg m-2].
1549  real, dimension(max(nsw,1),SZI_(G),SZK_(GV)), intent(in) :: opacity_band !< The opacity in each band of
1550  !! penetrating shortwave radiation [H-1 ~> m-1 or m2 kg-1].
1551  real, dimension(SZI_(G)), intent(inout) :: TKE !< The turbulent kinetic energy
1552  !! available for mixing over a time
1553  !! step [Z m2 T-2 ~> m3 s-2].
1554  real, dimension(SZI_(G)), intent(inout) :: Idecay_len_TKE !< The vertical TKE decay rate [H-1 ~> m-1 or m2 kg-1].
1555  integer, intent(in) :: j !< The j-index to work on.
1556  integer, dimension(SZI_(G),SZK_(GV)), &
1557  intent(in) :: ksort !< The density-sorted k-indicies.
1558  type(bulkmixedlayer_cs), pointer :: CS !< The control structure for this module.
1559 
1560 ! This subroutine calculates mechanically driven entrainment.
1561 
1562  ! Local variables
1563  real :: SW_trans ! The fraction of shortwave radiation that is not
1564  ! absorbed in a layer, nondimensional.
1565  real :: Pen_absorbed ! The amount of penetrative shortwave radiation
1566  ! that is absorbed in a layer [degC H ~> degC m or degC kg m-2].
1567  real :: h_avail ! The thickness in a layer available for entrainment [H ~> m or kg m-2].
1568  real :: h_ent ! The thickness from a layer that is entrained [H ~> m or kg m-2].
1569  real :: h_min, h_max ! Limits on the solution for h_ent [H ~> m or kg m-2].
1570  real :: dh_Newt ! The Newton's method estimate of the change in
1571  ! h_ent between iterations [H ~> m or kg m-2].
1572  real :: MKE_rate ! The fraction of the energy in resolved shears
1573  ! within the mixed layer that will be eliminated
1574  ! within a timestep, nondim, 0 to 1.
1575  real :: HpE ! The current thickness plus entrainment [H ~> m or kg m-2].
1576  real :: g_H_2Rho0 ! Half the gravitational acceleration times the
1577  ! conversion from H to m divided by the mean density,
1578  ! in [m5 T-2 H-1 kg-1 ~> m4 s-2 kg-1 or m7 s-2 kg-2].
1579  real :: TKE_full_ent ! The TKE remaining if a layer is fully entrained
1580  ! [Z m2 T-2 ~> m3 s-2].
1581  real :: dRL ! Work required to mix water from the next layer
1582  ! across the mixed layer [m2 T-2 ~> m2 s-2].
1583  real :: Pen_En_Contrib ! Penetrating SW contributions to the changes in
1584  ! TKE, divided by layer thickness in m [m2 T2 ~> m2 s-2].
1585  real :: Cpen1 ! A temporary variable [m2 T-2 ~> m2 s-2].
1586  real :: dMKE ! A temporary variable related to the release of mean
1587  ! kinetic energy [H Z m2 T-2 ~> m4 s-2 or kg m s-2]
1588  real :: TKE_ent ! The TKE that remains if h_ent were entrained [Z m2 T-2 ~> m3 s-2].
1589  real :: TKE_ent1 ! The TKE that would remain, without considering the
1590  ! release of mean kinetic energy [Z m2 T-2 ~> m3 s-2].
1591  real :: dTKE_dh ! The partial derivative of TKE with h_ent [Z m2 T-2 H-1 ~> m2 s-2 or m5 s-2 kg-1].
1592  real :: Pen_dTKE_dh_Contrib ! The penetrating shortwave contribution to
1593  ! dTKE_dh [m2 T-2 ~> m2 s-2].
1594  real :: EF4_val ! The result of EF4() (see later) [H-1 ~> m-1 or m2 kg-1].
1595  real :: h_neglect ! A thickness that is so small it is usually lost
1596  ! in roundoff and can be neglected [H ~> m or kg m-2].
1597  real :: dEF4_dh ! The partial derivative of EF4 with h [H-2 ~> m-2 or m4 kg-2].
1598  real :: Pen_En1 ! A nondimensional temporary variable.
1599  real :: kh, exp_kh ! Nondimensional temporary variables related to the
1600  real :: f1_kh ! fractional decay of TKE across a layer.
1601  real :: x1, e_x1 ! Nondimensional temporary variables related to
1602  real :: f1_x1, f2_x1 ! the relative decay of TKE and SW radiation across
1603  real :: f3_x1 ! a layer, and exponential-related functions of x1.
1604  real :: E_HxHpE ! Entrainment divided by the product of the new and old
1605  ! thicknesses [H-1 ~> m-1 or m2 kg-1].
1606  real :: Hmix_min ! The minimum mixed layer depth [H ~> m or kg m-2].
1607  real :: opacity
1608  real :: C1_3, C1_6, C1_24 ! 1/3, 1/6, and 1/24.
1609  integer :: is, ie, nz, i, k, ks, itt, n
1610 
1611  c1_3 = 1.0/3.0 ; c1_6 = 1.0/6.0 ; c1_24 = 1.0/24.0
1612  g_h_2rho0 = (us%L_to_m**2*gv%g_Earth * gv%H_to_Z) / (2.0 * gv%Rho0)
1613  hmix_min = cs%Hmix_min
1614  h_neglect = gv%H_subroundoff
1615  is = g%isc ; ie = g%iec ; nz = gv%ke
1616 
1617  do ks=1,nz
1618 
1619  do i=is,ie ; if (ksort(i,ks) > 0) then
1620  k = ksort(i,ks)
1621 
1622  h_avail = h(i,k) - eps(i,k)
1623  if ((h_avail > 0.) .and. ((tke(i) > 0.) .or. (htot(i) < hmix_min))) then
1624  drl = g_h_2rho0 * (r0(i,k)*htot(i) - r0_tot(i) )
1625  dmke = (gv%H_to_Z * cs%bulk_Ri_ML) * 0.5 * us%T_to_s**2 * &
1626  ((uhtot(i)-u(i,k)*htot(i))**2 + (vhtot(i)-v(i,k)*htot(i))**2)
1627 
1628 ! Find the TKE that would remain if the entire layer were entrained.
1629  kh = idecay_len_tke(i)*h_avail ; exp_kh = exp(-kh)
1630  if (kh >= 2.0e-5) then ; f1_kh = (1.0-exp_kh) / kh
1631  else ; f1_kh = (1.0 - kh*(0.5 - c1_6*kh)) ; endif
1632 
1633  pen_en_contrib = 0.0
1634  do n=1,nsw ; if (pen_sw_bnd(n,i) > 0.0) then
1635  opacity = opacity_band(n,i,k)
1636 ! Two different forms are used here to make sure that only negative
1637 ! values are taken into exponentials to avoid excessively large
1638 ! numbers. They are, of course, mathematically identical.
1639  if (idecay_len_tke(i) > opacity) then
1640  x1 = (idecay_len_tke(i) - opacity) * h_avail
1641  if (x1 >= 2.0e-5) then
1642  e_x1 = exp(-x1) ; f1_x1 = ((1.0-e_x1)/(x1))
1643  f3_x1 = ((e_x1-(1.0-x1))/(x1*x1))
1644  else
1645  f1_x1 = (1.0 - x1*(0.5 - c1_6*x1))
1646  f3_x1 = (0.5 - x1*(c1_6 - c1_24*x1))
1647  endif
1648 
1649  pen_en1 = exp(-opacity*h_avail) * &
1650  ((1.0+opacity*htot(i))*f1_x1 + opacity*h_avail*f3_x1)
1651  else
1652  x1 = (opacity - idecay_len_tke(i)) * h_avail
1653  if (x1 >= 2.0e-5) then
1654  e_x1 = exp(-x1) ; f1_x1 = ((1.0-e_x1)/(x1))
1655  f2_x1 = ((1.0-(1.0+x1)*e_x1)/(x1*x1))
1656  else
1657  f1_x1 = (1.0 - x1*(0.5 - c1_6*x1))
1658  f2_x1 = (0.5 - x1*(c1_3 - 0.125*x1))
1659  endif
1660 
1661  pen_en1 = exp_kh * ((1.0+opacity*htot(i))*f1_x1 + &
1662  opacity*h_avail*f2_x1)
1663  endif
1664  pen_en_contrib = pen_en_contrib + &
1665  (g_h_2rho0*dr0_dt(i)*pen_sw_bnd(n,i)) * (pen_en1 - f1_kh)
1666  endif ; enddo
1667 
1668  hpe = htot(i)+h_avail
1669  mke_rate = 1.0/(1.0 + (cmke(1,i)*hpe + cmke(2,i)*hpe**2))
1670  ef4_val = ef4(htot(i)+h_neglect,h_avail,idecay_len_tke(i))
1671  tke_full_ent = (exp_kh*tke(i) - (h_avail*gv%H_to_Z)*(drl*f1_kh + pen_en_contrib)) + &
1672  mke_rate*dmke*ef4_val
1673  if ((tke_full_ent >= 0.0) .or. (h_avail+htot(i) <= hmix_min)) then
1674  ! The layer will be fully entrained.
1675  h_ent = h_avail
1676 
1677  if (cs%TKE_diagnostics) then
1678  e_hxhpe = h_ent / ((htot(i)+h_neglect)*(htot(i)+h_ent+h_neglect))
1679  cs%diag_TKE_mech_decay(i,j) = cs%diag_TKE_mech_decay(i,j) + &
1680  idt_diag * ((exp_kh-1.0)*tke(i) + (h_ent*gv%H_to_Z)*drl*(1.0-f1_kh) + &
1681  mke_rate*dmke*(ef4_val-e_hxhpe))
1682  cs%diag_TKE_mixing(i,j) = cs%diag_TKE_mixing(i,j) - &
1683  idt_diag*(gv%H_to_Z*h_ent)*drl
1684  cs%diag_TKE_pen_SW(i,j) = cs%diag_TKE_pen_SW(i,j) - &
1685  idt_diag*(gv%H_to_Z*h_ent)*pen_en_contrib
1686  cs%diag_TKE_RiBulk(i,j) = cs%diag_TKE_RiBulk(i,j) + &
1687  idt_diag*mke_rate*dmke*e_hxhpe
1688  endif
1689 
1690  tke(i) = tke_full_ent
1691  !### The minimum TKE value in this line may be problematically small.
1692  if (tke(i) <= 0.0) tke(i) = 1.0e-150*us%T_to_s**2*us%m_to_Z
1693  else
1694 ! The layer is only partially entrained. The amount that will be
1695 ! entrained is determined iteratively. No further layers will be
1696 ! entrained.
1697  h_min = 0.0 ; h_max = h_avail
1698  if (tke(i) <= 0.0) then
1699  h_ent = 0.0
1700  else
1701  h_ent = h_avail * tke(i) / (tke(i) - tke_full_ent)
1702 
1703  do itt=1,15
1704  ! Evaluate the TKE that would remain if h_ent were entrained.
1705 
1706  kh = idecay_len_tke(i)*h_ent ; exp_kh = exp(-kh)
1707  if (kh >= 2.0e-5) then
1708  f1_kh = (1.0-exp_kh) / kh
1709  else
1710  f1_kh = (1.0 - kh*(0.5 - c1_6*kh))
1711  endif
1712 
1713 
1714  pen_en_contrib = 0.0 ; pen_dtke_dh_contrib = 0.0
1715  do n=1,nsw ; if (pen_sw_bnd(n,i) > 0.0) then
1716  ! Two different forms are used here to make sure that only negative
1717  ! values are taken into exponentials to avoid excessively large
1718  ! numbers. They are, of course, mathematically identical.
1719  opacity = opacity_band(n,i,k)
1720  sw_trans = exp(-h_ent*opacity)
1721  if (idecay_len_tke(i) > opacity) then
1722  x1 = (idecay_len_tke(i) - opacity) * h_ent
1723  if (x1 >= 2.0e-5) then
1724  e_x1 = exp(-x1) ; f1_x1 = ((1.0-e_x1)/(x1))
1725  f3_x1 = ((e_x1-(1.0-x1))/(x1*x1))
1726  else
1727  f1_x1 = (1.0 - x1*(0.5 - c1_6*x1))
1728  f3_x1 = (0.5 - x1*(c1_6 - c1_24*x1))
1729  endif
1730  pen_en1 = sw_trans * ((1.0+opacity*htot(i))*f1_x1 + &
1731  opacity*h_ent*f3_x1)
1732  else
1733  x1 = (opacity - idecay_len_tke(i)) * h_ent
1734  if (x1 >= 2.0e-5) then
1735  e_x1 = exp(-x1) ; f1_x1 = ((1.0-e_x1)/(x1))
1736  f2_x1 = ((1.0-(1.0+x1)*e_x1)/(x1*x1))
1737  else
1738  f1_x1 = (1.0 - x1*(0.5 - c1_6*x1))
1739  f2_x1 = (0.5 - x1*(c1_3 - 0.125*x1))
1740  endif
1741 
1742  pen_en1 = exp_kh * ((1.0+opacity*htot(i))*f1_x1 + &
1743  opacity*h_ent*f2_x1)
1744  endif
1745  cpen1 = g_h_2rho0*dr0_dt(i)*pen_sw_bnd(n,i)
1746  pen_en_contrib = pen_en_contrib + cpen1*(pen_en1 - f1_kh)
1747  pen_dtke_dh_contrib = pen_dtke_dh_contrib + &
1748  cpen1*((1.0-sw_trans) - opacity*(htot(i) + h_ent)*sw_trans)
1749  endif ; enddo ! (Pen_SW_bnd(n,i) > 0.0)
1750 
1751  tke_ent1 = exp_kh*tke(i) - (h_ent*gv%H_to_Z)*(drl*f1_kh + pen_en_contrib)
1752  ef4_val = ef4(htot(i)+h_neglect,h_ent,idecay_len_tke(i),def4_dh)
1753  hpe = htot(i)+h_ent
1754  mke_rate = 1.0/(1.0 + (cmke(1,i)*hpe + cmke(2,i)*hpe**2))
1755  tke_ent = tke_ent1 + dmke*ef4_val*mke_rate
1756  ! TKE_ent is the TKE that would remain if h_ent were entrained.
1757 
1758  dtke_dh = ((-idecay_len_tke(i)*tke_ent1 - drl*gv%H_to_Z) + &
1759  pen_dtke_dh_contrib*gv%H_to_Z) + dmke * mke_rate* &
1760  (def4_dh - ef4_val*mke_rate*(cmke(1,i)+2.0*cmke(2,i)*hpe))
1761  ! dh_Newt = -TKE_ent / dTKE_dh
1762  ! Bisect if the Newton's method prediction is outside of the bounded range.
1763  if (tke_ent > 0.0) then
1764  if ((h_max-h_ent)*(-dtke_dh) > tke_ent) then
1765  dh_newt = -tke_ent / dtke_dh
1766  else
1767  dh_newt = 0.5*(h_max-h_ent)
1768  endif
1769  h_min = h_ent
1770  else
1771  if ((h_min-h_ent)*(-dtke_dh) < tke_ent) then
1772  dh_newt = -tke_ent / dtke_dh
1773  else
1774  dh_newt = 0.5*(h_min-h_ent)
1775  endif
1776  h_max = h_ent
1777  endif
1778  h_ent = h_ent + dh_newt
1779 
1780  if (abs(dh_newt) < 0.2*gv%Angstrom_H) exit
1781  enddo
1782  endif
1783 
1784  if (h_ent < hmix_min-htot(i)) h_ent = hmix_min - htot(i)
1785 
1786  if (cs%TKE_diagnostics) then
1787  hpe = htot(i)+h_ent
1788  mke_rate = 1.0/(1.0 + cmke(1,i)*hpe + cmke(2,i)*hpe**2)
1789  ef4_val = ef4(htot(i)+h_neglect,h_ent,idecay_len_tke(i))
1790 
1791  e_hxhpe = h_ent / ((htot(i)+h_neglect)*(hpe+h_neglect))
1792  cs%diag_TKE_mech_decay(i,j) = cs%diag_TKE_mech_decay(i,j) + &
1793  idt_diag * ((exp_kh-1.0)*tke(i) + (h_ent*gv%H_to_Z)*drl*(1.0-f1_kh) + &
1794  dmke*mke_rate*(ef4_val-e_hxhpe))
1795  cs%diag_TKE_mixing(i,j) = cs%diag_TKE_mixing(i,j) - &
1796  idt_diag*(h_ent*gv%H_to_Z)*drl
1797  cs%diag_TKE_pen_SW(i,j) = cs%diag_TKE_pen_SW(i,j) - &
1798  idt_diag*(h_ent*gv%H_to_Z)*pen_en_contrib
1799  cs%diag_TKE_RiBulk(i,j) = cs%diag_TKE_RiBulk(i,j) + &
1800  idt_diag*dmke*mke_rate*e_hxhpe
1801  endif
1802 
1803  tke(i) = 0.0
1804  endif ! TKE_full_ent > 0.0
1805 
1806  pen_absorbed = 0.0
1807  do n=1,nsw ; if (pen_sw_bnd(n,i) > 0.0) then
1808  sw_trans = exp(-h_ent*opacity_band(n,i,k))
1809  pen_absorbed = pen_absorbed + pen_sw_bnd(n,i) * (1.0 - sw_trans)
1810  pen_sw_bnd(n,i) = pen_sw_bnd(n,i) * sw_trans
1811  endif ; enddo
1812 
1813  htot(i) = htot(i) + h_ent
1814  r0_tot(i) = r0_tot(i) + (h_ent * r0(i,k) + pen_absorbed*dr0_dt(i))
1815  h(i,k) = h(i,k) - h_ent
1816  d_eb(i,k) = d_eb(i,k) - h_ent
1817 
1818  stot(i) = stot(i) + h_ent * s(i,k)
1819  ttot(i) = ttot(i) + (h_ent * t(i,k) + pen_absorbed)
1820  rcv_tot(i) = rcv_tot(i) + (h_ent*rcv(i,k) + pen_absorbed*drcv_dt(i))
1821 
1822  uhtot(i) = uhtot(i) + u(i,k)*h_ent
1823  vhtot(i) = vhtot(i) + v(i,k)*h_ent
1824  endif ! h_avail > 0.0 .AND TKE(i) > 0.0
1825 
1826  endif ; enddo ! i loop
1827  enddo ! k loop
1828 
1829 end subroutine mechanical_entrainment
1830 
1831 !> This subroutine generates an array of indices that are sorted by layer
1832 !! density.
1833 subroutine sort_ml(h, R0, eps, G, GV, CS, ksort)
1834  type(ocean_grid_type), intent(in) :: G !< The ocean's grid structure.
1835  type(verticalgrid_type), intent(in) :: GV !< The ocean's vertical grid structure.
1836  real, dimension(SZI_(G),SZK_(GV)), intent(in) :: h !< Layer thickness [H ~> m or kg m-2].
1837  real, dimension(SZI_(G),SZK_(GV)), intent(in) :: R0 !< The potential density used to sort
1838  !! the layers [kg m-3].
1839  real, dimension(SZI_(G),SZK_(GV)), intent(in) :: eps !< The (small) thickness that must
1840  !! remain in each layer [H ~> m or kg m-2].
1841  type(bulkmixedlayer_cs), pointer :: CS !< The control structure returned by a
1842  !! previous call to mixedlayer_init.
1843  integer, dimension(SZI_(G),SZK_(GV)), intent(out) :: ksort !< The k-index to use in the sort.
1844 
1845  ! Local variables
1846  real :: R0sort(SZI_(G),SZK_(GV))
1847  integer :: nsort(SZI_(G))
1848  logical :: done_sorting(SZI_(G))
1849  integer :: i, k, ks, is, ie, nz, nkmb
1850 
1851  is = g%isc ; ie = g%iec ; nz = gv%ke
1852  nkmb = cs%nkml+cs%nkbl
1853 
1854  ! Come up with a sorted index list of layers with increasing R0.
1855  ! Assume that the layers below nkmb are already stably stratified.
1856  ! Only layers that are thicker than eps are in the list. Extra elements
1857  ! have an index of -1.
1858 
1859  ! This is coded using straight insertion, on the assumption that the
1860  ! layers are usually in the right order (or massless) anyway.
1861 
1862  do k=1,nz ; do i=is,ie ; ksort(i,k) = -1 ; enddo ; enddo
1863 
1864  do i=is,ie ; nsort(i) = 0 ; done_sorting(i) = .false. ; enddo
1865  do k=1,nz ; do i=is,ie ; if (h(i,k) > eps(i,k)) then
1866  if (done_sorting(i)) then ; ks = nsort(i) ; else
1867  do ks=nsort(i),1,-1
1868  if (r0(i,k) >= r0sort(i,ks)) exit
1869  r0sort(i,ks+1) = r0sort(i,ks) ; ksort(i,ks+1) = ksort(i,ks)
1870  enddo
1871  if ((k > nkmb) .and. (ks == nsort(i))) done_sorting(i) = .true.
1872  endif
1873 
1874  ksort(i,ks+1) = k
1875  r0sort(i,ks+1) = r0(i,k)
1876  nsort(i) = nsort(i) + 1
1877  endif ; enddo ; enddo
1878 
1879 end subroutine sort_ml
1880 
1881 !> This subroutine actually moves properties between layers to achieve a
1882 !! resorted state, with all of the resorted water either moved into the correct
1883 !! interior layers or in the top nkmb layers.
1884 subroutine resort_ml(h, T, S, R0, Rcv, RcvTgt, eps, d_ea, d_eb, ksort, G, GV, CS, &
1885  dR0_dT, dR0_dS, dRcv_dT, dRcv_dS)
1886  type(ocean_grid_type), intent(in) :: G !< The ocean's grid structure.
1887  type(verticalgrid_type), intent(in) :: GV !< The ocean's vertical grid
1888  !! structure.
1889  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: h !< Layer thickness [H ~> m or kg m-2].
1890  !! Layer 0 is the new mixed layer.
1891  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: T !< Layer temperatures [degC].
1892  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: S !< Layer salinities [ppt].
1893  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: R0 !< Potential density referenced to
1894  !! surface pressure [kg m-3].
1895  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: Rcv !< The coordinate defining
1896  !! potential density [kg m-3].
1897  real, dimension(SZK_(GV)), intent(in) :: RcvTgt !< The target value of Rcv for each
1898  !! layer [kg m-3].
1899  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: eps !< The (small) thickness that must
1900  !! remain in each layer [H ~> m or kg m-2].
1901  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: d_ea !< The upward increase across a
1902  !! layer in the entrainment from
1903  !! above [H ~> m or kg m-2].
1904  !! Positive d_ea goes with layer
1905  !! thickness increases.
1906  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: d_eb !< The downward increase across a
1907  !! layer in the entrainment from
1908  !! below [H ~> m or kg m-2]. Positive values go
1909  !! with mass gain by a layer.
1910  integer, dimension(SZI_(G),SZK_(GV)), intent(in) :: ksort !< The density-sorted k-indicies.
1911  type(bulkmixedlayer_cs), pointer :: CS !< The control structure for this
1912  !! module.
1913  real, dimension(SZI_(G)), intent(in) :: dR0_dT !< The partial derivative of
1914  !! potential density referenced
1915  !! to the surface with potential
1916  !! temperature [kg m-3 degC-1].
1917  real, dimension(SZI_(G)), intent(in) :: dR0_dS !< The partial derivative of
1918  !! cpotential density referenced
1919  !! to the surface with salinity,
1920  !! [kg m-3 ppt-1].
1921  real, dimension(SZI_(G)), intent(in) :: dRcv_dT !< The partial derivative of
1922  !! coordinate defining potential
1923  !! density with potential
1924  !! temperature [kg m-3 degC-1].
1925  real, dimension(SZI_(G)), intent(in) :: dRcv_dS !< The partial derivative of
1926  !! coordinate defining potential
1927  !! density with salinity,
1928  !! [kg m-3 ppt-1].
1929 
1930 ! If there are no massive light layers above the deepest of the mixed- and
1931 ! buffer layers, do nothing (except perhaps to reshuffle these layers).
1932 ! If there are nkbl or fewer layers above the deepest mixed- or buffer-
1933 ! layers, move them (in sorted order) into the buffer layers, even if they
1934 ! were previously interior layers.
1935 ! If there are interior layers that are intermediate in density (both in-situ
1936 ! and the coordinate density (sigma-2)) between the newly forming mixed layer
1937 ! and a residual buffer- or mixed layer, and the number of massive layers above
1938 ! the deepest massive buffer or mixed layer is greater than nkbl, then split
1939 ! those buffer layers into peices that match the target density of the two
1940 ! nearest interior layers.
1941 ! Otherwise, if there are more than nkbl+1 remaining massive layers
1942 
1943  ! Local variables
1944  real :: h_move, h_tgt_old, I_hnew
1945  real :: dT_dS_wt2, dT_dR, dS_dR, I_denom
1946  real :: Rcv_int
1947  real :: T_up, S_up, R0_up, I_hup, h_to_up
1948  real :: T_dn, S_dn, R0_dn, I_hdn, h_to_dn
1949  real :: wt_dn
1950  real :: dR1, dR2
1951  real :: dPE, hmin, min_dPE, min_hmin
1952  real, dimension(SZK_(GV)) :: &
1953  h_tmp, R0_tmp, T_tmp, S_tmp, Rcv_tmp
1954  integer :: ks_min
1955  logical :: sorted, leave_in_layer
1956  integer :: ks_deep(SZI_(G)), k_count(SZI_(G)), ks2_reverse(SZI_(G), SZK_(GV))
1957  integer :: ks2(SZK_(GV))
1958  integer :: i, k, ks, is, ie, nz, k1, k2, k_tgt, k_src, k_int_top
1959  integer :: nks, nkmb, num_interior, top_interior_ks
1960 
1961  is = g%isc ; ie = g%iec ; nz = gv%ke
1962  nkmb = cs%nkml+cs%nkbl
1963 
1964  dt_ds_wt2 = cs%dT_dS_wt**2
1965 
1966 ! Find out how many massive layers are above the deepest buffer or mixed layer.
1967  do i=is,ie ; ks_deep(i) = -1 ; k_count(i) = 0 ; enddo
1968  do ks=nz,1,-1 ; do i=is,ie ; if (ksort(i,ks) > 0) then
1969  k = ksort(i,ks)
1970 
1971  if (h(i,k) > eps(i,k)) then
1972  if (ks_deep(i) == -1) then
1973  if (k <= nkmb) then
1974  ks_deep(i) = ks ; k_count(i) = k_count(i) + 1
1975  ks2_reverse(i,k_count(i)) = k
1976  endif
1977  else
1978  k_count(i) = k_count(i) + 1
1979  ks2_reverse(i,k_count(i)) = k
1980  endif
1981  endif
1982  endif ; enddo ; enddo
1983 
1984  do i=is,ie ; if (k_count(i) > 1) then
1985  ! This column might need to be reshuffled.
1986  nks = k_count(i)
1987 
1988  ! Put ks2 in the right order and check whether reshuffling is needed.
1989  sorted = .true.
1990  ks2(nks) = ks2_reverse(i,1)
1991  do ks=nks-1,1,-1
1992  ks2(ks) = ks2_reverse(i,1+nks-ks)
1993  if (ks2(ks) > ks2(ks+1)) sorted = .false.
1994  enddo
1995 
1996  ! Go to the next column of no reshuffling is needed.
1997  if (sorted) cycle
1998 
1999  ! Find out how many interior layers are being reshuffled. If none,
2000  ! then this is a simple swapping procedure.
2001  num_interior = 0 ; top_interior_ks = 0
2002  do ks=nks,1,-1 ; if (ks2(ks) > nkmb) then
2003  num_interior = num_interior+1 ; top_interior_ks = ks
2004  endif ; enddo
2005 
2006  if (num_interior >= 1) then
2007  ! Find the lightest interior layer with a target coordinate density
2008  ! greater than the newly forming mixed layer.
2009  do k=nkmb+1,nz ; if (rcv(i,0) < rcvtgt(k)) exit ; enddo
2010  k_int_top = k ; rcv_int = rcvtgt(k)
2011 
2012  i_denom = 1.0 / (drcv_ds(i)**2 + dt_ds_wt2*drcv_dt(i)**2)
2013  dt_dr = dt_ds_wt2*drcv_dt(i) * i_denom
2014  ds_dr = drcv_ds(i) * i_denom
2015 
2016 
2017  ! Examine whether layers can be split out of existence. Stop when there
2018  ! is a layer that cannot be handled this way, or when the topmost formerly
2019  ! interior layer has been dealt with.
2020  do ks = nks,top_interior_ks,-1
2021  k = ks2(ks)
2022  leave_in_layer = .false.
2023  if ((k > nkmb) .and. (rcv(i,k) <= rcvtgt(k))) then
2024  if (rcvtgt(k)-rcv(i,k) < cs%BL_split_rho_tol*(rcvtgt(k) - rcvtgt(k-1))) &
2025  leave_in_layer = .true.
2026  elseif (k > nkmb) then
2027  if (rcv(i,k)-rcvtgt(k) < cs%BL_split_rho_tol*(rcvtgt(k+1) - rcvtgt(k))) &
2028  leave_in_layer = .true.
2029  endif
2030 
2031  if (leave_in_layer) then
2032  ! Just drop this layer from the sorted list.
2033  nks = nks-1
2034  elseif (rcv(i,k) < rcv_int) then
2035  ! There is no interior layer with a target density that is intermediate
2036  ! between this layer and the mixed layer.
2037  exit
2038  else
2039  ! Try splitting the layer between two interior isopycnal layers.
2040  ! Find the target densities that bracket this layer.
2041  do k2=k_int_top+1,nz ; if (rcv(i,k) < rcvtgt(k2)) exit ; enddo
2042  if (k2>nz) exit
2043 
2044  ! This layer is bracketed in density between layers k2-1 and k2.
2045 
2046  dr1 = (rcvtgt(k2-1) - rcv(i,k)) ; dr2 = (rcvtgt(k2) - rcv(i,k))
2047  t_up = t(i,k) + dt_dr * dr1
2048  s_up = s(i,k) + ds_dr * dr1
2049  t_dn = t(i,k) + dt_dr * dr2
2050  s_dn = s(i,k) + ds_dr * dr2
2051 
2052  r0_up = r0(i,k) + (dt_dr*dr0_dt(i) + ds_dr*dr0_ds(i)) * dr1
2053  r0_dn = r0(i,k) + (dt_dr*dr0_dt(i) + ds_dr*dr0_ds(i)) * dr2
2054 
2055  ! Make sure the new properties are acceptable.
2056  if ((r0_up > r0(i,0)) .or. (r0_dn > r0(i,0))) &
2057  ! Avoid creating obviously unstable profiles.
2058  exit
2059 
2060  wt_dn = (rcv(i,k) - rcvtgt(k2-1)) / (rcvtgt(k2) - rcvtgt(k2-1))
2061  h_to_up = (h(i,k)-eps(i,k)) * (1.0 - wt_dn)
2062  h_to_dn = (h(i,k)-eps(i,k)) * wt_dn
2063 
2064  i_hup = 1.0 / (h(i,k2-1) + h_to_up)
2065  i_hdn = 1.0 / (h(i,k2) + h_to_dn)
2066  r0(i,k2-1) = (r0(i,k2)*h(i,k2-1) + r0_up*h_to_up) * i_hup
2067  r0(i,k2) = (r0(i,k2)*h(i,k2) + r0_dn*h_to_dn) * i_hdn
2068 
2069  t(i,k2-1) = (t(i,k2)*h(i,k2-1) + t_up*h_to_up) * i_hup
2070  t(i,k2) = (t(i,k2)*h(i,k2) + t_dn*h_to_dn) * i_hdn
2071  s(i,k2-1) = (s(i,k2)*h(i,k2-1) + s_up*h_to_up) * i_hup
2072  s(i,k2) = (s(i,k2)*h(i,k2) + s_dn*h_to_dn) * i_hdn
2073  rcv(i,k2-1) = (rcv(i,k2)*h(i,k2-1) + rcvtgt(k2-1)*h_to_up) * i_hup
2074  rcv(i,k2) = (rcv(i,k2)*h(i,k2) + rcvtgt(k2)*h_to_dn) * i_hdn
2075 
2076  h(i,k) = eps(i,k)
2077  h(i,k2) = h(i,k2) + h_to_dn
2078  h(i,k2-1) = h(i,k2-1) + h_to_up
2079 
2080  if (k > k2-1) then
2081  d_eb(i,k) = d_eb(i,k) - h_to_up
2082  d_eb(i,k2-1) = d_eb(i,k2-1) + h_to_up
2083  elseif (k < k2-1) then
2084  d_ea(i,k) = d_ea(i,k) - h_to_up
2085  d_ea(i,k2-1) = d_ea(i,k2-1) + h_to_up
2086  endif
2087  if (k > k2) then
2088  d_eb(i,k) = d_eb(i,k) - h_to_dn
2089  d_eb(i,k2) = d_eb(i,k2) + h_to_dn
2090  elseif (k < k2) then
2091  d_ea(i,k) = d_ea(i,k) - h_to_dn
2092  d_ea(i,k2) = d_ea(i,k2) + h_to_dn
2093  endif
2094  nks = nks-1
2095  endif
2096  enddo
2097  endif
2098 
2099  do while (nks > nkmb)
2100  ! Having already tried to move surface layers into the interior, there
2101  ! are still too many layers, and layers must be merged until nks=nkmb.
2102  ! Examine every merger of a layer with its neighbors, and merge the ones
2103  ! that increase the potential energy the least. If there are layers
2104  ! with (apparently?) negative potential energy change, choose the one
2105  ! with the smallest total thickness. Repeat until nkmb layers remain.
2106  ! Choose the smaller value for the remaining index for convenience.
2107 
2108  ks_min = -1 ; min_dpe = 1.0 ; min_hmin = 0.0
2109  do ks=1,nks-1
2110  k1 = ks2(ks) ; k2 = ks2(ks+1)
2111  dpe = max(0.0, (r0(i,k2)-r0(i,k1)) * h(i,k1) * h(i,k2))
2112  hmin = min(h(i,k1)-eps(i,k1), h(i,k2)-eps(i,k2))
2113  if ((ks_min < 0) .or. (dpe < min_dpe) .or. &
2114  ((dpe <= 0.0) .and. (hmin < min_hmin))) then
2115  ks_min = ks ; min_dpe = dpe ; min_hmin = hmin
2116  endif
2117  enddo
2118 
2119  ! Now merge the two layers that do the least damage.
2120  k1 = ks2(ks_min) ; k2 = ks2(ks_min+1)
2121  if (k1 < k2) then ; k_tgt = k1 ; k_src = k2
2122  else ; k_tgt = k2 ; k_src = k1 ; ks2(ks_min) = k2 ; endif
2123 
2124  h_tgt_old = h(i,k_tgt)
2125  h_move = h(i,k_src)-eps(i,k_src)
2126  h(i,k_src) = eps(i,k_src)
2127  h(i,k_tgt) = h(i,k_tgt) + h_move
2128  i_hnew = 1.0 / (h(i,k_tgt))
2129  r0(i,k_tgt) = (r0(i,k_tgt)*h_tgt_old + r0(i,k_src)*h_move) * i_hnew
2130 
2131  t(i,k_tgt) = (t(i,k_tgt)*h_tgt_old + t(i,k_src)*h_move) * i_hnew
2132  s(i,k_tgt) = (s(i,k_tgt)*h_tgt_old + s(i,k_src)*h_move) * i_hnew
2133  rcv(i,k_tgt) = (rcv(i,k_tgt)*h_tgt_old + rcv(i,k_src)*h_move) * i_hnew
2134 
2135  d_eb(i,k_src) = d_eb(i,k_src) - h_move
2136  d_eb(i,k_tgt) = d_eb(i,k_tgt) + h_move
2137 
2138  ! Remove the newly missing layer from the sorted list.
2139  do ks=ks_min+1,nks ; ks2(ks) = ks2(ks+1) ; enddo
2140  nks = nks-1
2141  enddo
2142 
2143  ! Check again whether the layers are sorted, and go on to the next column
2144  ! if they are.
2145  sorted = .true.
2146  do ks=1,nks-1 ; if (ks2(ks) > ks2(ks+1)) sorted = .false. ; enddo
2147  if (sorted) cycle
2148 
2149  if (nks > 1) then
2150  ! At this point, actually swap the properties of the layers, and place
2151  ! the remaining layers in order starting with nkmb.
2152 
2153  ! Save all the properties of the nkmb layers that might be replaced.
2154  do k=1,nkmb
2155  h_tmp(k) = h(i,k) ; r0_tmp(k) = r0(i,k)
2156  t_tmp(k) = t(i,k) ; s_tmp(k) = s(i,k) ; rcv_tmp(k) = rcv(i,k)
2157 
2158  h(i,k) = 0.0
2159  enddo
2160 
2161  do ks=nks,1,-1
2162  k_tgt = nkmb - nks + ks ; k_src = ks2(ks)
2163  if (k_tgt == k_src) then
2164  h(i,k_tgt) = h_tmp(k_tgt) ! This layer doesn't move, so put the water back.
2165  cycle
2166  endif
2167 
2168  ! Note below that eps=0 for k<=nkmb.
2169  if (k_src > nkmb) then
2170  h_move = h(i,k_src)-eps(i,k_src)
2171  h(i,k_src) = eps(i,k_src)
2172  h(i,k_tgt) = h_move
2173  r0(i,k_tgt) = r0(i,k_src)
2174 
2175  t(i,k_tgt) = t(i,k_src) ; s(i,k_tgt) = s(i,k_src)
2176  rcv(i,k_tgt) = rcv(i,k_src)
2177 
2178  d_eb(i,k_src) = d_eb(i,k_src) - h_move
2179  d_eb(i,k_tgt) = d_eb(i,k_tgt) + h_move
2180  else
2181  h(i,k_tgt) = h_tmp(k_src)
2182  r0(i,k_tgt) = r0_tmp(k_src)
2183 
2184  t(i,k_tgt) = t_tmp(k_src) ; s(i,k_tgt) = s_tmp(k_src)
2185  rcv(i,k_tgt) = rcv_tmp(k_src)
2186 
2187  if (k_src > k_tgt) then
2188  d_eb(i,k_src) = d_eb(i,k_src) - h_tmp(k_src)
2189  d_eb(i,k_tgt) = d_eb(i,k_tgt) + h_tmp(k_src)
2190  else
2191  d_ea(i,k_src) = d_ea(i,k_src) - h_tmp(k_src)
2192  d_ea(i,k_tgt) = d_ea(i,k_tgt) + h_tmp(k_src)
2193  endif
2194  endif
2195  enddo
2196  endif
2197 
2198  endif ; enddo
2199 
2200 end subroutine resort_ml
2201 
2202 !> This subroutine moves any water left in the former mixed layers into the
2203 !! two buffer layers and may also move buffer layer water into the interior
2204 !! isopycnal layers.
2205 subroutine mixedlayer_detrain_2(h, T, S, R0, Rcv, RcvTgt, dt_in_T, dt_diag, d_ea, j, G, GV, US, CS, &
2206  dR0_dT, dR0_dS, dRcv_dT, dRcv_dS, max_BL_det)
2207  type(ocean_grid_type), intent(in) :: G !< The ocean's grid structure.
2208  type(verticalgrid_type), intent(in) :: GV !< The ocean's vertical grid structure.
2209  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: h !< Layer thickness [H ~> m or kg m-2].
2210  !! Layer 0 is the new mixed layer.
2211  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: T !< Potential temperature [degC].
2212  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: S !< Salinity [ppt].
2213  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: R0 !< Potential density referenced to
2214  !! surface pressure [kg m-3].
2215  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: Rcv !< The coordinate defining potential
2216  !! density [kg m-3].
2217  real, dimension(SZK_(GV)), intent(in) :: RcvTgt !< The target value of Rcv for each
2218  !! layer [kg m-3].
2219  real, intent(in) :: dt_in_T !< Time increment [T ~> s].
2220  real, intent(in) :: dt_diag !< The diagnostic time step [T ~> s].
2221  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: d_ea !< The upward increase across a layer in
2222  !! the entrainment from above
2223  !! [H ~> m or kg m-2]. Positive d_ea
2224  !! goes with layer thickness increases.
2225  integer, intent(in) :: j !< The meridional row to work on.
2226  type(unit_scale_type), intent(in) :: US !< A dimensional unit scaling type
2227  type(bulkmixedlayer_cs), pointer :: CS !< The control structure returned by a
2228  !! previous call to mixedlayer_init.
2229  real, dimension(SZI_(G)), intent(in) :: dR0_dT !< The partial derivative of
2230  !! potential density referenced to the
2231  !! surface with potential temperature,
2232  !! [kg m-3 degC-1].
2233  real, dimension(SZI_(G)), intent(in) :: dR0_dS !< The partial derivative of
2234  !! cpotential density referenced to the
2235  !! surface with salinity
2236  !! [kg m-3 ppt-1].
2237  real, dimension(SZI_(G)), intent(in) :: dRcv_dT !< The partial derivative of
2238  !! coordinate defining potential density
2239  !! with potential temperature,
2240  !! [kg m-3 degC-1].
2241  real, dimension(SZI_(G)), intent(in) :: dRcv_dS !< The partial derivative of
2242  !! coordinate defining potential density
2243  !! with salinity [kg m-3 ppt-1].
2244  real, dimension(SZI_(G)), intent(in) :: max_BL_det !< If non-negative, the maximum
2245  !! detrainment permitted from the buffer
2246  !! layers [H ~> m or kg m-2].
2247 
2248 ! This subroutine moves any water left in the former mixed layers into the
2249 ! two buffer layers and may also move buffer layer water into the interior
2250 ! isopycnal layers.
2251 
2252  ! Local variables
2253  real :: h_to_bl ! The total thickness detrained to the buffer
2254  ! layers [H ~> m or kg m-2].
2255  real :: R0_to_bl ! The depth integrated amount of R0 that is detrained to the
2256  ! buffer layer [H kg m-3 ~> kg m-2 or kg2 m-5]
2257  real :: Rcv_to_bl ! The depth integrated amount of Rcv that is detrained to the
2258  ! buffer layer [H kg m-3 ~> kg m-2 or kg2 m-5]
2259  real :: T_to_bl ! The depth integrated amount of T that is detrained to the
2260  ! buffer layer [degC H ~> degC m or degC kg m-2]
2261  real :: S_to_bl ! The depth integrated amount of S that is detrained to the
2262  ! buffer layer [ppt H ~> ppt m or ppt kg m-2]
2263  real :: h_min_bl ! The minimum buffer layer thickness [H ~> m or kg m-2].
2264 
2265  real :: h1, h2 ! Scalar variables holding the values of
2266  ! h(i,CS%nkml+1) and h(i,CS%nkml+2) [H ~> m or kg m-2].
2267  real :: h1_avail ! The thickness of the upper buffer layer
2268  ! available to move into the lower buffer
2269  ! layer [H ~> m or kg m-2].
2270  real :: stays ! stays is the thickness of the upper buffer
2271  ! layer that remains there [H ~> m or kg m-2].
2272  real :: stays_min, stays_max ! The minimum and maximum permitted values of
2273  ! stays [H ~> m or kg m-2].
2274 
2275  logical :: mergeable_bl ! If true, it is an option to combine the two
2276  ! buffer layers and create water that matches
2277  ! the target density of an interior layer.
2278  real :: stays_merge ! If the two buffer layers can be combined
2279  ! stays_merge is the thickness of the upper
2280  ! layer that remains [H ~> m or kg m-2].
2281  real :: stays_min_merge ! The minimum allowed value of stays_merge [H ~> m or kg m-2].
2282 
2283  real :: dR0_2dz, dRcv_2dz ! Half the vertical gradients of R0 and Rcv [kg m-3 H-1 ~> kg m-4 or m-1]
2284 ! real :: dT_2dz, dS_2dz ! Half the vertical gradients of T and S, in degC H-1, and ppt H-1.
2285  real :: scale_slope ! A nondimensional number < 1 used to scale down
2286  ! the slope within the upper buffer layer when
2287  ! water MUST be detrained to the lower layer.
2288 
2289  real :: dPE_extrap ! The potential energy change due to dispersive
2290  ! advection or mixing layers, divided by
2291  ! rho_0*g [H2 ~> m2 or kg2 m-4].
2292  real :: dPE_det, dPE_merge ! The energy required to mix the detrained water
2293  ! into the buffer layer or the merge the two
2294  ! buffer layers [kg H2 Z T-2 m-3 ~> J m-2 or J kg2 m-8].
2295 
2296  real :: h_from_ml ! The amount of additional water that must be
2297  ! drawn from the mixed layer [H ~> m or kg m-2].
2298  real :: h_det_h2 ! The amount of detrained water and mixed layer
2299  ! water that will go directly into the lower
2300  ! buffer layer [H ~> m or kg m-2].
2301  real :: h_det_to_h2, h_ml_to_h2 ! All of the variables hA_to_hB are the thickness fluxes
2302  real :: h_det_to_h1, h_ml_to_h1 ! from one layer to another [H ~> m or kg m-2],
2303  real :: h1_to_h2, h1_to_k0 ! with h_det the detrained water, h_ml
2304  real :: h2_to_k1, h2_to_k1_rem ! the actively mixed layer, h1 and h2 the upper
2305  ! and lower buffer layers, and k0 and k1 the
2306  ! interior layers that are just lighter and
2307  ! just denser than the lower buffer layer.
2308 
2309  real :: R0_det, T_det, S_det ! Detrained values of R0 [kg m-3], T [degC], and S [ppt].
2310  real :: Rcv_stays, R0_stays ! Values of Rcv and R0 that stay in a layer.
2311  real :: T_stays, S_stays ! Values of T and S that stay in a layer.
2312  real :: dSpice_det, dSpice_stays! The spiciness difference between an original
2313  ! buffer layer and the water that moves into
2314  ! an interior layer or that stays in that
2315  ! layer [kg m-3].
2316  real :: dSpice_lim, dSpice_lim2 ! Limits to the spiciness difference between
2317  ! the lower buffer layer and the water that
2318  ! moves into an interior layer [kg m-3].
2319  real :: dSpice_2dz ! The vertical gradient of spiciness used for
2320  ! advection [kg m-3 H-1 ~> kg m-4 or m-1].
2321 
2322  real :: dPE_ratio ! Multiplier of dPE_det at which merging is
2323  ! permitted - here (detrainment_per_day/dt)*30
2324  ! days?
2325  real :: num_events ! The number of detrainment events over which
2326  ! to prefer merging the buffer layers.
2327  real :: dPE_time_ratio ! Larger of 1 and the detrainment timescale over dt [nondim].
2328  real :: dT_dS_gauge, dS_dT_gauge ! The relative scales of temperature and
2329  ! salinity changes in defining spiciness, in
2330  ! [degC ppt-1] and [ppt degC-1].
2331  real :: I_denom ! A work variable with units of [ppt2 m6 kg-2].
2332 
2333  real :: g_2 ! 1/2 g_Earth [m2 Z-1 T-2 ~> m s-2].
2334  real :: Rho0xG ! Rho0 times G_Earth [kg m-1 Z-1 T-2 ~> kg m-2 s-2].
2335  real :: I2Rho0 ! 1 / (2 Rho0) [m3 kg-1].
2336  real :: Idt_H2 ! The square of the conversion from thickness to Z
2337  ! divided by the time step [Z2 H-2 T-1 ~> s-1 or m6 kg-2 s-1].
2338  logical :: stable_Rcv ! If true, the buffer layers are stable with
2339  ! respect to the coordinate potential density.
2340  real :: h_neglect ! A thickness that is so small it is usually lost
2341  ! in roundoff and can be neglected [H ~> m or kg m-2].
2342 
2343  real :: s1en ! A work variable [H2 kg m T-3 ~> kg m3 s-3 or kg3 m-3 s-3].
2344  real :: s1, s2, bh0 ! Work variables [H ~> m or kg m-2].
2345  real :: s3sq ! A work variable [H2 ~> m2 or kg2 m-4].
2346  real :: I_ya, b1 ! Nondimensional work variables.
2347  real :: Ih, Ihdet, Ih1f, Ih2f ! Assorted inverse thickness work variables,
2348  real :: Ihk0, Ihk1, Ih12 ! all in [H-1 ~> m-1 or m2 kg-1].
2349  real :: dR1, dR2, dR2b, dRk1 ! Assorted density difference work variables,
2350  real :: dR0, dR21, dRcv ! all in [kg m-3].
2351  real :: dRcv_stays, dRcv_det, dRcv_lim
2352  real :: Angstrom ! The minumum layer thickness [H ~> m or kg m-2].
2353 
2354  real :: h2_to_k1_lim, T_new, S_new, T_max, T_min, S_max, S_min
2355  character(len=200) :: mesg
2356 
2357  integer :: i, k, k0, k1, is, ie, nz, kb1, kb2, nkmb
2358  is = g%isc ; ie = g%iec ; nz = gv%ke
2359  kb1 = cs%nkml+1; kb2 = cs%nkml+2
2360  nkmb = cs%nkml+cs%nkbl
2361  h_neglect = gv%H_subroundoff
2362  g_2 = 0.5 * us%L_to_m**2*gv%g_Earth
2363  rho0xg = gv%Rho0 * us%L_to_m**2*gv%g_Earth
2364  idt_h2 = gv%H_to_Z**2 / dt_diag
2365  i2rho0 = 0.5 / gv%Rho0
2366  angstrom = gv%Angstrom_H
2367 
2368  ! This is hard coding of arbitrary and dimensional numbers.
2369  dt_ds_gauge = cs%dT_dS_wt ; ds_dt_gauge = 1.0 / dt_ds_gauge
2370  num_events = 10.0
2371 
2372  if (cs%nkbl /= 2) call mom_error(fatal, "MOM_mixed_layer"// &
2373  "CS%nkbl must be 2 in mixedlayer_detrain_2.")
2374 
2375  if (dt_in_t < cs%BL_detrain_time) then ; dpe_time_ratio = cs%BL_detrain_time / (dt_in_t)
2376  else ; dpe_time_ratio = 1.0 ; endif
2377 
2378  do i=is,ie
2379 
2380  ! Determine all of the properties being detrained from the mixed layer.
2381 
2382  ! As coded this has the k and i loop orders switched, but k is CS%nkml is
2383  ! often just 1 or 2, so this seems like it should not be a problem, especially
2384  ! since it means that a number of variables can now be scalars, not arrays.
2385  h_to_bl = 0.0 ; r0_to_bl = 0.0
2386  rcv_to_bl = 0.0 ; t_to_bl = 0.0 ; s_to_bl = 0.0
2387 
2388  do k=1,cs%nkml ; if (h(i,k) > 0.0) then
2389  h_to_bl = h_to_bl + h(i,k)
2390  r0_to_bl = r0_to_bl + r0(i,k)*h(i,k)
2391 
2392  rcv_to_bl = rcv_to_bl + rcv(i,k)*h(i,k)
2393  t_to_bl = t_to_bl + t(i,k)*h(i,k)
2394  s_to_bl = s_to_bl + s(i,k)*h(i,k)
2395 
2396  d_ea(i,k) = d_ea(i,k) - h(i,k)
2397  h(i,k) = 0.0
2398  endif ; enddo
2399  if (h_to_bl > 0.0) then ; r0_det = r0_to_bl / h_to_bl
2400  else ; r0_det = r0(i,0) ; endif
2401 
2402  ! This code does both downward detrainment from both the mixed layer and the
2403  ! buffer layers.
2404  ! Several considerations apply in detraining water into the interior:
2405  ! (1) Water only moves into the interior from the deeper buffer layer,
2406  ! so the deeper buffer layer must have some mass.
2407  ! (2) The upper buffer layer must have some mass so the extrapolation of
2408  ! density is meaningful (i.e. there is not detrainment from the buffer
2409  ! layers when there is strong mixed layer entrainment).
2410  ! (3) The lower buffer layer density extrapolated to its base with a
2411  ! linear fit between the two layers must exceed the density of the
2412  ! next denser interior layer.
2413  ! (4) The average extroplated coordinate density that is moved into the
2414  ! isopycnal interior matches the target value for that layer.
2415  ! (5) The potential energy change is calculated and might be used later
2416  ! to allow the upper buffer layer to mix more into the lower buffer
2417  ! layer.
2418 
2419  ! Determine whether more must be detrained from the mixed layer to keep a
2420  ! minimal amount of mass in the buffer layers. In this case the 5% of the
2421  ! mixed layer thickness is hard-coded, but probably shouldn't be!
2422  h_min_bl = min(cs%Hbuffer_min, cs%Hbuffer_rel_min*h(i,0))
2423 
2424  stable_rcv = .true.
2425  if (((r0(i,kb2)-r0(i,kb1)) * (rcv(i,kb2)-rcv(i,kb1)) <= 0.0)) &
2426  stable_rcv = .false.
2427 
2428  h1 = h(i,kb1) ; h2 = h(i,kb2)
2429 
2430  h2_to_k1_rem = (h1 + h2) + h_to_bl
2431  if ((max_bl_det(i) >= 0.0) .and. (h2_to_k1_rem > max_bl_det(i))) &
2432  h2_to_k1_rem = max_bl_det(i)
2433 
2434 
2435  if ((h2 == 0.0) .and. (h1 > 0.0)) then
2436  ! The lower buffer layer has been eliminated either by convective
2437  ! adjustment or entrainment from the interior, and its current properties
2438  ! are not meaningful, but may later be used to determine the properties of
2439  ! waters moving into the lower buffer layer. So the properties of the
2440  ! lower buffer layer are set to be between those of the upper buffer layer
2441  ! and the next denser interior layer, measured by R0. This probably does
2442  ! not happen very often, so I am not too worried about the inefficiency of
2443  ! the following loop.
2444  do k1=kb2+1,nz ; if (h(i,k1) > 2.0*angstrom) exit ; enddo
2445 
2446  r0(i,kb2) = r0(i,kb1)
2447 
2448  rcv(i,kb2)=rcv(i,kb1) ; t(i,kb2)=t(i,kb1) ; s(i,kb2)=s(i,kb1)
2449 
2450 
2451  if (k1 <= nz) then ; if (r0(i,k1) >= r0(i,kb1)) then
2452  r0(i,kb2) = 0.5*(r0(i,kb1)+r0(i,k1))
2453 
2454  rcv(i,kb2) = 0.5*(rcv(i,kb1)+rcv(i,k1))
2455  t(i,kb2) = 0.5*(t(i,kb1)+t(i,k1))
2456  s(i,kb2) = 0.5*(s(i,kb1)+s(i,k1))
2457  endif ; endif
2458  endif ! (h2 = 0 && h1 > 0)
2459 
2460  dpe_extrap = 0.0 ; dpe_merge = 0.0
2461  mergeable_bl = .false.
2462  if ((h1 > 0.0) .and. (h2 > 0.0) .and. (h_to_bl > 0.0) .and. &
2463  (stable_rcv)) then
2464  ! Check whether it is permissible for the buffer layers to detrain
2465  ! into the interior isopycnal layers.
2466 
2467  ! Determine the layer that has the lightest target density that is
2468  ! denser than the lowermost buffer layer.
2469  do k1=kb2+1,nz ; if (rcvtgt(k1) >= rcv(i,kb2)) exit ; enddo ; k0 = k1-1
2470  dr1 = rcvtgt(k0)-rcv(i,kb1) ; dr2 = rcv(i,kb2)-rcvtgt(k0)
2471 
2472  ! Use an energy-balanced combination of downwind advection into the next
2473  ! denser interior layer and upwind advection from the upper buffer layer
2474  ! into the lower one, each with an energy change that equals that required
2475  ! to mix the detrained water with the upper buffer layer.
2476  h1_avail = h1 - max(0.0,h_min_bl-h_to_bl)
2477  if ((k1<=nz) .and. (h2 > h_min_bl) .and. (h1_avail > 0.0) .and. &
2478  (r0(i,kb1) < r0(i,kb2)) .and. (h_to_bl*r0(i,kb1) > r0_to_bl)) then
2479  drk1 = (rcvtgt(k1) - rcv(i,kb2)) * (r0(i,kb2) - r0(i,kb1)) / &
2480  (rcv(i,kb2) - rcv(i,kb1))
2481  b1 = drk1 / (r0(i,kb2) - r0(i,kb1))
2482  ! b1 = RcvTgt(k1) - Rcv(i,kb2)) / (Rcv(i,kb2) - Rcv(i,kb1))
2483 
2484  ! Apply several limits to the detrainment.
2485  ! Entrain less than the mass in h2, and keep the base of the buffer
2486  ! layers from becoming shallower than any neighbors.
2487  h2_to_k1 = min(h2 - h_min_bl, h2_to_k1_rem)
2488  ! Balance downwind advection of density into the layer below the
2489  ! buffer layers with upwind advection from the layer above.
2490  if (h2_to_k1*(h1_avail + b1*(h1_avail + h2)) > h2*h1_avail) &
2491  h2_to_k1 = (h2*h1_avail) / (h1_avail + b1*(h1_avail + h2))
2492  if (h2_to_k1*(drk1 * h2) > (h_to_bl*r0(i,kb1) - r0_to_bl) * h1) &
2493  h2_to_k1 = (h_to_bl*r0(i,kb1) - r0_to_bl) * h1 / (drk1 * h2)
2494 
2495  if ((k1==kb2+1) .and. (cs%BL_extrap_lim > 0.)) then
2496  ! Simply do not detrain very light water into the lightest isopycnal
2497  ! coordinate layers if the density jump is too large.
2498  drcv_lim = rcv(i,kb2)-rcv(i,0)
2499  do k=1,kb2 ; drcv_lim = max(drcv_lim, rcv(i,kb2)-rcv(i,k)) ; enddo
2500  drcv_lim = cs%BL_extrap_lim*drcv_lim
2501  if ((rcvtgt(k1) - rcv(i,kb2)) >= drcv_lim) then
2502  h2_to_k1 = 0.0
2503  elseif ((rcvtgt(k1) - rcv(i,kb2)) > 0.5*drcv_lim) then
2504  h2_to_k1 = h2_to_k1 * (2.0 - 2.0*((rcvtgt(k1) - rcv(i,kb2)) / drcv_lim))
2505  endif
2506  endif
2507 
2508  drcv = (rcvtgt(k1) - rcv(i,kb2))
2509 
2510  ! Use 2nd order upwind advection of spiciness, limited by the values
2511  ! in deeper thick layers to determine the detrained temperature and
2512  ! salinity.
2513  dspice_det = (ds_dt_gauge*drcv_ds(i)*(t(i,kb2)-t(i,kb1)) - &
2514  dt_ds_gauge*drcv_dt(i)*(s(i,kb2)-s(i,kb1))) * &
2515  (h2 - h2_to_k1) / (h1 + h2)
2516  dspice_lim = 0.0
2517  if (h(i,k1) > 10.0*angstrom) then
2518  dspice_lim = ds_dt_gauge*drcv_ds(i)*(t(i,k1)-t(i,kb2)) - &
2519  dt_ds_gauge*drcv_dt(i)*(s(i,k1)-s(i,kb2))
2520  if (dspice_det*dspice_lim <= 0.0) dspice_lim = 0.0
2521  endif
2522  if (k1<nz) then ; if (h(i,k1+1) > 10.0*angstrom) then
2523  dspice_lim2 = ds_dt_gauge*drcv_ds(i)*(t(i,k1+1)-t(i,kb2)) - &
2524  dt_ds_gauge*drcv_dt(i)*(s(i,k1+1)-s(i,kb2))
2525  if ((dspice_det*dspice_lim2 > 0.0) .and. &
2526  (abs(dspice_lim2) > abs(dspice_lim))) dspice_lim = dspice_lim2
2527  endif ; endif
2528  if (abs(dspice_det) > abs(dspice_lim)) dspice_det = dspice_lim
2529 
2530  i_denom = 1.0 / (drcv_ds(i)**2 + (dt_ds_gauge*drcv_dt(i))**2)
2531  t_det = t(i,kb2) + dt_ds_gauge * i_denom * &
2532  (dt_ds_gauge * drcv_dt(i) * drcv + drcv_ds(i) * dspice_det)
2533  s_det = s(i,kb2) + i_denom * &
2534  (drcv_ds(i) * drcv - dt_ds_gauge * drcv_dt(i) * dspice_det)
2535  ! The detrained values of R0 are based on changes in T and S.
2536  r0_det = r0(i,kb2) + (t_det-t(i,kb2)) * dr0_dt(i) + &
2537  (s_det-s(i,kb2)) * dr0_ds(i)
2538 
2539  if (cs%BL_extrap_lim >= 0.) then
2540  ! Only do this detrainment if the new layer's temperature and salinity
2541  ! are not too far outside of the range of previous values.
2542  if (h(i,k1) > 10.0*angstrom) then
2543  t_min = min(t(i,kb1), t(i,kb2), t(i,k1)) - cs%Allowed_T_chg
2544  t_max = max(t(i,kb1), t(i,kb2), t(i,k1)) + cs%Allowed_T_chg
2545  s_min = min(s(i,kb1), s(i,kb2), s(i,k1)) - cs%Allowed_S_chg
2546  s_max = max(s(i,kb1), s(i,kb2), s(i,k1)) + cs%Allowed_S_chg
2547  else
2548  t_min = min(t(i,kb1), t(i,kb2)) - cs%Allowed_T_chg
2549  t_max = max(t(i,kb1), t(i,kb2)) + cs%Allowed_T_chg
2550  s_min = min(s(i,kb1), s(i,kb2)) - cs%Allowed_S_chg
2551  s_max = max(s(i,kb1), s(i,kb2)) + cs%Allowed_S_chg
2552  endif
2553  ihk1 = 1.0 / (h(i,k1) + h2_to_k1)
2554  t_new = (h(i,k1)*t(i,k1) + h2_to_k1*t_det) * ihk1
2555  s_new = (h(i,k1)*s(i,k1) + h2_to_k1*s_det) * ihk1
2556  ! A less restrictive limit might be used here.
2557  if ((t_new < t_min) .or. (t_new > t_max) .or. &
2558  (s_new < s_min) .or. (s_new > s_max)) &
2559  h2_to_k1 = 0.0
2560  endif
2561 
2562  h1_to_h2 = b1*h2*h2_to_k1 / (h2 - (1.0+b1)*h2_to_k1)
2563 
2564  ihk1 = 1.0 / (h(i,k1) + h_neglect + h2_to_k1)
2565  ih2f = 1.0 / ((h(i,kb2) - h2_to_k1) + h1_to_h2)
2566 
2567  rcv(i,kb2) = ((h(i,kb2)*rcv(i,kb2) - h2_to_k1*rcvtgt(k1)) + &
2568  h1_to_h2*rcv(i,kb1))*ih2f
2569  rcv(i,k1) = ((h(i,k1)+h_neglect)*rcv(i,k1) + h2_to_k1*rcvtgt(k1)) * ihk1
2570 
2571  t(i,kb2) = ((h(i,kb2)*t(i,kb2) - h2_to_k1*t_det) + &
2572  h1_to_h2*t(i,kb1)) * ih2f
2573  t(i,k1) = ((h(i,k1)+h_neglect)*t(i,k1) + h2_to_k1*t_det) * ihk1
2574 
2575  s(i,kb2) = ((h(i,kb2)*s(i,kb2) - h2_to_k1*s_det) + &
2576  h1_to_h2*s(i,kb1)) * ih2f
2577  s(i,k1) = ((h(i,k1)+h_neglect)*s(i,k1) + h2_to_k1*s_det) * ihk1
2578 
2579  ! Changes in R0 are based on changes in T and S.
2580  r0(i,kb2) = ((h(i,kb2)*r0(i,kb2) - h2_to_k1*r0_det) + &
2581  h1_to_h2*r0(i,kb1)) * ih2f
2582  r0(i,k1) = ((h(i,k1)+h_neglect)*r0(i,k1) + h2_to_k1*r0_det) * ihk1
2583 
2584  h(i,kb1) = h(i,kb1) - h1_to_h2 ; h1 = h(i,kb1)
2585  h(i,kb2) = (h(i,kb2) - h2_to_k1) + h1_to_h2 ; h2 = h(i,kb2)
2586  h(i,k1) = h(i,k1) + h2_to_k1
2587 
2588  d_ea(i,kb1) = d_ea(i,kb1) - h1_to_h2
2589  d_ea(i,kb2) = (d_ea(i,kb2) - h2_to_k1) + h1_to_h2
2590  d_ea(i,k1) = d_ea(i,k1) + h2_to_k1
2591  h2_to_k1_rem = max(h2_to_k1_rem - h2_to_k1, 0.0)
2592 
2593  ! The lower buffer layer has become lighter - it may be necessary to
2594  ! adjust k1 lighter.
2595  if ((k1>kb2+1) .and. (rcvtgt(k1-1) >= rcv(i,kb2))) then
2596  do k1=k1,kb2+1,-1 ; if (rcvtgt(k1-1) < rcv(i,kb2)) exit ; enddo
2597  endif
2598  endif
2599 
2600  k0 = k1-1
2601  dr1 = rcvtgt(k0)-rcv(i,kb1) ; dr2 = rcv(i,kb2)-rcvtgt(k0)
2602 
2603  if ((k0>kb2) .and. (dr1 > 0.0) .and. (h1 > h_min_bl) .and. &
2604  (h2*dr2 < h1*dr1) .and. (r0(i,kb2) > r0(i,kb1))) then
2605  ! An interior isopycnal layer (k0) is intermediate in density between
2606  ! the two buffer layers, and there can be detrainment. The entire
2607  ! lower buffer layer is combined with a portion of the upper buffer
2608  ! layer to match the target density of layer k0.
2609  stays_merge = 2.0*(h1+h2)*(h1*dr1 - h2*dr2) / &
2610  ((dr1+dr2)*h1 + dr1*(h1+h2) + &
2611  sqrt((dr2*h1-dr1*h2)**2 + 4*(h1+h2)*h2*(dr1+dr2)*dr2))
2612 
2613  stays_min_merge = max(h_min_bl, 2.0*h_min_bl - h_to_bl, &
2614  h1 - (h1+h2)*(r0(i,kb1) - r0_det) / (r0(i,kb2) - r0(i,kb1)))
2615  if ((stays_merge > stays_min_merge) .and. &
2616  (stays_merge + h2_to_k1_rem >= h1 + h2)) then
2617  mergeable_bl = .true.
2618  dpe_merge = g_2*(r0(i,kb2)-r0(i,kb1))*(h1-stays_merge)*(h2-stays_merge)
2619  endif
2620  endif
2621 
2622  if ((k1<=nz).and.(.not.mergeable_bl)) then
2623  ! Check whether linear extrapolation of density (i.e. 2nd order upwind
2624  ! advection) will allow some of the lower buffer layer to detrain into
2625  ! the next denser interior layer (k1).
2626  dr2b = rcvtgt(k1)-rcv(i,kb2) ; dr21 = rcv(i,kb2) - rcv(i,kb1)
2627  if (dr2b*(h1+h2) < h2*dr21) then
2628  ! Some of layer kb2 is denser than k1.
2629  h2_to_k1 = min(h2 - (h1+h2) * dr2b / dr21, h2_to_k1_rem)
2630 
2631  if (h2 > h2_to_k1) then
2632  drcv = (rcvtgt(k1) - rcv(i,kb2))
2633 
2634  ! Use 2nd order upwind advection of spiciness, limited by the values
2635  ! in deeper thick layers to determine the detrained temperature and
2636  ! salinity.
2637  dspice_det = (ds_dt_gauge*drcv_ds(i)*(t(i,kb2)-t(i,kb1)) - &
2638  dt_ds_gauge*drcv_dt(i)*(s(i,kb2)-s(i,kb1))) * &
2639  (h2 - h2_to_k1) / (h1 + h2)
2640  dspice_lim = 0.0
2641  if (h(i,k1) > 10.0*angstrom) then
2642  dspice_lim = ds_dt_gauge*drcv_ds(i)*(t(i,k1)-t(i,kb2)) - &
2643  dt_ds_gauge*drcv_dt(i)*(s(i,k1)-s(i,kb2))
2644  if (dspice_det*dspice_lim <= 0.0) dspice_lim = 0.0
2645  endif
2646  if (k1<nz) then; if (h(i,k1+1) > 10.0*angstrom) then
2647  dspice_lim2 = ds_dt_gauge*drcv_ds(i)*(t(i,k1+1)-t(i,kb2)) - &
2648  dt_ds_gauge*drcv_dt(i)*(s(i,k1+1)-s(i,kb2))
2649  if ((dspice_det*dspice_lim2 > 0.0) .and. &
2650  (abs(dspice_lim2) > abs(dspice_lim))) dspice_lim = dspice_lim2
2651  endif; endif
2652  if (abs(dspice_det) > abs(dspice_lim)) dspice_det = dspice_lim
2653 
2654  i_denom = 1.0 / (drcv_ds(i)**2 + (dt_ds_gauge*drcv_dt(i))**2)
2655  t_det = t(i,kb2) + dt_ds_gauge * i_denom * &
2656  (dt_ds_gauge * drcv_dt(i) * drcv + drcv_ds(i) * dspice_det)
2657  s_det = s(i,kb2) + i_denom * &
2658  (drcv_ds(i) * drcv - dt_ds_gauge * drcv_dt(i) * dspice_det)
2659  ! The detrained values of R0 are based on changes in T and S.
2660  r0_det = r0(i,kb2) + (t_det-t(i,kb2)) * dr0_dt(i) + &
2661  (s_det-s(i,kb2)) * dr0_ds(i)
2662 
2663  ! Now that the properties of the detrained water are known,
2664  ! potentially limit the amount of water that is detrained to
2665  ! avoid creating unphysical properties in the remaining water.
2666  ih2f = 1.0 / (h2 - h2_to_k1)
2667 
2668  t_min = min(t(i,kb2), t(i,kb1)) - cs%Allowed_T_chg
2669  t_max = max(t(i,kb2), t(i,kb1)) + cs%Allowed_T_chg
2670  t_new = (h2*t(i,kb2) - h2_to_k1*t_det)*ih2f
2671  if (t_new < t_min) then
2672  h2_to_k1_lim = h2 * (t(i,kb2) - t_min) / (t_det - t_min)
2673 ! write(mesg,'("Low temperature limits det to ", &
2674 ! & 1pe12.5, " from ", 1pe12.5, " at ", 1pg11.4,"E, ",1pg11.4,"N. T=", &
2675 ! & 5(1pe12.5))') &
2676 ! h2_to_k1_lim, h2_to_k1, G%geoLonT(i,j), G%geoLatT(i,j), &
2677 ! T_new, T(i,kb2), T(i,kb1), T_det, T_new-T_min
2678 ! call MOM_error(WARNING, mesg)
2679  h2_to_k1 = h2_to_k1_lim
2680  ih2f = 1.0 / (h2 - h2_to_k1)
2681  elseif (t_new > t_max) then
2682  h2_to_k1_lim = h2 * (t(i,kb2) - t_max) / (t_det - t_max)
2683 ! write(mesg,'("High temperature limits det to ", &
2684 ! & 1pe12.5, " from ", 1pe12.5, " at ", 1pg11.4,"E, ",1pg11.4,"N. T=", &
2685 ! & 5(1pe12.5))') &
2686 ! h2_to_k1_lim, h2_to_k1, G%geoLonT(i,j), G%geoLatT(i,j), &
2687 ! T_new, T(i,kb2), T(i,kb1), T_det, T_new-T_max
2688 ! call MOM_error(WARNING, mesg)
2689  h2_to_k1 = h2_to_k1_lim
2690  ih2f = 1.0 / (h2 - h2_to_k1)
2691  endif
2692  s_min = max(min(s(i,kb2), s(i,kb1)) - cs%Allowed_S_chg, 0.0)
2693  s_max = max(s(i,kb2), s(i,kb1)) + cs%Allowed_S_chg
2694  s_new = (h2*s(i,kb2) - h2_to_k1*s_det)*ih2f
2695  if (s_new < s_min) then
2696  h2_to_k1_lim = h2 * (s(i,kb2) - s_min) / (s_det - s_min)
2697 ! write(mesg,'("Low salinity limits det to ", &
2698 ! & 1pe12.5, " from ", 1pe12.5, " at ", 1pg11.4,"E, ",1pg11.4,"N. S=", &
2699 ! & 5(1pe12.5))') &
2700 ! h2_to_k1_lim, h2_to_k1, G%geoLonT(i,j), G%geoLatT(i,j), &
2701 ! S_new, S(i,kb2), S(i,kb1), S_det, S_new-S_min
2702 ! call MOM_error(WARNING, mesg)
2703  h2_to_k1 = h2_to_k1_lim
2704  ih2f = 1.0 / (h2 - h2_to_k1)
2705  elseif (s_new > s_max) then
2706  h2_to_k1_lim = h2 * (s(i,kb2) - s_max) / (s_det - s_max)
2707 ! write(mesg,'("High salinity limits det to ", &
2708 ! & 1pe12.5, " from ", 1pe12.5, " at ", 1pg11.4,"E, ",1pg11.4,"N. S=", &
2709 ! & 5(1pe12.5))') &
2710 ! h2_to_k1_lim, h2_to_k1, G%geoLonT(i,j), G%geoLatT(i,j), &
2711 ! S_new, S(i,kb2), S(i,kb1), S_det, S_new-S_max
2712 ! call MOM_error(WARNING, mesg)
2713  h2_to_k1 = h2_to_k1_lim
2714  ih2f = 1.0 / (h2 - h2_to_k1)
2715  endif
2716 
2717  ihk1 = 1.0 / (h(i,k1) + h_neglect + h2_to_k1)
2718  rcv(i,k1) = ((h(i,k1)+h_neglect)*rcv(i,k1) + h2_to_k1*rcvtgt(k1)) * ihk1
2719  rcv(i,kb2) = rcv(i,kb2) - h2_to_k1*drcv*ih2f
2720 
2721  t(i,kb2) = (h2*t(i,kb2) - h2_to_k1*t_det)*ih2f
2722  t(i,k1) = ((h(i,k1)+h_neglect)*t(i,k1) + h2_to_k1*t_det) * ihk1
2723 
2724  s(i,kb2) = (h2*s(i,kb2) - h2_to_k1*s_det) * ih2f
2725  s(i,k1) = ((h(i,k1)+h_neglect)*s(i,k1) + h2_to_k1*s_det) * ihk1
2726 
2727  ! Changes in R0 are based on changes in T and S.
2728  r0(i,kb2) = (h2*r0(i,kb2) - h2_to_k1*r0_det) * ih2f
2729  r0(i,k1) = ((h(i,k1)+h_neglect)*r0(i,k1) + h2_to_k1*r0_det) * ihk1
2730  else
2731  ! h2==h2_to_k1 can happen if dR2b = 0 exactly, but this is very
2732  ! unlikely. In this case the entirety of layer kb2 is detrained.
2733  h2_to_k1 = h2 ! These 2 lines are probably unnecessary.
2734  ihk1 = 1.0 / (h(i,k1) + h2)
2735 
2736  rcv(i,k1) = (h(i,k1)*rcv(i,k1) + h2*rcv(i,kb2)) * ihk1
2737  t(i,k1) = (h(i,k1)*t(i,k1) + h2*t(i,kb2)) * ihk1
2738  s(i,k1) = (h(i,k1)*s(i,k1) + h2*s(i,kb2)) * ihk1
2739  r0(i,k1) = (h(i,k1)*r0(i,k1) + h2*r0(i,kb2)) * ihk1
2740  endif
2741 
2742  h(i,k1) = h(i,k1) + h2_to_k1
2743  h(i,kb2) = h(i,kb2) - h2_to_k1 ; h2 = h(i,kb2)
2744  ! dPE_extrap should be positive here.
2745  dpe_extrap = i2rho0*(r0_det-r0(i,kb2))*h2_to_k1*h2
2746 
2747  d_ea(i,kb2) = d_ea(i,kb2) - h2_to_k1
2748  d_ea(i,k1) = d_ea(i,k1) + h2_to_k1
2749  h2_to_k1_rem = max(h2_to_k1_rem - h2_to_k1, 0.0)
2750  endif
2751  endif ! Detrainment by extrapolation.
2752 
2753  endif ! Detrainment to the interior at all.
2754 
2755  ! Does some of the detrained water go into the lower buffer layer?
2756  h_det_h2 = max(h_min_bl-(h1+h2), 0.0)
2757  if (h_det_h2 > 0.0) then
2758  ! Detrained water will go into both upper and lower buffer layers.
2759  ! h(kb2) will be h_min_bl, but h(kb1) may be larger if there was already
2760  ! ample detrainment; all water in layer kb1 moves into layer kb2.
2761 
2762  ! Determine the fluxes between the various layers.
2763  h_det_to_h2 = min(h_to_bl, h_det_h2)
2764  h_ml_to_h2 = h_det_h2 - h_det_to_h2
2765  h_det_to_h1 = h_to_bl - h_det_to_h2
2766  h_ml_to_h1 = max(h_min_bl-h_det_to_h1,0.0)
2767 
2768  ih = 1.0/h_min_bl
2769  ihdet = 0.0 ; if (h_to_bl > 0.0) ihdet = 1.0 / h_to_bl
2770  ih1f = 1.0 / (h_det_to_h1 + h_ml_to_h1)
2771 
2772  r0(i,kb2) = ((h2*r0(i,kb2) + h1*r0(i,kb1)) + &
2773  (h_det_to_h2*r0_to_bl*ihdet + h_ml_to_h2*r0(i,0))) * ih
2774  r0(i,kb1) = (h_det_to_h1*r0_to_bl*ihdet + h_ml_to_h1*r0(i,0)) * ih1f
2775 
2776  rcv(i,kb2) = ((h2*rcv(i,kb2) + h1*rcv(i,kb1)) + &
2777  (h_det_to_h2*rcv_to_bl*ihdet + h_ml_to_h2*rcv(i,0))) * ih
2778  rcv(i,kb1) = (h_det_to_h1*rcv_to_bl*ihdet + h_ml_to_h1*rcv(i,0)) * ih1f
2779 
2780  t(i,kb2) = ((h2*t(i,kb2) + h1*t(i,kb1)) + &
2781  (h_det_to_h2*t_to_bl*ihdet + h_ml_to_h2*t(i,0))) * ih
2782  t(i,kb1) = (h_det_to_h1*t_to_bl*ihdet + h_ml_to_h1*t(i,0)) * ih1f
2783 
2784  s(i,kb2) = ((h2*s(i,kb2) + h1*s(i,kb1)) + &
2785  (h_det_to_h2*s_to_bl*ihdet + h_ml_to_h2*s(i,0))) * ih
2786  s(i,kb1) = (h_det_to_h1*s_to_bl*ihdet + h_ml_to_h1*s(i,0)) * ih1f
2787 
2788  ! Recall that h1 = h(i,kb1) & h2 = h(i,kb2).
2789  d_ea(i,1) = d_ea(i,1) - (h_ml_to_h1 + h_ml_to_h2)
2790  d_ea(i,kb1) = d_ea(i,kb1) + ((h_det_to_h1 + h_ml_to_h1) - h1)
2791  d_ea(i,kb2) = d_ea(i,kb2) + (h_min_bl - h2)
2792 
2793  h(i,kb1) = h_det_to_h1 + h_ml_to_h1 ; h(i,kb2) = h_min_bl
2794  h(i,0) = h(i,0) - (h_ml_to_h1 + h_ml_to_h2)
2795 
2796 
2797  if (allocated(cs%diag_PE_detrain) .or. allocated(cs%diag_PE_detrain2)) then
2798  r0_det = r0_to_bl*ihdet
2799  s1en = g_2 * idt_h2 * ( ((r0(i,kb2)-r0(i,kb1))*h1*h2 + &
2800  h_det_to_h2*( (r0(i,kb1)-r0_det)*h1 + (r0(i,kb2)-r0_det)*h2 ) + &
2801  h_ml_to_h2*( (r0(i,kb2)-r0(i,0))*h2 + (r0(i,kb1)-r0(i,0))*h1 + &
2802  (r0_det-r0(i,0))*h_det_to_h2 ) + &
2803  h_det_to_h1*h_ml_to_h1*(r0_det-r0(i,0))) - 2.0*gv%Rho0*dpe_extrap )
2804 
2805  if (allocated(cs%diag_PE_detrain)) &
2806  cs%diag_PE_detrain(i,j) = cs%diag_PE_detrain(i,j) + s1en
2807 
2808  if (allocated(cs%diag_PE_detrain2)) cs%diag_PE_detrain2(i,j) = &
2809  cs%diag_PE_detrain2(i,j) + s1en + idt_h2*rho0xg*dpe_extrap
2810  endif
2811 
2812  elseif ((h_to_bl > 0.0) .or. (h1 < h_min_bl) .or. (h2 < h_min_bl)) then
2813  ! Determine how much of the upper buffer layer will be moved into
2814  ! the lower buffer layer and the properties with which it is moving.
2815  ! This implementation assumes a 2nd-order upwind advection of density
2816  ! from the uppermost buffer layer into the next one down.
2817  h_from_ml = h_min_bl + max(h_min_bl-h2,0.0) - h1 - h_to_bl
2818  if (h_from_ml > 0.0) then
2819  ! Some water needs to be moved from the mixed layer so that the upper
2820  ! (and perhaps lower) buffer layers exceed their minimum thicknesses.
2821  dpe_extrap = dpe_extrap - i2rho0*h_from_ml*(r0_to_bl - r0(i,0)*h_to_bl)
2822  r0_to_bl = r0_to_bl + h_from_ml*r0(i,0)
2823  rcv_to_bl = rcv_to_bl + h_from_ml*rcv(i,0)
2824  t_to_bl = t_to_bl + h_from_ml*t(i,0)
2825  s_to_bl = s_to_bl + h_from_ml*s(i,0)
2826 
2827  h_to_bl = h_to_bl + h_from_ml
2828  h(i,0) = h(i,0) - h_from_ml
2829  d_ea(i,1) = d_ea(i,1) - h_from_ml
2830  endif
2831 
2832  ! The absolute value should be unnecessary and 1e9 is just a large number.
2833  b1 = 1.0e9
2834  if (r0(i,kb2) - r0(i,kb1) > 1.0e-9*abs(r0(i,kb1) - r0_det)) &
2835  b1 = abs(r0(i,kb1) - r0_det) / (r0(i,kb2) - r0(i,kb1))
2836  stays_min = max((1.0-b1)*h1 - b1*h2, 0.0, h_min_bl - h_to_bl)
2837  stays_max = h1 - max(h_min_bl-h2,0.0)
2838 
2839  scale_slope = 1.0
2840  if (stays_max <= stays_min) then
2841  stays = stays_max
2842  mergeable_bl = .false.
2843  if (stays_max < h1) scale_slope = (h1 - stays_min) / (h1 - stays_max)
2844  else
2845  ! There are numerous temporary variables used here that should not be
2846  ! used outside of this "else" branch: s1, s2, s3sq, I_ya, bh0
2847  bh0 = b1*h_to_bl
2848  i_ya = (h1 + h2) / ((h1 + h2) + h_to_bl)
2849  ! s1 is the amount staying that minimizes the PE increase.
2850  s1 = 0.5*(h1 + (h2 - bh0) * i_ya) ; s2 = h1 - s1
2851 
2852  if (s2 < 0.0) then
2853  ! The energy released by detrainment from the lower buffer layer can be
2854  ! used to mix water from the upper buffer layer into the lower one.
2855  s3sq = i_ya*max(bh0*h1-dpe_extrap, 0.0)
2856  else
2857  s3sq = i_ya*(bh0*h1-min(dpe_extrap,0.0))
2858  endif
2859 
2860  if (s3sq == 0.0) then
2861  ! There is a simple, exact solution to the quadratic equation, namely:
2862  stays = h1 ! This will revert to stays_max later.
2863  elseif (s2*s2 <= s3sq) then
2864  ! There is no solution with 0 PE change - use the minimum energy input.
2865  stays = s1
2866  else
2867  ! The following choose the solutions that are continuous with all water
2868  ! staying in the upper buffer layer when there is no detrainment,
2869  ! namely the + root when s2>0 and the - root otherwise. They also
2870  ! carefully avoid differencing large numbers, using s2 = (h1-s).
2871  if (bh0 <= 0.0) then ; stays = h1
2872  elseif (s2 > 0.0) then
2873  ! stays = s + sqrt(s2*s2 - s3sq) ! Note that s2 = h1-s
2874  if (s1 >= stays_max) then ; stays = stays_max
2875  elseif (s1 >= 0.0) then ; stays = s1 + sqrt(s2*s2 - s3sq)
2876  else ; stays = (h1*(s2-s1) - s3sq) / (-s1 + sqrt(s2*s2 - s3sq))
2877  endif
2878  else
2879  ! stays = s - sqrt(s2*s2 - s3sq) ! Note that s2 = h1-s & stays_min >= 0
2880  if (s1 <= stays_min) then ; stays = stays_min
2881  else ; stays = (h1*(s1-s2) + s3sq) / (s1 + sqrt(s2*s2 - s3sq))
2882  endif
2883  endif
2884  endif
2885 
2886  ! Limit the amount that stays so that the motion of water is from the
2887  ! upper buffer layer into the lower, but no more than is in the upper
2888  ! layer, and the water left in the upper layer is no lighter than the
2889  ! detrained water.
2890  if (stays >= stays_max) then ; stays = stays_max
2891  elseif (stays < stays_min) then ; stays = stays_min
2892  endif
2893  endif
2894 
2895  dpe_det = g_2*((r0(i,kb1)*h_to_bl - r0_to_bl)*stays + &
2896  (r0(i,kb2)-r0(i,kb1)) * (h1-stays) * &
2897  (h2 - scale_slope*stays*((h1+h2)+h_to_bl)/(h1+h2)) ) - &
2898  rho0xg*dpe_extrap
2899 
2900  if (dpe_time_ratio*h_to_bl > h_to_bl+h(i,0)) then
2901  dpe_ratio = (h_to_bl+h(i,0)) / h_to_bl
2902  else
2903  dpe_ratio = dpe_time_ratio
2904  endif
2905 
2906  if ((mergeable_bl) .and. (num_events*dpe_ratio*dpe_det > dpe_merge)) then
2907  ! It is energetically preferable to merge the two buffer layers, detrain
2908  ! them into interior layer (k0), move the remaining upper buffer layer
2909  ! water into the lower buffer layer, and detrain undiluted into the
2910  ! upper buffer layer.
2911  h1_to_k0 = (h1-stays_merge)
2912  stays = max(h_min_bl-h_to_bl,0.0)
2913  h1_to_h2 = stays_merge - stays
2914 
2915  ihk0 = 1.0 / ((h1_to_k0 + h2) + h(i,k0))
2916  ih1f = 1.0 / (h_to_bl + stays); ih2f = 1.0 / h1_to_h2
2917  ih12 = 1.0 / (h1 + h2)
2918 
2919  drcv_2dz = (rcv(i,kb1) - rcv(i,kb2)) * ih12
2920  drcv_stays = drcv_2dz*(h1_to_k0 + h1_to_h2)
2921  drcv_det = - drcv_2dz*(stays + h1_to_h2)
2922  rcv(i,k0) = ((h1_to_k0*(rcv(i,kb1) + drcv_det) + &
2923  h2*rcv(i,kb2)) + h(i,k0)*rcv(i,k0)) * ihk0
2924  rcv(i,kb2) = rcv(i,kb1) + drcv_2dz*(h1_to_k0-stays)
2925  rcv(i,kb1) = (rcv_to_bl + stays*(rcv(i,kb1) + drcv_stays)) * ih1f
2926 
2927  ! Use 2nd order upwind advection of spiciness, limited by the value in
2928  ! the water from the mixed layer to determine the temperature and
2929  ! salinity of the water that stays in the buffer layers.
2930  i_denom = 1.0 / (drcv_ds(i)**2 + (dt_ds_gauge*drcv_dt(i))**2)
2931  dspice_2dz = (ds_dt_gauge*drcv_ds(i)*(t(i,kb1)-t(i,kb2)) - &
2932  dt_ds_gauge*drcv_dt(i)*(s(i,kb1)-s(i,kb2))) * ih12
2933  dspice_lim = (ds_dt_gauge*dr0_ds(i)*(t_to_bl-t(i,kb1)*h_to_bl) - &
2934  dt_ds_gauge*dr0_dt(i)*(s_to_bl-s(i,kb1)*h_to_bl)) / h_to_bl
2935  if (dspice_lim * dspice_2dz <= 0.0) dspice_2dz = 0.0
2936 
2937  if (stays > 0.0) then
2938  ! Limit the spiciness of the water that stays in the upper buffer layer.
2939  if (abs(dspice_lim) < abs(dspice_2dz*(h1_to_k0 + h1_to_h2))) &
2940  dspice_2dz = dspice_lim/(h1_to_k0 + h1_to_h2)
2941 
2942  dspice_stays = dspice_2dz*(h1_to_k0 + h1_to_h2)
2943  t_stays = t(i,kb1) + dt_ds_gauge * i_denom * &
2944  (dt_ds_gauge * drcv_dt(i) * drcv_stays + drcv_ds(i) * dspice_stays)
2945  s_stays = s(i,kb1) + i_denom * &
2946  (drcv_ds(i) * drcv_stays - dt_ds_gauge * drcv_dt(i) * dspice_stays)
2947  ! The values of R0 are based on changes in T and S.
2948  r0_stays = r0(i,kb1) + (t_stays-t(i,kb1)) * dr0_dt(i) + &
2949  (s_stays-s(i,kb1)) * dr0_ds(i)
2950  else
2951  ! Limit the spiciness of the water that moves into the lower buffer layer.
2952  if (abs(dspice_lim) < abs(dspice_2dz*h1_to_k0)) &
2953  dspice_2dz = dspice_lim/h1_to_k0
2954  ! These will be multiplied by 0 later.
2955  t_stays = 0.0 ; s_stays = 0.0 ; r0_stays = 0.0
2956  endif
2957 
2958  dspice_det = - dspice_2dz*(stays + h1_to_h2)
2959  t_det = t(i,kb1) + dt_ds_gauge * i_denom * &
2960  (dt_ds_gauge * drcv_dt(i) * drcv_det + drcv_ds(i) * dspice_det)
2961  s_det = s(i,kb1) + i_denom * &
2962  (drcv_ds(i) * drcv_det - dt_ds_gauge * drcv_dt(i) * dspice_det)
2963  ! The values of R0 are based on changes in T and S.
2964  r0_det = r0(i,kb1) + (t_det-t(i,kb1)) * dr0_dt(i) + &
2965  (s_det-s(i,kb1)) * dr0_ds(i)
2966 
2967  t(i,k0) = ((h1_to_k0*t_det + h2*t(i,kb2)) + h(i,k0)*t(i,k0)) * ihk0
2968  t(i,kb2) = (h1*t(i,kb1) - stays*t_stays - h1_to_k0*t_det) * ih2f
2969  t(i,kb1) = (t_to_bl + stays*t_stays) * ih1f
2970 
2971  s(i,k0) = ((h1_to_k0*s_det + h2*s(i,kb2)) + h(i,k0)*s(i,k0)) * ihk0
2972  s(i,kb2) = (h1*s(i,kb1) - stays*s_stays - h1_to_k0*s_det) * ih2f
2973  s(i,kb1) = (s_to_bl + stays*s_stays) * ih1f
2974 
2975  r0(i,k0) = ((h1_to_k0*r0_det + h2*r0(i,kb2)) + h(i,k0)*r0(i,k0)) * ihk0
2976  r0(i,kb2) = (h1*r0(i,kb1) - stays*r0_stays - h1_to_k0*r0_det) * ih2f
2977  r0(i,kb1) = (r0_to_bl + stays*r0_stays) * ih1f
2978 
2979 ! ! The following is 2nd-order upwind advection without limiters.
2980 ! dT_2dz = (T(i,kb1) - T(i,kb2)) * Ih12
2981 ! T(i,k0) = (h1_to_k0*(T(i,kb1) - dT_2dz*(stays+h1_to_h2)) + &
2982 ! h2*T(i,kb2) + h(i,k0)*T(i,k0)) * Ihk0
2983 ! T(i,kb2) = T(i,kb1) + dT_2dz*(h1_to_k0-stays)
2984 ! T(i,kb1) = (T_to_bl + stays*(T(i,kb1) + &
2985 ! dT_2dz*(h1_to_k0 + h1_to_h2))) * Ih1f
2986 ! dS_2dz = (S(i,kb1) - S(i,kb2)) * Ih12
2987 ! S(i,k0) = (h1_to_k0*(S(i,kb1) - dS_2dz*(stays+h1_to_h2)) + &
2988 ! h2*S(i,kb2) + h(i,k0)*S(i,k0)) * Ihk0
2989 ! S(i,kb2) = S(i,kb1) + dS_2dz*(h1_to_k0-stays)
2990 ! S(i,kb1) = (S_to_bl + stays*(S(i,kb1) + &
2991 ! dS_2dz*(h1_to_k0 + h1_to_h2))) * Ih1f
2992 ! dR0_2dz = (R0(i,kb1) - R0(i,kb2)) * Ih12
2993 ! R0(i,k0) = (h1_to_k0*(R0(i,kb1) - dR0_2dz*(stays+h1_to_h2)) + &
2994 ! h2*R0(i,kb2) + h(i,k0)*R0(i,k0)) * Ihk0
2995 ! R0(i,kb2) = R0(i,kb1) + dR0_2dz*(h1_to_k0-stays)
2996 ! R0(i,kb1) = (R0_to_bl + stays*(R0(i,kb1) + &
2997 ! dR0_2dz*(h1_to_k0 + h1_to_h2))) * Ih1f
2998 
2999  d_ea(i,kb1) = (d_ea(i,kb1) + h_to_bl) + (stays - h1)
3000  d_ea(i,kb2) = d_ea(i,kb2) + (h1_to_h2 - h2)
3001  d_ea(i,k0) = d_ea(i,k0) + (h1_to_k0 + h2)
3002 
3003  h(i,kb1) = stays + h_to_bl
3004  h(i,kb2) = h1_to_h2
3005  h(i,k0) = h(i,k0) + (h1_to_k0 + h2)
3006  if (allocated(cs%diag_PE_detrain)) &
3007  cs%diag_PE_detrain(i,j) = cs%diag_PE_detrain(i,j) + idt_h2*dpe_merge
3008  if (allocated(cs%diag_PE_detrain2)) cs%diag_PE_detrain2(i,j) = &
3009  cs%diag_PE_detrain2(i,j) + idt_h2*(dpe_det + rho0xg*dpe_extrap)
3010  else ! Not mergeable_bl.
3011  ! There is no further detrainment from the buffer layers, and the
3012  ! upper buffer layer water is distributed optimally between the
3013  ! upper and lower buffer layer.
3014  h1_to_h2 = h1 - stays
3015  ih1f = 1.0 / (h_to_bl + stays) ; ih2f = 1.0 / (h2 + h1_to_h2)
3016  ih = 1.0 / (h1 + h2)
3017  dr0_2dz = (r0(i,kb1) - r0(i,kb2)) * ih
3018  r0(i,kb2) = (h2*r0(i,kb2) + h1_to_h2*(r0(i,kb1) - &
3019  scale_slope*dr0_2dz*stays)) * ih2f
3020  r0(i,kb1) = (r0_to_bl + stays*(r0(i,kb1) + &
3021  scale_slope*dr0_2dz*h1_to_h2)) * ih1f
3022 
3023  ! Use 2nd order upwind advection of spiciness, limited by the value
3024  ! in the detrained water to determine the detrained temperature and
3025  ! salinity.
3026  dr0 = scale_slope*dr0_2dz*h1_to_h2
3027  dspice_stays = (ds_dt_gauge*dr0_ds(i)*(t(i,kb1)-t(i,kb2)) - &
3028  dt_ds_gauge*dr0_dt(i)*(s(i,kb1)-s(i,kb2))) * &
3029  scale_slope*h1_to_h2 * ih
3030  if (h_to_bl > 0.0) then
3031  dspice_lim = (ds_dt_gauge*dr0_ds(i)*(t_to_bl-t(i,kb1)*h_to_bl) - &
3032  dt_ds_gauge*dr0_dt(i)*(s_to_bl-s(i,kb1)*h_to_bl)) /&
3033  h_to_bl
3034  else
3035  dspice_lim = ds_dt_gauge*dr0_ds(i)*(t(i,0)-t(i,kb1)) - &
3036  dt_ds_gauge*dr0_dt(i)*(s(i,0)-s(i,kb1))
3037  endif
3038  if (dspice_stays*dspice_lim <= 0.0) then
3039  dspice_stays = 0.0
3040  elseif (abs(dspice_stays) > abs(dspice_lim)) then
3041  dspice_stays = dspice_lim
3042  endif
3043  i_denom = 1.0 / (dr0_ds(i)**2 + (dt_ds_gauge*dr0_dt(i))**2)
3044  t_stays = t(i,kb1) + dt_ds_gauge * i_denom * &
3045  (dt_ds_gauge * dr0_dt(i) * dr0 + dr0_ds(i) * dspice_stays)
3046  s_stays = s(i,kb1) + i_denom * &
3047  (dr0_ds(i) * dr0 - dt_ds_gauge * dr0_dt(i) * dspice_stays)
3048  ! The detrained values of Rcv are based on changes in T and S.
3049  rcv_stays = rcv(i,kb1) + (t_stays-t(i,kb1)) * drcv_dt(i) + &
3050  (s_stays-s(i,kb1)) * drcv_ds(i)
3051 
3052  t(i,kb2) = (h2*t(i,kb2) + h1*t(i,kb1) - t_stays*stays) * ih2f
3053  t(i,kb1) = (t_to_bl + stays*t_stays) * ih1f
3054  s(i,kb2) = (h2*s(i,kb2) + h1*s(i,kb1) - s_stays*stays) * ih2f
3055  s(i,kb1) = (s_to_bl + stays*s_stays) * ih1f
3056  rcv(i,kb2) = (h2*rcv(i,kb2) + h1*rcv(i,kb1) - rcv_stays*stays) * ih2f
3057  rcv(i,kb1) = (rcv_to_bl + stays*rcv_stays) * ih1f
3058 
3059 ! ! The following is 2nd-order upwind advection without limiters.
3060 ! dRcv_2dz = (Rcv(i,kb1) - Rcv(i,kb2)) * Ih
3061 ! dRcv = scale_slope*dRcv_2dz*h1_to_h2
3062 ! Rcv(i,kb2) = (h2*Rcv(i,kb2) + h1_to_h2*(Rcv(i,kb1) - &
3063 ! scale_slope*dRcv_2dz*stays)) * Ih2f
3064 ! Rcv(i,kb1) = (Rcv_to_bl + stays*(Rcv(i,kb1) + dRcv)) * Ih1f
3065 ! dT_2dz = (T(i,kb1) - T(i,kb2)) * Ih
3066 ! T(i,kb2) = (h2*T(i,kb2) + h1_to_h2*(T(i,kb1) - &
3067 ! scale_slope*dT_2dz*stays)) * Ih2f
3068 ! T(i,kb1) = (T_to_bl + stays*(T(i,kb1) + &
3069 ! scale_slope*dT_2dz*h1_to_h2)) * Ih1f
3070 ! dS_2dz = (S(i,kb1) - S(i,kb2)) * Ih
3071 ! S(i,kb2) = (h2*S(i,kb2) + h1_to_h2*(S(i,kb1) - &
3072 ! scale_slope*dS_2dz*stays)) * Ih2f
3073 ! S(i,kb1) = (S_to_bl + stays*(S(i,kb1) + &
3074 ! scale_slope*dS_2dz*h1_to_h2)) * Ih1f
3075 
3076  d_ea(i,kb1) = d_ea(i,kb1) + ((stays - h1) + h_to_bl)
3077  d_ea(i,kb2) = d_ea(i,kb2) + h1_to_h2
3078 
3079  h(i,kb1) = stays + h_to_bl
3080  h(i,kb2) = h(i,kb2) + h1_to_h2
3081 
3082  if (allocated(cs%diag_PE_detrain)) &
3083  cs%diag_PE_detrain(i,j) = cs%diag_PE_detrain(i,j) + idt_h2*dpe_det
3084  if (allocated(cs%diag_PE_detrain2)) cs%diag_PE_detrain2(i,j) = &
3085  cs%diag_PE_detrain2(i,j) + idt_h2*(dpe_det + rho0xg*dpe_extrap)
3086  endif
3087  endif ! End of detrainment...
3088 
3089  enddo ! i loop
3090 
3091 end subroutine mixedlayer_detrain_2
3092 
3093 !> This subroutine moves any water left in the former mixed layers into the
3094 !! single buffer layers and may also move buffer layer water into the interior
3095 !! isopycnal layers.
3096 subroutine mixedlayer_detrain_1(h, T, S, R0, Rcv, RcvTgt, dt_in_T, dt_diag, d_ea, d_eb, &
3097  j, G, GV, US, CS, dRcv_dT, dRcv_dS, max_BL_det)
3098  type(ocean_grid_type), intent(in) :: G !< The ocean's grid structure.
3099  type(verticalgrid_type), intent(in) :: GV !< The ocean's vertical grid structure.
3100  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: h !< Layer thickness [H ~> m or kg m-2].
3101  !! Layer 0 is the new mixed layer.
3102  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: T !< Potential temperature [degC].
3103  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: S !< Salinity [ppt].
3104  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: R0 !< Potential density referenced to
3105  !! surface pressure [kg m-3].
3106  real, dimension(SZI_(G),SZK0_(GV)), intent(inout) :: Rcv !< The coordinate defining potential
3107  !! density [kg m-3].
3108  real, dimension(SZK_(GV)), intent(in) :: RcvTgt !< The target value of Rcv for each
3109  !! layer [kg m-3].
3110  real, intent(in) :: dt_in_T !< Time increment [T ~> s].
3111  real, intent(in) :: dt_diag !< The accumulated time interval for
3112  !! diagnostics [T ~> s].
3113  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: d_ea !< The upward increase across a layer in
3114  !! the entrainment from above
3115  !! [H ~> m or kg m-2]. Positive d_ea
3116  !! goes with layer thickness increases.
3117  real, dimension(SZI_(G),SZK_(GV)), intent(inout) :: d_eb !< The downward increase across a layer
3118  !! in the entrainment from below [H ~> m or kg m-2].
3119  !! Positive values go with mass gain by
3120  !! a layer.
3121  integer, intent(in) :: j !< The meridional row to work on.
3122  type(unit_scale_type), intent(in) :: US !< A dimensional unit scaling type
3123  type(bulkmixedlayer_cs), pointer :: CS !< The control structure returned by a
3124  !! previous call to mixedlayer_init.
3125  real, dimension(SZI_(G)), intent(in) :: dRcv_dT !< The partial derivative of
3126  !! coordinate defining potential density
3127  !! with potential temperature
3128  !! [kg m-3 degC-1].
3129  real, dimension(SZI_(G)), intent(in) :: dRcv_dS !< The partial derivative of
3130  !! coordinate defining potential density
3131  !! with salinity [kg m-3 ppt-1].
3132  real, dimension(SZI_(G)), intent(in) :: max_BL_det !< If non-negative, the maximum
3133  !! detrainment permitted from the buffer
3134  !! layers [H ~> m or kg m-2].
3135 
3136  ! Local variables
3137  real :: Ih ! The inverse of a thickness [H-1 ~> m-1 or m2 kg-1].
3138  real :: h_ent ! The thickness from a layer that is
3139  ! entrained [H ~> m or kg m-2].
3140  real :: max_det_rem(SZI_(G)) ! Remaining permitted detrainment [H ~> m or kg m-2].
3141  real :: detrain(SZI_(G)) ! The thickness of fluid to detrain
3142  ! from the mixed layer [H ~> m or kg m-2].
3143  real :: dT_dR, dS_dR, dRml, dR0_dRcv, dT_dS_wt2
3144  real :: I_denom ! A work variable [ppt2 m6 kg-2].
3145  real :: Sdown, Tdown
3146  real :: dt_Time ! The timestep divided by the detrainment timescale [nondim].
3147  real :: g_H2_2Rho0dt ! Half the gravitational acceleration times the square of the
3148  ! conversion from H to m divided by the mean density times the time
3149  ! step [m7 T-3 Z-1 H-2 kg-1 ~> m4 s-3 kg-1 or m10 s-3 kg-3].
3150  real :: g_H2_2dt ! Half the gravitational acceleration times the square of the
3151  ! conversion from H to m divided by the diagnostic time step
3152  ! [m4 Z-1 H-2 T-3 ~> m s-3 or m7 kg-2 s-3].
3153 
3154  logical :: splittable_BL(SZI_(G)), orthogonal_extrap
3155  real :: x1
3156 
3157  integer :: i, is, ie, k, k1, nkmb, nz
3158  is = g%isc ; ie = g%iec ; nz = gv%ke
3159  nkmb = cs%nkml+cs%nkbl
3160  if (cs%nkbl /= 1) call mom_error(fatal,"MOM_mixed_layer: "// &
3161  "CS%nkbl must be 1 in mixedlayer_detrain_1.")
3162 
3163  dt_time = dt_in_t / cs%BL_detrain_time
3164  g_h2_2rho0dt = (us%L_to_m**2*gv%g_Earth * gv%H_to_Z**2) / (2.0 * gv%Rho0 * dt_diag)
3165  g_h2_2dt = (us%L_to_m**2*gv%g_Earth * gv%H_to_Z**2) / (2.0 * dt_diag)
3166 
3167  ! Move detrained water into the buffer layer.
3168  do k=1,cs%nkml
3169  do i=is,ie ; if (h(i,k) > 0.0) then
3170  ih = 1.0 / (h(i,nkmb) + h(i,k))
3171  if (cs%TKE_diagnostics) &
3172  cs%diag_TKE_conv_s2(i,j) = cs%diag_TKE_conv_s2(i,j) + &
3173  g_h2_2rho0dt * h(i,k) * h(i,nkmb) * (r0(i,nkmb) - r0(i,k))
3174  if (allocated(cs%diag_PE_detrain)) &
3175  cs%diag_PE_detrain(i,j) = cs%diag_PE_detrain(i,j) + &
3176  g_h2_2dt * h(i,k) * h(i,nkmb) * (r0(i,nkmb) - r0(i,k))
3177  if (allocated(cs%diag_PE_detrain2)) &
3178  cs%diag_PE_detrain2(i,j) = cs%diag_PE_detrain2(i,j) + &
3179  g_h2_2dt * h(i,k) * h(i,nkmb) * (r0(i,nkmb) - r0(i,k))
3180 
3181  r0(i,nkmb) = (r0(i,nkmb)*h(i,nkmb) + r0(i,k)*h(i,k)) * ih
3182  rcv(i,nkmb) = (rcv(i,nkmb)*h(i,nkmb) + rcv(i,k)*h(i,k)) * ih
3183  t(i,nkmb) = (t(i,nkmb)*h(i,nkmb) + t(i,k)*h(i,k)) * ih
3184  s(i,nkmb) = (s(i,nkmb)*h(i,nkmb) + s(i,k)*h(i,k)) * ih
3185 
3186  d_ea(i,k) = d_ea(i,k) - h(i,k)
3187  d_ea(i,nkmb) = d_ea(i,nkmb) + h(i,k)
3188  h(i,nkmb) = h(i,nkmb) + h(i,k)
3189  h(i,k) = 0.0
3190  endif ; enddo
3191  enddo
3192 
3193  do i=is,ie
3194  max_det_rem(i) = 10.0 * h(i,nkmb)
3195  if (max_bl_det(i) >= 0.0) max_det_rem(i) = max_bl_det(i)
3196  enddo
3197 
3198 ! If the mixed layer was denser than the densest interior layer,
3199 ! but is now lighter than this layer, leaving a buffer layer that
3200 ! is denser than this layer, there are problems. This should prob-
3201 ! ably be considered a case of an inadequate choice of resolution in
3202 ! density space and should be avoided. To make the model run sens-
3203 ! ibly in this case, it will make the mixed layer denser while making
3204 ! the buffer layer the density of the densest interior layer (pro-
3205 ! vided that the this will not make the mixed layer denser than the
3206 ! interior layer). Otherwise, make the mixed layer the same density
3207 ! as the densest interior layer and lighten the buffer layer with
3208 ! the released buoyancy. With multiple buffer layers, much more
3209 ! graceful options are available.
3210  do i=is,ie ; if (h(i,nkmb) > 0.0) then
3211  if ((r0(i,0)<r0(i,nz)) .and. (r0(i,nz)<r0(i,nkmb))) then
3212  if ((r0(i,nz)-r0(i,0))*h(i,0) > &
3213  (r0(i,nkmb)-r0(i,nz))*h(i,nkmb)) then
3214  detrain(i) = (r0(i,nkmb)-r0(i,nz))*h(i,nkmb) / (r0(i,nkmb)-r0(i,0))
3215  else
3216  detrain(i) = (r0(i,nz)-r0(i,0))*h(i,0) / (r0(i,nkmb)-r0(i,0))
3217  endif
3218 
3219  d_eb(i,cs%nkml) = d_eb(i,cs%nkml) + detrain(i)
3220  d_ea(i,cs%nkml) = d_ea(i,cs%nkml) - detrain(i)
3221  d_eb(i,nkmb) = d_eb(i,nkmb) - detrain(i)
3222  d_ea(i,nkmb) = d_ea(i,nkmb) + detrain(i)
3223 
3224  if (allocated(cs%diag_PE_detrain)) cs%diag_PE_detrain(i,j) = &
3225  cs%diag_PE_detrain(i,j) + g_h2_2dt * detrain(i)* &
3226  (h(i,0) + h(i,nkmb)) * (r0(i,nkmb) - r0(i,0))
3227  x1 = r0(i,0)
3228  r0(i,0) = r0(i,0) - detrain(i)*(r0(i,0)-r0(i,nkmb)) / h(i,0)
3229  r0(i,nkmb) = r0(i,nkmb) - detrain(i)*(r0(i,nkmb)-x1) / h(i,nkmb)
3230  x1 = rcv(i,0)
3231  rcv(i,0) = rcv(i,0) - detrain(i)*(rcv(i,0)-rcv(i,nkmb)) / h(i,0)
3232  rcv(i,nkmb) = rcv(i,nkmb) - detrain(i)*(rcv(i,nkmb)-x1) / h(i,nkmb)
3233  x1 = t(i,0)
3234  t(i,0) = t(i,0) - detrain(i)*(t(i,0)-t(i,nkmb)) / h(i,0)
3235  t(i,nkmb) = t(i,nkmb) - detrain(i)*(t(i,nkmb)-x1) / h(i,nkmb)
3236  x1 = s(i,0)
3237  s(i,0) = s(i,0) - detrain(i)*(s(i,0)-s(i,nkmb)) / h(i,0)
3238  s(i,nkmb) = s(i,nkmb) - detrain(i)*(s(i,nkmb)-x1) / h(i,nkmb)
3239 
3240  endif
3241  endif ; enddo
3242 
3243  ! Move water out of the buffer layer, if convenient.
3244 ! Split the buffer layer if possible, and replace the buffer layer
3245 ! with a small amount of fluid from the mixed layer.
3246 ! This is the exponential-in-time splitting, circa 2005.
3247  do i=is,ie
3248  if (h(i,nkmb) > 0.0) then ; splittable_bl(i) = .true.
3249  else ; splittable_bl(i) = .false. ; endif
3250  enddo
3251 
3252  dt_ds_wt2 = cs%dT_dS_wt**2
3253 
3254  do k=nz-1,nkmb+1,-1 ; do i=is,ie
3255  if (splittable_bl(i)) then
3256  if (rcvtgt(k)<=rcv(i,nkmb)) then
3257 ! Estimate dR/drho, dTheta/dR, and dS/dR, where R is the coordinate variable
3258 ! and rho is in-situ (or surface) potential density.
3259 ! There is no "right" way to do this, so this keeps things reasonable, if
3260 ! slightly arbitrary.
3261  splittable_bl(i) = .false.
3262 
3263  k1 = k+1 ; orthogonal_extrap = .false.
3264  ! Here we try to find a massive layer to use for interpolating the
3265  ! temperature and salinity. If none is available a pseudo-orthogonal
3266  ! extrapolation is used. The 10.0 and 0.9 in the following are
3267  ! arbitrary but probably about right.
3268  if ((h(i,k+1) < 10.0*gv%Angstrom_H) .or. &
3269  ((rcvtgt(k+1)-rcv(i,nkmb)) >= 0.9*(rcv(i,k1) - rcv(i,0)))) then
3270  if (k>=nz-1) then ; orthogonal_extrap = .true.
3271  elseif ((h(i,k+2) <= 10.0*gv%Angstrom_H) .and. &
3272  ((rcvtgt(k+1)-rcv(i,nkmb)) < 0.9*(rcv(i,k+2)-rcv(i,0)))) then
3273  k1 = k+2
3274  else ; orthogonal_extrap = .true. ; endif
3275  endif
3276 
3277  if ((r0(i,0) >= r0(i,k1)) .or. (rcv(i,0) >= rcv(i,nkmb))) cycle
3278  ! In this case there is an inversion of in-situ density relative to
3279  ! the coordinate variable. Do not detrain from the buffer layer.
3280 
3281  if (orthogonal_extrap) then
3282  ! 36 here is a typical oceanic value of (dR/dS) / (dR/dT) - it says
3283  ! that the relative weights of T & S changes is a plausible 6:1.
3284  ! Also, this was coded on Athena's 6th birthday!
3285  i_denom = 1.0 / (drcv_ds(i)**2 + dt_ds_wt2*drcv_dt(i)**2)
3286  dt_dr = dt_ds_wt2*drcv_dt(i) * i_denom
3287  ds_dr = drcv_ds(i) * i_denom
3288  else
3289  dt_dr = (t(i,0) - t(i,k1)) / (rcv(i,0) - rcv(i,k1))
3290  ds_dr = (s(i,0) - s(i,k1)) / (rcv(i,0) - rcv(i,k1))
3291  endif
3292  drml = dt_time * (r0(i,nkmb) - r0(i,0)) * &
3293  (rcv(i,0) - rcv(i,k1)) / (r0(i,0) - r0(i,k1))
3294  ! Once again, there is an apparent density inversion in Rcv.
3295  if (drml < 0.0) cycle
3296  dr0_drcv = (r0(i,0) - r0(i,k1)) / (rcv(i,0) - rcv(i,k1))
3297 
3298  if ((rcv(i,nkmb) - drml < rcvtgt(k)) .and. (max_det_rem(i) > h(i,nkmb))) then
3299  ! In this case, the buffer layer is split into two isopycnal layers.
3300  detrain(i) = h(i,nkmb)*(rcv(i,nkmb) - rcvtgt(k)) / &
3301  (rcvtgt(k+1) - rcvtgt(k))
3302 
3303  if (allocated(cs%diag_PE_detrain)) cs%diag_PE_detrain(i,j) = &
3304  cs%diag_PE_detrain(i,j) - g_h2_2dt * detrain(i) * &
3305  (h(i,nkmb)-detrain(i)) * (rcvtgt(k+1) - rcvtgt(k)) * dr0_drcv
3306 
3307  tdown = detrain(i) * (t(i,nkmb) + dt_dr*(rcvtgt(k+1)-rcv(i,nkmb)))
3308  t(i,k) = (h(i,k) * t(i,k) + &
3309  (h(i,nkmb) * t(i,nkmb) - tdown)) / &
3310  (h(i,k) + (h(i,nkmb) - detrain(i)))
3311  t(i,k+1) = (h(i,k+1) * t(i,k+1) + tdown)/ &
3312  (h(i,k+1) + detrain(i))
3313  t(i,nkmb) = t(i,0)
3314  sdown = detrain(i) * (s(i,nkmb) + ds_dr*(rcvtgt(k+1)-rcv(i,nkmb)))
3315  s(i,k) = (h(i,k) * s(i,k) + &
3316  (h(i,nkmb) * s(i,nkmb) - sdown)) / &
3317  (h(i,k) + (h(i,nkmb) - detrain(i)))
3318  s(i,k+1) = (h(i,k+1) * s(i,k+1) + sdown)/ &
3319  (h(i,k+1) + detrain(i))
3320  s(i,nkmb) = s(i,0)
3321  rcv(i,nkmb) = rcv(i,0)
3322 
3323  d_ea(i,k+1) = d_ea(i,k+1) + detrain(i)
3324  d_ea(i,k) = d_ea(i,k) + (h(i,nkmb) - detrain(i))
3325  d_ea(i,nkmb) = d_ea(i,nkmb) - h(i,nkmb)
3326 
3327  h(i,k+1) = h(i,k+1) + detrain(i)
3328  h(i,k) = h(i,k) + h(i,nkmb) - detrain(i)
3329  h(i,nkmb) = 0.0
3330  else
3331  ! Here only part of the buffer layer is moved into the interior.
3332  detrain(i) = h(i,nkmb) * drml / (rcvtgt(k+1) - rcv(i,nkmb) + drml)
3333  if (detrain(i) > max_det_rem(i)) detrain(i) = max_det_rem(i)
3334  ih = 1.0 / (h(i,k+1) + detrain(i))
3335 
3336  tdown = (t(i,nkmb) + dt_dr*(rcvtgt(k+1)-rcv(i,nkmb)))
3337  t(i,nkmb) = t(i,nkmb) - dt_dr * drml
3338  t(i,k+1) = (h(i,k+1) * t(i,k+1) + detrain(i) * tdown) * ih
3339  sdown = (s(i,nkmb) + ds_dr*(rcvtgt(k+1)-rcv(i,nkmb)))
3340 ! The following two expressions updating S(nkmb) are mathematically identical.
3341 ! S(i,nkmb) = (h(i,nkmb) * S(i,nkmb) - detrain(i) * Sdown) / &
3342 ! (h(i,nkmb) - detrain(i))
3343  s(i,nkmb) = s(i,nkmb) - ds_dr * drml
3344  s(i,k+1) = (h(i,k+1) * s(i,k+1) + detrain(i) * sdown) * ih
3345 
3346  d_ea(i,k+1) = d_ea(i,k+1) + detrain(i)
3347  d_ea(i,nkmb) = d_ea(i,nkmb) - detrain(i)
3348 
3349  h(i,k+1) = h(i,k+1) + detrain(i)
3350  h(i,nkmb) = h(i,nkmb) - detrain(i)
3351 
3352  if (allocated(cs%diag_PE_detrain)) cs%diag_PE_detrain(i,j) = &
3353  cs%diag_PE_detrain(i,j) - g_h2_2dt * detrain(i) * dr0_drcv * &
3354  (h(i,nkmb)-detrain(i)) * (rcvtgt(k+1) - rcv(i,nkmb) + drml)
3355  endif
3356  endif ! RcvTgt(k)<=Rcv(i,nkmb)
3357  endif ! splittable_BL
3358  enddo ; enddo ! i & k loops
3359 
3360 ! The numerical behavior of the buffer layer is dramatically improved
3361 ! if it is always at least a small fraction (say 10%) of the thickness
3362 ! of the mixed layer. As the physical distinction between the mixed
3363 ! and buffer layers is vague anyway, this seems hard to argue against.
3364  do i=is,ie
3365  if (h(i,nkmb) < 0.1*h(i,0)) then
3366  h_ent = 0.1*h(i,0) - h(i,nkmb)
3367  ih = 10.0/h(i,0)
3368  t(i,nkmb) = (h(i,nkmb)*t(i,nkmb) + h_ent*t(i,0)) * ih
3369  s(i,nkmb) = (h(i,nkmb)*s(i,nkmb) + h_ent*s(i,0)) * ih
3370 
3371  d_ea(i,1) = d_ea(i,1) - h_ent
3372  d_ea(i,nkmb) = d_ea(i,nkmb) + h_ent
3373 
3374  h(i,0) = h(i,0) - h_ent
3375  h(i,nkmb) = h(i,nkmb) + h_ent
3376  endif
3377  enddo
3378 
3379 end subroutine mixedlayer_detrain_1
3380 
3381 !> This subroutine initializes the MOM bulk mixed layer module.
3382 subroutine bulkmixedlayer_init(Time, G, GV, US, param_file, diag, CS)
3383  type(time_type), target, intent(in) :: time !< The model's clock with the current time.
3384  type(ocean_grid_type), intent(in) :: g !< The ocean's grid structure.
3385  type(verticalgrid_type), intent(in) :: gv !< The ocean's vertical grid structure.
3386  type(unit_scale_type), intent(in) :: us !< A dimensional unit scaling type
3387  type(param_file_type), intent(in) :: param_file !< A structure to parse for run-time
3388  !! parameters.
3389  type(diag_ctrl), target, intent(inout) :: diag !< A structure that is used to regulate diagnostic
3390  !! output.
3391  type(bulkmixedlayer_cs), pointer :: cs !< A pointer that is set to point to the control
3392  !! structure for this module.
3393 ! Arguments: Time - The current model time.
3394 ! (in) G - The ocean's grid structure.
3395 ! (in) GV - The ocean's vertical grid structure.
3396 ! (in) param_file - A structure indicating the open file to parse for
3397 ! model parameter values.
3398 ! (in) diag - A structure that is used to regulate diagnostic output.
3399 ! (in/out) CS - A pointer that is set to point to the control structure
3400 ! for this module
3401 ! This include declares and sets the variable "version".
3402 #include "version_variable.h"
3403  character(len=40) :: mdl = "MOM_mixed_layer" ! This module's name.
3404  real :: bl_detrain_time_dflt ! The default value for BUFFER_LAY_DETRAIN_TIME [s]
3405  real :: omega_frac_dflt, ustar_min_dflt, hmix_min_m
3406  integer :: isd, ied, jsd, jed
3407  logical :: use_temperature, use_omega
3408  isd = g%isd ; ied = g%ied ; jsd = g%jsd ; jed = g%jed
3409 
3410  if (associated(cs)) then
3411  call mom_error(warning, "mixedlayer_init called with an associated"// &
3412  "associated control structure.")
3413  return
3414  else ; allocate(cs) ; endif
3415 
3416  cs%diag => diag
3417  cs%Time => time
3418 
3419  if (gv%nkml < 1) return
3420 
3421 ! Set default, read and log parameters
3422  call log_version(param_file, mdl, version, "")
3423 
3424  cs%nkml = gv%nkml
3425  call log_param(param_file, mdl, "NKML", cs%nkml, &
3426  "The number of sublayers within the mixed layer if "//&
3427  "BULKMIXEDLAYER is true.", units="nondim", default=2)
3428  cs%nkbl = gv%nk_rho_varies - gv%nkml
3429  call log_param(param_file, mdl, "NKBL", cs%nkbl, &
3430  "The number of variable density buffer layers if "//&
3431  "BULKMIXEDLAYER is true.", units="nondim", default=2)
3432  call get_param(param_file, mdl, "MSTAR", cs%mstar, &
3433  "The ratio of the friction velocity cubed to the TKE "//&
3434  "input to the mixed layer.", "units=nondim", default=1.2)
3435  call get_param(param_file, mdl, "NSTAR", cs%nstar, &
3436  "The portion of the buoyant potential energy imparted by "//&
3437  "surface fluxes that is available to drive entrainment "//&
3438  "at the base of mixed layer when that energy is positive.", &
3439  units="nondim", default=0.15)
3440  call get_param(param_file, mdl, "BULK_RI_ML", cs%bulk_Ri_ML, &
3441  "The efficiency with which mean kinetic energy released "//&
3442  "by mechanically forced entrainment of the mixed layer "//&
3443  "is converted to turbulent kinetic energy.", units="nondim",&
3444  fail_if_missing=.true.)
3445  call get_param(param_file, mdl, "ABSORB_ALL_SW", cs%absorb_all_sw, &
3446  "If true, all shortwave radiation is absorbed by the "//&
3447  "ocean, instead of passing through to the bottom mud.", &
3448  default=.false.)
3449  call get_param(param_file, mdl, "TKE_DECAY", cs%TKE_decay, &
3450  "TKE_DECAY relates the vertical rate of decay of the "//&
3451  "TKE available for mechanical entrainment to the natural "//&
3452  "Ekman depth.", units="nondim", default=2.5)
3453  call get_param(param_file, mdl, "NSTAR2", cs%nstar2, &
3454  "The portion of any potential energy released by "//&
3455  "convective adjustment that is available to drive "//&
3456  "entrainment at the base of mixed layer. By default "//&
3457  "NSTAR2=NSTAR.", units="nondim", default=cs%nstar)
3458  call get_param(param_file, mdl, "BULK_RI_CONVECTIVE", cs%bulk_Ri_convective, &
3459  "The efficiency with which convectively released mean "//&
3460  "kinetic energy is converted to turbulent kinetic "//&
3461  "energy. By default BULK_RI_CONVECTIVE=BULK_RI_ML.", &
3462  units="nondim", default=cs%bulk_Ri_ML)
3463  call get_param(param_file, mdl, "HMIX_MIN", cs%Hmix_min, &
3464  "The minimum mixed layer depth if the mixed layer depth "//&
3465  "is determined dynamically.", units="m", default=0.0, scale=gv%m_to_H, &
3466  unscaled=hmix_min_m)
3467 
3468  call get_param(param_file, mdl, "LIMIT_BUFFER_DETRAIN", cs%limit_det, &
3469  "If true, limit the detrainment from the buffer layers "//&
3470  "to not be too different from the neighbors.", default=.false.)
3471  call get_param(param_file, mdl, "ALLOWED_DETRAIN_TEMP_CHG", cs%Allowed_T_chg, &
3472  "The amount by which temperature is allowed to exceed "//&
3473  "previous values during detrainment.", units="K", default=0.5)
3474  call get_param(param_file, mdl, "ALLOWED_DETRAIN_SALT_CHG", cs%Allowed_S_chg, &
3475  "The amount by which salinity is allowed to exceed "//&
3476  "previous values during detrainment.", units="PSU", default=0.1)
3477  call get_param(param_file, mdl, "ML_DT_DS_WEIGHT", cs%dT_dS_wt, &
3478  "When forced to extrapolate T & S to match the layer "//&
3479  "densities, this factor (in deg C / PSU) is combined "//&
3480  "with the derivatives of density with T & S to determine "//&
3481  "what direction is orthogonal to density contours. It "//&
3482  "should be a typical value of (dR/dS) / (dR/dT) in "//&
3483  "oceanic profiles.", units="degC PSU-1", default=6.0)
3484  call get_param(param_file, mdl, "BUFFER_LAYER_EXTRAP_LIMIT", cs%BL_extrap_lim, &
3485  "A limit on the density range over which extrapolation "//&
3486  "can occur when detraining from the buffer layers, "//&
3487  "relative to the density range within the mixed and "//&
3488  "buffer layers, when the detrainment is going into the "//&
3489  "lightest interior layer, nondimensional, or a negative "//&
3490  "value not to apply this limit.", units="nondim", default = -1.0)
3491  call get_param(param_file, mdl, "BUFFER_LAYER_HMIN_THICK", cs%Hbuffer_min, &
3492  "The minimum buffer layer thickness when the mixed layer is very thick.", &
3493  units="m", default=5.0, scale=gv%m_to_H)
3494  call get_param(param_file, mdl, "BUFFER_LAYER_HMIN_REL", cs%Hbuffer_rel_min, &
3495  "The minimum buffer layer thickness relative to the combined mixed "//&
3496  "land buffer ayer thicknesses when they are thin.", &
3497  units="nondim", default=0.1/cs%nkbl)
3498  bl_detrain_time_dflt = 4.0*3600.0 ; if (cs%nkbl==1) bl_detrain_time_dflt = 86400.0*30.0
3499  call get_param(param_file, mdl, "BUFFER_LAY_DETRAIN_TIME", cs%BL_detrain_time, &
3500  "A timescale that characterizes buffer layer detrainment events.", &
3501  units="s", default=bl_detrain_time_dflt, scale=us%s_to_T)
3502  call get_param(param_file, mdl, "BUFFER_SPLIT_RHO_TOL", cs%BL_split_rho_tol, &
3503  "The fractional tolerance for matching layer target densities when splitting "//&
3504  "layers to deal with massive interior layers that are lighter than one of the "//&
3505  "mixed or buffer layers.", units="nondim", default=0.1)
3506 
3507  call get_param(param_file, mdl, "DEPTH_LIMIT_FLUXES", cs%H_limit_fluxes, &
3508  "The surface fluxes are scaled away when the total ocean "//&
3509  "depth is less than DEPTH_LIMIT_FLUXES.", &
3510  units="m", default=0.1*hmix_min_m, scale=gv%m_to_H)
3511  call get_param(param_file, mdl, "OMEGA", cs%omega, &
3512  "The rotation rate of the earth.", &
3513  default=7.2921e-5, units="s-1", scale=us%T_to_s)
3514  call get_param(param_file, mdl, "ML_USE_OMEGA", use_omega, &
3515  "If true, use the absolute rotation rate instead of the "//&
3516  "vertical component of rotation when setting the decay "//&
3517  "scale for turbulence.", default=.false., do_not_log=.true.)
3518  omega_frac_dflt = 0.0
3519  if (use_omega) then
3520  call mom_error(warning, "ML_USE_OMEGA is depricated; use ML_OMEGA_FRAC=1.0 instead.")
3521  omega_frac_dflt = 1.0
3522  endif
3523  call get_param(param_file, mdl, "ML_OMEGA_FRAC", cs%omega_frac, &
3524  "When setting the decay scale for turbulence, use this "//&
3525  "fraction of the absolute rotation rate blended with the "//&
3526  "local value of f, as sqrt((1-of)*f^2 + of*4*omega^2).", &
3527  units="nondim", default=omega_frac_dflt)
3528  call get_param(param_file, mdl, "ML_RESORT", cs%ML_resort, &
3529  "If true, resort the topmost layers by potential density "//&
3530  "before the mixed layer calculations.", default=.false.)
3531  if (cs%ML_resort) &
3532  call get_param(param_file, mdl, "ML_PRESORT_NK_CONV_ADJ", cs%ML_presort_nz_conv_adj, &
3533  "Convectively mix the first ML_PRESORT_NK_CONV_ADJ "//&
3534  "layers before sorting when ML_RESORT is true.", &
3535  units="nondim", default=0, fail_if_missing=.true.) ! Fail added by AJA.
3536  ! This gives a minimum decay scale that is typically much less than Angstrom.
3537  ustar_min_dflt = 2e-4*us%s_to_T*cs%omega*(gv%Angstrom_m + gv%H_to_m*gv%H_subroundoff)
3538  call get_param(param_file, mdl, "BML_USTAR_MIN", cs%ustar_min, &
3539  "The minimum value of ustar that should be used by the "//&
3540  "bulk mixed layer model in setting vertical TKE decay "//&
3541  "scales. This must be greater than 0.", units="m s-1", &
3542  default=ustar_min_dflt, scale=us%m_to_Z*us%T_to_s)
3543  if (cs%ustar_min<=0.0) call mom_error(fatal, "BML_USTAR_MIN must be positive.")
3544 
3545  call get_param(param_file, mdl, "RESOLVE_EKMAN", cs%Resolve_Ekman, &
3546  "If true, the NKML>1 layers in the mixed layer are "//&
3547  "chosen to optimally represent the impact of the Ekman "//&
3548  "transport on the mixed layer TKE budget. Otherwise, "//&
3549  "the sublayers are distributed uniformly through the "//&
3550  "mixed layer.", default=.false.)
3551  call get_param(param_file, mdl, "CORRECT_ABSORPTION_DEPTH", cs%correct_absorption, &
3552  "If true, the average depth at which penetrating shortwave "//&
3553  "radiation is absorbed is adjusted to match the average "//&
3554  "heating depth of an exponential profile by moving some "//&
3555  "of the heating upward in the water column.", default=.false.)
3556  call get_param(param_file, mdl, "DO_RIVERMIX", cs%do_rivermix, &
3557  "If true, apply additional mixing wherever there is "//&
3558  "runoff, so that it is mixed down to RIVERMIX_DEPTH, "//&
3559  "if the ocean is that deep.", default=.false.)
3560  if (cs%do_rivermix) &
3561  call get_param(param_file, mdl, "RIVERMIX_DEPTH", cs%rivermix_depth, &
3562  "The depth to which rivers are mixed if DO_RIVERMIX is "//&
3563  "defined.", units="m", default=0.0, scale=us%m_to_Z)
3564  call get_param(param_file, mdl, "USE_RIVER_HEAT_CONTENT", cs%use_river_heat_content, &
3565  "If true, use the fluxes%runoff_Hflx field to set the "//&
3566  "heat carried by runoff, instead of using SST*CP*liq_runoff.", &
3567  default=.false.)
3568  call get_param(param_file, mdl, "USE_CALVING_HEAT_CONTENT", cs%use_calving_heat_content, &
3569  "If true, use the fluxes%calving_Hflx field to set the "//&
3570  "heat carried by runoff, instead of using SST*CP*froz_runoff.", &
3571  default=.false.)
3572 
3573  call get_param(param_file, mdl, "ALLOW_CLOCKS_IN_OMP_LOOPS", &
3574  cs%allow_clocks_in_omp_loops, &
3575  "If true, clocks can be called from inside loops that can "//&
3576  "be threaded. To run with multiple threads, set to False.", &
3577  default=.true.)
3578 
3579  cs%id_ML_depth = register_diag_field('ocean_model', 'h_ML', diag%axesT1, &
3580  time, 'Surface mixed layer depth', 'm')
3581  cs%id_TKE_wind = register_diag_field('ocean_model', 'TKE_wind', diag%axesT1, &
3582  time, 'Wind-stirring source of mixed layer TKE', 'm3 s-3', conversion=us%Z_to_m*us%T_to_s**3)
3583  cs%id_TKE_RiBulk = register_diag_field('ocean_model', 'TKE_RiBulk', diag%axesT1, &
3584  time, 'Mean kinetic energy source of mixed layer TKE', 'm3 s-3', conversion=us%Z_to_m*us%T_to_s**3)
3585  cs%id_TKE_conv = register_diag_field('ocean_model', 'TKE_conv', diag%axesT1, &
3586  time, 'Convective source of mixed layer TKE', 'm3 s-3', conversion=us%Z_to_m*us%T_to_s**3)
3587  cs%id_TKE_pen_SW = register_diag_field('ocean_model', 'TKE_pen_SW', diag%axesT1, &
3588  time, 'TKE consumed by mixing penetrative shortwave radation through the mixed layer', &
3589  'm3 s-3', conversion=us%Z_to_m)
3590  cs%id_TKE_mixing = register_diag_field('ocean_model', 'TKE_mixing', diag%axesT1, &
3591  time, 'TKE consumed by mixing that deepens the mixed layer', 'm3 s-3', conversion=us%Z_to_m*us%T_to_s**3)
3592  cs%id_TKE_mech_decay = register_diag_field('ocean_model', 'TKE_mech_decay', diag%axesT1, &
3593  time, 'Mechanical energy decay sink of mixed layer TKE', 'm3 s-3', conversion=us%Z_to_m*us%T_to_s**3)
3594  cs%id_TKE_conv_decay = register_diag_field('ocean_model', 'TKE_conv_decay', diag%axesT1, &
3595  time, 'Convective energy decay sink of mixed layer TKE', 'm3 s-3', conversion=us%Z_to_m*us%T_to_s**3)
3596  cs%id_TKE_conv_s2 = register_diag_field('ocean_model', 'TKE_conv_s2', diag%axesT1, &
3597  time, 'Spurious source of mixed layer TKE from sigma2', 'm3 s-3', conversion=us%Z_to_m*us%T_to_s**3)
3598  cs%id_PE_detrain = register_diag_field('ocean_model', 'PE_detrain', diag%axesT1, &
3599  time, 'Spurious source of potential energy from mixed layer detrainment', &
3600  'W m-2', conversion=us%Z_to_m*us%T_to_s**3)
3601  cs%id_PE_detrain2 = register_diag_field('ocean_model', 'PE_detrain2', diag%axesT1, &
3602  time, 'Spurious source of potential energy from mixed layer only detrainment', &
3603  'W m-2', conversion=us%Z_to_m*us%T_to_s**3)
3604  cs%id_h_mismatch = register_diag_field('ocean_model', 'h_miss_ML', diag%axesT1, &
3605  time, 'Summed absolute mismatch in entrainment terms', 'm', conversion=us%Z_to_m)
3606  cs%id_Hsfc_used = register_diag_field('ocean_model', 'Hs_used', diag%axesT1, &
3607  time, 'Surface region thickness that is used', 'm', conversion=us%Z_to_m)
3608  cs%id_Hsfc_max = register_diag_field('ocean_model', 'Hs_max', diag%axesT1, &
3609  time, 'Maximum surface region thickness', 'm', conversion=us%Z_to_m)
3610  cs%id_Hsfc_min = register_diag_field('ocean_model', 'Hs_min', diag%axesT1, &
3611  time, 'Minimum surface region thickness', 'm', conversion=us%Z_to_m)
3612  !CS%lim_det_dH_sfc = 0.5 ; CS%lim_det_dH_bathy = 0.2 ! Technically these should not get used if limit_det is false?
3613  if (cs%limit_det .or. (cs%id_Hsfc_min > 0)) then
3614  call get_param(param_file, mdl, "LIMIT_BUFFER_DET_DH_SFC", cs%lim_det_dH_sfc, &
3615  "The fractional limit in the change between grid points "//&
3616  "of the surface region (mixed & buffer layer) thickness.", &
3617  units="nondim", default=0.5)
3618  call get_param(param_file, mdl, "LIMIT_BUFFER_DET_DH_BATHY", cs%lim_det_dH_bathy, &
3619  "The fraction of the total depth by which the thickness "//&
3620  "of the surface region (mixed & buffer layer) is allowed "//&
3621  "to change between grid points.", units="nondim", default=0.2)
3622  endif
3623 
3624  call get_param(param_file, mdl, "ENABLE_THERMODYNAMICS", use_temperature, &
3625  "If true, temperature and salinity are used as state "//&
3626  "variables.", default=.true.)
3627  cs%nsw = 0
3628  if (use_temperature) then
3629  call get_param(param_file, mdl, "PEN_SW_NBANDS", cs%nsw, default=1)
3630  endif
3631 
3632 
3633  if (max(cs%id_TKE_wind, cs%id_TKE_RiBulk, cs%id_TKE_conv, cs%id_TKE_mixing, &
3634  cs%id_TKE_pen_SW, cs%id_TKE_mech_decay, cs%id_TKE_conv_decay) > 0) then
3635  call safe_alloc_alloc(cs%diag_TKE_wind, isd, ied, jsd, jed)
3636  call safe_alloc_alloc(cs%diag_TKE_RiBulk, isd, ied, jsd, jed)
3637  call safe_alloc_alloc(cs%diag_TKE_conv, isd, ied, jsd, jed)
3638  call safe_alloc_alloc(cs%diag_TKE_pen_SW, isd, ied, jsd, jed)
3639  call safe_alloc_alloc(cs%diag_TKE_mixing, isd, ied, jsd, jed)
3640  call safe_alloc_alloc(cs%diag_TKE_mech_decay, isd, ied, jsd, jed)
3641  call safe_alloc_alloc(cs%diag_TKE_conv_decay, isd, ied, jsd, jed)
3642  call safe_alloc_alloc(cs%diag_TKE_conv_s2, isd, ied, jsd, jed)
3643 
3644  cs%TKE_diagnostics = .true.
3645  endif
3646  if (cs%id_PE_detrain > 0) call safe_alloc_alloc(cs%diag_PE_detrain, isd, ied, jsd, jed)
3647  if (cs%id_PE_detrain2 > 0) call safe_alloc_alloc(cs%diag_PE_detrain2, isd, ied, jsd, jed)
3648  if (cs%id_ML_depth > 0) call safe_alloc_alloc(cs%ML_depth, isd, ied, jsd, jed)
3649 
3650  if (cs%allow_clocks_in_omp_loops) then
3651  id_clock_detrain = cpu_clock_id('(Ocean mixed layer detrain)', grain=clock_routine)
3652  id_clock_mech = cpu_clock_id('(Ocean mixed layer mechanical entrainment)', grain=clock_routine)
3653  id_clock_conv = cpu_clock_id('(Ocean mixed layer convection)', grain=clock_routine)
3654  if (cs%ML_resort) then
3655  id_clock_resort = cpu_clock_id('(Ocean mixed layer resorting)', grain=clock_routine)
3656  else
3657  id_clock_adjustment = cpu_clock_id('(Ocean mixed layer convective adjustment)', grain=clock_routine)
3658  endif
3659  id_clock_eos = cpu_clock_id('(Ocean mixed layer EOS)', grain=clock_routine)
3660  endif
3661 
3662  if (cs%limit_det .or. (cs%id_Hsfc_min > 0)) &
3663  id_clock_pass = cpu_clock_id('(Ocean mixed layer halo updates)', grain=clock_routine)
3664 
3665 
3666 ! if (CS%limit_det) then
3667 ! endif
3668 
3669 end subroutine bulkmixedlayer_init
3670 
3671 !> This subroutine returns an approximation to the integral
3672 !! R = exp(-L*(H+E)) integral(LH to L(H+E)) L/(1-(1+x)exp(-x)) dx.
3673 !! The approximation to the integrand is good to within -2% at x~.3
3674 !! and +25% at x~3.5, but the exponential deemphasizes the importance of
3675 !! large x. When L=0, EF4 returns E/((Ht+E)*Ht).
3676 function ef4(Ht, En, I_L, dR_de)
3677  real, intent(in) :: ht !< Total thickness [H ~> m or kg m-2].
3678  real, intent(in) :: en !< Entrainment [H ~> m or kg m-2].
3679  real, intent(in) :: i_l !< The e-folding scale [H-1 ~> m-1 or m2 kg-1]
3680  real, optional, intent(inout) :: dr_de !< The partial derivative of the result R with E [H-2 ~> m-2 or m4 kg-2].
3681  real :: ef4 !< The integral [H-1 ~> m-1 or m2 kg-1].
3682 
3683  ! Local variables
3684  real :: exp_lhpe ! A nondimensional exponential decay.
3685  real :: i_hpe ! An inverse thickness plus entrainment [H-1 ~> m-1 or m2 kg-1].
3686  real :: res ! The result of the integral above [H-1 ~> m-1 or m2 kg-1].
3687 
3688  exp_lhpe = exp(-i_l*(en+ht))
3689  i_hpe = 1.0/(ht+en)
3690  res = exp_lhpe * (en*i_hpe/ht - 0.5*i_l*log(ht*i_hpe) + 0.5*i_l*i_l*en)
3691  if (PRESENT(dr_de)) &
3692  dr_de = -i_l*res + exp_lhpe*(i_hpe*i_hpe + 0.5*i_l*i_hpe + 0.5*i_l*i_l)
3693  ef4 = res
3694 
3695 end function ef4
3696 
3697 !> \namespace mom_bulk_mixed_layer
3698 !!
3699 !! By Robert Hallberg, 1997 - 2005.
3700 !!
3701 !! This file contains the subroutine (bulkmixedlayer) that
3702 !! implements a Kraus-Turner-like bulk mixed layer, based on the work
3703 !! of various people, as described in the review paper by Niiler and
3704 !! Kraus (1979), with particular attention to the form proposed by
3705 !! Oberhuber (JPO, 1993, 808-829), with an extension to a refied bulk
3706 !! mixed layer as described in Hallberg (Aha Huliko'a, 2003). The
3707 !! physical processes portrayed in this subroutine include convective
3708 !! adjustment and mixed layer entrainment and detrainment.
3709 !! Penetrating shortwave radiation and an exponential decay of TKE
3710 !! fluxes are also supported by this subroutine. Several constants
3711 !! can alternately be set to give a traditional Kraus-Turner mixed
3712 !! layer scheme, although that is not the preferred option. The
3713 !! physical processes and arguments are described in detail below.
3714 
3715 end module mom_bulk_mixed_layer
mom_verticalgrid
Provides a transparent vertical ocean grid type and supporting routines.
Definition: MOM_verticalGrid.F90:2
mom_file_parser::log_version
An overloaded interface to log version information about modules.
Definition: MOM_file_parser.F90:109
mom_diag_mediator
The subroutines here provide convenient wrappers to the fms diag_manager interfaces with additional d...
Definition: MOM_diag_mediator.F90:3
mom_variables::thermo_var_ptrs
Pointers to an assortment of thermodynamic fields that may be available, including potential temperat...
Definition: MOM_variables.F90:82
mom_eos
Provides subroutines for quantities specific to the equation of state.
Definition: MOM_EOS.F90:2
mom_bulk_mixed_layer
Build mixed layer parameterization.
Definition: MOM_bulk_mixed_layer.F90:2
mom_file_parser::param_file_type
A structure that can be parsed to read and document run-time parameters.
Definition: MOM_file_parser.F90:54
mom_file_parser::get_param
An overloaded interface to read and log the values of various types of parameters.
Definition: MOM_file_parser.F90:102
mom_unit_scaling::unit_scale_type
Describes various unit conversion factors.
Definition: MOM_unit_scaling.F90:14
mom_diag_mediator::post_data
Make a diagnostic available for averaging or output.
Definition: MOM_diag_mediator.F90:70
mom_forcing_type
This module implements boundary forcing for MOM6.
Definition: MOM_forcing_type.F90:2
mom_verticalgrid::verticalgrid_type
Describes the vertical ocean grid, including unit conversion factors.
Definition: MOM_verticalGrid.F90:24
mom_domains
Describes the decomposed MOM domain and has routines for communications across PEs.
Definition: MOM_domains.F90:2
mom_variables
Provides transparent structures with groups of MOM6 variables and supporting routines.
Definition: MOM_variables.F90:2
mom_bulk_mixed_layer::bulkmixedlayer_cs
The control structure with parameters for the MOM_bulk_mixed_layer module.
Definition: MOM_bulk_mixed_layer.F90:32
mom_cpu_clock
Wraps the MPP cpu clock functions.
Definition: MOM_cpu_clock.F90:2
mom_file_parser
The MOM6 facility to parse input files for runtime parameters.
Definition: MOM_file_parser.F90:2
mom_eos::calculate_density_derivs
Calculate the derivatives of density with temperature and salinity from T, S, and P.
Definition: MOM_EOS.F90:70
mom_opacity::optics_type
This type is used to store information about ocean optical properties.
Definition: MOM_opacity.F90:25
mom_grid
Provides the ocean grid type.
Definition: MOM_grid.F90:2
mom_unit_scaling
Provides a transparent unit rescaling type to facilitate dimensional consistency testing.
Definition: MOM_unit_scaling.F90:2
mom_forcing_type::forcing
Structure that contains pointers to the boundary forcing used to drive the liquid ocean simulated by ...
Definition: MOM_forcing_type.F90:49
mom_file_parser::log_param
An overloaded interface to log the values of various types of parameters.
Definition: MOM_file_parser.F90:96
mom_domains::create_group_pass
Set up a group of halo updates.
Definition: MOM_domains.F90:79
mom_opacity
Routines used to calculate the opacity of the ocean.
Definition: MOM_opacity.F90:2
mom_error_handler
Routines for error handling and I/O management.
Definition: MOM_error_handler.F90:2
mom_grid::ocean_grid_type
Ocean grid type. See mom_grid for details.
Definition: MOM_grid.F90:25
mom_diag_mediator::diag_ctrl
The following data type a list of diagnostic fields an their variants, as well as variables that cont...
Definition: MOM_diag_mediator.F90:239
mom_eos::calculate_density
Calculates density of sea water from T, S and P.
Definition: MOM_EOS.F90:60