source: trunk/LMDZ.GENERIC/libf/phystd/physiq_mod.F90 @ 3730

Last change on this file since 3730 was 3725, checked in by emillour, 3 months ago

Generic PCM:
Change the way the rate of outputs for diagfi.nc files is specified:
IMPORTANT: Specifying "ecritphy" no longer possible and will trigger an error.
Use "diagfi_output_rate" to specify output rate (in physics steps) instead.
This should makes things (hopefully) clearer for users and also better
enforces a cleaner and clearer separation between dynamics and physics.
EM

  • Property svn:executable set to *
File size: 124.5 KB
Line 
1      module physiq_mod
2
3      implicit none
4
5      contains
6
7      subroutine physiq(ngrid,nlayer,nq,   &
8                  firstcall,lastcall,      &
9                  pday,ptime,ptimestep,    &
10                  pplev,pplay,pphi,        &
11                  pu,pv,pt,pq,             &
12                  flxw,                    &
13                  pdu,pdv,pdt,pdq,pdpsrf)
14
15!!
16      use write_field_phy, only: Writefield_phy
17!!
18      use ioipsl_getin_p_mod, only: getin_p
19      use radinc_h, only : L_NSPECTI,L_NSPECTV,naerkind, corrkdir, banddir
20      use watercommon_h, only : RLVTT, Psat_water,epsi,su_watercycle, RW, T_h2o_ice_liq
21      use generic_cloud_common_h, only : epsi_generic, Psat_generic
22      use thermcell_mod, only: init_thermcell_mod
23      use gases_h, only: gnom, gfrac, ngasmx
24      use radcommon_h, only: sigma, glat, grav, BWNV, WNOI, DWNI, DWNV, WNOV
25      use suaer_corrk_mod, only: suaer_corrk
26      use radii_mod, only: h2o_reffrad, co2_reffrad
27      use aerosol_mod, only: iniaerosol, iaero_co2, iaero_h2o
28      use surfdat_h, only: phisfi, zmea, zstd, zsig, zgam, zthe, &
29                           dryness
30      use comdiurn_h, only: coslat, sinlat, coslon, sinlon
31      use comsaison_h, only: mu0, fract, dist_star, declin, right_ascen
32      use comsoil_h, only: nsoilmx, layer, mlayer, inertiedat
33      use geometry_mod, only: latitude, longitude, cell_area
34      USE comgeomfi_h, only: totarea, totarea_planet
35      USE tracer_h, only: noms, mmol, radius, rho_q, qext, &
36                          alpha_lift, alpha_devil, qextrhor, &
37                          igcm_h2o_ice, igcm_h2o_vap, igcm_dustbin, &
38                          igcm_co2_ice, nesp, is_chim, is_condensable,constants_epsi_generic
39      use time_phylmdz_mod, only: diagfi_output_rate, nday
40      use phyetat0_mod, only: phyetat0,tab_cntrl_mod
41      use surfini_mod, only: surfini
42      use wstats_mod, only: callstats, wstats, mkstats
43      use phyredem, only: physdem0, physdem1
44!!      use slab_ice_h, only: capcalocean, capcalseaice,capcalsno, &
45!!                            noceanmx
46!!      use ocean_slab_mod, only :ocean_slab_init, ocean_slab_ice, &
47!!                                capcalocean, capcalseaice,capcalsno, nslay, &
48!!                                ocean_slab_final
49!!      use surf_heat_transp_mod,only :init_masquv
50      use ocean_slab_mod, only :ocean_slab_init, ocean_slab_noice, ocean_slab_ice, &
51                                ocean_slab_frac, ocean_slab_get_vars, &
52                                capcalocean, capcalseaice,capcalsno, nslay, knon, &
53                                ocean_slab_final
54      use planetwide_mod, only: planetwide_minval,planetwide_maxval,planetwide_sumval
55      use mod_phys_lmdz_para, only : is_master
56      use planete_mod, only: apoastr, periastr, year_day, peri_day, &
57                            obliquit, nres, z0
58      use comcstfi_mod, only: pi, g, rcp, r, rad, mugaz, cpp
59      use time_phylmdz_mod, only: daysec
60      use callkeys_mod, only: albedo_spectral_mode, calladj, calldifv, &
61                              calllott_nonoro, callrad, callsoil, nosurf, &
62                              calltherm, CLFvarying, co2cond, corrk, diagdtau, &
63                              diurnal, enertest, fat1au, flatten, j2, &
64                              hydrology, intheat, iradia, kastprof, &
65                              lwrite, mass_redistrib, massplanet, meanOLR, &
66                              nearco2cond, newtonian, noseason_day, oblate, &
67                              ok_slab_ocean, photochem, rings_shadow, rmean, &
68                              season, sedimentation,generic_condensation, &
69                              specOLR, callthermos, callvolcano, &
70                              startphy_file, testradtimes, tlocked, &
71                              tracer, UseTurbDiff, water, watercond, &
72                              waterrain, generic_rain, global1d, szangle, &
73                              moistadjustment, moistadjustment_generic, varspec, varspec_data, nvarlayer
74      use generic_tracer_index_mod, only: generic_tracer_index
75      use nonoro_gwd_ran_mod, only: nonoro_gwd_ran
76      use check_fields_mod, only: check_physics_fields
77      use conc_mod, only: rnew, cpnew, ini_conc_mod
78      use phys_state_var_mod
79      use callcorrk_mod, only: callcorrk
80      use conduction_mod, only: conduction
81      use volcano_mod, only: volcano
82      use pindex_mod, only: pindex
83      use convadj_mod, only: convadj
84      use vdifc_mod, only: vdifc
85      use turbdiff_mod, only: turbdiff
86      use turb_mod, only : q2,sensibFlux,turb_resolved
87      use callsedim_mod, only: callsedim
88      use mass_redistribution_mod, only: mass_redistribution
89      use condensation_generic_mod, only: condensation_generic
90      use datafile_mod, only: datadir
91      use newton_cooling_hotJ, only: newtcool_MOCHA ! LT, adding for MOCHA protocol
92
93#ifndef MESOSCALE
94      USE vertical_layers_mod, ONLY: ap,bp,aps,bps,presnivs,pseudoalt
95      use mod_phys_lmdz_omp_data, ONLY: is_omp_master
96#else
97      use comm_wrf, only : comm_HR_SW, comm_HR_LW,  &
98         comm_CLOUDFRAC,comm_TOTCLOUDFRAC, comm_RH, &
99         comm_SURFRAIN,comm_REEVAP,comm_HR_DYN,     &
100         comm_DQICE,comm_DQVAP,comm_ALBEQ,   &
101         comm_FLUXTOP_DN,comm_FLUXABS_SW,           &
102         comm_FLUXTOP_LW,comm_FLUXSURF_SW,          &
103         comm_FLUXSURF_LW,comm_FLXGRD,              &
104         comm_DTRAIN,comm_DTLSC,comm_H2OICE_REFF,   &
105         comm_LATENT_HF
106
107#endif
108
109#ifdef CPP_XIOS
110      use xios_output_mod, only: initialize_xios_output, &
111                                 update_xios_timestep, &
112                                 send_xios_field
113      use wxios, only: wxios_context_init, xios_context_finalize
114#endif
115      use write_output_mod, only: write_output
116
117      implicit none
118
119
120!==================================================================
121!
122!     Purpose
123!     -------
124!     Central subroutine for all the physics parameterisations in the
125!     universal model. Originally adapted from the Mars LMDZ model.
126!
127!     The model can be run without or with tracer transport
128!     depending on the value of "tracer" in file "callphys.def".
129!
130!
131!   It includes:
132!
133!      I. Initialization :
134!         I.1 Firstcall initializations.
135!         I.2 Initialization for every call to physiq.
136!
137!      II. Compute radiative transfer tendencies (longwave and shortwave) :
138!         II.a Option 1 : Call correlated-k radiative transfer scheme.
139!         II.b Option 2 : Call Newtonian cooling scheme.
140!         II.c Option 3 : Atmosphere has no radiative effect.
141!
142!      III. Vertical diffusion (turbulent mixing) :
143!
144!      IV. Convection :
145!         IV.a Thermal plume model
146!         IV.b Dry convective adjusment
147!
148!      V. Condensation and sublimation of gases (currently just CO2).
149!
150!      VI. Tracers
151!         VI.1. Water and water ice.
152!         VI.2  Photochemistry
153!         VI.3. Aerosols and particles.
154!         VI.4. Updates (pressure variations, surface budget).
155!         VI.5. Slab Ocean.
156!         VI.6. Surface Tracer Update.
157!
158!      VII. Surface and sub-surface soil temperature.
159!
160!      VIII. Perform diagnostics and write output files.
161!
162!
163!   arguments
164!   ---------
165!
166!   INPUT
167!   -----
168!
169!    ngrid                 Size of the horizontal grid.
170!    nlayer                Number of vertical layers.
171!    nq                    Number of advected fields.
172!
173!    firstcall             True at the first call.
174!    lastcall              True at the last call.
175!
176!    pday                  Number of days counted from the North. Spring equinoxe.
177!    ptime                 Universal time (0<ptime<1): ptime=0.5 at 12:00 UT.
178!    ptimestep             timestep (s).
179!
180!    pplay(ngrid,nlayer)   Pressure at the middle of the layers (Pa).
181!    pplev(ngrid,nlayer+1) Intermediate pressure levels (Pa).
182!    pphi(ngrid,nlayer)    Geopotential at the middle of the layers (m2.s-2).
183!
184!    pu(ngrid,nlayer)      u, zonal component of the wind (ms-1).
185!    pv(ngrid,nlayer)      v, meridional component of the wind (ms-1).
186!
187!    pt(ngrid,nlayer)      Temperature (K).
188!
189!    pq(ngrid,nlayer,nq)   Advected fields.
190!
191!    pudyn(ngrid,nlayer)    \
192!    pvdyn(ngrid,nlayer)     \ Dynamical temporal derivative for the
193!    ptdyn(ngrid,nlayer)     / corresponding variables.
194!    pqdyn(ngrid,nlayer,nq) /
195!    flxw(ngrid,nlayer)      vertical mass flux (kg/s) at layer lower boundary
196!
197!   OUTPUT
198!   ------
199!
200!    pdu(ngrid,nlayer)        \
201!    pdv(ngrid,nlayer)         \  Temporal derivative of the corresponding
202!    pdt(ngrid,nlayer)         /  variables due to physical processes.
203!    pdq(ngrid,nlayer)        /
204!    pdpsrf(ngrid)             /
205!
206!
207!     Authors
208!     -------
209!           Frederic Hourdin        15/10/93
210!           Francois Forget        1994
211!           Christophe Hourdin        02/1997
212!           Subroutine completely rewritten by F. Forget (01/2000)
213!           Water ice clouds: Franck Montmessin (update 06/2003)
214!           Radiatively active tracers: J.-B. Madeleine (10/2008-06/2009)
215!           New correlated-k radiative scheme: R. Wordsworth (2009)
216!           Many specifically Martian subroutines removed: R. Wordsworth (2009)
217!           Improved water cycle: R. Wordsworth / B. Charnay (2010)
218!           To F90: R. Wordsworth (2010)
219!           New turbulent diffusion scheme: J. Leconte (2012)
220!           Loops converted to F90 matrix format: J. Leconte (2012)
221!           No more ngridmx/nqmx, F90 commons and adaptation to parallel: A. Spiga (2012)
222!           Purge of the code : M. Turbet (2015)
223!           Photochemical core developped by F. Lefevre: B. Charnay (2017)
224!==================================================================
225
226
227!    0.  Declarations :
228!    ------------------
229
230include "netcdf.inc"
231
232! Arguments :
233! -----------
234
235!   INPUTS:
236!   -------
237
238      integer,intent(in) :: ngrid             ! Number of atmospheric columns.
239      integer,intent(in) :: nlayer            ! Number of atmospheric layers.
240      integer,intent(in) :: nq                ! Number of tracers.
241
242      logical,intent(in) :: firstcall ! Signals first call to physics.
243      logical,intent(in) :: lastcall  ! Signals last call to physics.
244
245      real,intent(in) :: pday                  ! Number of elapsed sols since reference Ls=0.
246      real,intent(in) :: ptime                 ! "Universal time", given as fraction of sol (e.g.: 0.5 for noon).
247      real,intent(in) :: ptimestep             ! Physics timestep (s).
248      real,intent(in) :: pplev(ngrid,nlayer+1) ! Inter-layer pressure (Pa).
249      real,intent(in) :: pplay(ngrid,nlayer)   ! Mid-layer pressure (Pa).
250      real,intent(in) :: pphi(ngrid,nlayer)    ! Geopotential at mid-layer (m2s-2).
251      real,intent(in) :: pu(ngrid,nlayer)      ! Zonal wind component (m/s).
252      real,intent(in) :: pv(ngrid,nlayer)      ! Meridional wind component (m/s).
253      real,intent(in) :: pt(ngrid,nlayer)      ! Temperature (K).
254      real,intent(in) :: pq(ngrid,nlayer,nq)   ! Tracers (kg/kg_of_air).
255      real,intent(in) :: flxw(ngrid,nlayer)    ! Vertical mass flux (ks/s) at lower boundary of layer
256
257!   OUTPUTS:
258!   --------
259
260!     Physical tendencies :
261
262      real,intent(out) :: pdu(ngrid,nlayer)    ! Zonal wind tendencies (m/s/s).
263      real,intent(out) :: pdv(ngrid,nlayer)    ! Meridional wind tendencies (m/s/s).
264      real,intent(out) :: pdt(ngrid,nlayer)    ! Temperature tendencies (K/s).
265      real,intent(out) :: pdq(ngrid,nlayer,nq) ! Tracer tendencies (kg/kg_of_air/s).
266      real,intent(out) :: pdpsrf(ngrid)        ! Surface pressure tendency (Pa/s).
267
268! Local saved variables:
269! ----------------------
270      integer,save :: day_ini                                      ! Initial date of the run (sol since Ls=0).
271      integer,save :: icount                                       ! Counter of calls to physiq during the run.
272!$OMP THREADPRIVATE(day_ini,icount)
273
274! Local variables :
275! -----------------
276
277!     Aerosol (dust or ice) extinction optical depth  at reference wavelength
278!     for the "naerkind" optically active aerosols:
279
280      real,save,allocatable :: aerosol(:,:,:) ! Aerosols
281!$OMP THREADPRIVATE(aerosol)
282      real zh(ngrid,nlayer)               ! Potential temperature (K).
283      real pw(ngrid,nlayer)               ! Vertical velocity (m/s). (NOTE : >0 WHEN DOWNWARDS !!)
284      real omega(ngrid,nlayer)            ! omega velocity (Pa/s, >0 when downward)
285
286      integer l,ig,ierr,iq,nw,isoil,iesp, igcm_generic_vap, igcm_generic_ice
287      logical call_ice_vap_generic ! to call only one time the ice/vap pair of a tracer
288
289      real zls                       ! Solar longitude (radians).
290      real zlss                      ! Sub solar point longitude (radians).
291      real zday                      ! Date (time since Ls=0, calculated in sols).
292      real zzlay(ngrid,nlayer)       ! Altitude at the middle of the atmospheric layers.
293      real zzlev(ngrid,nlayer+1)     ! Altitude at the atmospheric layer boundaries.
294
295! VARIABLES for the thermal plume model
296
297      real f(ngrid)                       ! Mass flux norm
298      real fm(ngrid,nlayer+1)             ! Mass flux
299      real fm_bis(ngrid,nlayer)           ! Recasted fm
300      real entr(ngrid,nlayer)             ! Entrainment
301      real detr(ngrid,nlayer)             ! Detrainment
302      real dqevap(ngrid,nlayer,nq)        ! water tracer mass mixing ratio variations due to evaporation
303      real dtevap(ngrid,nlayer)           ! temperature variation due to evaporation
304      real zqtherm(ngrid,nlayer,nq)       ! vapor mass mixing ratio after evaporation
305      real zttherm(ngrid,nlayer)          ! temperature after evaporation
306      real fraca(ngrid,nlayer+1)          ! Fraction of the surface that plumes occupies
307      real zw2(ngrid,nlayer+1)            ! Vertical speed
308      real zw2_bis(ngrid,nlayer)          ! Recasted zw2
309
310! TENDENCIES due to various processes :
311
312      ! For Surface Temperature : (K/s)
313      real zdtsurf(ngrid)     ! Cumulated tendencies.
314      real zdtsurfmr(ngrid)   ! Mass_redistribution routine.
315      real zdtsurfc(ngrid)    ! Condense_co2 routine.
316      real zdtsdif(ngrid)     ! Turbdiff/vdifc routines.
317      real zdtsurf_hyd(ngrid) ! Hydrol routine.
318
319      ! For Thermosphere : (K/s)
320      real zdtconduc(ngrid,nlayer)
321
322      ! For Atmospheric Temperatures : (K/s)
323      real dtlscale(ngrid,nlayer)                             ! Largescale routine.
324      real dt_generic_condensation(ngrid,nlayer)              ! condensation_generic routine.
325      real zdtc(ngrid,nlayer)                                 ! Condense_co2 routine.
326      real zdtdif(ngrid,nlayer)                               ! Turbdiff/vdifc routines.
327      real zdttherm(ngrid,nlayer)                             ! Calltherm routine.
328      real zdtmr(ngrid,nlayer)                                ! Mass_redistribution routine.
329      real zdtrain(ngrid,nlayer)                              ! Rain routine.
330      real zdtrain_generic(ngrid,nlayer)                      ! Rain_generic routine.
331      real dtmoist(ngrid,nlayer)                              ! Moistadj routine.
332      real dt_ekman(ngrid,nslay), dt_hdiff(ngrid,nslay), dt_gm(ngrid,nslay) ! Slab_ocean routine.
333      real zdtsw1(ngrid,nlayer), zdtlw1(ngrid,nlayer)         ! Callcorrk routine.
334      real zdtchim(ngrid,nlayer)                              ! Calchim routine.
335
336      ! For Surface Tracers : (kg/m2/s)
337      real dqsurf(ngrid,nq)                 ! Cumulated tendencies.
338      real zdqsurfc(ngrid)                  ! Condense_co2 routine.
339      real zdqsdif(ngrid,nq)                ! Turbdiff/vdifc routines.
340      real zdqssed(ngrid,nq)                ! Callsedim routine.
341      real zdqsurfmr(ngrid,nq)              ! Mass_redistribution routine.
342      real zdqsrain(ngrid), zdqssnow(ngrid) ! Rain routine.
343      real zdqsrain_generic(ngrid,nq), zdqssnow_generic(ngrid,nq) ! Rain_generic routine.
344      real dqs_hyd(ngrid,nq)                ! Hydrol routine.
345      real reevap_precip(ngrid)             ! re-evaporation flux of precipitation (integrated over the atmospheric column)
346      real reevap_precip_generic(ngrid,nq)
347
348      ! For Tracers : (kg/kg_of_air/s)
349      real zdqc(ngrid,nlayer,nq)      ! Condense_co2 routine.
350      real zdqadj(ngrid,nlayer,nq)    ! Convadj routine.
351      real zdqdif(ngrid,nlayer,nq)    ! Turbdiff/vdifc routines.
352      real zdqevap(ngrid,nlayer)      ! Turbdiff routine.
353      real zdqtherm(ngrid,nlayer,nq)  ! Calltherm routine.
354      real zdqsed(ngrid,nlayer,nq)    ! Callsedim routine.
355      real zdqmr(ngrid,nlayer,nq)     ! Mass_redistribution routine.
356      real zdqrain(ngrid,nlayer,nq)   ! Rain routine.
357      real dqmoist(ngrid,nlayer,nq)   ! Moistadj routine.
358      real dqvaplscale(ngrid,nlayer)  ! Largescale routine.
359      real dqcldlscale(ngrid,nlayer)  ! Largescale routine.
360      real dqvaplscale_generic(ngrid,nlayer,nq) ! condensation_generic routine.
361      real dqcldlscale_generic(ngrid,nlayer,nq) ! condensation_generic routine.
362      real dq_rain_generic_vap(ngrid,nlayer,nq) ! rain_generic routine
363      real dq_rain_generic_cld(ngrid,nlayer,nq) ! rain_generic routine
364      REAL,allocatable,save :: zdqchim(:,:,:) ! Calchim_asis routine
365      REAL,allocatable,save :: zdqschim(:,:)  ! Calchim_asis routine
366      REAL zdqradio(ngrid,nlayer,nq)   ! Radioactive decay
367!$OMP THREADPRIVATE(zdqchim,zdqschim)
368      real zdqvolc(ngrid,nlayer,nq) ! injection by volcanoes (kg/kg_of_air/s)
369
370      REAL array_zero1(ngrid)
371      REAL array_zero2(ngrid,nlayer)
372
373      ! For Winds : (m/s/s)
374      real zdvadj(ngrid,nlayer), zduadj(ngrid,nlayer)       ! Convadj routine.
375      real zdutherm(ngrid,nlayer), zdvtherm(ngrid,nlayer)   ! Calltherm routine.
376      real zdumr(ngrid,nlayer), zdvmr(ngrid,nlayer)         ! Mass_redistribution routine.
377      real zdvdif(ngrid,nlayer), zdudif(ngrid,nlayer)       ! Turbdiff/vdifc routines.
378      real zdhdif(ngrid,nlayer)                             ! Turbdiff/vdifc routines.
379      real zdhadj(ngrid,nlayer)                             ! Convadj routine.
380
381      ! For Pressure and Mass :
382      real zdmassmr(ngrid,nlayer) ! Atmospheric Mass tendency for mass_redistribution (kg_of_air/m2/s).
383      real zdmassmr_col(ngrid)    ! Atmospheric Column Mass tendency for mass_redistribution (kg_of_air/m2/s).
384      real zdpsrfmr(ngrid)        ! Pressure tendency for mass_redistribution routine (Pa/s).
385
386
387
388! Local variables for LOCAL CALCULATIONS:
389! ---------------------------------------
390      real zflubid(ngrid)
391      real zplanck(ngrid),zpopsk(ngrid,nlayer)
392      real ztim1,ztim2,ztim3, z1,z2
393      real ztime_fin
394      real zdh(ngrid,nlayer)
395      real gmplanet
396      real taux(ngrid),tauy(ngrid)
397
398
399! local variables for DIAGNOSTICS : (diagfi & stat)
400! -------------------------------------------------
401
402      real tice(ngrid)                                   ! Sea ice temperature
403
404      real ps(ngrid)                                     ! Surface Pressure.
405      real zt(ngrid,nlayer)                              ! Atmospheric Temperature.
406      real zu(ngrid,nlayer),zv(ngrid,nlayer)             ! Zonal and Meridional Winds.
407      real zq(ngrid,nlayer,nq)                           ! Atmospheric Tracers.
408      real zdtadj(ngrid,nlayer)                          ! Convadj Diagnostic.
409      real zdtdyn(ngrid,nlayer)                          ! Dynamical Heating (K/s).
410      real zdudyn(ngrid,nlayer)                          ! Dynamical Zonal Wind tendency (m.s-2).
411
412      real reff(ngrid,nlayer)                       ! Effective dust radius (used if doubleq=T).
413      real vmr(ngrid,nlayer)                        ! volume mixing ratio
414      real time_phys
415
416      real ISR,ASR,OLR,GND,DYN,GSR,Ts1,Ts2,Ts3,TsS ! for Diagnostic.
417
418      real qcol(ngrid,nq) ! Tracer Column Mass (kg/m2).
419
420!     included by RW for H2O Manabe scheme
421      real rneb_man(ngrid,nlayer) ! H2O cloud fraction (moistadj).
422      real rneb_lsc(ngrid,nlayer) ! H2O cloud fraction (large scale).
423
424
425!     to test energy conservation (RW+JL)
426      real mass(ngrid,nlayer),massarea(ngrid,nlayer)
427      real dEtot, dEtots, AtmToSurf_TurbFlux
428      real,save :: dEtotSW, dEtotsSW, dEtotLW, dEtotsLW
429!$OMP THREADPRIVATE(dEtotSW, dEtotsSW, dEtotLW, dEtotsLW)
430
431!JL12 conservation test for mean flow kinetic energy has been disabled temporarily
432
433      real dtmoist_max,dtmoist_min
434      real dItot, dItot_tmp, dVtot, dVtot_tmp
435
436
437      real h2otot                      ! Total Amount of water. For diagnostic.
438      real icesrf,liqsrf,icecol,vapcol ! Total Amounts of water (ice,liq,vap). For diagnostic.
439      real dWtot, dWtot_tmp, dWtots, dWtots_tmp
440      logical,save :: watertest
441!$OMP THREADPRIVATE(watertest)
442
443      real qsat(ngrid,nlayer) ! Water Vapor Volume Mixing Ratio at saturation (kg/kg_of_air).
444      real RH(ngrid,nlayer)   ! Relative humidity.
445      real psat_tmp
446
447      real qsat_generic(ngrid,nlayer,nq) ! generic condensable tracers (GCS) specific concentration at saturation (kg/kg_of_air).
448      real RH_generic(ngrid,nlayer,nq)   ! generic condensable tracers (GCS) Relative humidity.
449      real rneb_generic(ngrid,nlayer,nq) ! GCS cloud fraction (generic condensation).
450      real psat_tmp_generic
451      real, save :: metallicity ! metallicity of planet --- is not used here, but necessary to call function Psat_generic
452!$OMP THREADPRIVATE(metallicity)
453
454      real reffrad_generic_zeros_for_wrf(ngrid,nlayer) !  !!! this is temporary, it is only a list of zeros, it will be replaced when a generic aerosol will be implemented
455
456      logical clearsky ! For double radiative transfer call. By BC
457
458      ! For Clear Sky Case.
459      real fluxsurfabs_sw1(ngrid)  ! For SW/LW flux.
460      real tau_col1(ngrid)                                                   ! For aerosol optical depth diagnostic.
461      real OLR_nu1(ngrid,L_NSPECTI) ! Clear sky TOA LW radiation in each IR band
462      real OSR_nu1(ngrid,L_NSPECTV) ! Clear sky TOA SW radiation in each VI band
463      real GSR_nu1(ngrid,L_NSPECTV) ! Clear sky Surface SW radiation in each VI band
464      real int_dtaui1(ngrid,nlayer,L_NSPECTI),int_dtauv1(ngrid,nlayer,L_NSPECTV) ! For optical thickness diagnostics.
465      real tf, ntf
466
467      real net_fluxsurf_lw(ngrid) ! net longwave flux at the surface (for diagnostics only)
468
469      real nconsMAX, vdifcncons(ngrid), cadjncons(ngrid) ! Vdfic water conservation test. By RW
470
471      real muvar(ngrid,nlayer+1) ! For Runaway Greenhouse 1D study. By RW
472
473      ! For fixed variable molar mass
474      real, dimension(:),allocatable,save :: p_var
475      real, dimension(:),allocatable,save :: mu_var
476      real, dimension(:,:),allocatable,save :: frac_var
477!$OMP THREADPRIVATE(p_var,mu_var,frac_var)
478      real :: mu_vari(nlayer)
479      real :: muvari(ngrid,nlayer)
480      integer ios,k
481      character*100 dt_file
482
483      real,save,allocatable :: reffcol(:,:)
484!$OMP THREADPRIVATE(reffcol)
485
486!  Non-oro GW tendencies
487      REAL d_u_hin(ngrid,nlayer), d_v_hin(ngrid,nlayer)
488      REAL d_t_hin(ngrid,nlayer)
489!  Diagnostics 2D of gw_nonoro
490      REAL zustrhi(ngrid), zvstrhi(ngrid)
491
492
493      real :: tsurf2(ngrid)
494!!      real :: flux_o(ngrid),flux_g(ngrid)
495      real :: flux_g(ngrid)
496      real :: flux_sens_lat(ngrid)
497      real :: qsurfint(ngrid,nq)
498#ifdef MESOSCALE
499      REAL :: lsf_dt(nlayer)
500      REAL :: lsf_dq(nlayer)
501#endif
502
503      ! flags to trigger extra sanity checks
504      logical, save ::  check_physics_inputs=.false.
505      logical, save ::  check_physics_outputs=.false.
506!$OPM THREADPRIVATE(check_physics_inputs,check_physics_outputs)
507
508      ! Misc
509      character*2 :: str2
510      character(len=10) :: tmp1
511      character(len=10) :: tmp2
512!==================================================================================================
513
514! -----------------
515! I. INITIALISATION
516! -----------------
517
518! --------------------------------
519! I.1   First Call Initialisation.
520! --------------------------------
521      if (firstcall) then
522         call getin_p("check_physics_inputs", check_physics_inputs)
523         call getin_p("check_physics_outputs", check_physics_outputs)
524
525         ! Allocate saved arrays (except for 1D model, where this has already
526         ! been done)
527#ifndef MESOSCALE
528         if (ngrid>1) call phys_state_var_init(nq)
529#endif
530
531!        Variables set to 0
532!        ~~~~~~~~~~~~~~~~~~
533         dtrad(:,:) = 0.0
534         fluxrad(:) = 0.0
535         tau_col(:) = 0.0
536         zdtsw(:,:) = 0.0
537         zdtlw(:,:) = 0.0
538         zdtconduc(:,:) = 0.0
539
540!        Initialize fixed variable mu
541!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
542
543         if(varspec) then
544           IF (.NOT.ALLOCATED(p_var))  ALLOCATE(p_var(nvarlayer))
545           IF (.NOT.ALLOCATED(mu_var))  ALLOCATE(mu_var(nvarlayer))
546           IF (.NOT.ALLOCATED(frac_var))  ALLOCATE(frac_var(nvarlayer,ngasmx))
547           p_var = 0.0
548           mu_var = 0.0
549           frac_var = 0.0
550           muvari = 0.0
551           dt_file=TRIM(varspec_data)
552           open(33,file=dt_file,form='formatted',status='old',iostat=ios)
553           if (ios.ne.0) then        ! file not found
554             write(*,*) 'Error from varspec'
555             write(*,*) 'Data file ',trim(varspec_data),' not found.'
556             write(*,*) 'Check that the data is in your run repository.'
557             call abort_physic !a verifier
558           else
559             do k=1,nvarlayer
560               read(33,*) p_var(k), mu_var(k),frac_var(k,1:ngasmx)
561               !The order of columns in frac_var must correspond to order of molecules gases.def
562               !The format of your file must be:
563               ! pressure(k) molar_mass(k), molar_fraction_of_gas_1(k), molar_fraction_of_gas_2(k),..., molar_fraction_of_gas_ngasmx(k)
564             enddo
565           endif
566           close(33)
567         else
568           IF (.NOT.ALLOCATED(p_var))  ALLOCATE(p_var(nlayer))
569           IF (.NOT.ALLOCATED(mu_var))  ALLOCATE(mu_var(nlayer))
570           IF (.NOT.ALLOCATED(frac_var))  ALLOCATE(frac_var(nlayer,ngasmx))
571         endif
572
573!        Initialize tracer names, indexes and properties.
574!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
575         IF (.NOT.ALLOCATED(noms)) ALLOCATE(noms(nq)) ! (because noms is an argument of physdem1 whether or not tracer is on)
576         if (tracer) then
577            call initracer(ngrid,nq)
578            if(photochem) then
579              call ini_conc_mod(ngrid,nlayer)
580              IF (.NOT.ALLOCATED(zdqchim))  ALLOCATE(zdqchim(ngrid,nlayer,nesp))
581              IF (.NOT.ALLOCATED(zdqschim)) ALLOCATE(zdqschim(ngrid,nesp))
582            endif
583         endif
584!        Initialize aerosol indexes.
585!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~
586         call iniaerosol
587         ! allocate related local arrays
588         ! (need be allocated instead of automatic because of "naerkind")
589         allocate(aerosol(ngrid,nlayer,naerkind))
590         allocate(reffcol(ngrid,naerkind))
591
592#ifdef CPP_XIOS
593         ! Initialize XIOS context
594         write(*,*) "physiq: call wxios_context_init"
595         CALL wxios_context_init
596#endif
597
598!        Read 'startfi.nc' file.
599!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
600#ifndef MESOSCALE
601         call phyetat0(startphy_file,                                 &
602                       ngrid,nlayer,"startfi.nc",0,0,nsoilmx,nq,      &
603                       day_ini,time_phys,tsurf,tsoil,emis,albedo,     &
604                       q2,qsurf,cloudfrac,totcloudfrac,hice,          &
605                       rnat,pctsrf_sic,tslab,tsea_ice,tice,sea_ice)
606
607#else
608
609         day_ini = pday
610#endif
611
612#ifndef MESOSCALE
613         if (.not.startphy_file) then
614           ! additional "academic" initialization of physics
615           if (is_master) write(*,*) "Physiq: initializing tsurf(:) to pt(:,1) !!"
616           tsurf(:)=pt(:,1)
617           if (is_master) write(*,*) "Physiq: initializing tsoil(:) to pt(:,1) !!"
618           do isoil=1,nsoilmx
619             tsoil(1:ngrid,isoil)=tsurf(1:ngrid)
620           enddo
621           if (is_master) write(*,*) "Physiq: initializing day_ini to pday !"
622           day_ini=pday
623         endif
624#endif
625         if (pday.ne.day_ini) then
626             write(*,*) "ERROR in physiq.F90:"
627             write(*,*) "bad synchronization between physics and dynamics"
628             write(*,*) "dynamics day: ",pday
629             write(*,*) "physics day:  ",day_ini
630             stop
631         endif
632
633         write (*,*) 'In physiq day_ini =', day_ini
634
635!        Initialize albedo calculation.
636!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
637         call surfini(ngrid,nq,qsurf,albedo,albedo_bareground,&
638                      albedo_snow_SPECTV,albedo_co2_ice_SPECTV)
639
640!        Initialize orbital calculation.
641!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
642         call iniorbit(apoastr,periastr,year_day,peri_day,obliquit)
643
644
645         if(tlocked)then
646            print*,'Planet is tidally locked at resonance n=',nres
647            print*,'Make sure you have the right rotation rate!!!'
648         endif
649
650!        Initialize oceanic variables.
651!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
652
653         if (ok_slab_ocean)then
654
655!!           call ocean_slab_init(ngrid,ptimestep, tslab, &
656!!                                sea_ice, pctsrf_sic)
657
658!!           call ini_surf_heat_transp_mod()
659
660           knindex(:) = 0
661           knon = 0
662
663           do ig=1,ngrid
664              zmasq(ig)=1
665!              knindex(ig) = ig
666              if (nint(rnat(ig)).eq.0) then ! rnat = 0 (ocean), 1 (continent)
667                 zmasq(ig)=0
668                 knon=knon+1
669                 knindex(knon)=ig
670              endif
671           enddo
672
673           call ocean_slab_init(ptimestep, pctsrf_sic, tslab, tice, sea_ice, zmasq)
674
675!!           CALL init_masquv(ngrid,zmasq)
676           ! ensure that "slab" variables match "physiq" ones
677           call ocean_slab_get_vars(ngrid, tslab, tice, sea_ice, flux_g, &
678                      dt_hdiff, dt_ekman, dt_gm)
679
680         endif ! end of 'ok_slab_ocean'.
681
682
683!        Initialize soil.
684!        ~~~~~~~~~~~~~~~~
685         if (callsoil) then
686
687            call soil(ngrid,nsoilmx,firstcall,lastcall,inertiedat, &
688                      ptimestep,tsurf,tsoil,capcal,fluxgrd)
689
690            if (ok_slab_ocean) then
691              ! mimic what is done during a regular time step
692              do ig=1,ngrid
693                fluxgrdocean(ig)=fluxgrd(ig)
694                if (nint(rnat(ig)).eq.0) then
695                  capcal(ig)=capcalocean
696                  fluxgrd(ig)=0.
697                  ! Dividing by cell area to have flux in W/m2
698                  fluxgrdocean(ig)=flux_g(ig)+(1-pctsrf_sic(ig))*(dt_hdiff(ig,1)+dt_ekman(ig,1)+dt_gm(ig,1))/cell_area(ig)
699                  do iq=1,nsoilmx
700                    tsoil(ig,iq)=tsurf(ig)
701                  enddo
702                  if (pctsrf_sic(ig).gt.0.5) then
703                    capcal(ig)=capcalseaice
704                    if (qsurf(ig,igcm_h2o_ice).gt.0.) then
705                      capcal(ig)=capcalsno
706                    endif
707                  endif ! of if (pctsrf_sic(ig).gt.0.5)
708                endif ! of if (nint(rnat(ig)).eq.0)
709              enddo ! of do ig=1,ngrid
710            endif ! end of 'ok_slab_ocean'.
711
712         else ! else of 'callsoil'.
713
714            print*,'WARNING! Thermal conduction in the soil turned off'
715            capcal(:)=1.e6
716            fluxgrd(:)=intheat
717            print*,'Flux from ground = ',intheat,' W m^-2'
718
719         endif ! end of 'callsoil'.
720
721         icount=1
722
723         ! Here is defined the type of the surface : Continent or Ocean.
724         ! BC2014 : This is now already done in newstart.
725         ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
726         if (.not.ok_slab_ocean) then
727
728           rnat(:)=1.
729           if (.not.nosurf) then ! inertiedat only defined if there is a surface
730            do ig=1,ngrid
731              if(inertiedat(ig,1).gt.1.E4)then
732                 rnat(ig)=0
733              endif
734            enddo
735
736            print*,'WARNING! Surface type currently decided by surface inertia'
737            print*,'This should be improved e.g. in newstart.F'
738           endif
739         endif ! end of 'ok_slab_ocean'.
740
741
742!        Initialize surface history variable.
743!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
744         qsurf_hist(:,:)=qsurf(:,:)
745
746!        Initialize variable for dynamical heating and zonal wind tendency diagnostic
747!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
748         ztprevious(:,:)=pt(:,:)
749         zuprevious(:,:)=pu(:,:)
750
751!        Set temperature just above condensation temperature (for Early Mars)
752!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
753         if(nearco2cond) then
754            write(*,*)' WARNING! Starting at Tcond+1K'
755            do l=1, nlayer
756               do ig=1,ngrid
757                  pdt(ig,l)= ((-3167.8)/(log(.01*pplay(ig,l))-23.23)+4     &
758                      -pt(ig,l)) / ptimestep
759               enddo
760            enddo
761         endif
762
763         if(meanOLR)then
764            call system('rm -f rad_bal.out') ! to record global radiative balance.
765            call system('rm -f tem_bal.out') ! to record global mean/max/min temperatures.
766            call system('rm -f h2o_bal.out') ! to record global hydrological balance.
767         endif
768
769
770         watertest=.false.
771         if(water)then ! Initialize variables for water cycle
772
773            if(enertest)then
774               watertest = .true.
775            endif
776
777         endif
778
779!        Set metallicity for GCS
780!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
781         metallicity=0.0 ! default value --- is not used here but necessary to call function Psat_generic
782         call getin_p("metallicity",metallicity) ! --- is not used here but necessary to call function Psat_generic
783
784!        Set some parameters for the thermal plume model
785!        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
786         if (calltherm) then
787            CALL init_thermcell_mod(g, rcp, r, pi, T_h2o_ice_liq, RW)
788         endif
789
790         call su_watercycle ! even if we don't have a water cycle, we might
791                            ! need epsi for the wvp definitions in callcorrk.F
792                            ! or RETV, RLvCp for the thermal plume model
793
794#ifndef MESOSCALE
795         !if (ngrid.ne.1) then ! Note : no need to create a restart file in 1d.
796            call physdem0("restartfi.nc",longitude,latitude,nsoilmx,ngrid,nlayer,nq, &
797                         ptimestep,pday+nday,time_phys,cell_area,          &
798                         albedo_bareground,inertiedat,zmea,zstd,zsig,zgam,zthe)
799         !endif
800
801#endif
802         if (corrk) then
803            ! We initialise the spectral grid here instead of
804            ! at firstcall of callcorrk so we can output XspecIR, XspecVI
805            ! when using Dynamico
806            print*, "physiq_mod: Correlated-k data base folder:",trim(datadir)
807            call getin_p("corrkdir",corrkdir)
808            print*,"corrkdir = ", corrkdir
809            write (tmp1, '(i4)') L_NSPECTI
810            write (tmp2, '(i4)') L_NSPECTV
811            banddir=trim(trim(adjustl(tmp1))//'x'//trim(adjustl(tmp2)))
812            banddir=trim(trim(adjustl(corrkdir))//'/'//trim(adjustl(banddir)))
813            call setspi !Basic infrared properties.
814            call setspv ! Basic visible properties.
815            call sugas_corrk       ! Set up gaseous absorption properties.
816            call suaer_corrk       ! Set up aerosol optical properties.
817         endif
818
819         ! XIOS outputs
820#ifdef CPP_XIOS
821
822         write(*,*) "physiq: call initialize_xios_output"
823         call initialize_xios_output(pday,ptime,ptimestep,daysec, &
824                                     year_day,presnivs,pseudoalt,WNOI,WNOV)
825#endif
826
827         write(*,*) "physiq: end of firstcall"
828      endif ! end of 'firstcall'
829
830
831      if (check_physics_inputs) then
832         !check the validity of input fields coming from the dynamics
833         call check_physics_fields("begin physiq:", pt, pu, pv, pplev, pq)
834      endif
835
836
837! ------------------------------------------------------
838! I.2   Initializations done at every physical timestep:
839! ------------------------------------------------------
840
841#ifdef CPP_XIOS
842      ! update XIOS time/calendar
843      call update_xios_timestep
844#endif
845
846      ! Initialize various variables
847      ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
848
849      if ( .not.nearco2cond ) then
850         pdt(1:ngrid,1:nlayer) = 0.0
851      endif
852      zdtsurf(1:ngrid)      = 0.0
853      pdq(1:ngrid,1:nlayer,1:nq) = 0.0
854      dqsurf(1:ngrid,1:nq)= 0.0
855      pdu(1:ngrid,1:nlayer) = 0.0
856      pdv(1:ngrid,1:nlayer) = 0.0
857      pdpsrf(1:ngrid)       = 0.0
858      zflubid(1:ngrid)      = 0.0
859      flux_sens_lat(1:ngrid) = 0.0
860      taux(1:ngrid) = 0.0
861      tauy(1:ngrid) = 0.0
862      net_fluxsurf_lw(1:ngrid) = 0.0
863
864      zday=pday+ptime ! Compute time, in sols (and fraction thereof).
865
866      ! Compute Stellar Longitude (Ls), and orbital parameters.
867      ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
868      if (season) then
869         call stellarlong(zday,zls)
870      else
871         call stellarlong(noseason_day,zls)
872      end if
873
874      call orbite(zls,dist_star,declin,right_ascen)
875
876      if (tlocked) then
877              zlss=Mod(-(2.*pi*(zday/year_day)*nres - right_ascen),2.*pi)
878      elseif (diurnal) then
879              zlss=-2.*pi*(zday-.5)
880      else if(diurnal .eqv. .false.) then
881              zlss=9999.
882      endif
883
884
885      ! Compute variations of g with latitude (oblate case).
886      ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
887      if (oblate .eqv. .false.) then
888         glat(:) = g
889      else if (flatten .eq. 0.0 .or. J2 .eq. 0.0 .or. Rmean .eq. 0.0 .or. MassPlanet .eq. 0.0) then
890         print*,'I need values for flatten, J2, Rmean and MassPlanet to compute glat (else set oblate=.false.)'
891         call abort
892      else
893         gmplanet = MassPlanet*grav*1e24
894         do ig=1,ngrid
895            glat(ig)= gmplanet/(Rmean**2) * (1.D0 + 0.75 *J2 - 2.0*flatten/3. + (2.*flatten - 15./4.* J2) * cos(2. * (pi/2. - latitude(ig))))
896         end do
897      endif
898
899      ! Compute geopotential between layers.
900      ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
901      zzlay(1:ngrid,1:nlayer)=pphi(1:ngrid,1:nlayer)
902      do l=1,nlayer
903         zzlay(1:ngrid,l)= zzlay(1:ngrid,l)/glat(1:ngrid)
904      enddo
905
906      zzlev(1:ngrid,1)=0.
907
908      do l=2,nlayer
909         do ig=1,ngrid
910            z1=(pplay(ig,l-1)+pplev(ig,l))/(pplay(ig,l-1)-pplev(ig,l))
911            z2=(pplev(ig,l)+pplay(ig,l))/(pplev(ig,l)-pplay(ig,l))
912            zzlev(ig,l)=(z1*zzlay(ig,l-1)+z2*zzlay(ig,l))/(z1+z2)
913         enddo
914      enddo
915
916      !Altitude of top interface (nlayer+1), using the thicknesss of the level below the top one. LT22
917
918      zzlev(1:ngrid,nlayer+1) = 2*zzlev(1:ngrid,nlayer)-zzlev(1:ngrid,nlayer-1)
919
920      ! Compute potential temperature
921      ! Note : Potential temperature calculation may not be the same in physiq and dynamic...
922      ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
923      do l=1,nlayer
924         do ig=1,ngrid
925            zpopsk(ig,l)=(pplay(ig,l)/pplev(ig,1))**rcp
926            zh(ig,l)=pt(ig,l)/zpopsk(ig,l)
927            mass(ig,l)  = (pplev(ig,l) - pplev(ig,l+1))/glat(ig)
928            massarea(ig,l)=mass(ig,l)*cell_area(ig)
929         enddo
930      enddo
931
932     ! Compute vertical velocity (m/s) from vertical mass flux
933     ! w = F / (rho*area) and rho = P/(r*T)
934     ! But first linearly interpolate mass flux to mid-layers
935      do l=1,nlayer-1
936         pw(1:ngrid,l)=0.5*(flxw(1:ngrid,l)+flxw(1:ngrid,l+1))
937      enddo
938      pw(1:ngrid,nlayer)=0.5*flxw(1:ngrid,nlayer) ! since flxw(nlayer+1)=0
939      do l=1,nlayer
940         pw(1:ngrid,l)=(pw(1:ngrid,l)*r*pt(1:ngrid,l)) /  &
941                       (pplay(1:ngrid,l)*cell_area(1:ngrid))
942      enddo
943      ! omega in Pa/s
944      do l=1,nlayer-1
945         omega(1:ngrid,l)=0.5*(flxw(1:ngrid,l)+flxw(1:ngrid,l+1))
946      enddo
947      omega(1:ngrid,nlayer)=0.5*flxw(1:ngrid,nlayer) ! since flxw(nlayer+1)=0
948      do l=1,nlayer
949         omega(1:ngrid,l)=g*omega(1:ngrid,l)/cell_area(1:ngrid)
950      enddo
951
952      ! ----------------------------------------------------------------
953      ! Compute mean mass, cp, and R
954      ! --------------------------------
955#ifndef MESOSCALE
956      if(photochem) then
957         call concentrations(ngrid,nlayer,nq,pplay,pt,pdt,pq,pdq,ptimestep)
958      endif
959#endif
960
961!---------------------------------
962! II. Compute radiative tendencies
963!---------------------------------
964
965      ! Compute local stellar zenith angles
966      ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
967      if (tlocked) then
968      ! JL14 corrects tidally resonant (and inclined) cases. nres=omega_rot/omega_orb
969         ztim1=SIN(declin)
970         ztim2=COS(declin)*COS(zlss)
971         ztim3=COS(declin)*SIN(zlss)
972
973         call stelang(ngrid,sinlon,coslon,sinlat,coslat,    &
974                        ztim1,ztim2,ztim3,mu0,fract, flatten)
975
976      elseif (diurnal) then
977         ztim1=SIN(declin)
978         ztim2=COS(declin)*COS(2.*pi*(zday-.5))
979         ztim3=-COS(declin)*SIN(2.*pi*(zday-.5))
980
981         call stelang(ngrid,sinlon,coslon,sinlat,coslat,    &
982                        ztim1,ztim2,ztim3,mu0,fract, flatten)
983      else if(diurnal .eqv. .false.) then
984
985         call mucorr(ngrid,declin,latitude,mu0,fract,10000.,rad,flatten)
986         ! WARNING: this function appears not to work in 1D
987
988         if ((ngrid.eq.1).and.(global1d)) then ! Fixed zenith angle 'szangle' in 1D simulations w/ globally-averaged sunlight.
989            mu0 = cos(pi*szangle/180.0)
990         endif
991
992      endif
993
994      if (callrad) then
995
996         if( mod(icount-1,iradia).eq.0) then
997
998            ! Eclipse incoming sunlight (e.g. Saturn ring shadowing).
999            if(rings_shadow) then
1000                call call_rings(ngrid, ptime, pday, diurnal)
1001            endif
1002
1003
1004            if (corrk) then
1005
1006! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1007! II.a Call correlated-k radiative transfer scheme
1008! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1009               if(kastprof)then
1010                  print*,'kastprof should not = true here'
1011                  call abort
1012               endif
1013               if(water) then
1014                  ! take into account water effect on mean molecular weight
1015                  muvar(1:ngrid,1:nlayer)=mugaz/(1.e0+(1.e0/epsi-1.e0)*pq(1:ngrid,1:nlayer,igcm_h2o_vap))
1016                  muvar(1:ngrid,nlayer+1)=mugaz/(1.e0+(1.e0/epsi-1.e0)*pq(1:ngrid,nlayer,igcm_h2o_vap))
1017               elseif(generic_condensation) then
1018                  ! take into account generic condensable specie (GCS) effect on mean molecular weight
1019                  do iq=1,nq
1020
1021                     call generic_tracer_index(nq,iq,igcm_generic_vap,igcm_generic_ice,call_ice_vap_generic)
1022
1023                     if (call_ice_vap_generic) then ! to call only one time the ice/vap pair of a tracer
1024
1025                        epsi_generic=constants_epsi_generic(iq)
1026
1027                        muvar(1:ngrid,1:nlayer)=mugaz/(1.e0+(1.e0/epsi_generic-1.e0)*pq(1:ngrid,1:nlayer,igcm_generic_vap))
1028                        muvar(1:ngrid,nlayer+1)=mugaz/(1.e0+(1.e0/epsi_generic-1.e0)*pq(1:ngrid,nlayer,igcm_generic_vap))
1029
1030                     endif
1031                  end do ! do iq=1,nq loop on tracers
1032               elseif(varspec) then
1033                  !take into account fixed variable mean molecular weight
1034                  do ig=1,ngrid
1035                    call pindex(p_var,mu_var,pplay(ig,:),nvarlayer,nlayer,mu_vari)
1036                    muvari(ig,:) = mu_vari
1037                  enddo
1038
1039                  muvar(1:ngrid,1:nlayer) = muvari(1:ngrid,1:nlayer)
1040                  muvar(1:ngrid,nlayer+1) = muvari(1:ngrid,nlayer)
1041
1042               else
1043                  muvar(1:ngrid,1:nlayer+1)=mugaz
1044               endif
1045
1046
1047               if(ok_slab_ocean) then
1048                  tsurf2(:)=tsurf(:)
1049                  do ig=1,ngrid
1050                     if (nint(rnat(ig))==0) then
1051                        tsurf(ig)=((1.-pctsrf_sic(ig))*tslab(ig,1)**4+pctsrf_sic(ig)*tsea_ice(ig)**4)**0.25
1052                     endif
1053                  enddo
1054               endif !(ok_slab_ocean)
1055
1056               ! standard callcorrk
1057               clearsky=.false.
1058               call callcorrk(ngrid,nlayer,pq,nq,qsurf,                           &
1059                              albedo,albedo_equivalent,emis,mu0,pplev,pplay,pt,   &
1060                              tsurf,fract,dist_star,aerosol,muvar,                &
1061                              zdtlw,zdtsw,fluxsurf_lw,fluxsurf_sw,                &
1062                              fluxsurfabs_sw,fluxtop_lw,                          &
1063                              fluxabs_sw,fluxtop_dn,OLR_nu,OSR_nu,GSR_nu,         &
1064                              int_dtaui,int_dtauv,                                &
1065                              tau_col,cloudfrac,totcloudfrac,                     &
1066                              clearsky,p_var,frac_var,firstcall,lastcall)
1067
1068                !GG (feb2021): Option to "artificially" decrease the raditive time scale in
1069                !the deep atmosphere  press > 0.1 bar. Suggested by MT.
1070                !! COEFF_RAD to be "tuned" to facilitate convergence of tendency
1071
1072                !coeff_rad=0.   ! 0 values, it doesn't accelerate the convergence
1073                !coeff_rad=0.5
1074                !coeff_rad=1.
1075                !do l=1, nlayer
1076                !  do ig=1,ngrid
1077                !    if(pplay(ig,l).ge.1.d4) then
1078                !      zdtsw(ig,l)=zdtsw(ig,l)*(pplay(ig,l)/1.d4)**coeff_rad
1079                !      zdtlw(ig,l)=zdtlw(ig,l)*(pplay(ig,l)/1.d4)**coeff_rad
1080                !    endif
1081                !  enddo
1082                !enddo
1083
1084                ! Option to call scheme once more for clear regions
1085               if(CLFvarying)then
1086
1087                  ! ---> PROBLEMS WITH ALLOCATED ARRAYS : temporary solution in callcorrk: do not deallocate if CLFvarying ...
1088                  clearsky=.true.
1089                  call callcorrk(ngrid,nlayer,pq,nq,qsurf,                           &
1090                                 albedo,albedo_equivalent1,emis,mu0,pplev,pplay,pt,  &
1091                                 tsurf,fract,dist_star,aerosol,muvar,                &
1092                                 zdtlw1,zdtsw1,fluxsurf_lw1,fluxsurf_sw1,            &
1093                                 fluxsurfabs_sw1,fluxtop_lw1,                        &
1094                                 fluxabs_sw1,fluxtop_dn,OLR_nu1,OSR_nu1,GSR_nu1,     &
1095                                 int_dtaui1,int_dtauv1,                              &
1096                                 tau_col1,cloudfrac,totcloudfrac,                    &
1097                                 clearsky,p_var,frac_var,firstcall,lastcall)
1098                  clearsky = .false.  ! just in case.
1099
1100                  ! Sum the fluxes and heating rates from cloudy/clear cases
1101                  do ig=1,ngrid
1102                     tf=totcloudfrac(ig)
1103                     ntf=1.-tf
1104                     fluxsurf_lw(ig)       = ntf*fluxsurf_lw1(ig)       + tf*fluxsurf_lw(ig)
1105                     fluxsurf_sw(ig)       = ntf*fluxsurf_sw1(ig)       + tf*fluxsurf_sw(ig)
1106                     albedo_equivalent(ig) = ntf*albedo_equivalent1(ig) + tf*albedo_equivalent(ig)
1107                     fluxsurfabs_sw(ig)    = ntf*fluxsurfabs_sw1(ig)    + tf*fluxsurfabs_sw(ig)
1108                     fluxtop_lw(ig)        = ntf*fluxtop_lw1(ig)        + tf*fluxtop_lw(ig)
1109                     fluxabs_sw(ig)        = ntf*fluxabs_sw1(ig)        + tf*fluxabs_sw(ig)
1110                     tau_col(ig)           = ntf*tau_col1(ig)           + tf*tau_col(ig)
1111
1112                     zdtlw(ig,1:nlayer) = ntf*zdtlw1(ig,1:nlayer) + tf*zdtlw(ig,1:nlayer)
1113                     zdtsw(ig,1:nlayer) = ntf*zdtsw1(ig,1:nlayer) + tf*zdtsw(ig,1:nlayer)
1114
1115                     OSR_nu(ig,1:L_NSPECTV) = ntf*OSR_nu1(ig,1:L_NSPECTV) + tf*OSR_nu(ig,1:L_NSPECTV)
1116                     GSR_nu(ig,1:L_NSPECTV) = ntf*GSR_nu1(ig,1:L_NSPECTV) + tf*GSR_nu(ig,1:L_NSPECTV)
1117                     OLR_nu(ig,1:L_NSPECTI) = ntf*OLR_nu1(ig,1:L_NSPECTI) + tf*OLR_nu(ig,1:L_NSPECTI)
1118                     if (diagdtau) then
1119                       int_dtauv(ig,:,1:L_NSPECTV) = ntf*int_dtauv1(ig,:,1:L_NSPECTV) + tf*int_dtauv(ig,:,1:L_NSPECTV)
1120                       int_dtaui(ig,:,1:L_NSPECTI) = ntf*int_dtaui1(ig,:,1:L_NSPECTI) + tf*int_dtaui(ig,:,1:L_NSPECTI)
1121                     endif
1122                  enddo
1123
1124               endif ! end of CLFvarying.
1125
1126               if(ok_slab_ocean) then
1127                  tsurf(:)=tsurf2(:)
1128               endif
1129
1130
1131               ! Radiative flux from the sky absorbed by the surface (W.m-2).
1132               GSR=0.0
1133               fluxrad_sky(1:ngrid)=emis(1:ngrid)*fluxsurf_lw(1:ngrid)+fluxsurfabs_sw(1:ngrid)
1134               net_fluxsurf_lw(1:ngrid)=emis(1:ngrid)*fluxsurf_lw(1:ngrid)
1135
1136                            !if(noradsurf)then ! no lower surface; SW flux just disappears
1137                            !   GSR = SUM(fluxsurf_sw(1:ngrid)*cell_area(1:ngrid))/totarea
1138                            !   fluxrad_sky(1:ngrid)=emis(1:ngrid)*fluxsurf_lw(1:ngrid)
1139                            !   print*,'SW lost in deep atmosphere = ',GSR,' W m^-2'
1140                            !endif
1141
1142               ! Net atmospheric radiative heating rate (K.s-1)
1143               dtrad(1:ngrid,1:nlayer)=zdtsw(1:ngrid,1:nlayer)+zdtlw(1:ngrid,1:nlayer)
1144
1145               ! Late initialization of the Ice Spectral Albedo. We needed the visible bands to do that !
1146               if (firstcall .and. albedo_spectral_mode) then
1147                  call spectral_albedo_calc(albedo_snow_SPECTV)
1148               endif
1149
1150            elseif(newtonian)then
1151
1152! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1153! II.b Call Newtonian cooling scheme
1154! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1155               ! call newtrelax(ngrid,nlayer,mu0,sinlat,zpopsk,pt,pplay,pplev,dtrad,firstcall)
1156               call newtcool_MOCHA(ngrid,nlayer,coslon,coslat,pt,pplay,firstcall,lastcall,dtrad)
1157
1158               zdtsurf(1:ngrid) = +(pt(1:ngrid,1)-tsurf(1:ngrid))/ptimestep
1159               ! e.g. surface becomes proxy for 1st atmospheric layer ?
1160               fluxrad_sky(1:ngrid) = 0. ! otherwise, not initialized!
1161
1162            else
1163
1164! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1165! II.c Atmosphere has no radiative effect
1166! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1167               fluxtop_dn(1:ngrid)  = fract(1:ngrid)*mu0(1:ngrid)*Fat1AU/dist_star**2
1168               if(ngrid.eq.1)then ! / by 4 globally in 1D case...
1169                  fluxtop_dn(1)  = fract(1)*Fat1AU/dist_star**2/2.0
1170               endif
1171               fluxsurf_sw(1:ngrid) = fluxtop_dn(1:ngrid)
1172               print*,'------------WARNING---WARNING------------' ! by MT2015.
1173               print*,'You are in corrk=false mode, '
1174               print*,'and the surface albedo is taken equal to the first visible spectral value'
1175
1176               fluxsurfabs_sw(1:ngrid) = fluxtop_dn(1:ngrid)*(1.-albedo(1:ngrid,1))
1177               fluxrad_sky(1:ngrid)    = fluxsurfabs_sw(1:ngrid)
1178               fluxtop_lw(1:ngrid)  = emis(1:ngrid)*sigma*tsurf(1:ngrid)**4
1179
1180               dtrad(1:ngrid,1:nlayer)=0.0 ! no atmospheric radiative heating
1181
1182            endif ! end of corrk
1183
1184         endif ! of if(mod(icount-1,iradia).eq.0)
1185
1186
1187         ! Transformation of the radiative tendencies
1188         ! ------------------------------------------
1189
1190         zplanck(1:ngrid)=tsurf(1:ngrid)*tsurf(1:ngrid)
1191         zplanck(1:ngrid)=emis(1:ngrid)*sigma*zplanck(1:ngrid)*zplanck(1:ngrid)
1192         net_fluxsurf_lw(1:ngrid)=net_fluxsurf_lw(1:ngrid)-zplanck(1:ngrid)
1193         fluxrad(1:ngrid)=fluxrad_sky(1:ngrid)-zplanck(1:ngrid)
1194         pdt(1:ngrid,1:nlayer)=pdt(1:ngrid,1:nlayer)+dtrad(1:ngrid,1:nlayer)
1195
1196         ! Test of energy conservation
1197         !----------------------------
1198         if(enertest)then
1199            call planetwide_sumval(cpp*massarea(:,:)*zdtsw(:,:)/totarea_planet,dEtotSW)
1200            call planetwide_sumval(cpp*massarea(:,:)*zdtlw(:,:)/totarea_planet,dEtotLW)
1201            !call planetwide_sumval(fluxsurf_sw(:)*(1.-albedo_equivalent(:))*cell_area(:)/totarea_planet,dEtotsSW) !JL13 carefull, albedo can have changed since the last time we called corrk
1202            call planetwide_sumval(fluxsurfabs_sw(:)*cell_area(:)/totarea_planet,dEtotsSW) !JL13 carefull, albedo can have changed since the last time we called corrk
1203            call planetwide_sumval((fluxsurf_lw(:)*emis(:)-zplanck(:))*cell_area(:)/totarea_planet,dEtotsLW)
1204            dEzRadsw(:,:)=cpp*mass(:,:)*zdtsw(:,:)
1205            dEzRadlw(:,:)=cpp*mass(:,:)*zdtlw(:,:)
1206            if (is_master) then
1207               print*,'---------------------------------------------------------------'
1208               print*,'In corrk SW atmospheric heating       =',dEtotSW,' W m-2'
1209               print*,'In corrk LW atmospheric heating       =',dEtotLW,' W m-2'
1210               print*,'atmospheric net rad heating (SW+LW)   =',dEtotLW+dEtotSW,' W m-2'
1211               print*,'In corrk SW surface heating           =',dEtotsSW,' W m-2'
1212               print*,'In corrk LW surface heating           =',dEtotsLW,' W m-2'
1213               print*,'surface net rad heating (SW+LW)       =',dEtotsLW+dEtotsSW,' W m-2'
1214            endif
1215         endif ! end of 'enertest'
1216
1217      endif ! of if (callrad)
1218
1219
1220!  --------------------------------------------
1221!  III. Vertical diffusion (turbulent mixing) :
1222!  --------------------------------------------
1223
1224      if (calldifv) then
1225
1226         zflubid(1:ngrid)=fluxrad(1:ngrid)+fluxgrd(1:ngrid)
1227
1228         ! JL12 the following if test is temporarily there to allow us to compare the old vdifc with turbdiff.
1229         if (UseTurbDiff) then
1230
1231            call turbdiff(ngrid,nlayer,nq,rnat,                  &
1232                          ptimestep,capcal,                      &
1233                          pplay,pplev,zzlay,zzlev,z0,            &
1234                          pu,pv,pt,zpopsk,pq,tsurf,emis,qsurf,   &
1235                          pdt,pdq,zflubid,                       &
1236                          zdudif,zdvdif,zdtdif,zdtsdif,          &
1237                          sensibFlux,q2,zdqdif,zdqevap,zdqsdif,  &
1238                          taux,tauy)
1239
1240         else
1241
1242            zdh(1:ngrid,1:nlayer)=pdt(1:ngrid,1:nlayer)/zpopsk(1:ngrid,1:nlayer)
1243
1244            call vdifc(ngrid,nlayer,nq,rnat,zpopsk,           &
1245                       ptimestep,capcal,lwrite,               &
1246                       pplay,pplev,zzlay,zzlev,z0,            &
1247                       pu,pv,zh,pq,tsurf,emis,qsurf,          &
1248                       zdh,pdq,zflubid,                       &
1249                       zdudif,zdvdif,zdhdif,zdtsdif,          &
1250                       sensibFlux,q2,zdqdif,zdqsdif)
1251
1252            zdtdif(1:ngrid,1:nlayer)=zdhdif(1:ngrid,1:nlayer)*zpopsk(1:ngrid,1:nlayer) ! for diagnostic only
1253            zdqevap(1:ngrid,1:nlayer)=0.
1254
1255         end if !end of 'UseTurbDiff'
1256
1257         zdtsurf(1:ngrid)=zdtsurf(1:ngrid)+zdtsdif(1:ngrid)
1258
1259         !!! this is always done, except for turbulence-resolving simulations
1260         if (.not. turb_resolved) then
1261           pdv(1:ngrid,1:nlayer)=pdv(1:ngrid,1:nlayer)+zdvdif(1:ngrid,1:nlayer)
1262           pdu(1:ngrid,1:nlayer)=pdu(1:ngrid,1:nlayer)+zdudif(1:ngrid,1:nlayer)
1263           pdt(1:ngrid,1:nlayer)=pdt(1:ngrid,1:nlayer)+zdtdif(1:ngrid,1:nlayer)
1264         endif
1265
1266         if(ok_slab_ocean)then
1267            flux_sens_lat(1:ngrid)=(zdtsdif(1:ngrid)*capcal(1:ngrid)-fluxrad(1:ngrid))
1268         endif
1269
1270         if (tracer) then
1271           pdq(1:ngrid,1:nlayer,1:nq)=pdq(1:ngrid,1:nlayer,1:nq)+ zdqdif(1:ngrid,1:nlayer,1:nq)
1272           dqsurf(1:ngrid,1:nq)=dqsurf(1:ngrid,1:nq) + zdqsdif(1:ngrid,1:nq)
1273         end if ! of if (tracer)
1274
1275
1276         ! test energy conservation
1277         !-------------------------
1278         if(enertest)then
1279
1280            dEzdiff(:,:)=cpp*mass(:,:)*zdtdif(:,:)
1281            do ig = 1, ngrid
1282               dEdiff(ig)=SUM(dEzdiff (ig,:))+ sensibFlux(ig)! subtract flux to the ground
1283               dEzdiff(ig,1)= dEzdiff(ig,1)+ sensibFlux(ig)! subtract flux to the ground
1284            enddo
1285
1286            call planetwide_sumval(dEdiff(:)*cell_area(:)/totarea_planet,dEtot)
1287            dEdiffs(:)=capcal(:)*zdtsdif(:)-zflubid(:)-sensibFlux(:)
1288            call planetwide_sumval(dEdiffs(:)*cell_area(:)/totarea_planet,dEtots)
1289            call planetwide_sumval(sensibFlux(:)*cell_area(:)/totarea_planet,AtmToSurf_TurbFlux)
1290
1291            if (is_master) then
1292
1293               if (UseTurbDiff) then
1294                         print*,'In TurbDiff sensible flux (atm=>surf) =',AtmToSurf_TurbFlux,' W m-2'
1295                         print*,'In TurbDiff non-cons atm nrj change   =',dEtot,' W m-2'
1296                  print*,'In TurbDiff (correc rad+latent heat) surf nrj change =',dEtots,' W m-2'
1297               else
1298                         print*,'In vdifc sensible flux (atm=>surf)    =',AtmToSurf_TurbFlux,' W m-2'
1299                         print*,'In vdifc non-cons atm nrj change      =',dEtot,' W m-2'
1300                         print*,'In vdifc (correc rad+latent heat) surf nrj change =',dEtots,' W m-2'
1301               end if
1302            endif ! end of 'is_master'
1303
1304         ! JL12 : note that the black body radiative flux emitted by the surface has been updated by the implicit scheme but not given back elsewhere.
1305         endif ! end of 'enertest'
1306
1307
1308         ! Test water conservation.
1309         if(watertest.and.water)then
1310
1311            call planetwide_sumval(massarea(:,:)*zdqdif(:,:,igcm_h2o_vap)*ptimestep/totarea_planet,dWtot_tmp)
1312            call planetwide_sumval(zdqsdif(:,igcm_h2o_vap)*cell_area(:)*ptimestep/totarea_planet,dWtots_tmp)
1313            do ig = 1, ngrid
1314               vdifcncons(ig)=SUM(mass(ig,:)*zdqdif(ig,:,igcm_h2o_vap))
1315            enddo
1316            call planetwide_sumval(massarea(:,:)*zdqdif(:,:,igcm_h2o_ice)*ptimestep/totarea_planet,dWtot)
1317            call planetwide_sumval(zdqsdif(:,igcm_h2o_ice)*cell_area(:)*ptimestep/totarea_planet,dWtots)
1318            dWtot = dWtot + dWtot_tmp
1319            dWtots = dWtots + dWtots_tmp
1320            do ig = 1, ngrid
1321               vdifcncons(ig)=vdifcncons(ig) + SUM(mass(ig,:)*zdqdif(ig,:,igcm_h2o_ice))
1322            enddo
1323            call planetwide_maxval(vdifcncons(:),nconsMAX)
1324
1325            if (is_master) then
1326               print*,'---------------------------------------------------------------'
1327               print*,'In difv atmospheric water change        =',dWtot,' kg m-2'
1328               print*,'In difv surface water change            =',dWtots,' kg m-2'
1329               print*,'In difv non-cons factor                 =',dWtot+dWtots,' kg m-2'
1330               print*,'In difv MAX non-cons factor             =',nconsMAX,' kg m-2 s-1'
1331            endif
1332
1333         endif ! end of 'watertest'
1334         !-------------------------
1335
1336      else ! calldifv
1337
1338         if(.not.newtonian)then
1339
1340            zdtsurf(1:ngrid) = zdtsurf(1:ngrid) + (fluxrad(1:ngrid) + fluxgrd(1:ngrid))/capcal(1:ngrid)
1341
1342         endif
1343
1344      endif ! end of 'calldifv'
1345
1346
1347!-------------------
1348!   IV. Convection :
1349!-------------------
1350
1351! ~~~~~~~~~~~~~~~~~~~~~~~~~~
1352! IV.a Thermal plume model :
1353! ~~~~~~~~~~~~~~~~~~~~~~~~~~
1354
1355      IF (calltherm) THEN
1356
1357! AB: We need to evaporate ice before calling thermcell_main.
1358         IF (water) THEN
1359            CALL evap(ngrid,nlayer,nq,ptimestep,pt,pq,pdq,pdt,dqevap,dtevap,zqtherm,zttherm)
1360         !ALS24 adapats for generic tracer
1361         ELSEIF (generic_condensation .and. .not. water) THEN
1362            DO iq=1,nq
1363               CALL generic_tracer_index(nq,iq,igcm_generic_vap,igcm_generic_ice,call_ice_vap_generic)
1364               CALL evap_generic(ngrid,nlayer,nq,ptimestep,pt,pq,pdq,pdt,igcm_generic_vap, &
1365                       igcm_generic_ice,dqevap,dtevap,zqtherm,zttherm)
1366            ENDDO
1367         ELSE
1368            zttherm(:,:)   = pt(:,:)   + pdt(:,:)   * ptimestep
1369            zqtherm(:,:,:) = pq(:,:,:) + pdq(:,:,:) * ptimestep
1370         ENDIF
1371
1372         CALL thermcell_main(ngrid, nlayer, nq, ptimestep, firstcall,            &
1373                             pplay, pplev, pphi, zpopsk,                         &
1374                             pu, pv, zttherm, zqtherm,                           &
1375                             zdutherm, zdvtherm, zdttherm, zdqtherm,             &
1376                             fm, entr, detr, zw2, fraca)
1377
1378         pdu(1:ngrid,1:nlayer) = pdu(1:ngrid,1:nlayer) + zdutherm(1:ngrid,1:nlayer)
1379         pdv(1:ngrid,1:nlayer) = pdv(1:ngrid,1:nlayer) + zdvtherm(1:ngrid,1:nlayer)
1380         pdt(1:ngrid,1:nlayer) = pdt(1:ngrid,1:nlayer) + zdttherm(1:ngrid,1:nlayer)
1381
1382         IF (tracer) THEN
1383            pdq(1:ngrid,1:nlayer,1:nq) = pdq(1:ngrid,1:nlayer,1:nq) + zdqtherm(1:ngrid,1:nlayer,1:nq)
1384         ENDIF
1385
1386      ENDIF ! end of 'calltherm'
1387
1388! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1389! IV.b Dry convective adjustment :
1390! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1391
1392      if(calladj) then
1393
1394         zdh(1:ngrid,1:nlayer) = pdt(1:ngrid,1:nlayer)/zpopsk(1:ngrid,1:nlayer)
1395         zduadj(1:ngrid,1:nlayer)=0.0
1396         zdvadj(1:ngrid,1:nlayer)=0.0
1397         zdhadj(1:ngrid,1:nlayer)=0.0
1398
1399
1400         call convadj(ngrid,nlayer,nq,ptimestep,            &
1401                      pplay,pplev,zpopsk,                   &
1402                      pu,pv,zh,pq,                          &
1403                      pdu,pdv,zdh,pdq,                      &
1404                      zduadj,zdvadj,zdhadj,                 &
1405                      zdqadj)
1406
1407         pdu(1:ngrid,1:nlayer) = pdu(1:ngrid,1:nlayer) + zduadj(1:ngrid,1:nlayer)
1408         pdv(1:ngrid,1:nlayer) = pdv(1:ngrid,1:nlayer) + zdvadj(1:ngrid,1:nlayer)
1409         pdt(1:ngrid,1:nlayer)    = pdt(1:ngrid,1:nlayer) + zdhadj(1:ngrid,1:nlayer)*zpopsk(1:ngrid,1:nlayer)
1410         zdtadj(1:ngrid,1:nlayer) = zdhadj(1:ngrid,1:nlayer)*zpopsk(1:ngrid,1:nlayer) ! for diagnostic only
1411
1412         if(tracer) then
1413            pdq(1:ngrid,1:nlayer,1:nq) = pdq(1:ngrid,1:nlayer,1:nq) + zdqadj(1:ngrid,1:nlayer,1:nq)
1414         end if
1415
1416         ! Test energy conservation
1417         if(enertest)then
1418            call planetwide_sumval(cpp*massarea(:,:)*zdtadj(:,:)/totarea_planet,dEtot)
1419            if (is_master) print*,'In convadj atmospheric energy change  =',dEtot,' W m-2'
1420         endif
1421
1422         ! Test water conservation
1423         if(watertest)then
1424            call planetwide_sumval(massarea(:,:)*zdqadj(:,:,igcm_h2o_vap)*ptimestep/totarea_planet,dWtot_tmp)
1425            do ig = 1, ngrid
1426               cadjncons(ig)=SUM(mass(ig,:)*zdqadj(ig,:,igcm_h2o_vap))
1427            enddo
1428            call planetwide_sumval(massarea(:,:)*zdqadj(:,:,igcm_h2o_ice)*ptimestep/totarea_planet,dWtot)
1429            dWtot = dWtot + dWtot_tmp
1430            do ig = 1, ngrid
1431               cadjncons(ig)=cadjncons(ig) + SUM(mass(ig,:)*zdqadj(ig,:,igcm_h2o_ice))
1432            enddo
1433            call planetwide_maxval(cadjncons(:),nconsMAX)
1434
1435            if (is_master) then
1436               print*,'In convadj atmospheric water change     =',dWtot,' kg m-2'
1437               print*,'In convadj MAX non-cons factor          =',nconsMAX,' kg m-2 s-1'
1438            endif
1439
1440         endif ! end of 'watertest'
1441
1442      endif ! end of 'calladj'
1443!----------------------------------------------
1444!   Non orographic Gravity Waves:
1445!---------------------------------------------
1446      IF (calllott_nonoro) THEN
1447
1448         CALL nonoro_gwd_ran(ngrid,nlayer,ptimestep,        &
1449                    cpnew, rnew,                            &
1450                    pplay,                                  &
1451                    zmax_th,                                &! max altitude reached by thermals (m)
1452                    pt, pu, pv,                             &
1453                    pdt, pdu, pdv,                          &
1454                    zustrhi,zvstrhi,                        &
1455                    d_t_hin, d_u_hin, d_v_hin)
1456
1457!  Update tendencies
1458         pdt(1:ngrid,1:nlayer) = pdt(1:ngrid,1:nlayer)      &
1459                               + d_t_hin(1:ngrid,1:nlayer)
1460         pdu(1:ngrid,1:nlayer) = pdu(1:ngrid,1:nlayer)      &
1461                               + d_u_hin(1:ngrid,1:nlayer)
1462         pdv(1:ngrid,1:nlayer) = pdv(1:ngrid,1:nlayer)      &
1463                               + d_v_hin(1:ngrid,1:nlayer)
1464         print*,'du_nonoro: max ', maxval(d_u_hin), 'min ', minval(d_u_hin)
1465         print*,'dv_nonoro: max ', maxval(d_v_hin), 'min ', minval(d_v_hin)
1466
1467      ENDIF ! of IF (calllott_nonoro)
1468
1469
1470
1471!-----------------------------------------------
1472!   V. Carbon dioxide condensation-sublimation :
1473!-----------------------------------------------
1474
1475      if (co2cond) then
1476
1477         if (.not.tracer) then
1478            print*,'We need a CO2 ice tracer to condense CO2'
1479            call abort
1480         endif
1481         call condense_co2(ngrid,nlayer,nq,ptimestep,                    &
1482                           capcal,pplay,pplev,tsurf,pt,                  &
1483                           pdt,zdtsurf,pq,pdq,                           &
1484                           qsurf,zdqsurfc,albedo,emis,                   &
1485                           albedo_bareground,albedo_co2_ice_SPECTV,      &
1486                           zdtc,zdtsurfc,pdpsrf,zdqc)
1487
1488         pdt(1:ngrid,1:nlayer) = pdt(1:ngrid,1:nlayer)+zdtc(1:ngrid,1:nlayer)
1489         zdtsurf(1:ngrid)      = zdtsurf(1:ngrid) + zdtsurfc(1:ngrid)
1490
1491         pdq(1:ngrid,1:nlayer,1:nq)   = pdq(1:ngrid,1:nlayer,1:nq)+ zdqc(1:ngrid,1:nlayer,1:nq)
1492         dqsurf(1:ngrid,igcm_co2_ice) = dqsurf(1:ngrid,igcm_co2_ice) + zdqsurfc(1:ngrid)
1493
1494
1495         ! test energy conservation
1496         if(enertest)then
1497            call planetwide_sumval(cpp*massarea(:,:)*zdtc(:,:)/totarea_planet,dEtot)
1498            call planetwide_sumval(capcal(:)*zdtsurfc(:)*cell_area(:)/totarea_planet,dEtots)
1499            if (is_master) then
1500               print*,'In co2cloud atmospheric energy change   =',dEtot,' W m-2'
1501               print*,'In co2cloud surface energy change       =',dEtots,' W m-2'
1502            endif
1503         endif
1504
1505      endif  ! end of 'co2cond'
1506
1507
1508!---------------------------------------------
1509!   VI. Specific parameterizations for tracers
1510!---------------------------------------------
1511
1512      if (tracer) then
1513
1514  ! -----------------------------------------------------
1515  !   VI.0. Volcanoes injecting tracers in the atmosphere
1516  ! -----------------------------------------------------
1517        if (callvolcano) then
1518          call volcano(ngrid,nlayer,pplev,pu,pv,pt,zdqvolc,nq,massarea,&
1519                       zday,ptimestep)
1520          pdq(1:ngrid,1:nlayer,1:nq) = pdq(1:ngrid,1:nlayer,1:nq) + &
1521                                       zdqvolc(1:ngrid,1:nlayer,1:nq)
1522        endif
1523
1524  ! ---------------------
1525  !   VI.1. Water and ice
1526  ! ---------------------
1527         if (water) then
1528
1529            ! Water ice condensation in the atmosphere
1530            if(watercond.and.(RLVTT.gt.1.e-8))then
1531
1532               if ((.not.calltherm).and.moistadjustment) then
1533                  dqmoist(1:ngrid,1:nlayer,1:nq)=0.
1534                  dtmoist(1:ngrid,1:nlayer)=0.
1535
1536                  ! Moist Convective Adjustment.
1537                  ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1538
1539                  call moistadj(ngrid,nlayer,nq,pt,pq,pdq,pplev,pplay,dtmoist,dqmoist,ptimestep,rneb_man)
1540
1541                  pdq(1:ngrid,1:nlayer,igcm_h2o_vap) = pdq(1:ngrid,1:nlayer,igcm_h2o_vap)     &
1542                                                     + dqmoist(1:ngrid,1:nlayer,igcm_h2o_vap)
1543                  pdq(1:ngrid,1:nlayer,igcm_h2o_ice) = pdq(1:ngrid,1:nlayer,igcm_h2o_ice)     &
1544                                                     + dqmoist(1:ngrid,1:nlayer,igcm_h2o_ice)
1545                  pdt(1:ngrid,1:nlayer) = pdt(1:ngrid,1:nlayer)+dtmoist(1:ngrid,1:nlayer)
1546
1547                  ! Test energy conservation.
1548                  if(enertest)then
1549                     call planetwide_sumval(cpp*massarea(:,:)*dtmoist(:,:)/totarea_planet,dEtot)
1550                     call planetwide_maxval(dtmoist(:,:),dtmoist_max)
1551                     call planetwide_minval(dtmoist(:,:),dtmoist_min)
1552                     madjdEz(:,:)=cpp*mass(:,:)*dtmoist(:,:)
1553
1554                     do ig=1,ngrid
1555                        madjdE(ig) = cpp*SUM(mass(:,:)*dtmoist(:,:))
1556                     enddo
1557
1558                     if (is_master) then
1559                        print*,'In moistadj atmospheric energy change   =',dEtot,' W m-2'
1560                        print*,'In moistadj MAX atmospheric energy change   =',dtmoist_max*ptimestep,'K/step'
1561                        print*,'In moistadj MIN atmospheric energy change   =',dtmoist_min*ptimestep,'K/step'
1562                     endif
1563
1564                     call planetwide_sumval(massarea(:,:)*dqmoist(:,:,igcm_h2o_vap)*ptimestep/totarea_planet+        &
1565                                            massarea(:,:)*dqmoist(:,:,igcm_h2o_ice)*ptimestep/totarea_planet,dWtot)
1566                     if (is_master) print*,'In moistadj atmospheric water change    =',dWtot,' kg m-2'
1567
1568                  endif ! end of 'enertest'
1569               else
1570                  ! rneb_man, dqmoist are output of moistadj, but used later on
1571                  ! so set them to zero if moistadj is not called
1572                  rneb_man(:,:)=0
1573                  dqmoist(:,:,:)=0
1574               endif ! end of '(.not.calltherm).and.moistadjustment'
1575
1576               ! Large scale condensation/evaporation.
1577               ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1578               call largescale(ngrid,nlayer,nq,ptimestep,pplev,pplay,pt,pq,pdt,pdq,dtlscale,dqvaplscale,dqcldlscale,rneb_lsc)
1579
1580               pdt(1:ngrid,1:nlayer) = pdt(1:ngrid,1:nlayer)+dtlscale(1:ngrid,1:nlayer)
1581               pdq(1:ngrid,1:nlayer,igcm_h2o_vap) = pdq(1:ngrid,1:nlayer,igcm_h2o_vap)+dqvaplscale(1:ngrid,1:nlayer)
1582               pdq(1:ngrid,1:nlayer,igcm_h2o_ice) = pdq(1:ngrid,1:nlayer,igcm_h2o_ice)+dqcldlscale(1:ngrid,1:nlayer)
1583
1584               ! Test energy conservation.
1585               if(enertest)then
1586                  lscaledEz(:,:) = cpp*mass(:,:)*dtlscale(:,:)
1587                  do ig=1,ngrid
1588                     lscaledE(ig) = cpp*SUM(mass(:,:)*dtlscale(:,:))
1589                  enddo
1590                  call planetwide_sumval(cpp*massarea(:,:)*dtlscale(:,:)/totarea_planet,dEtot)
1591
1592                  if (is_master) print*,'In largescale atmospheric energy change =',dEtot,' W m-2'
1593
1594                  ! Test water conservation.
1595                  call planetwide_sumval(massarea(:,:)*dqvaplscale(:,:)*ptimestep/totarea_planet+        &
1596                                           SUM(massarea(:,:)*dqcldlscale(:,:))*ptimestep/totarea_planet,dWtot)
1597
1598                  if (is_master) print*,'In largescale atmospheric water change  =',dWtot,' kg m-2'
1599               endif ! end of 'enertest'
1600
1601               ! Compute cloud fraction.
1602               do l = 1, nlayer
1603                  do ig=1,ngrid
1604                     cloudfrac(ig,l)=MAX(rneb_lsc(ig,l),rneb_man(ig,l))
1605                  enddo
1606               enddo
1607
1608            endif ! end of 'watercond'
1609
1610            ! Water ice / liquid precipitation.
1611            ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1612            zdqrain(1:ngrid,1:nlayer,1:nq) = 0.0  !JL18 need to do that everytimestep if mass redis is on.
1613
1614            if(waterrain)then
1615
1616               zdqsrain(1:ngrid)    = 0.0
1617               zdqssnow(1:ngrid)    = 0.0
1618
1619               call rain(ngrid,nlayer,nq,ptimestep,pplev,pplay,pphi,pt,pdt,pq,pdq,            &
1620                         zdtrain,zdqrain,zdqsrain,zdqssnow,reevap_precip,cloudfrac)
1621
1622               pdq(1:ngrid,1:nlayer,igcm_h2o_vap) = pdq(1:ngrid,1:nlayer,igcm_h2o_vap) &
1623                                                  + zdqrain(1:ngrid,1:nlayer,igcm_h2o_vap)
1624               pdq(1:ngrid,1:nlayer,igcm_h2o_ice) = pdq(1:ngrid,1:nlayer,igcm_h2o_ice) &
1625                                                  + zdqrain(1:ngrid,1:nlayer,igcm_h2o_ice)
1626               pdt(1:ngrid,1:nlayer) = pdt(1:ngrid,1:nlayer)+zdtrain(1:ngrid,1:nlayer)
1627
1628               dqsurf(1:ngrid,igcm_h2o_vap) = dqsurf(1:ngrid,igcm_h2o_vap)+zdqsrain(1:ngrid)
1629               dqsurf(1:ngrid,igcm_h2o_ice) = dqsurf(1:ngrid,igcm_h2o_ice)+zdqssnow(1:ngrid)
1630
1631               ! Test energy conservation.
1632               if(enertest)then
1633
1634                  call planetwide_sumval(cpp*massarea(:,:)*zdtrain(:,:)/totarea_planet,dEtot)
1635                  if (is_master) print*,'In rain atmospheric T energy change       =',dEtot,' W m-2'
1636                  call planetwide_sumval(massarea(:,:)*zdqrain(:,:,igcm_h2o_ice)/totarea_planet*RLVTT/cpp,dItot_tmp)
1637                  call planetwide_sumval(cell_area(:)*zdqssnow(:)/totarea_planet*RLVTT/cpp,dItot)
1638                  dItot = dItot + dItot_tmp
1639                  call planetwide_sumval(massarea(:,:)*zdqrain(:,:,igcm_h2o_vap)*ptimestep/totarea_planet,dVtot_tmp)
1640                  call planetwide_sumval(cell_area(:)*zdqsrain(:)/totarea_planet*RLVTT/cpp,dVtot)
1641                  dVtot = dVtot + dVtot_tmp
1642                  dEtot = dItot + dVtot
1643
1644                  if (is_master) then
1645                     print*,'In rain dItot =',dItot,' W m-2'
1646                     print*,'In rain dVtot =',dVtot,' W m-2'
1647                     print*,'In rain atmospheric L energy change       =',dEtot,' W m-2'
1648                  endif
1649
1650                  ! Test water conservation
1651                  call planetwide_sumval(massarea(:,:)*zdqrain(:,:,igcm_h2o_vap)*ptimestep/totarea_planet+        &
1652                          massarea(:,:)*zdqrain(:,:,igcm_h2o_ice)*ptimestep/totarea_planet,dWtot)
1653                  call planetwide_sumval((zdqsrain(:)+zdqssnow(:))*cell_area(:)*ptimestep/totarea_planet,dWtots)
1654
1655                  if (is_master) then
1656                          print*,'In rain atmospheric water change        =',dWtot,' kg m-2'
1657                          print*,'In rain surface water change            =',dWtots,' kg m-2'
1658                          print*,'In rain non-cons factor                 =',dWtot+dWtots,' kg m-2'
1659                  endif
1660
1661               endif ! end of 'enertest'
1662
1663            end if ! enf of 'waterrain'
1664
1665         end if ! end of 'water'
1666
1667 ! -------------------------
1668  !   VI.2. Photochemistry
1669  ! -------------------------
1670
1671#ifndef MESOSCALE
1672         IF (photochem) then
1673
1674             DO ig=1,ngrid
1675               array_zero1(ig)=0.0
1676               DO l=1,nlayer
1677                 array_zero2(ig,l)=0.
1678               ENDDO
1679             ENDDO
1680
1681            call calchim_asis(ngrid,nlayer,nq,                          &
1682                        ptimestep,pplay,pplev,pt,pdt,dist_star,mu0,     &
1683                        fract,zzlev,zzlay,zday,pq,pdq,zdqchim,zdqschim, &
1684                        array_zero1,array_zero1,                        &
1685                        pu,pdu,pv,pdv,array_zero2,array_zero2,icount,zdtchim)
1686
1687           ! increment values of tracers:
1688           iesp = 0
1689           DO iq=1,nq   ! loop on all tracers; tendencies for non-chemistry
1690                        ! tracers is zero anyways
1691                        ! September 2020: flag is_chim to increment only on chemical species
1692             IF (is_chim(iq)==1) THEN
1693               iesp = iesp + 1
1694               DO l=1,nlayer
1695                 DO ig=1,ngrid
1696                   pdq(ig,l,iq)=pdq(ig,l,iq)+zdqchim(ig,l,iesp)
1697                 ENDDO
1698               ENDDO
1699             ENDIF
1700           ENDDO ! of DO iq=1,nq
1701
1702
1703           ! increment surface values of tracers:
1704           DO iq=1,nq ! loop on all tracers; tendencies for non-chemistry
1705                      ! tracers is zero anyways
1706             DO ig=1,ngrid
1707!               dqsurf(ig,iq)=dqsurf(ig,iq)+zdqschim(ig,iq)
1708             ENDDO
1709           ENDDO ! of DO iq=1,nq
1710
1711           ! increment values of temperature:
1712           pdt(1:ngrid,1:nlayer)=pdt(1:ngrid,1:nlayer)+zdtchim(1:ngrid,1:nlayer)
1713
1714         END IF  ! of IF (photochem)
1715#endif
1716
1717
1718  ! ------------------------------------------
1719  !   VI.3.a Generic Condensable Species (GCS)
1720  ! ------------------------------------------
1721
1722         if (generic_condensation) then
1723            if ((.not.water).and.(.not.calltherm).and.moistadjustment_generic) then
1724               write(*,*) "moist adjustment for GCS"
1725               dqmoist(1:ngrid,1:nlayer,1:nq)=0.
1726               dtmoist(1:ngrid,1:nlayer)=0.
1727
1728               ! Moist Convective Adjustment.
1729               ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1730               call moistadj_generic(ngrid,nlayer,nq,pt,pq,pdq,pplev,pplay,dtmoist,dqmoist,ptimestep,rneb_man)
1731
1732               pdq(1:ngrid,1:nlayer,1:nq) = pdq(1:ngrid,1:nlayer,1:nq)     &
1733                                                  + dqmoist(1:ngrid,1:nlayer,1:nq)
1734               pdt(1:ngrid,1:nlayer) = pdt(1:ngrid,1:nlayer)+dtmoist(1:ngrid,1:nlayer)
1735
1736               ! Test energy conservation.
1737               if(enertest)then
1738                  call planetwide_sumval(cpp*massarea(:,:)*dtmoist(:,:)/totarea_planet,dEtot)
1739                  call planetwide_maxval(dtmoist(:,:),dtmoist_max)
1740                  call planetwide_minval(dtmoist(:,:),dtmoist_min)
1741                  madjdEz(:,:)=cpp*mass(:,:)*dtmoist(:,:)
1742
1743                  do ig=1,ngrid
1744                     madjdE(ig) = cpp*SUM(mass(:,:)*dtmoist(:,:))
1745                  enddo
1746
1747                  if (is_master) then
1748                     print*,'In moistadj_generic atmospheric energy change   =',dEtot,' W m-2'
1749                     print*,'In moistadj_generic MAX atmospheric energy change   =',dtmoist_max*ptimestep,'K/step'
1750                     print*,'In moistadj_generic MIN atmospheric energy change   =',dtmoist_min*ptimestep,'K/step'
1751                  endif
1752
1753                  ! igcm_generic_vap & igcm_generic_ice are not declared below
1754                  call planetwide_sumval(massarea(:,:)*dqmoist(:,:,1)*ptimestep/totarea_planet+        &
1755                                         massarea(:,:)*dqmoist(:,:,2)*ptimestep/totarea_planet,dWtot)
1756                  if (is_master) print*,'In moistadj_generic atmospheric GCS change    =',dWtot,' kg m-2'
1757
1758               endif ! end of 'enertest'
1759            else
1760               ! rneb_man, dqmoist are output of moistadj, but used later on
1761               ! so set them to zero if moistadj is not called
1762               rneb_man(:,:)=0
1763               dqmoist(:,:,:)=0
1764            endif ! end of '(.not.calltherm).and.moistadjustment_generic'
1765
1766            call condensation_generic(ngrid,nlayer,nq,ptimestep,pplev,pplay,   &
1767                                          pt,pq,pdt,pdq,dt_generic_condensation, &
1768                                          dqvaplscale_generic,dqcldlscale_generic,rneb_generic)
1769            pdt(1:ngrid,1:nlayer) = pdt(1:ngrid,1:nlayer)+dt_generic_condensation(1:ngrid,1:nlayer)
1770            pdq(1:ngrid,1:nlayer,1:nq) = pdq(1:ngrid,1:nlayer,1:nq)+dqvaplscale_generic(1:ngrid,1:nlayer,1:nq)
1771            pdq(1:ngrid,1:nlayer,1:nq) = pdq(1:ngrid,1:nlayer,1:nq)+dqcldlscale_generic(1:ngrid,1:nlayer,1:nq)
1772
1773            if(enertest)then
1774               do ig=1,ngrid
1775                  genericconddE(ig) = cpp*SUM(mass(:,:)*dt_generic_condensation(:,:))
1776               enddo
1777
1778               call planetwide_sumval(cpp*massarea(:,:)*dt_generic_condensation(:,:)/totarea_planet,dEtot)
1779
1780               if (is_master) print*,'In generic condensation atmospheric energy change =',dEtot,' W m-2'
1781            end if
1782
1783            if (.not. water) then
1784               ! Compute GCS (Generic Condensable Specie) cloud fraction. For now we can not have both water cloud fraction and GCS cloud fraction
1785               ! Water is the priority
1786               ! If you have set water and generic_condensation, then cloudfrac will be water cloudfrac
1787               !
1788               ! If you have set generic_condensation (and not water) and you have set several GCS
1789               ! then cloudfrac will be only the cloudfrac of the last generic tracer
1790               ! (Because it is rewritten every tracer in the loop)
1791               !
1792               ! Maybe one should create a cloudfrac_generic(ngrid,nlayer,nq) with 3 dimensions, the last one for tracers
1793
1794               ! Let's loop on tracers
1795               cloudfrac(:,:)=0.0
1796               do iq=1,nq
1797                  call generic_tracer_index(nq,iq,igcm_generic_vap,igcm_generic_ice,call_ice_vap_generic)
1798                  if (call_ice_vap_generic) then ! to call only one time the ice/vap pair of a tracer
1799                     do l = 1, nlayer
1800                        do ig=1,ngrid
1801                           cloudfrac(ig,l)=rneb_generic(ig,l,iq)
1802                        enddo
1803                     enddo
1804                  endif
1805            end do ! do iq=1,nq loop on tracers
1806            endif ! .not. water
1807
1808         endif !generic_condensation
1809
1810         !Generic Rain
1811
1812         if (generic_rain) then
1813
1814            zdqsrain_generic(1:ngrid,1:nq)    = 0.0
1815            zdqssnow_generic(1:ngrid,1:nq)    = 0.0
1816
1817            call rain_generic(ngrid,nlayer,nq,ptimestep,pplev,pplay,pphi,pt,pdt,pq,pdq,            &
1818                        zdtrain_generic,dq_rain_generic_vap,dq_rain_generic_cld,              &
1819                        zdqsrain_generic,zdqssnow_generic,reevap_precip_generic,cloudfrac)
1820
1821            pdq(1:ngrid,1:nlayer,1:nq) = pdq(1:ngrid,1:nlayer,1:nq) &
1822                                                + dq_rain_generic_vap(1:ngrid,1:nlayer,1:nq)
1823            ! only the parts with indexes of generic vapor tracers are filled in dq_rain_generic_vap, other parts are 0.
1824            pdq(1:ngrid,1:nlayer,1:nq) = pdq(1:ngrid,1:nlayer,1:nq) &
1825                                                + dq_rain_generic_cld(1:ngrid,1:nlayer,1:nq)
1826            ! only the parts with indexes of generic ice(cloud) tracers are filled in dq_rain_generic_cld, other parts are 0.
1827
1828            pdt(1:ngrid,1:nlayer) = pdt(1:ngrid,1:nlayer)+zdtrain_generic(1:ngrid,1:nlayer)
1829
1830            dqsurf(1:ngrid,1:nq) = dqsurf(1:ngrid,1:nq)+zdqsrain_generic(1:ngrid,1:nq)
1831
1832            ! Test energy conservation.
1833            if(enertest)then
1834
1835               call planetwide_sumval(cpp*massarea(:,:)*zdtrain_generic(:,:)/totarea_planet,dEtot)
1836               if (is_master) print*,'In rain_generic atmospheric T energy change       =',dEtot,' W m-2'
1837
1838               ! Test conservationfor each generic condensable specie (GCS) tracer
1839
1840               ! Let's loop on tracers
1841
1842               do iq=1,nq
1843
1844                  call generic_tracer_index(nq,iq,igcm_generic_vap,igcm_generic_ice,call_ice_vap_generic)
1845
1846                  if (call_ice_vap_generic) then ! to call only one time the ice/vap pair of a tracer
1847
1848                     call planetwide_sumval(massarea(:,:)*dq_rain_generic_cld(:,:,igcm_generic_ice)/totarea_planet*RLVTT/cpp,dItot_tmp)
1849                     call planetwide_sumval(cell_area(:)*zdqssnow_generic(:,igcm_generic_ice)/totarea_planet*RLVTT/cpp,dItot)
1850                     dItot = dItot + dItot_tmp
1851                     call planetwide_sumval(massarea(:,:)*dq_rain_generic_vap(:,:,igcm_generic_vap)/totarea_planet*RLVTT/cpp,dVtot_tmp)
1852                     call planetwide_sumval(cell_area(:)*zdqsrain_generic(:,igcm_generic_ice)/totarea_planet*RLVTT/cpp,dVtot)
1853                     dVtot = dVtot + dVtot_tmp
1854                     dEtot = dItot + dVtot
1855
1856                     if (is_master) then
1857                        print*,'In rain_generic dItot =',dItot,' W m-2'
1858                        print*,'In rain_generic dVtot =',dVtot,' W m-2'
1859                        print*,'In rain_generic atmospheric L energy change       =',dEtot,' W m-2'
1860                     endif
1861
1862                     call planetwide_sumval(massarea(:,:)*dq_rain_generic_vap(:,:,igcm_generic_vap)*ptimestep/totarea_planet+        &
1863                           massarea(:,:)*dq_rain_generic_cld(:,:,igcm_generic_ice)*ptimestep/totarea_planet,dWtot)
1864                     call planetwide_sumval((zdqsrain_generic(:,igcm_generic_ice)+zdqssnow_generic(:,igcm_generic_ice))*cell_area(:)*ptimestep/totarea_planet,dWtots)
1865
1866                     if (is_master) then
1867                           print*,'In rain_generic atmospheric generic tracer change        =',dWtot,' kg m-2'
1868                           print*,'In rain_generic surface generic tracer change            =',dWtots,' kg m-2'
1869                           print*,'In rain_generic non-cons factor                 =',dWtot+dWtots,' kg m-2'
1870                     endif
1871
1872                  endif
1873
1874               end do ! do iq=1,nq loop on tracers
1875
1876            endif ! end of 'enertest'
1877
1878         endif !generic_rain
1879
1880  ! -------------------------
1881  !   VI.3.b. Sedimentation.
1882  ! -------------------------
1883         if (sedimentation) then
1884
1885            zdqsed(1:ngrid,1:nlayer,1:nq) = 0.0
1886            zdqssed(1:ngrid,1:nq)  = 0.0
1887
1888            if(watertest)then
1889
1890               iq=igcm_h2o_ice
1891               call planetwide_sumval(massarea(:,:)*pq(:,:,iq)*ptimestep/totarea_planet,dWtot)
1892               call planetwide_sumval(massarea(:,:)*pdq(:,:,iq)*ptimestep/totarea_planet,dWtots)
1893               if (is_master) then
1894                        print*,'Before sedim pq  =',dWtot,' kg m-2'
1895                  print*,'Before sedim pdq =',dWtots,' kg m-2'
1896               endif
1897            endif
1898
1899            call callsedim(ngrid,nlayer,ptimestep,           &
1900                          pplev,zzlev,pt,pdt,pq,pdq,        &
1901                          zdqsed,zdqssed,nq)
1902
1903            if(watertest)then
1904               iq=igcm_h2o_ice
1905               call planetwide_sumval(massarea(:,:)*pq(:,:,iq)*ptimestep/totarea_planet,dWtot)
1906               call planetwide_sumval(massarea(:,:)*pdq(:,:,iq)*ptimestep/totarea_planet,dWtots)
1907               if (is_master) then
1908                        print*,'After sedim pq  =',dWtot,' kg m-2'
1909                        print*,'After sedim pdq =',dWtots,' kg m-2'
1910                 endif
1911            endif
1912
1913            ! Whether it falls as rain or snow depends only on the surface temperature
1914            pdq(1:ngrid,1:nlayer,1:nq) = pdq(1:ngrid,1:nlayer,1:nq) + zdqsed(1:ngrid,1:nlayer,1:nq)
1915            dqsurf(1:ngrid,1:nq) = dqsurf(1:ngrid,1:nq) + zdqssed(1:ngrid,1:nq)
1916
1917            ! Test water conservation
1918            if(watertest)then
1919               call planetwide_sumval(massarea(:,:)*(zdqsed(:,:,igcm_h2o_vap)+zdqsed(:,:,igcm_h2o_ice))*ptimestep/totarea_planet,dWtot)
1920               call planetwide_sumval((zdqssed(:,igcm_h2o_vap)+zdqssed(:,igcm_h2o_ice))*cell_area(:)*ptimestep/totarea_planet,dWtots)
1921               if (is_master) then
1922                        print*,'In sedim atmospheric ice change         =',dWtot,' kg m-2'
1923                        print*,'In sedim surface ice change             =',dWtots,' kg m-2'
1924                        print*,'In sedim non-cons factor                =',dWtot+dWtots,' kg m-2'
1925               endif
1926            endif
1927
1928         end if ! end of 'sedimentation'
1929
1930
1931  ! ---------------
1932  !   VI.4. Updates
1933  ! ---------------
1934
1935         ! Updating Atmospheric Mass and Tracers budgets.
1936         if(mass_redistrib) then
1937
1938            zdmassmr(1:ngrid,1:nlayer) = mass(1:ngrid,1:nlayer) *     &
1939               (   zdqevap(1:ngrid,1:nlayer)                          &
1940                 + zdqrain(1:ngrid,1:nlayer,igcm_h2o_vap)             &
1941                 + dqmoist(1:ngrid,1:nlayer,igcm_h2o_vap)             &
1942                 + dqvaplscale(1:ngrid,1:nlayer) )
1943
1944            do ig = 1, ngrid
1945               zdmassmr_col(ig)=SUM(zdmassmr(ig,1:nlayer))
1946            enddo
1947
1948            call writediagfi(ngrid,"mass_evap","mass gain"," ",3,zdmassmr)
1949            call writediagfi(ngrid,"mass_evap_col","mass gain col"," ",2,zdmassmr_col)
1950            call writediagfi(ngrid,"mass","mass","kg/m2",3,mass)
1951
1952            call mass_redistribution(ngrid,nlayer,nq,ptimestep,                     &
1953                                     rnat,capcal,pplay,pplev,pt,tsurf,pq,qsurf,     &
1954                                     pu,pv,pdt,zdtsurf,pdq,pdu,pdv,zdmassmr,        &
1955                                     zdtmr,zdtsurfmr,zdpsrfmr,zdumr,zdvmr,zdqmr,zdqsurfmr)
1956
1957            pdq(1:ngrid,1:nlayer,1:nq) = pdq(1:ngrid,1:nlayer,1:nq) + zdqmr(1:ngrid,1:nlayer,1:nq)
1958            dqsurf(1:ngrid,1:nq)       = dqsurf(1:ngrid,1:nq) + zdqsurfmr(1:ngrid,1:nq)
1959            pdt(1:ngrid,1:nlayer)      = pdt(1:ngrid,1:nlayer) + zdtmr(1:ngrid,1:nlayer)
1960            pdu(1:ngrid,1:nlayer)      = pdu(1:ngrid,1:nlayer) + zdumr(1:ngrid,1:nlayer)
1961            pdv(1:ngrid,1:nlayer)      = pdv(1:ngrid,1:nlayer) + zdvmr(1:ngrid,1:nlayer)
1962            pdpsrf(1:ngrid)            = pdpsrf(1:ngrid) + zdpsrfmr(1:ngrid)
1963            zdtsurf(1:ngrid)           = zdtsurf(1:ngrid) + zdtsurfmr(1:ngrid)
1964
1965         endif
1966
1967
1968  ! ------------------
1969  !   VI.5. Slab Ocean
1970  ! ------------------
1971
1972         if (ok_slab_ocean)then
1973
1974            do ig=1,ngrid
1975               qsurfint(:,igcm_h2o_ice)=qsurf(:,igcm_h2o_ice)
1976            enddo
1977
1978!! These two commented functions are from BC2014 (only kept for record)
1979!!
1980!!            call ocean_slab_ice(ptimestep,                          &
1981!!                                ngrid, knindex, tsea_ice, fluxrad,  &
1982!!                               zdqssnow, qsurf(:,igcm_h2o_ice),    &
1983!!                              - zdqsdif(:,igcm_h2o_vap),            &
1984!!                                flux_sens_lat,tsea_ice, pctsrf_sic, &
1985!!                               taux,tauy,icount)
1986!!            call ocean_slab_get_vars(ngrid,tslab,      &
1987!!                                     sea_ice, flux_o,  &
1988!!                                     flux_g, dt_hdiff, &
1989!!                                     dt_ekman)
1990
1991            call ocean_slab_noice(icount, ptimestep, knon, knindex, &
1992                      zdqssnow, tsea_ice, &
1993                      fluxrad, qsurf(:,igcm_h2o_ice), flux_sens_lat, &
1994                      tsea_ice, taux, tauy, zmasq)
1995
1996            call ocean_slab_ice(icount, ptimestep, knon, knindex, &
1997                      zdqssnow, tsea_ice, &
1998                      fluxrad, qsurf(:,igcm_h2o_ice), flux_sens_lat, &
1999                      tsea_ice, -zdqsdif(:,igcm_h2o_vap), taux, tauy, zmasq)
2000
2001            call ocean_slab_frac(pctsrf_sic, zmasq)
2002
2003            call ocean_slab_get_vars(ngrid, tslab, tice, sea_ice, flux_g, &
2004                      dt_hdiff, dt_ekman, dt_gm)
2005
2006!!!            call ocean_slab_get_vars(ngrid, tslab, tsea_ice, sea_ice, flux_g, &
2007!!!                      dt_hdiff, dt_ekman, dt_gm)
2008
2009!! sea_ice defines the sea ice thickness in kg/m2
2010!! pctsrf_sic defines the percentage of the oceanic grid that is covered by sea ice (between 0 and **almost** 1)
2011!! qsurf(:,igcm_h2o_ice) defines the amount of snow that accumulates on top of the sea ice (in kg/m2) ; note that the snow fraction depends on the amount of snow.
2012!! therefore, beware that qsurf(:,igcm_h2o_ice) has its own meaning for oceanic grid points (when ok_slab_ocean activated)
2013
2014
2015            do ig=1,ngrid
2016               if (nint(rnat(ig)).eq.1)then
2017                  tslab(ig,1) = 0.
2018                  tslab(ig,2) = 0.
2019                  tsea_ice(ig) = 0.
2020!                  tice(ig) = 0.
2021                  sea_ice(ig) = 0.
2022                  pctsrf_sic(ig) = 0.
2023                  qsurf(ig,igcm_h2o_ice) = qsurfint(ig,igcm_h2o_ice)
2024               endif
2025            enddo
2026
2027         endif ! end of 'ok_slab_ocean'
2028
2029
2030  ! -----------------------------
2031  !   VI.6. Surface Tracer Update
2032  ! -----------------------------
2033
2034         if(hydrology)then
2035
2036            call hydrol(ngrid,nq,ptimestep,rnat,tsurf,qsurf,dqsurf,dqs_hyd, &
2037                        capcal,albedo,albedo_bareground,                    &
2038                        albedo_snow_SPECTV,albedo_co2_ice_SPECTV,           &
2039                        mu0,zdtsurf,zdtsurf_hyd,hice,pctsrf_sic,            &
2040                        sea_ice)
2041
2042            zdtsurf(1:ngrid)     = zdtsurf(1:ngrid) + zdtsurf_hyd(1:ngrid)
2043            dqsurf(1:ngrid,1:nq) = dqsurf(1:ngrid,1:nq) + dqs_hyd(1:ngrid,1:nq)
2044
2045
2046            qsurf(1:ngrid,1:nq) = qsurf(1:ngrid,1:nq) + ptimestep*dqsurf(1:ngrid,1:nq)
2047
2048            ! Test energy conservation
2049            if(enertest)then
2050               call planetwide_sumval(cell_area(:)*capcal(:)*zdtsurf_hyd(:)/totarea_planet,dEtots)
2051               if (is_master) print*,'In hydrol surface energy change     =',dEtots,' W m-2'
2052            endif
2053
2054            ! test water conservation
2055            if(watertest)then
2056               call planetwide_sumval(dqs_hyd(:,igcm_h2o_ice)*cell_area(:)*ptimestep/totarea_planet,dWtots)
2057               if (is_master) print*,'In hydrol surface ice change            =',dWtots,' kg m-2'
2058                  call planetwide_sumval(dqs_hyd(:,igcm_h2o_vap)*cell_area(:)*ptimestep/totarea_planet,dWtots)
2059               if (is_master) then
2060                  print*,'In hydrol surface water change          =',dWtots,' kg m-2'
2061                  print*,'---------------------------------------------------------------'
2062               endif
2063            endif
2064
2065         else ! of if (hydrology)
2066
2067            qsurf(1:ngrid,1:nq) = qsurf(1:ngrid,1:nq) + ptimestep*dqsurf(1:ngrid,1:nq)
2068
2069         end if ! of if (hydrology)
2070
2071         ! Add qsurf to qsurf_hist, which is what we save in diagfi.nc. At the same time, we set the water
2072         ! content of ocean gridpoints back to zero, in order to avoid rounding errors in vdifc, rain.
2073         qsurf_hist(:,:) = qsurf(:,:)
2074
2075  ! -----------------------------
2076  !   VI.7. Radioactive Tracers
2077  ! -----------------------------
2078         
2079         call radioactive_tracers(ngrid,nlayer,nq,ptimestep,pq,zdqradio)
2080         pdq(1:ngrid,1:nlayer,1:nq) = pdq(1:ngrid,1:nlayer,1:nq) + zdqradio(1:ngrid,1:nlayer,1:nq)
2081
2082      endif! end of if 'tracer'
2083
2084
2085!------------------------------------------------
2086!   VII. Surface and sub-surface soil temperature
2087!------------------------------------------------
2088
2089
2090      ! Increment surface temperature
2091      if(ok_slab_ocean)then
2092         do ig=1,ngrid
2093           if (nint(rnat(ig)).eq.0)then
2094             zdtsurf(ig)= (tslab(ig,1)              &
2095             + pctsrf_sic(ig)*(tsea_ice(ig)-tslab(ig,1))-tsurf(ig))/ptimestep
2096           endif
2097           tsurf(ig)=tsurf(ig)+ptimestep*zdtsurf(ig)
2098         enddo
2099
2100      else
2101        tsurf(1:ngrid)=tsurf(1:ngrid)+ptimestep*zdtsurf(1:ngrid)
2102      endif ! end of 'ok_slab_ocean'
2103
2104
2105      ! Compute soil temperatures and subsurface heat flux.
2106      if (callsoil) then
2107         call soil(ngrid,nsoilmx,.false.,lastcall,inertiedat,   &
2108                   ptimestep,tsurf,tsoil,capcal,fluxgrd)
2109      endif
2110
2111
2112      if (ok_slab_ocean) then
2113
2114         do ig=1,ngrid
2115
2116            fluxgrdocean(ig)=fluxgrd(ig)
2117            if (nint(rnat(ig)).eq.0) then
2118               capcal(ig)=capcalocean
2119               fluxgrd(ig)=0.
2120!!               fluxgrdocean(ig)=pctsrf_sic(ig)*flux_g(ig)+(1-pctsrf_sic(ig))*(dt_hdiff(ig,1)+dt_ekman(ig,1))
2121               ! Dividing by cell area to have flux in W/m2
2122               fluxgrdocean(ig)=flux_g(ig)+(1-pctsrf_sic(ig))*(dt_hdiff(ig,1)+dt_ekman(ig,1)+dt_gm(ig,1))/cell_area(ig)
2123!               fluxgrdocean(ig)=(flux_g(ig)-fluxabs_sw(ig))+(1-pctsrf_sic(ig))*(dt_hdiff(ig,1)+dt_ekman(ig,1)+dt_gm(ig,1))/cell_area(ig)
2124               do iq=1,nsoilmx
2125                  tsoil(ig,iq)=tsurf(ig)
2126               enddo
2127               if (pctsrf_sic(ig).gt.0.5) then
2128                  capcal(ig)=capcalseaice
2129                  if (qsurf(ig,igcm_h2o_ice).gt.0.) then
2130                     capcal(ig)=capcalsno
2131                  endif
2132               endif
2133            endif
2134
2135         enddo
2136
2137      endif !end of 'ok_slab_ocean'
2138
2139
2140      ! Test energy conservation
2141      if(enertest)then
2142         call planetwide_sumval(cell_area(:)*capcal(:)*zdtsurf(:)/totarea_planet,dEtots)
2143         if (is_master) print*,'Surface energy change                 =',dEtots,' W m-2'
2144      endif
2145
2146
2147!---------------------------------------------------
2148!   VIII. Perform diagnostics and write output files
2149!---------------------------------------------------
2150
2151      ! Note : For output only: the actual model integration is performed in the dynamics.
2152
2153
2154
2155      ! Temperature, zonal and meridional winds.
2156      zt(1:ngrid,1:nlayer) = pt(1:ngrid,1:nlayer) + pdt(1:ngrid,1:nlayer)*ptimestep
2157      zu(1:ngrid,1:nlayer) = pu(1:ngrid,1:nlayer) + pdu(1:ngrid,1:nlayer)*ptimestep
2158      zv(1:ngrid,1:nlayer) = pv(1:ngrid,1:nlayer) + pdv(1:ngrid,1:nlayer)*ptimestep
2159
2160      ! Recast thermal plume vertical velocity array for outputs
2161      IF (calltherm) THEN
2162         DO ig=1,ngrid
2163            DO l=1,nlayer
2164               zw2_bis(ig,l) = zw2(ig,l)
2165               fm_bis(ig,l) = fm(ig,l)
2166            ENDDO
2167         ENDDO
2168      ENDIF
2169
2170      ! Diagnostic.
2171      zdtdyn(1:ngrid,1:nlayer)     = (pt(1:ngrid,1:nlayer)-ztprevious(1:ngrid,1:nlayer)) / ptimestep
2172      ztprevious(1:ngrid,1:nlayer) = zt(1:ngrid,1:nlayer)
2173
2174      zdudyn(1:ngrid,1:nlayer)     = (pu(1:ngrid,1:nlayer)-zuprevious(1:ngrid,1:nlayer)) / ptimestep
2175      zuprevious(1:ngrid,1:nlayer) = zu(1:ngrid,1:nlayer)
2176
2177      if(firstcall)then
2178         zdtdyn(1:ngrid,1:nlayer)=0.0
2179         zdudyn(1:ngrid,1:nlayer)=0.0
2180      endif
2181
2182      ! Dynamical heating diagnostic.
2183      do ig=1,ngrid
2184         fluxdyn(ig)= SUM(zdtdyn(ig,:) *mass(ig,:))*cpp
2185      enddo
2186
2187      ! Tracers.
2188      zq(1:ngrid,1:nlayer,1:nq) = pq(1:ngrid,1:nlayer,1:nq) + pdq(1:ngrid,1:nlayer,1:nq)*ptimestep
2189
2190      ! Surface pressure.
2191      ps(1:ngrid) = pplev(1:ngrid,1) + pdpsrf(1:ngrid)*ptimestep
2192
2193
2194
2195      ! Surface and soil temperature information
2196      call planetwide_sumval(cell_area(:)*tsurf(:)/totarea_planet,Ts1)
2197      call planetwide_minval(tsurf(:),Ts2)
2198      call planetwide_maxval(tsurf(:),Ts3)
2199      if(callsoil)then
2200         TsS = SUM(cell_area(:)*tsoil(:,nsoilmx))/totarea        ! mean temperature at bottom soil layer
2201         if (is_master) then
2202            print*,'          ave[Tsurf]             min[Tsurf]             max[Tsurf]             ave[Tdeep]'
2203            print*,Ts1,Ts2,Ts3,TsS
2204         end if
2205      else
2206         if (is_master) then
2207            print*,'          ave[Tsurf]             min[Tsurf]             max[Tsurf]'
2208            print*,Ts1,Ts2,Ts3
2209         endif
2210      end if
2211
2212
2213      ! Check the energy balance of the simulation during the run
2214      if(corrk)then
2215
2216         call planetwide_sumval(cell_area(:)*fluxtop_dn(:)/totarea_planet,ISR)
2217         call planetwide_sumval(cell_area(:)*fluxabs_sw(:)/totarea_planet,ASR)
2218         call planetwide_sumval(cell_area(:)*fluxtop_lw(:)/totarea_planet,OLR)
2219         call planetwide_sumval(cell_area(:)*fluxgrd(:)/totarea_planet,GND)
2220         call planetwide_sumval(cell_area(:)*fluxdyn(:)/totarea_planet,DYN)
2221         do ig=1,ngrid
2222            if(fluxtop_dn(ig).lt.0.0)then
2223               print*,'fluxtop_dn has gone crazy'
2224               print*,'fluxtop_dn=',fluxtop_dn(ig)
2225               print*,'tau_col=',tau_col(ig)
2226               print*,'aerosol=',aerosol(ig,:,:)
2227               print*,'temp=   ',pt(ig,:)
2228               print*,'pplay=  ',pplay(ig,:)
2229               call abort
2230            endif
2231         end do
2232
2233         if(ngrid.eq.1)then
2234            DYN=0.0
2235         endif
2236
2237         if (is_master) then
2238            print*,'  ISR            ASR            OLR            GND            DYN [W m^-2]'
2239            print*, ISR,ASR,OLR,GND,DYN
2240         endif
2241
2242         if(enertest .and. is_master)then
2243            print*,'SW flux/heating difference SW++ - ASR = ',dEtotSW+dEtotsSW-ASR,' W m-2'
2244            print*,'LW flux/heating difference LW++ - OLR = ',dEtotLW+dEtotsLW+OLR,' W m-2'
2245            print*,'LW energy balance LW++ + ASR = ',dEtotLW+dEtotsLW+ASR,' W m-2'
2246         endif
2247
2248         if(meanOLR .and. is_master)then
2249            if((ngrid.gt.1) .or. (mod(icount-1,diagfi_output_rate).eq.0))then
2250               ! to record global radiative balance
2251               open(92,file="rad_bal.out",form='formatted',position='append')
2252               write(92,*) zday,ISR,ASR,OLR
2253               close(92)
2254               open(93,file="tem_bal.out",form='formatted',position='append')
2255               if(callsoil)then
2256                         write(93,*) zday,Ts1,Ts2,Ts3,TsS
2257               else
2258                  write(93,*) zday,Ts1,Ts2,Ts3
2259               endif
2260               close(93)
2261            endif
2262         endif
2263
2264      endif ! end of 'corrk'
2265
2266
2267      ! Diagnostic to test radiative-convective timescales in code.
2268      if(testradtimes)then
2269         open(38,file="tau_phys.out",form='formatted',position='append')
2270         ig=1
2271         do l=1,nlayer
2272            write(38,*) -1./pdt(ig,l),pt(ig,l),pplay(ig,l)
2273         enddo
2274         close(38)
2275         print*,'As testradtimes enabled,'
2276         print*,'exiting physics on first call'
2277         call abort
2278      endif
2279
2280
2281      ! Compute column amounts (kg m-2) if tracers are enabled.
2282      if(tracer)then
2283         qcol(1:ngrid,1:nq)=0.0
2284         do iq=1,nq
2285            do ig=1,ngrid
2286               qcol(ig,iq) = SUM( zq(ig,1:nlayer,iq) * mass(ig,1:nlayer))
2287            enddo
2288         enddo
2289
2290         ! Generalised for arbitrary aerosols now. By LK
2291         reffcol(1:ngrid,1:naerkind)=0.0
2292         if(co2cond.and.(iaero_co2.ne.0))then
2293            call co2_reffrad(ngrid,nlayer,nq,zq,reffrad(1,1,iaero_co2))
2294            do ig=1,ngrid
2295               reffcol(ig,iaero_co2) = SUM(zq(ig,1:nlayer,igcm_co2_ice)*reffrad(ig,1:nlayer,iaero_co2)*mass(ig,1:nlayer))
2296            enddo
2297         endif
2298         if(water.and.(iaero_h2o.ne.0))then
2299            call h2o_reffrad(ngrid,nlayer,zq(1,1,igcm_h2o_ice),zt, &
2300                             reffrad(1,1,iaero_h2o),nueffrad(1,1,iaero_h2o))
2301            do ig=1,ngrid
2302               reffcol(ig,iaero_h2o) = SUM(zq(ig,1:nlayer,igcm_h2o_ice)*reffrad(ig,1:nlayer,iaero_h2o)*mass(ig,1:nlayer))
2303            enddo
2304         endif
2305
2306      endif ! end of 'tracer'
2307
2308
2309      ! Test for water conservation.
2310      if(water)then
2311
2312         call planetwide_sumval(cell_area(:)*qsurf_hist(:,igcm_h2o_ice)/totarea_planet,icesrf)
2313         call planetwide_sumval(cell_area(:)*qsurf_hist(:,igcm_h2o_vap)/totarea_planet,liqsrf)
2314         call planetwide_sumval(cell_area(:)*qcol(:,igcm_h2o_ice)/totarea_planet,icecol)
2315         call planetwide_sumval(cell_area(:)*qcol(:,igcm_h2o_vap)/totarea_planet,vapcol)
2316
2317         h2otot = icesrf + liqsrf + icecol + vapcol
2318
2319         if (is_master) then
2320            print*,' Total water amount [kg m^-2]: ',h2otot
2321            print*,' Surface ice    Surface liq.   Atmos. con.     Atmos. vap. [kg m^-2] '
2322            print*, icesrf,liqsrf,icecol,vapcol
2323         endif
2324
2325         if(meanOLR .and. is_master)then
2326            if((ngrid.gt.1) .or. (mod(icount-1,diagfi_output_rate).eq.0))then
2327               ! to record global water balance
2328               open(98,file="h2o_bal.out",form='formatted',position='append')
2329               write(98,*) zday,icesrf,liqsrf,icecol,vapcol
2330               close(98)
2331            endif
2332         endif
2333
2334      endif
2335
2336
2337      ! Calculate RH (Relative Humidity) for diagnostic.
2338      if(water)then
2339
2340         do l = 1, nlayer
2341            do ig=1,ngrid
2342               call Psat_water(zt(ig,l),pplay(ig,l),psat_tmp,qsat(ig,l))
2343               RH(ig,l) = zq(ig,l,igcm_h2o_vap) / qsat(ig,l)
2344            enddo
2345         enddo
2346
2347         ! Compute maximum possible H2O column amount (100% saturation).
2348         do ig=1,ngrid
2349            H2Omaxcol(ig) = SUM( qsat(ig,:) * mass(ig,:))
2350         enddo
2351
2352      endif ! end of 'water'
2353
2354      ! Calculate RH_generic (Generic Relative Humidity) for diagnostic.
2355      if(generic_condensation)then
2356         RH_generic(:,:,:)=0.0
2357         do iq=1,nq
2358
2359            call generic_tracer_index(nq,iq,igcm_generic_vap,igcm_generic_ice,call_ice_vap_generic)
2360
2361            if (call_ice_vap_generic) then ! to call only one time the ice/vap pair of a tracer
2362
2363               do l = 1, nlayer
2364                  do ig=1,ngrid
2365                     call Psat_generic(zt(ig,l),pplay(ig,l),metallicity,psat_tmp_generic,qsat_generic(ig,l,iq))
2366                     RH_generic(ig,l,iq) = zq(ig,l,igcm_generic_vap) / qsat_generic(ig,l,iq)
2367                  enddo
2368               enddo
2369
2370            end if
2371
2372         end do ! iq=1,nq
2373
2374      endif ! end of 'generic_condensation'
2375
2376
2377      if (is_master) print*,'--> Ls =',zls*180./pi
2378
2379
2380! -------------------------
2381!   IX. Thermosphere
2382! -------------------------
2383      if (callthermos) then
2384        call conduction(ngrid,nlayer,nq,ptimestep,pplay,pplev,  &
2385                          pt,tsurf,zzlev,zzlay,muvar,pq,firstcall,zdtconduc)
2386        pdt(1:ngrid,1:nlayer)=pdt(1:ngrid,1:nlayer)+zdtconduc(1:ngrid,1:nlayer)
2387      endif ! of if (callthermos)
2388
2389
2390!----------------------------------------------------------------------
2391!        Writing NetCDF file  "RESTARTFI" at the end of the run
2392!----------------------------------------------------------------------
2393
2394!        Note: 'restartfi' is stored just before dynamics are stored
2395!              in 'restart'. Between now and the writting of 'restart',
2396!              there will have been the itau=itau+1 instruction and
2397!              a reset of 'time' (lastacll = .true. when itau+1= itaufin)
2398!              thus we store for time=time+dtvr
2399
2400
2401
2402      if(lastcall) then
2403         ztime_fin = ptime + (ptimestep/daysec)
2404
2405#ifndef MESOSCALE
2406
2407         !if (ngrid.ne.1) then
2408            write(*,*)'PHYSIQ: for physdem ztime_fin =',ztime_fin
2409
2410            if (ok_slab_ocean) then
2411              ! fetch "ocean variables" to ensure they are stored
2412              call ocean_slab_get_vars(ngrid, tslab, tice, sea_ice, flux_g, &
2413                                       dt_hdiff, dt_ekman, dt_gm)
2414            endif
2415
2416            call physdem1("restartfi.nc",nsoilmx,ngrid,nlayer,nq, &
2417                          ptimestep,ztime_fin,                    &
2418                          tsurf,tsoil,emis,albedo,q2,qsurf_hist,  &
2419                          cloudfrac,totcloudfrac,hice,            &
2420                          rnat,pctsrf_sic,tslab,tsea_ice,tice,sea_ice)
2421         !endif
2422#endif
2423         if(ok_slab_ocean) then
2424            call ocean_slab_final!(tslab, seaice)
2425         end if
2426
2427    endif ! end of 'lastcall'
2428
2429
2430! -----------------------------------------------------------------
2431! WSTATS: Saving statistics
2432! -----------------------------------------------------------------
2433! ("stats" stores and accumulates key variables in file "stats.nc"
2434!  which can later be used to make the statistic files of the run:
2435!  if flag "callstats" from callphys.def is .true.)
2436
2437
2438         call wstats(ngrid,"ps","Surface pressure","Pa",2,ps)
2439         call wstats(ngrid,"tsurf","Surface temperature","K",2,tsurf)
2440         call wstats(ngrid,"fluxsurf_lw",                               &
2441                     "Thermal IR radiative flux to surface","W.m-2",2,  &
2442                     fluxsurf_lw)
2443         call wstats(ngrid,"fluxtop_lw",                                &
2444                     "Thermal IR radiative flux to space","W.m-2",2,    &
2445                     fluxtop_lw)
2446
2447!            call wstats(ngrid,"fluxsurf_sw",                               &
2448!                        "Solar radiative flux to surface","W.m-2",2,       &
2449!                         fluxsurf_sw_tot)
2450!            call wstats(ngrid,"fluxtop_sw",                                &
2451!                        "Solar radiative flux to space","W.m-2",2,         &
2452!                        fluxtop_sw_tot)
2453
2454
2455         call wstats(ngrid,"ISR","incoming stellar rad.","W m-2",2,fluxtop_dn)
2456         call wstats(ngrid,"ASR","absorbed stellar rad.","W m-2",2,fluxabs_sw)
2457         call wstats(ngrid,"OLR","outgoing longwave rad.","W m-2",2,fluxtop_lw)
2458         !call wstats(ngrid,"ALB","Surface albedo"," ",2,albedo_equivalent)
2459         !call wstats(ngrid,"ALB_1st","First Band Surface albedo"," ",2,albedo(:,1))
2460         call wstats(ngrid,"p","Pressure","Pa",3,pplay)
2461         call wstats(ngrid,"temp","Atmospheric temperature","K",3,zt)
2462         call wstats(ngrid,"u","Zonal (East-West) wind","m.s-1",3,zu)
2463         call wstats(ngrid,"v","Meridional (North-South) wind","m.s-1",3,zv)
2464         call wstats(ngrid,"w","Vertical (down-up) wind","m.s-1",3,pw)
2465         call wstats(ngrid,"q2","Boundary layer eddy kinetic energy","m2.s-2",3,q2)
2466
2467         if (tracer) then
2468            do iq=1,nq
2469               call wstats(ngrid,noms(iq),noms(iq),'kg/kg',3,zq(1,1,iq))
2470               call wstats(ngrid,trim(noms(iq))//'_surf',trim(noms(iq))//'_surf',  &
2471                           'kg m^-2',2,qsurf(1,iq) )
2472               call wstats(ngrid,trim(noms(iq))//'_col',trim(noms(iq))//'_col',    &
2473                          'kg m^-2',2,qcol(1,iq) )
2474
2475!              call wstats(ngrid,trim(noms(iq))//'_reff',                          &
2476!                          trim(noms(iq))//'_reff',                                   &
2477!                          'm',3,reffrad(1,1,iq))
2478
2479            end do
2480
2481            if (water) then
2482               vmr=zq(1:ngrid,1:nlayer,igcm_h2o_vap)*mugaz/mmol(igcm_h2o_vap)
2483               call wstats(ngrid,"vmr_h2ovapor",                             &
2484                           "H2O vapour volume mixing ratio","mol/mol",       &
2485                           3,vmr)
2486            endif
2487
2488         endif ! end of 'tracer'
2489
2490         if(watercond.and.CLFvarying)then
2491            call wstats(ngrid,"rneb_man","H2O cloud fraction (conv)"," ",3,rneb_man)
2492            call wstats(ngrid,"rneb_lsc","H2O cloud fraction (large scale)"," ",3,rneb_lsc)
2493            call wstats(ngrid,"CLF","H2O cloud fraction"," ",3,cloudfrac)
2494            call wstats(ngrid,"CLFt","H2O column cloud fraction"," ",2,totcloudfrac)
2495            call wstats(ngrid,"RH","relative humidity"," ",3,RH)
2496         endif
2497
2498         if (ok_slab_ocean) then
2499            call wstats(ngrid,"dt_hdiff1","dt_hdiff1","W m-2",2,dt_hdiff(:,1))
2500            call wstats(ngrid,"dt_hdiff2","dt_hdiff2","W m-2",2,dt_hdiff(:,2))
2501            call wstats(ngrid,"dt_ekman1","dt_ekman1","W m-2",2,dt_ekman(:,1))
2502            call wstats(ngrid,"dt_ekman2","dt_ekman2","W m-2",2,dt_ekman(:,2))
2503            call wstats(ngrid,"dt_gm1","dt_gm1","W m-2",2,dt_gm(:,1))
2504            call wstats(ngrid,"dt_gm2","dt_gm2","W m-2",2,dt_gm(:,2))
2505            call wstats(ngrid,"tslab1","tslab1","K",2,tslab(:,1))
2506            call wstats(ngrid,"tslab2","tslab2","K",2,tslab(:,2))
2507            call wstats(ngrid,"pctsrf_sic","pct ice/sea","",2,pctsrf_sic)
2508            call wstats(ngrid,"tsea_ice","top layer temp, snow/ice","K",2,tsea_ice)
2509!            call wstats(ngrid,"tice","sea ice temperature","K",2,tice)
2510            call wstats(ngrid,"sea_ice","sea ice","kg/m2",2,sea_ice)
2511            call wstats(ngrid,"rnat","nature of the surface","",2,rnat)
2512         endif
2513
2514         if(lastcall.and.callstats) then
2515            write (*,*) "Writing stats..."
2516            call mkstats(ierr)
2517         endif
2518
2519
2520#ifndef MESOSCALE
2521
2522!-----------------------------------------------------------------------------------------------------
2523!           OUTPUT in netcdf file "DIAGFI.NC", containing any variable for diagnostic
2524!
2525!             Note 1 : output with  period "diagfi_output_rate", set in "run.def"
2526!
2527!             Note 2 : writediagfi can also be called from any other subroutine for any variable,
2528!                      but its preferable to keep all the calls in one place ...
2529!-----------------------------------------------------------------------------------------------------
2530
2531      call write_output("Ls","solar longitude","deg",zls*180./pi)
2532      call write_output("Lss","sub solar longitude","deg",zlss*180./pi)
2533      call write_output("RA","right ascension","deg",right_ascen*180./pi)
2534      call write_output("Declin","solar declination","deg",declin*180./pi)
2535      call write_output("dist_star","dist_star","AU",dist_star)
2536
2537      call write_output("tsurf","Surface temperature","K",tsurf)
2538      call write_output("ps","Surface pressure","Pa",ps)
2539      call write_output("emis","Emissivity","",emis)
2540      call write_output("temperature","temperature","K",zt)
2541      call write_output("teta","potential temperature","K",zh)
2542      call write_output("u","Zonal wind","m.s-1",zu)
2543      call write_output("v","Meridional wind","m.s-1",zv)
2544      call write_output("w","Vertical wind","m.s-1",pw)
2545      call write_output("p","Pressure","Pa",pplay)
2546      call write_output("omega","omega","Pa/s",omega)
2547
2548!     Subsurface temperatures
2549!        call writediagsoil(ngrid,"tsurf","Surface temperature","K",2,tsurf)
2550
2551      ! Oceanic layers
2552      if(ok_slab_ocean) then
2553         call write_output("pctsrf_sic","pct ice/sea","",pctsrf_sic)
2554         call write_output("tsea_ice","top layer temp, snow/ice","K",tsea_ice)
2555!         call write_output("tice","sea ice temperature","K",tice)
2556         call write_output("sea_ice","sea ice","kg/m2",sea_ice)
2557         call write_output("tslab1","tslab1","K",tslab(:,1))
2558         call write_output("tslab2","tslab2","K",tslab(:,2))
2559         call write_output("dt_hdiff1","dt_hdiff1","W m-2",dt_hdiff(:,1))
2560         call write_output("dt_hdiff2","dt_hdiff2","W m-2",dt_hdiff(:,2))
2561         call write_output("dt_ekman1","dt_ekman1","W m-2",dt_ekman(:,1))
2562         call write_output("dt_ekman2","dt_ekman2","W m-2",dt_ekman(:,2))
2563         call write_output("dt_gm1","dt_gm1","W m-2",dt_gm(:,1))
2564         call write_output("dt_gm2","dt_gm2","W m-2",dt_gm(:,2))
2565         call write_output("rnat","nature of the surface","",rnat)
2566         call write_output("sensibFlux","sensible heat flux","w.m^-2",sensibFlux)
2567         call write_output("latentFlux","latent heat flux","w.m^-2",zdqsdif(:,igcm_h2o_vap)*RLVTT)
2568      endif
2569
2570      ! Thermal plume model
2571      if (calltherm) then
2572         call write_output('entr','Entrainment','kg m$^{-2}$ s$^{-1}$', entr)
2573         call write_output('detr','Detrainment','kg m$^{-2}$ s$^{-1}$', detr)
2574         call write_output('fm','Mass flux','kg m$^{-2}$ s$^{-1}$', fm_bis)
2575         call write_output('w_plm','Squared vertical velocity','m s$^{-1}$', zw2_bis)
2576         call write_output('fraca','Updraft fraction','', fraca)
2577         call write_output("zdttherm","dt due to plumes","K-1 s-1",zdttherm) !ALS24
2578         IF (tracer) THEN
2579            call write_output("zdqtherm","dq due to plumes, iq = 1","kg kg-1 s-1",&
2580                   zdqtherm(1:ngrid,1:nlayer,1)) !ALS24
2581            call write_output("zdqtherm2","dq due to plumes; iq = 2","kg kg-1 s-1",&
2582                   zdqtherm(1:ngrid,1:nlayer,2)) !ALS24
2583         ENDIF
2584      endif
2585
2586!        GW non-oro outputs
2587      if (calllott_nonoro) then
2588         call write_output("dugwno","GW non-oro dU","m/s2", d_u_hin)
2589         call write_output("dvgwno","GW non-oro dV","m/s2", d_v_hin)
2590      endif
2591
2592      ! Total energy balance diagnostics
2593      if(callrad.and.(.not.newtonian))then
2594
2595         call write_output("ALB","Surface albedo"," ",albedo_equivalent)
2596         call write_output("ASR","absorbed stellar rad.","W m-2",fluxabs_sw)
2597         call write_output("ISR","incoming stellar rad.","W m-2",fluxtop_dn)
2598         call write_output("OLR","outgoing longwave rad.","W m-2",fluxtop_lw)
2599         call write_output("DYN","dynamical heat input","W m-2",fluxdyn)
2600         call write_output("shad","rings"," ", fract)
2601!           call writediagfi(ngrid,"ASRcs","absorbed stellar rad (cs).","W m-2",2,fluxabs_sw1)
2602!           call writediagfi(ngrid,"OLRcs","outgoing longwave rad (cs).","W m-2",2,fluxtop_lw1)
2603!           call writediagfi(ngrid,"fluxsurfsw","sw surface flux.","W m-2",2,fluxsurf_sw)
2604!           call writediagfi(ngrid,"fluxsurflw","lw back radiation.","W m-2",2,fluxsurf_lw)
2605!           call writediagfi(ngrid,"fluxsurfswcs","sw surface flux (cs).","W m-2",2,fluxsurf_sw1)
2606!           call writediagfi(ngrid,"fluxsurflwcs","lw back radiation (cs).","W m-2",2,fluxsurf_lw1)
2607!           call writediagfi(ngrid,"netfluxsurflw","lw net surface flux","W m-2",2,net_fluxsurf_lw)
2608
2609         if(ok_slab_ocean) then
2610            call write_output("GND","heat flux from ground","W m-2",fluxgrdocean)
2611         else
2612            call write_output("GND","heat flux from ground","W m-2",fluxgrd)
2613         endif
2614      endif ! end of 'callrad'
2615
2616      if(enertest) then
2617
2618         if (calldifv) then
2619            call write_output("q2","turbulent kinetic energy","J.kg^-1",q2)
2620            call write_output("sensibFlux","sensible heat flux","w.m^-2",sensibFlux)
2621!             call writediagfi(ngrid,"dEzdiff","turbulent diffusion heating (-sensible flux)","w.m^-2",3,dEzdiff)
2622!             call writediagfi(ngrid,"dEdiff","integrated turbulent diffusion heating (-sensible flux)","w.m^-2",2,dEdiff)
2623!             call writediagfi(ngrid,"dEdiffs","In TurbDiff (correc rad+latent heat) surf nrj change","w.m^-2",2,dEdiffs)
2624         endif
2625
2626         if (corrk) then
2627            call write_output("dEzradsw","radiative heating","w.m^-2",dEzradsw)
2628            call write_output("dEzradlw","radiative heating","w.m^-2",dEzradlw)
2629         endif
2630
2631         if(watercond) then
2632            call write_output("lscaledE","heat from largescale","W m-2",lscaledE)
2633            if ((.not.calltherm).and.moistadjustment) then
2634               call write_output("madjdE","heat from moistadj","W m-2",madjdE)
2635            endif
2636            call write_output("qsatatm","atm qsat"," ",qsat)
2637!            call write_output("lscaledEz","heat from largescale","W m-2",lscaledEz)
2638!            call write_output("madjdEz","heat from moistadj","W m-2",madjdEz)
2639!            call write_output("h2o_max_col","maximum H2O column amount","kg.m^-2",H2Omaxcol)
2640         endif
2641
2642         if (generic_condensation) then
2643            call write_output("genericconddE","heat from generic condensation","W m-2",genericconddE)
2644            call write_output("dt_generic_condensation","heating from generic condensation","K s-1",dt_generic_condensation)
2645         endif
2646
2647      endif ! end of 'enertest'
2648
2649        ! Diagnostics of optical thickness
2650        ! Warning this is exp(-tau), I let you postproc with -log to have tau itself - JVO 19
2651        if (diagdtau) then
2652          do nw=1,L_NSPECTV
2653            write(str2,'(i2.2)') nw
2654            call write_output('dtauv'//str2,'Layer optical thickness attenuation in VI band '//str2,'',int_dtauv(:,nlayer:1:-1,nw))
2655          enddo
2656          do nw=1,L_NSPECTI
2657            write(str2,'(i2.2)') nw
2658            call write_output('dtaui'//str2,'Layer optical thickness attenuation in IR band '//str2,'',int_dtaui(:,nlayer:1:-1,nw))
2659          enddo
2660        endif
2661
2662        ! Temporary inclusions for heating diagnostics.
2663         call write_output("zdtsw","SW heating","T s-1",zdtsw)
2664         call write_output("zdtlw","LW heating","T s-1",zdtlw)
2665         call write_output("dtrad","radiative heating","K s-1",dtrad)
2666         call write_output("zdtdyn","Dyn. heating","T s-1",zdtdyn)
2667
2668        if (tracer .or. water) call write_output("dtmoistadj","moist adj heating","K s-1",dtmoist)
2669        if (calladj) call write_output("dtdryadj","dry adj heating","K s-1",zdtadj)
2670
2671        ! For Debugging.
2672        !call writediagfi(ngrid,'rnat','Terrain type',' ',2,real(rnat))
2673        !call writediagfi(ngrid,'pphi','Geopotential',' ',3,pphi)
2674
2675
2676      ! Output aerosols.
2677      if (igcm_co2_ice.ne.0.and.iaero_co2.ne.0) &
2678         call write_output('CO2ice_reff','CO2ice_reff','m',reffrad(:,:,iaero_co2))
2679      if (igcm_h2o_ice.ne.0.and.iaero_h2o.ne.0) &
2680         call write_output('H2Oice_reff','H2Oice_reff','m',reffrad(:,:,iaero_h2o))
2681      if (igcm_co2_ice.ne.0.and.iaero_co2.ne.0) &
2682         call write_output('CO2ice_reffcol','CO2ice_reffcol','um kg m^-2',reffcol(:,iaero_co2))
2683      if (igcm_h2o_ice.ne.0.and.iaero_h2o.ne.0) &
2684         call write_output('H2Oice_reffcol','H2Oice_reffcol','um kg m^-2',reffcol(:,iaero_h2o))
2685
2686      ! Output tracers.
2687      if (tracer) then
2688
2689         do iq=1,nq
2690            call write_output(noms(iq),noms(iq),'kg/kg',zq(:,:,iq))
2691            call write_output(trim(noms(iq))//'_surf',trim(noms(iq))//'_surf',  &
2692                            'kg m^-2',qsurf_hist(:,iq) )
2693            call write_output(trim(noms(iq))//'_col',trim(noms(iq))//'_col',    &
2694                           'kg m^-2',qcol(:,iq) )
2695            ! call write_output(trim(noms(iq))//'_surf',trim(noms(iq))//'_surf',  &
2696            !              'kg m^-2',qsurf(:,iq) )
2697
2698            if(watercond.or.CLFvarying)then
2699               call write_output("rneb_man","H2O cloud fraction (conv)"," ",rneb_man)
2700               call write_output("rneb_lsc","H2O cloud fraction (large scale)"," ",rneb_lsc)
2701               call write_output("CLF","H2O cloud fraction"," ",cloudfrac)
2702               call write_output("CLFt","H2O column cloud fraction"," ",totcloudfrac)
2703               call write_output("RH","relative humidity"," ",RH)
2704               call write_output("vteta","virtual potential temperature","K",zh * (1.+(1./epsi-1.) * &
2705                       zq(1:ngrid,1:nlayer,1)))
2706            endif
2707
2708            if(waterrain)then
2709               call write_output("rain","rainfall","kg m-2 s-1",zdqsrain)
2710               call write_output("snow","snowfall","kg m-2 s-1",zdqssnow)
2711               call write_output("reevap","reevaporation of precipitation","kg m-2 s-1",reevap_precip)
2712            endif
2713
2714            if(generic_condensation)then
2715               call write_output("CLF","GCS cloud fraction"," ",cloudfrac)
2716               !AF24: TODO fix rneb_generic and RH_generic failure with write_output()
2717               ! call write_output("rneb_generic","GCS cloud fraction (generic condensation)"," ",rneb_generic)
2718               ! call write_output("RH_generic","GCS relative humidity"," ",RH_generic)
2719               call writediagfi(ngrid,"rneb_generic","GCS cloud fraction (generic condensation)"," ",3,rneb_generic)
2720               call writediagfi(ngrid,"RH_generic","GCS relative humidity"," ",3,RH_generic)
2721               call write_output("vteta","virtual potential temperature","K",zh * (1.+(1./epsi_generic-1.) * &
2722                       zq(1:ngrid,1:nlayer,1) ))
2723            endif
2724
2725            if(generic_rain)then
2726               call write_output("rain","generic rainfall","kg m-2 s-1",zdqsrain_generic)
2727               call write_output("snow","generic snowfall","kg m-2 s-1",zdqssnow_generic)
2728               call write_output("reevap","generic reevaporation of precipitation","kg m-2 s-1",reevap_precip_generic)
2729            endif
2730
2731            if((hydrology).and.(.not.ok_slab_ocean))then
2732               call write_output("hice","oceanic ice height","m",hice)
2733            endif
2734
2735            call write_output("tau_col","Total aerosol optical depth","[]",tau_col)
2736         enddo ! end of 'nq' loop
2737       endif ! end of 'tracer'
2738
2739      ! Output spectrum.
2740      if(specOLR.and.corrk)then
2741         call writediagspecIR(ngrid,"OLR3D","OLR(lon,lat,band)","W/m^2/cm^-1",3,OLR_nu)
2742         call writediagspecVI(ngrid,"OSR3D","OSR(lon,lat,band)","W/m^2/cm^-1",3,OSR_nu)
2743         call writediagspecVI(ngrid,"GSR3D","GSR(lon,lat,band)","W/m^2/cm^-1",3,GSR_nu)
2744      endif
2745
2746#else
2747   comm_HR_SW(1:ngrid,1:nlayer) = zdtsw(1:ngrid,1:nlayer)
2748   comm_HR_LW(1:ngrid,1:nlayer) = zdtlw(1:ngrid,1:nlayer)
2749   comm_ALBEQ(1:ngrid)=albedo_equivalent(1:ngrid)
2750   if (.not.calldifv) comm_LATENT_HF(:)=0.0
2751   if ((tracer).and.(water)) then
2752     comm_CLOUDFRAC(1:ngrid,1:nlayer)=cloudfrac(1:ngrid,1:nlayer)
2753     comm_TOTCLOUDFRAC(1:ngrid)=totcloudfrac(1:ngrid)
2754     comm_SURFRAIN(1:ngrid)=zdqsrain(1:ngrid)
2755     comm_DQVAP(1:ngrid,1:nlayer)=pdq(1:ngrid,1:nlayer,igcm_h2o_vap)
2756     comm_DQICE(1:ngrid,1:nlayer)=pdq(1:ngrid,1:nlayer,igcm_h2o_ice)
2757     comm_H2OICE_REFF(1:ngrid,1:nlayer)=reffrad(1:ngrid,1:nlayer,iaero_h2o)
2758     comm_REEVAP(1:ngrid)=reevap_precip(1:ngrid)
2759     comm_DTRAIN(1:ngrid,1:nlayer)=zdtrain(1:ngrid,1:nlayer)
2760     comm_DTLSC(1:ngrid,1:nlayer)=dtlscale(1:ngrid,1:nlayer)
2761     comm_RH(1:ngrid,1:nlayer)=RH(1:ngrid,1:nlayer)
2762
2763   else if ((tracer).and.(generic_condensation).and.(.not. water)) then
2764
2765      ! If you have set generic_condensation (and not water) and you have set several GCS
2766      ! then the outputs given to WRF will be only the ones for the last generic tracer
2767      ! (Because it is rewritten every tracer in the loop)
2768      ! WRF can take only one moist tracer
2769
2770      do iq=1,nq
2771         call generic_tracer_index(nq,iq,igcm_generic_vap,igcm_generic_ice,call_ice_vap_generic)
2772
2773         if (call_ice_vap_generic) then ! to call only one time the ice/vap pair of a tracer
2774
2775            reffrad_generic_zeros_for_wrf(:,:) = 1.
2776
2777            comm_CLOUDFRAC(1:ngrid,1:nlayer) = cloudfrac(1:ngrid,1:nlayer)
2778            comm_TOTCLOUDFRAC(1:ngrid) = totcloudfrac(1:ngrid) !??????
2779            comm_SURFRAIN(1:ngrid) = zdqsrain_generic(1:ngrid,iq)
2780            comm_DQVAP(1:ngrid,1:nlayer) = pdq(1:ngrid,1:nlayer,igcm_generic_vap)
2781            comm_DQICE(1:ngrid,1:nlayer)=pdq(1:ngrid,1:nlayer,igcm_generic_ice)
2782            comm_H2OICE_REFF(1:ngrid,1:nlayer) = reffrad_generic_zeros_for_wrf(1:ngrid,1:nlayer) ! for now zeros !
2783            !comm_H2OICE_REFF(1:ngrid,1:nlayer) = 0*zdtrain_generic(1:ngrid,1:nlayer) ! for now zeros !
2784            comm_REEVAP(1:ngrid) = reevap_precip_generic(1:ngrid,iq)
2785            comm_DTRAIN(1:ngrid,1:nlayer) = zdtrain_generic(1:ngrid,1:nlayer)
2786            comm_DTLSC(1:ngrid,1:nlayer) = dt_generic_condensation(1:ngrid,1:nlayer)
2787            comm_RH(1:ngrid,1:nlayer) = RH_generic(1:ngrid,1:nlayer,iq)
2788
2789         endif
2790      end do ! do iq=1,nq loop on tracers
2791
2792   else
2793      comm_CLOUDFRAC(1:ngrid,1:nlayer)=0.
2794      comm_TOTCLOUDFRAC(1:ngrid)=0.
2795      comm_SURFRAIN(1:ngrid)=0.
2796      comm_DQVAP(1:ngrid,1:nlayer)=0.
2797      comm_DQICE(1:ngrid,1:nlayer)=0.
2798      comm_H2OICE_REFF(1:ngrid,1:nlayer)=0.
2799      comm_REEVAP(1:ngrid)=0.
2800      comm_DTRAIN(1:ngrid,1:nlayer)=0.
2801      comm_DTLSC(1:ngrid,1:nlayer)=0.
2802      comm_RH(1:ngrid,1:nlayer)=0.
2803
2804   endif ! if water, if generic_condensation, else
2805
2806   comm_FLUXTOP_DN(1:ngrid)=fluxtop_dn(1:ngrid)
2807   comm_FLUXABS_SW(1:ngrid)=fluxabs_sw(1:ngrid)
2808   comm_FLUXTOP_LW(1:ngrid)=fluxtop_lw(1:ngrid)
2809   comm_FLUXSURF_SW(1:ngrid)=fluxsurf_sw(1:ngrid)
2810   comm_FLUXSURF_LW(1:ngrid)=fluxsurf_lw(1:ngrid)
2811   comm_FLXGRD(1:ngrid)=fluxgrd(1:ngrid)
2812   sensibFlux(1:ngrid) = zflubid(1:ngrid) - capcal(1:ngrid)*zdtsdif(1:ngrid) !!! ????
2813   comm_HR_DYN(1:ngrid,1:nlayer) = zdtdyn(1:ngrid,1:nlayer)
2814
2815!      if (turb_resolved) then
2816!        open(17,file='lsf.txt',form='formatted',status='old')
2817!        rewind(17)
2818!        DO l=1,nlayer
2819!          read(17,*) lsf_dt(l),lsf_dq(l)
2820!        ENDDO
2821!        close(17)
2822!        do ig=1,ngrid
2823!          if ((tracer).and.(water)) then
2824!           pdq(ig,:,igcm_h2o_vap) = pdq(ig,:,igcm_h2o_vap) + lsf_dq(:)
2825!          endif
2826!          pdt(ig,:) = pdt(ig,:) + lsf_dt(:)
2827!          comm_HR_DYN(ig,:) = lsf_dt(:)
2828!        enddo
2829!      endif
2830#endif
2831
2832! XIOS outputs
2833#ifdef CPP_XIOS
2834      ! Send fields to XIOS: (NB these fields must also be defined as
2835      ! <field id="..." /> in context_lmdz_physics.xml to be correctly used)
2836      CALL send_xios_field("controle",tab_cntrl_mod,1)
2837
2838      CALL send_xios_field("ap",ap,1)
2839      CALL send_xios_field("bp",bp,1)
2840      CALL send_xios_field("aps",aps,1)
2841      CALL send_xios_field("bps",bps,1)
2842
2843      IF (water) THEN
2844         CALL send_xios_field('h2o_layer1',zq(:,1,igcm_h2o_vap))
2845         CALL send_xios_field('co2_layer1',zq(:,1,igcm_co2_ice))
2846      ENDIF
2847
2848      if (specOLR .and. corrk) then
2849         call send_xios_field("OLR3D",OLR_nu)
2850         call send_xios_field("IR_Bandwidth",DWNI)
2851         call send_xios_field("VI_Bandwidth",DWNV)
2852         call send_xios_field("OSR3D",OSR_nu)
2853         call send_xios_field("GSR3D",GSR_nu)
2854      endif
2855
2856      if (lastcall.and.is_omp_master) then
2857        write(*,*) "physiq: call xios_context_finalize"
2858        call xios_context_finalize
2859      endif
2860#endif
2861
2862      if (check_physics_outputs) then
2863         ! Check the validity of updated fields at the end of the physics step
2864         call check_physics_fields("end of physiq:", zt, zu, zv, pplev, zq)
2865      endif
2866
2867      icount=icount+1
2868
2869      end subroutine physiq
2870
2871   end module physiq_mod
Note: See TracBrowser for help on using the repository browser.