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

Last change on this file since 2704 was 2701, checked in by aslmd, 4 years ago

rename largescale_generic and genericcommon_h

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