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

Last change on this file since 3801 was 3773, checked in by afalco, 8 months ago

Generic: allow to write controle in XIOS output.
AF

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