netcdf_output_mod.f90 68.6 KB
Newer Older
1
2
! SPDX-FileCopyrightText: FLEXPART 1998-2019, see flexpart_license.txt
! SPDX-License-Identifier: GPL-3.0-or-later
3

4
5
6
7
8
  !*****************************************************************************
  !                                                                            *
  !  This module handles all gridded netcdf output for concentration or        *
  !  residence time and wet and dry deposition output.                         *
  !                                                                            *
9
  !  - writeheader_netcdf generates file including all information previously  *
10
  !    stored in separate header files                                         *
11
  !  - concoutput_netcdf write concentration output and wet and dry deposition *
12
13
14
15
16
17
18
19
20
  !                                                                            *
  !     Author: D. Brunner                                                     *
  !                                                                            *
  !     12 April 2013                                                          *
  !                                                                            *
  ! HSO: 21 Oct 2014
  !  - added option to not writeout releases information by changing 
  !    switch write_releases
  !  - additional updates for FLEXPART 9.x
21
22
23
24
  ! 
  ! ESO 2016
  !  - Deposition fields can be calculated in double precision, see variable
  !    'dep_prec' in par_mod
25
26
  !  - Hardcoded options 'write_vol' and 'write_area' for grid cell
  !    volume and area
27
28
29
30
31
32
33
34
35
36
37
  !*****************************************************************************


module netcdf_output_mod

  use netcdf

  use point_mod, only: ireleasestart,ireleaseend,kindz,&
                       xpoint1,ypoint1,xpoint2,ypoint2,zpoint1,zpoint2,npart,xmass
  use outg_mod,  only: outheight,oroout,densityoutgrid,factor3d,volume,&
                       wetgrid,wetgridsigma,drygrid,drygridsigma,grid,gridsigma,&
38
                       area,arean,volumen, orooutn, areaeast, areanorth, p0out, t0out
39
  use par_mod,   only: dep_prec, sp, dp, maxspec, maxreceptor, nclassunc,&
40
41
                       unitoutrecept,unitoutreceptppt, nxmax,unittmp, &
                       write_p0t0
42
  use com_mod,   only: path,length,ldirect,bdate,ibdate,ibtime,iedate,ietime, &
43
44
45
46
47
48
                       loutstep,loutaver,loutsample,outlon0,outlat0,&
                       numxgrid,numygrid,dxout,dyout,numzgrid, height, &
                       outlon0n,outlat0n,dxoutn,dyoutn,numxgridn,numygridn, &
                       nspec,maxpointspec_act,species,numpoint,&
                       dx,xlon0,dy,ylat0,compoint,method,lsubgrid,lconvection,&
                       ind_source,ind_receptor,nageclass,lage,&
49
50
                       drydep,wetdep,decay,weta_gas,wetb_gas, numbnests, &
                       ccn_aero,in_aero, & ! wetc_in,wetd_in, &
51
                       reldiff,henry,f0,density,dquer,dsigma,dryvel,&
52
                       weightmolar,ohcconst,ohdconst,vsetaver,&
53
54
55
56
57
58
59
                       ! for concoutput_netcdf and concoutput_nest_netcdf
                       nxmin1,nymin1,nz,oro,oron,rho,rhon,&
                       memind,xresoln,yresoln,xrn, xln, yrn,yln,nxn,nyn,&
                       xreceptor,yreceptor,numreceptor,creceptor,iout, &
                       itsplit, lsynctime, ctl, ifine, lagespectra, ipin, &
                       ioutputforeachrelease, iflux, mdomainfill, mquasilag, & 
                       nested_output, ipout, surf_only, linit_cond, &
60
                       flexversion,mpi_mode,DRYBKDEP,WETBKDEP, ps, tt2
61

62
63
  use mean_mod

64
65
  implicit none

66
67
68
  private

  public :: writeheader_netcdf,concoutput_surf_nest_netcdf,concoutput_netcdf,&
69
       &concoutput_nest_netcdf,concoutput_surf_netcdf,fluxoutput_netcdf
70

71
72
73
74
75
76
77
!  include 'netcdf.inc'

  ! parameter for data compression (1-9, 9 = most aggressive)
  integer, parameter :: deflate_level = 9
  logical, parameter :: min_size = .false.   ! if set true, redundant fields (topography) are not written to minimize file size
  character(len=255), parameter :: institution = 'NILU'

78
  integer            :: tpointer=0
79
80
81
82
83
  character(len=255) :: ncfname, ncfnamen

  ! netcdf dimension and variable IDs for main and nested output grid
  integer, dimension(maxspec) :: specID,specIDppt, wdspecID,ddspecID
  integer, dimension(maxspec) :: specIDn,specIDnppt, wdspecIDn,ddspecIDn
84
  integer :: psID, tt2ID
85
86
87
88
89
  integer                     :: timeID, timeIDn
  integer, dimension(6)       :: dimids, dimidsn
  integer, dimension(5)       :: depdimids, depdimidsn
  real,parameter :: eps=nxmax/3.e5

90
!  private:: writemetadata, output_units, nf90_err
91
92
93
94

  ! switch output of release point information on/off
  logical, parameter :: write_releases = .true.

95
96
97
98
  ! switch output of grid cell volume and area on/off
  logical, parameter :: write_vol = .false.
  logical, parameter :: write_area = .false.

99
100
  ! coordinate transformation from internal to world coord
  real :: xp1,yp1,xp2,yp2
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
contains

!****************************************************************
! determine output units (see table 1 in Stohl et al., ACP 2005
!****************************************************************
subroutine output_units(units)
  character(len=15), intent(out) :: units
  if (ldirect.eq.1) then
     ! forward simulation
     if (ind_source.eq.1) then
        if (ind_receptor.eq.1) then
           units = 'ng m-3'   ! hes the kg in Tab1 is only indicating the units of the relase not the output
        else
           units = 'ng kg-1'
        endif
     else
        if (ind_receptor.eq.1) then
           units = 'ng m-3'
        else
           units = 'ng kg-1'
        endif
     endif
  else
     ! backward simulation
     if (ind_source.eq.1) then
        if (ind_receptor.eq.1) then
           units = 's'
        else 
           units = 's m3 kg-1'
        endif
     else
        if (ind_receptor.eq.1) then
           units = 's kg m-3'
        else
           units = 's'
        endif
     endif
  endif
end subroutine output_units


!****************************************************************
! write metadata to netCDF file 
!****************************************************************
subroutine writemetadata(ncid,lnest)

  integer, intent(in) :: ncid
  logical, intent(in) :: lnest
  integer             :: status
  character           :: time*10,date*8,adate*8,atime*6
  character(5)        :: zone
  character(255)      :: login_name, host_name

! gather system information 
  call date_and_time(date,time,zone)
  call getlog(login_name)
  call hostnm(host_name)
  
! hes CF convention requires these attributes
  call nf90_err(nf90_put_att(ncid, nf90_global, 'Conventions', 'CF-1.6'))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'title', 'FLEXPART model output'))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'institution', trim(institution)))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'source', trim(flexversion)//' model output'))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'history', date(1:4)//'-'//date(5:6)// &
       '-'//date(7:8)//' '//time(1:2)//':'//time(3:4)//' '//zone//'  created by '//  &
       trim(login_name)//' on '//trim(host_name)))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'references', &
       'Stohl et al., Atmos. Chem. Phys., 2005, doi:10.5194/acp-5-2461-200'))

  ! attributes describing model run
  !************************************************************************************

  if (lnest) then
     call nf90_err(nf90_put_att(ncid, nf90_global, 'outlon0', outlon0n))
     call nf90_err(nf90_put_att(ncid, nf90_global, 'outlat0', outlat0n))
     call nf90_err(nf90_put_att(ncid, nf90_global, 'dxout', dxoutn))
     call nf90_err(nf90_put_att(ncid, nf90_global, 'dyout', dyoutn))
  else
     call nf90_err(nf90_put_att(ncid, nf90_global, 'outlon0', outlon0))
     call nf90_err(nf90_put_att(ncid, nf90_global, 'outlat0', outlat0))
     call nf90_err(nf90_put_att(ncid, nf90_global, 'dxout', dxout))
     call nf90_err(nf90_put_att(ncid, nf90_global, 'dyout', dyout))
  endif
184
!   vertical levels stored in grid structure
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248

  ! COMMAND file settings
  call nf90_err(nf90_put_att(ncid, nf90_global, 'ldirect', ldirect))
  write(adate,'(i8.8)') ibdate
  write(atime,'(i6.6)') ibtime
  call nf90_err(nf90_put_att(ncid, nf90_global, 'ibdate', adate))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'ibtime', atime))
  write(adate,'(i8.8)') iedate
  write(atime,'(i6.6)') ietime
  call nf90_err(nf90_put_att(ncid, nf90_global, 'iedate', adate))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'ietime', atime))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'loutstep', loutstep))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'loutaver', loutaver))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'loutsample', loutsample))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'itsplit', itsplit))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'lsynctime', lsynctime))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'ctl', ctl))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'ifine', ifine))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'iout', iout))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'ipout', ipout))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'lsubgrid', lsubgrid))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'lconvection', lconvection))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'lagespectra', lagespectra))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'ipin', ipin))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'ioutputforeachrelease', ioutputforeachrelease))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'iflux', iflux))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'mdomainfill', mdomainfill))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'ind_source', ind_source))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'ind_receptor', ind_receptor))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'mquasilag', mquasilag))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'nested_output', nested_output))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'surf_only', surf_only))
  call nf90_err(nf90_put_att(ncid, nf90_global, 'linit_cond', linit_cond))
 
end subroutine writemetadata


!****************************************************************
! netcdf error message handling
!****************************************************************
subroutine nf90_err(status)
  integer, intent (in) :: status
   if(status /= nf90_noerr) then
      print *, trim(nf90_strerror(status))
      stop 'Stopped'
    end if
end subroutine nf90_err


!****************************************************************
! Create netcdf file and write header/metadata information
! lnest = .false. : Create main output file
! lnest = .true.  : Create nested output file
!****************************************************************
subroutine writeheader_netcdf(lnest)

  implicit none

  logical, intent(in) :: lnest

  integer :: ncid, sID, wdsID, ddsID
  integer :: timeDimID, latDimID, lonDimID, levDimID
  integer :: nspecDimID, npointDimID, nageclassDimID, ncharDimID, pointspecDimID
  integer :: tID, lonID, latID, levID, poleID, lageID, oroID
249
  integer :: volID, areaID
250
251
252
253
254
255
256
  integer :: rellng1ID, rellng2ID, rellat1ID, rellat2ID, relzz1ID, relzz2ID
  integer :: relcomID, relkindzID, relstartID, relendID, relpartID, relxmassID
  integer :: nnx, nny 
  integer, dimension(6)       :: dIDs
  integer, dimension(5)       :: depdIDs
  character(len=255)          :: fname
  character(len=15)           :: units
257
  character(len=20)           :: fprefix
258
  character(len=3)            :: anspec
259
260
261
  CHARACTER                   :: adate*8,atime*6,timeunit*32
  !REAL, DIMENSION(1000)       :: coord
  real, allocatable, dimension(:) :: coord
262
263
264
265
266
267

  integer                     :: cache_size
  integer, dimension(6)       :: chunksizes
  integer, dimension(5)       :: dep_chunksizes

  integer                     :: i,ix,jy
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
  integer                     :: test_unit


  ! Check if output directory exists (the netcdf library will
  ! otherwise give an error which can look confusing). 
  ! *********************************************************************
  open(unit=unittmp,file=trim(path(2)(1:length(2)))//'test_dir.txt',status='replace',&
       &err=100)
  close (unittmp, status='delete')
  goto 101
100 write(*,FMT='(80("#"))') 
  write(*,*) 'ERROR: output directory ', trim(path(2)(1:length(2))), ' does not exist&
       & (or failed to write there).' 
  write(*,*) 'EXITING' 
  write(*,FMT='(80("#"))')
  stop
101 continue
285
286
287
288
289
290
291
292
293
294
295
296
297
298

  !************************
  ! Create netcdf file
  !************************

  if (ldirect.eq.1) then
     write(adate,'(i8.8)') ibdate
     write(atime,'(i6.6)') ibtime
     fprefix = 'grid_conc_'
  else
     write(adate,'(i8.8)') iedate
     write(atime,'(i6.6)') ietime
     fprefix = 'grid_time_'
  endif
299
300
  if (DRYBKDEP) fprefix='grid_drydep_'
  if (WETBKDEP) fprefix='grid_wetdep_'
301
302

  if (lnest) then
303
     fname = path(2)(1:length(2))//trim(fprefix)//adate//atime//'_nest.nc'
304
305
306
307
     ncfnamen = fname
     nnx = numxgridn
     nny = numygridn
  else
308
     fname = path(2)(1:length(2))//trim(fprefix)//adate//atime//'.nc'
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
     ncfname = fname
     nnx = numxgrid
     nny = numygrid
  endif

  cache_size = 16 * nnx * nny * numzgrid

  ! setting cache size in bytes. It is set to 4 times the largest data block that is written
  !   size_type x nx x ny x nz
  ! create file

  call nf90_err(nf90_create(trim(fname), cmode = nf90_hdf5, ncid = ncid, &
    cache_size = cache_size))  

  ! create dimensions:
  !*************************
  ! time
  call nf90_err(nf90_def_dim(ncid, 'time', nf90_unlimited, timeDimID))
  timeunit = 'seconds since '//adate(1:4)//'-'//adate(5:6)// &
     '-'//adate(7:8)//' '//atime(1:2)//':'//atime(3:4)

  ! lon
  call nf90_err(nf90_def_dim(ncid, 'longitude', nnx, lonDimID))
  ! lat
  call nf90_err(nf90_def_dim(ncid, 'latitude', nny, latDimID))
  ! level
  call nf90_err(nf90_def_dim(ncid, 'height', numzgrid, levDimID))
  ! number of species
  call nf90_err(nf90_def_dim(ncid, 'numspec', nspec, nspecDimID))
  ! number of release points
  call nf90_err(nf90_def_dim(ncid, 'pointspec', maxpointspec_act, pointspecDimID))
  ! number of age classes
  call nf90_err(nf90_def_dim(ncid, 'nageclass', nageclass, nageclassDimID))
  ! dimension for release point characters
  call nf90_err(nf90_def_dim(ncid, 'nchar', 45, ncharDimID))
  ! number of actual release points
  call nf90_err(nf90_def_dim(ncid, 'numpoint', numpoint, npointDimID))

347

348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
  ! create variables
  !*************************

  ! time
  call nf90_err(nf90_def_var(ncid, 'time', nf90_int, (/ timeDimID /), tID))
  call nf90_err(nf90_put_att(ncid, tID, 'units', timeunit))
  call nf90_err(nf90_put_att(ncid, tID, 'calendar', 'proleptic_gregorian'))
  if (lnest) then
     timeIDn = tID
  else
     timeID = tID
  endif

  ! lon
  call nf90_err(nf90_def_var(ncid, 'longitude', nf90_float, (/ lonDimID /), lonID))
  call nf90_err(nf90_put_att(ncid, lonID, 'long_name', 'longitude in degree east'))
  call nf90_err(nf90_put_att(ncid, lonID, 'axis', 'Lon'))
  call nf90_err(nf90_put_att(ncid, lonID, 'units', 'degrees_east'))
  call nf90_err(nf90_put_att(ncid, lonID, 'standard_name', 'grid_longitude'))
  call nf90_err(nf90_put_att(ncid, lonID, 'description', 'grid cell centers'))

  ! lat
  call nf90_err(nf90_def_var(ncid, 'latitude', nf90_float, (/ latDimID /), latID))
  call nf90_err(nf90_put_att(ncid, latID, 'long_name', 'latitude in degree north'))
  call nf90_err(nf90_put_att(ncid, latID, 'axis', 'Lat'))
  call nf90_err(nf90_put_att(ncid, latID, 'units', 'degrees_north'))
  call nf90_err(nf90_put_att(ncid, latID, 'standard_name', 'grid_latitude'))
  call nf90_err(nf90_put_att(ncid, latID, 'description', 'grid cell centers'))


  ! height
  call nf90_err(nf90_def_var(ncid, 'height', nf90_float, (/ levDimID /), levID))
! call nf90_err(nf90_put_att(ncid, levID, 'axis', 'Z'))
  call nf90_err(nf90_put_att(ncid, levID, 'units', 'meters'))
  call nf90_err(nf90_put_att(ncid, levID, 'positive', 'up'))
  call nf90_err(nf90_put_att(ncid, levID, 'standard_name', 'height'))
  call nf90_err(nf90_put_att(ncid, levID, 'long_name', 'height above ground'))

386
  ! volume
387
388
  if (write_vol) call nf90_err(nf90_def_var(ncid, 'volume', nf90_float, &
       &(/ lonDimID, latDimID, levDimID /), volID))
389
  ! area 
390
391
  if (write_area) call nf90_err(nf90_def_var(ncid, 'area', nf90_float, &
       &(/ lonDimID, latDimID /), areaID))
392

393
394
395
396
397
398
399
400
    ! surfarce pressure / temperature
    if (write_p0t0) then
       call nf90_err(nf90_def_var(ncid, 'pressure', nf90_float, &
            &(/ lonDimID, latDimID, timeDimID /), psID))
       call nf90_err(nf90_def_var(ncid, 'temperature', nf90_float, &
            &(/ lonDimID, latDimID, timeDimID /), tt2ID))
    end if

401

402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
  if (write_releases.eqv..true.) then
    ! release comment
    call nf90_err(nf90_def_var(ncid, 'RELCOM', nf90_char, (/ ncharDimID,npointDimID /), &
         relcomID))
    call nf90_err(nf90_put_att(ncid, relcomID, 'long_name', 'release point name'))
    ! release longitude 1
    call nf90_err(nf90_def_var(ncid, 'RELLNG1', nf90_float, (/ npointDimID /), rellng1ID))
    call nf90_err(nf90_put_att(ncid, rellng1ID, 'units', 'degrees_east'))
    call nf90_err(nf90_put_att(ncid, rellng1ID, 'long_name', &
         'release longitude lower left corner'))
    ! release longitude 2
    call nf90_err(nf90_def_var(ncid, 'RELLNG2', nf90_float, (/ npointDimID /), rellng2ID))
    call nf90_err(nf90_put_att(ncid, rellng2ID, 'units', 'degrees_east'))
    call nf90_err(nf90_put_att(ncid, rellng2ID, 'long_name', &
         'release longitude upper right corner'))
    ! release latitude 1
    call nf90_err(nf90_def_var(ncid, 'RELLAT1', nf90_float, (/ npointDimID /), rellat1ID))
    call nf90_err(nf90_put_att(ncid, rellat1ID, 'units', 'degrees_north'))
    call nf90_err(nf90_put_att(ncid, rellat1ID, 'long_name', &
         'release latitude lower left corner'))
    ! release latitude 2
    call nf90_err(nf90_def_var(ncid, 'RELLAT2', nf90_float, (/ npointDimID /), rellat2ID))
    call nf90_err(nf90_put_att(ncid, rellat2ID, 'units', 'degrees_north'))
    call nf90_err(nf90_put_att(ncid, rellat2ID, 'long_name', &
         'release latitude upper right corner'))

    ! hes: if rotated_ll it would be convenient also to write the the release points in rotated_coordinates

    ! release height bottom
    call nf90_err(nf90_def_var(ncid, 'RELZZ1', nf90_float, (/ npointDimID /), relzz1ID))
    call nf90_err(nf90_put_att(ncid, relzz1ID, 'units', 'meters'))
    call nf90_err(nf90_put_att(ncid, relzz1ID, 'long_name', 'release height bottom'))
    ! release height top
    call nf90_err(nf90_def_var(ncid, 'RELZZ2', nf90_float, (/ npointDimID /), relzz2ID))
    call nf90_err(nf90_put_att(ncid, relzz2ID, 'units', 'meters'))
    call nf90_err(nf90_put_att(ncid, relzz2ID, 'long_name', 'release height top'))
    ! release kind
    call nf90_err(nf90_def_var(ncid, 'RELKINDZ', nf90_int, (/ npointDimID /), relkindzID))
    call nf90_err(nf90_put_att(ncid, relkindzID, 'long_name', 'release kind'))
    ! release start
    call nf90_err(nf90_def_var(ncid, 'RELSTART', nf90_int, (/ npointDimID /), relstartID))
    call nf90_err(nf90_put_att(ncid, relstartID, 'units', 'seconds'))
    call nf90_err(nf90_put_att(ncid, relstartID, 'long_name', &
         'release start relative to simulation start'))
    ! release end
    call nf90_err(nf90_def_var(ncid, 'RELEND', nf90_int, (/ npointDimID /), relendID))
    call nf90_err(nf90_put_att(ncid, relendID, 'units', 'seconds'))
    call nf90_err(nf90_put_att(ncid, relendID, 'long_name', &
         'release end relative to simulation start'))
    ! release particles
    call nf90_err(nf90_def_var(ncid, 'RELPART', nf90_int, (/ npointDimID /), relpartID))
    call nf90_err(nf90_put_att(ncid, relpartID, 'long_name', 'number of release particles'))
    ! release particle masses
    call nf90_err(nf90_def_var(ncid, 'RELXMASS', nf90_float, (/ npointDimID, nspecDimID /), &
         relxmassID))
    call nf90_err(nf90_put_att(ncid, relxmassID, 'long_name', 'total release particle mass'))
  end if
 
  ! age classes
  call nf90_err(nf90_def_var(ncid, 'LAGE', nf90_int, (/ nageclassDimID /), lageID))
  call nf90_err(nf90_put_att(ncid, lageID, 'units', 'seconds'))
  call nf90_err(nf90_put_att(ncid, lageID, 'long_name', 'age class'))

  ! output orography
  if (.not. min_size) then
    call nf90_err(nf90_def_var(ncid, 'ORO', nf90_int, (/ lonDimID, latDimID /), oroID,  &
      deflate_level=deflate_level, chunksizes= (/ nnx, nny /)))
    call nf90_err(nf90_put_att(ncid, oroID, 'standard_name', 'surface altitude'))
    call nf90_err(nf90_put_att(ncid, oroID, 'long_name', 'outgrid surface altitude'))
    call nf90_err(nf90_put_att(ncid, oroID, 'units', 'm'))
  end if

  ! concentration output, wet and dry deposition variables (one per species)
  call output_units(units)

  dIDs = (/ londimid, latdimid, levdimid, timedimid, pointspecdimid, nageclassdimid /)
  depdIDs = (/ londimid, latdimid, timedimid, pointspecdimid, nageclassdimid /)
  if (lnest) then
     dimidsn    = dIDs
     depdimidsn = depdIDs
  else
     dimids    = dIDs
     depdimids = depdIDs
  endif

  ! set chunksizes according to largest written portion of data in an individual call to 
  ! nf90_put_var
  chunksizes = (/ nnx, nny, numzgrid, 1, 1, 1 /)
  dep_chunksizes = (/ nnx, nny, 1, 1, 1 /)

  do i = 1,nspec
     write(anspec,'(i3.3)') i

     ! concentration output
     if (iout.eq.1.or.iout.eq.3.or.iout.eq.5) then
        call nf90_err(nf90_def_var(ncid,'spec'//anspec//'_mr', nf90_float, dIDs, sID , &
             deflate_level = deflate_level,  &
             chunksizes = chunksizes ))
        call nf90_err(nf90_put_att(ncid, sID, 'units', units))
        call nf90_err(nf90_put_att(ncid, sID, 'long_name', species(i)))
        call nf90_err(nf90_put_att(ncid, sID, 'decay', decay(i)))
        call nf90_err(nf90_put_att(ncid, sID, 'weightmolar', weightmolar(i)))
!        call nf90_err(nf90_put_att(ncid, sID, 'ohreact', ohreact(i)))
        call nf90_err(nf90_put_att(ncid, sID, 'ohcconst', ohcconst(i)))
        call nf90_err(nf90_put_att(ncid, sID, 'ohdconst', ohdconst(i)))
        call nf90_err(nf90_put_att(ncid, sID, 'vsetaver', vsetaver(i)))

        if (lnest) then
           specIDn(i) = sID
        else
           specID(i) = sID
        endif
     endif

     ! mixing ratio output
     if (iout.eq.2.or.iout.eq.3) then
        call nf90_err(nf90_def_var(ncid,'spec'//anspec//'_pptv', nf90_float, dIDs, sID , &
             deflate_level = deflate_level,  &
             chunksizes = chunksizes ))
        call nf90_err(nf90_put_att(ncid, sID, 'units', 'pptv'))
        call nf90_err(nf90_put_att(ncid, sID, 'long_name', species(i)))
        call nf90_err(nf90_put_att(ncid, sID, 'decay', decay(i)))
        call nf90_err(nf90_put_att(ncid, sID, 'weightmolar', weightmolar(i)))
!        call nf90_err(nf90_put_att(ncid, sID, 'ohreact', ohreact(i)))
        call nf90_err(nf90_put_att(ncid, sID, 'ohcconst', ohcconst(i)))
        call nf90_err(nf90_put_att(ncid, sID, 'ohdconst', ohdconst(i)))
        call nf90_err(nf90_put_att(ncid, sID, 'vsetaver', vsetaver(i)))

        if (lnest) then
           specIDnppt(i) = sID
        else
           specIDppt(i) = sID
        endif
     endif

     ! wet and dry deposition fields for forward runs
     if (wetdep) then
        call nf90_err(nf90_def_var(ncid,'WD_spec'//anspec, nf90_float, depdIDs, &
             wdsID, deflate_level = deflate_level, &
             chunksizes = dep_chunksizes))
        call nf90_err(nf90_put_att(ncid, wdsID, 'units', '1e-12 kg m-2'))
543
544
545
546
        call nf90_err(nf90_put_att(ncid, wdsID, 'weta_gas', weta_gas(i)))
        call nf90_err(nf90_put_att(ncid, wdsID, 'wetb_gas', wetb_gas(i)))
        call nf90_err(nf90_put_att(ncid, wdsID, 'ccn_aero', ccn_aero(i)))
        call nf90_err(nf90_put_att(ncid, wdsID, 'in_aero', in_aero(i)))
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
        ! call nf90_err(nf90_put_att(ncid, wdsID, 'wetc_in', wetc_in(i)))
        ! call nf90_err(nf90_put_att(ncid, wdsID, 'wetd_in', wetd_in(i)))
        call nf90_err(nf90_put_att(ncid, wdsID, 'dquer', dquer(i)))
        call nf90_err(nf90_put_att(ncid, wdsID, 'henry', henry(i)))
        if (lnest) then
           wdspecIDn(i) = wdsID
        else
           wdspecID(i) = wdsID
        endif
     endif
     if (drydep) then
        call nf90_err(nf90_def_var(ncid,'DD_spec'//anspec, nf90_float, depdIDs, &
             ddsID, deflate_level = deflate_level, &
             chunksizes = dep_chunksizes))
        call nf90_err(nf90_put_att(ncid, ddsID, 'units', '1e-12 kg m-2'))
        call nf90_err(nf90_put_att(ncid, ddsID, 'dryvel', dryvel(i)))
        call nf90_err(nf90_put_att(ncid, ddsID, 'reldiff', reldiff(i)))
        call nf90_err(nf90_put_att(ncid, ddsID, 'henry', henry(i)))
        call nf90_err(nf90_put_att(ncid, ddsID, 'f0', f0(i)))
        call nf90_err(nf90_put_att(ncid, ddsID, 'dquer', dquer(i)))
        call nf90_err(nf90_put_att(ncid, ddsID, 'density', density(i)))
        call nf90_err(nf90_put_att(ncid, ddsID, 'dsigma', dsigma(i)))
        if (lnest) then
           ddspecIDn(i) = ddsID
        else
           ddspecID(i) = ddsID
        endif
     endif
  end do


  ! global (metadata) attributes
  !*******************************
  call writemetadata(ncid,lnest)


  ! moves the file from define to data mode
  call nf90_err(nf90_enddef(ncid))

!  ! hes: inquire var definition
!  do i = 1,nspec
!     write(anspec,'(i3.3)') i
!
!     ! concentration output
!     if (iout.eq.1.or.iout.eq.3.or.iout.eq.5) then
!        if (lnest) then
!           sID = specIDn(i)
!        else
!           sID = specID(i)
!        endif
!        call nf90_err(nf90_inquire_variable(ncid, sID, chunksizes=inq_chunksizes))
!        write(*,*) "Chunksizes for var "//anspec//": ", inq_chunksizes
!     endif
!  end do

  
  ! fill with data
  !******************************
  ! longitudes (grid cell centers)
  if (lnest) then
607
    if (.not.allocated(coord)) allocate(coord(numxgridn))
608
609
610
611
     do i = 1,numxgridn
        coord(i) = outlon0n + (i-0.5)*dxoutn
     enddo
     call nf90_err(nf90_put_var(ncid, lonID, coord(1:numxgridn)))
612
     deallocate(coord)
613
  else
614
    if (.not.allocated(coord)) allocate(coord(numxgrid))
615
616
617
618
     do i = 1,numxgrid
        coord(i) = outlon0 + (i-0.5)*dxout
     enddo
     call nf90_err(nf90_put_var(ncid, lonID, coord(1:numxgrid)))
619
     deallocate(coord)
620
621
622
  endif
  ! latitudes (grid cell centers)
  if (lnest) then
623
    if (.not.allocated(coord)) allocate(coord(numygridn))
624
625
626
627
     do i = 1,numygridn
        coord(i) = outlat0n + (i-0.5)*dyoutn
     enddo
     call nf90_err(nf90_put_var(ncid, latID, coord(1:numygridn)))
628
     deallocate(coord)
629
  else
630
    if (.not.allocated(coord)) allocate(coord(numygrid))
631
632
633
634
     do i = 1,numygrid
        coord(i) = outlat0 + (i-0.5)*dyout
     enddo
     call nf90_err(nf90_put_var(ncid, latID, coord(1:numygrid)))
635
     deallocate(coord)
636
637
638
  endif
  ! levels
  call nf90_err(nf90_put_var(ncid, levID, outheight(1:numzgrid)))
639
640

  ! volume
641
642
643
644
645
646
  if (write_vol) then
    if (lnest) then
      call nf90_err(nf90_put_var(ncid, volID, volumen(:,:,:)))
    else
      call nf90_err(nf90_put_var(ncid, volID, volume(:,:,:)))
    end if
647
  end if
648
649

  ! area
650
651
652
653
654
655
  if (write_area) then
    if (lnest) then
      call nf90_err(nf90_put_var(ncid, areaID, arean(:,:)))
    else
      call nf90_err(nf90_put_var(ncid, areaID, area(:,:)))
    end if
656
  end if
657

658
659
660
661
662
663
  if (write_releases.eqv..true.) then
    ! release point information
    do i = 1,numpoint
       call nf90_err(nf90_put_var(ncid, relstartID, ireleasestart(i), (/i/)))
       call nf90_err(nf90_put_var(ncid, relendID, ireleaseend(i), (/i/)))
       call nf90_err(nf90_put_var(ncid, relkindzID, kindz(i), (/i/)))
664
665
666
667
668
669
670
671
       xp1=xpoint1(i)*dx+xlon0
       yp1=ypoint1(i)*dy+ylat0
       xp2=xpoint2(i)*dx+xlon0
       yp2=ypoint2(i)*dy+ylat0
       call nf90_err(nf90_put_var(ncid, rellng1ID, xp1, (/i/)))
       call nf90_err(nf90_put_var(ncid, rellng2ID, xp2, (/i/)))
       call nf90_err(nf90_put_var(ncid, rellat1ID, yp1, (/i/)))
       call nf90_err(nf90_put_var(ncid, rellat2ID, yp2, (/i/)))
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
       call nf90_err(nf90_put_var(ncid, relzz1ID, zpoint1(i), (/i/)))
       call nf90_err(nf90_put_var(ncid, relzz2ID, zpoint2(i), (/i/)))
       call nf90_err(nf90_put_var(ncid, relpartID, npart(i), (/i/)))
       if (i .le. 1000) then
         call nf90_err(nf90_put_var(ncid, relcomID, compoint(i), (/1,i/), (/45,1/)))
       else
         call nf90_err(nf90_put_var(ncid, relcomID, 'NA', (/1,i/), (/45,1/)))
       endif 
       call nf90_err(nf90_put_var(ncid, relxmassID, xmass(i,1:nspec), (/i,1/), (/1,nspec/)))
    end do
  end if

  ! age classes
  call nf90_err(nf90_put_var(ncid, lageID, lage(1:nageclass)))

  ! orography 
  if (.not. min_size) then
    if (lnest) then
      call nf90_err(nf90_put_var(ncid, oroID, orooutn(0:(nnx-1), 0:(nny-1))))
    else
      call nf90_err(nf90_put_var(ncid, oroID, oroout(0:(nnx-1), 0:(nny-1))))
    endif
  end if

  call nf90_err(nf90_close(ncid))

  return

end subroutine writeheader_netcdf


subroutine concoutput_netcdf(itime,outnum,gridtotalunc,wetgridtotalunc,drygridtotalunc)
     
  !                          i     i          o             o
  !       o
  !*****************************************************************************
  !                                                                            *
  !     Output of the concentration grid and the receptor concentrations.      *
  !                                                                            *
  !     Author: A. Stohl                                                       *
  !                                                                            *
  !     24 May 1995                                                            *
  !                                                                            *
  !     13 April 1999, Major update: if output size is smaller, dump output in *
  !                    sparse matrix format; additional output of uncertainty  *
  !                                                                            *
  !     05 April 2000, Major update: output of age classes; output for backward*
  !                    runs is time spent in grid cell times total mass of     *
  !                    species.                                                *
  !                                                                            *
  !     17 February 2002, Appropriate dimensions for backward and forward runs *
  !                       are now specified in module par_mod                  *
  !                                                                            *
  !     June 2006, write grid in sparse matrix with a single write command     *
  !                in order to save disk space                                 *
  !                                                                            *
  !     2008 new sparse matrix format                                          *
  !                                                                            *
  !     February 2010, Dominik Brunner, Empa                                   *
  !                    Adapted for COSMO                                       *
  !                    Remark: calculation of density could be improved.       *
  !                    Currently, it is calculated for the lower left corner   *
  !                    of each output grid cell rather than for its center.    *
  !                    Furthermore, the average density could be calculated    *
  !                    from the difference in pressure at the top and bottom   *
  !                    of each cell rather than by interpolation.              *
  !                                                                            *
  !     April 2013, Dominik Brunner, Empa                                      *
  !                    Adapted for netcdf output                               *
  !                                                                            *
  !*****************************************************************************
  !                                                                            *
  ! Variables:                                                                 *
  ! outnum          number of samples                                          *
  ! ncells          number of cells with non-zero concentrations               *
  ! sparse          .true. if in sparse matrix format, else .false.            *
  ! tot_mu          1 for forward, initial mass mixing ration for backw. runs  *
  !                                                                            *
  !*****************************************************************************

  use unc_mod, only: gridunc,drygridunc,wetgridunc,drygridunc0,wetgridunc0

  implicit none

  integer, intent(in) :: itime
  real, intent(in)    :: outnum
758
759
  real(dep_prec),intent(out):: wetgridtotalunc,drygridtotalunc
  real, intent(out)   :: gridtotalunc
760
761
  real                :: densityoutrecept(maxreceptor)
  integer             :: ncid,kp,ks,kz,ix,jy,iix,jjy,kzz,kzzm1,ngrid
762
  integer             :: nage,i,l,jj
763
764
765
  real                :: tot_mu(maxspec,maxpointspec_act)
  real                :: halfheight,dz,dz1,dz2
  real                :: xl,yl,xlrot,ylrot,zagnd,zagndprev
766
767
768
769
770
771
772
  real(dep_prec)      :: auxgrid(nclassunc)
  real(dep_prec)      :: gridtotal,gridsigmatotal
  real(dep_prec)      :: wetgridtotal,wetgridsigmatotal
  real(dep_prec)      :: drygridtotal,drygridsigmatotal
  ! real(sp)            :: gridtotal,gridsigmatotal
  ! real(sp)            :: wetgridtotal,wetgridsigmatotal
  ! real(sp)            :: drygridtotal,drygridsigmatotal
773
774
    real :: ddx,ddy,p0h,t0h,p1,p2,p3,p4,rddx,rddy,xlon,xlat,ylat,xtn,ytn
    integer :: i1,ixp,j1,jyp,j
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901

  real, parameter     :: weightair=28.97


  ! open output file
  call nf90_err(nf90_open(trim(ncfname), nf90_write, ncid))

  ! write time
  tpointer = tpointer + 1
  call nf90_err(nf90_put_var( ncid, timeID, itime, (/ tpointer /)))
  
  ! For forward simulations, output fields have dimension MAXSPEC,
  ! for backward simulations, output fields have dimension MAXPOINT.
  ! Thus, make loops either about nspec, or about numpoint
  !*****************************************************************

  if (ldirect.eq.1) then
    do ks=1,nspec
      do kp=1,maxpointspec_act
        tot_mu(ks,kp)=1.0
      end do
    end do
  else
    do ks=1,nspec
      do kp=1,maxpointspec_act
        tot_mu(ks,kp)=xmass(kp,ks)
      end do
    end do
  endif


  !*******************************************************************
  ! Compute air density:
  ! brd134: we now take into account whether we are in the mother or in
  !    a nested domain (before only from mother domain)
  ! Determine center altitude of output layer, and interpolate density
  ! data to that altitude
  !*******************************************************************

  do kz=1,numzgrid
    if (kz.eq.1) then
      halfheight=outheight(1)/2.
    else
      halfheight=(outheight(kz)+outheight(kz-1))/2.
    endif
    do kzz=2,nz
      if ((height(kzz-1).lt.halfheight).and. &
           (height(kzz).gt.halfheight)) exit
    end do
    kzz=max(min(kzz,nz),2)
    dz1=halfheight-height(kzz-1)
    dz2=height(kzz)-halfheight
    dz=dz1+dz2

    do jy=0,numygrid-1
      do ix=0,numxgrid-1
        xl=outlon0+real(ix)*dxout
        yl=outlat0+real(jy)*dyout
        ! grid index in mother domain
        xl=(xl-xlon0)/dx
        yl=(yl-ylat0)/dx

        ngrid=0
        do jj=numbnests,1,-1
          if ( xl.gt.xln(jj)+eps .and. xl.lt.xrn(jj)-eps .and. &
                 yl.gt.yln(jj)+eps .and. yl.lt.yrn(jj)-eps ) then
            ngrid=jj
            exit 
          end if
        end do

        if (ngrid.eq.0) then
          iix=max(min(nint(xl),nxmin1),0) ! if output grid cell is outside mother domain
          jjy=max(min(nint(yl),nymin1),0)

          densityoutgrid(ix,jy,kz)=(rho(iix,jjy,kzz,memind(2))*dz1+ &
             rho(iix,jjy,kzz-1,memind(2))*dz2)/dz
        else
          xl=(xl-xln(ngrid))*xresoln(ngrid)
          yl=(yl-yln(ngrid))*yresoln(ngrid)
          iix=max(min(nint(xl),nxn(ngrid)-1),0)
          jjy=max(min(nint(yl),nyn(ngrid)-1),0)

          densityoutgrid(ix,jy,kz)=(rhon(iix,jjy,kzz,memind(2), ngrid)*dz1+ &
             rhon(iix,jjy,kzz-1,memind(2), ngrid)*dz2)/dz
        endif
      end do
    end do
  end do

  ! brd134: for receptor points no option for nests yet to specify density
  !    and also altitude zreceptor not considered yet (needs revision)
  do i=1,numreceptor
    xl=xreceptor(i)
    yl=yreceptor(i)
    iix=max(min(nint(xl),nxmin1),0)
    jjy=max(min(nint(yl),nymin1),0)
    densityoutrecept(i)=rho(iix,jjy,1,memind(2))
  end do

  ! Output is different for forward and backward simulations
  if (ldirect.eq.1) then
     do kz=1,numzgrid
        do jy=0,numygrid-1
           do ix=0,numxgrid-1
              factor3d(ix,jy,kz)=1.e12/volume(ix,jy,kz)/outnum
           end do
        end do
     end do
  else
     do kz=1,numzgrid
        do jy=0,numygrid-1
           do ix=0,numxgrid-1
              factor3d(ix,jy,kz)=real(abs(loutaver))/outnum
           end do
        end do
     end do
  endif

  !*********************************************************************
  ! Determine the standard deviation of the mean concentration or mixing
  ! ratio (uncertainty of the output) and the dry and wet deposition
  !*********************************************************************

  gridtotal=0.
  gridsigmatotal=0.
  gridtotalunc=0.
902
903
904
905
906
907
  wetgridtotal=0._dep_prec
  wetgridsigmatotal=0._dep_prec
  wetgridtotalunc=0._dep_prec
  drygridtotal=0._dep_prec
  drygridsigmatotal=0._dep_prec
  drygridtotalunc=0._dep_prec
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930

  do ks=1,nspec

    do kp=1,maxpointspec_act
      do nage=1,nageclass

        do jy=0,numygrid-1
          do ix=0,numxgrid-1

            ! WET DEPOSITION
            if ((wetdep).and.(ldirect.gt.0)) then
              if (mpi_mode.gt.0) then
                do l=1,nclassunc
                  auxgrid(l)=wetgridunc0(ix,jy,ks,kp,l,nage)
                end do
              else
                do l=1,nclassunc
                  auxgrid(l)=wetgridunc(ix,jy,ks,kp,l,nage)
                end do
              end if
              call mean(auxgrid,wetgrid(ix,jy), &
                   wetgridsigma(ix,jy),nclassunc)
              ! Multiply by number of classes to get total concentration
931
              wetgrid(ix,jy)=wetgrid(ix,jy)*real(nclassunc,kind=sp)
932
933
934
935
              wetgridtotal=wetgridtotal+wetgrid(ix,jy)
              ! Calculate standard deviation of the mean
              wetgridsigma(ix,jy)= &
                   wetgridsigma(ix,jy)* &
936
                   sqrt(real(nclassunc,kind=dep_prec))
937
938
939
940
941
942
943
944
              wetgridsigmatotal=wetgridsigmatotal+ &
                   wetgridsigma(ix,jy)
            endif

            ! DRY DEPOSITION
            if ((drydep).and.(ldirect.gt.0)) then
              if (mpi_mode.gt.0) then
                do l=1,nclassunc
945
                  auxgrid(l)=drygridunc0(ix,jy,ks,kp,l,nage)
946
947
948
949
950
951
952
953
954
                end do
              else
                do l=1,nclassunc
                  auxgrid(l)=drygridunc(ix,jy,ks,kp,l,nage)
                end do
              end if
              call mean(auxgrid,drygrid(ix,jy), &
                   drygridsigma(ix,jy),nclassunc)
              ! Multiply by number of classes to get total concentration
955
              drygrid(ix,jy)=drygrid(ix,jy)*real(nclassunc,kind=sp)
956
957
958
959
              drygridtotal=drygridtotal+drygrid(ix,jy)
              ! Calculate standard deviation of the mean
              drygridsigma(ix,jy)= &
                   drygridsigma(ix,jy)* &
960
                   sqrt(real(nclassunc, kind=dep_prec))
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
              drygridsigmatotal=drygridsigmatotal+ &
                   drygridsigma(ix,jy)
            endif

            ! CONCENTRATION OR MIXING RATIO
            do kz=1,numzgrid
              do l=1,nclassunc
                auxgrid(l)=gridunc(ix,jy,kz,ks,kp,l,nage)
              end do
              call mean(auxgrid,grid(ix,jy,kz), &
                   gridsigma(ix,jy,kz),nclassunc)
              ! Multiply by number of classes to get total concentration
              grid(ix,jy,kz)= &
                   grid(ix,jy,kz)*real(nclassunc)
              gridtotal=gridtotal+grid(ix,jy,kz)
              ! Calculate standard deviation of the mean
              gridsigma(ix,jy,kz)= &
                   gridsigma(ix,jy,kz)* &
                   sqrt(real(nclassunc))
              gridsigmatotal=gridsigmatotal+ &
                   gridsigma(ix,jy,kz)
            end do
          end do
        end do

!       print*,gridtotal,maxpointspec_act

        !*******************************************************************
        ! Generate output: may be in concentration (ng/m3) or in mixing
        ! ratio (ppt) or both
        ! Output the position and the values alternated multiplied by
        ! 1 or -1, first line is number of values, number of positions
        ! For backward simulations, the unit is seconds, stored in grid_time
        !*******************************************************************

        ! Concentration output
        !*********************
        if ((iout.eq.1).or.(iout.eq.3).or.(iout.eq.5)) then

          ! Wet deposition
          if ((ldirect.eq.1).and.(WETDEP)) then
            call nf90_err(nf90_put_var(ncid,wdspecID(ks),1.e12*&
                 wetgrid(0:numxgrid-1,0:numygrid-1)/area(0:numxgrid-1,0:numygrid-1),&
                 (/ 1,1,tpointer,kp,nage /), (/ numxgrid,numygrid,1,1,1 /)))
          end if

          ! Dry deposition
          if ((ldirect.eq.1).and.(DRYDEP)) then
            call nf90_err(nf90_put_var(ncid,ddspecID(ks),1.e12*&
                 drygrid(0:numxgrid-1,0:numygrid-1)/area(0:numxgrid-1,0:numygrid-1),&
                 (/ 1,1,tpointer,kp,nage /), (/ numxgrid,numygrid,1,1,1 /)))
          endif

          ! Concentrations
          call nf90_err(nf90_put_var(ncid,specID(ks),grid(0:numxgrid-1,0:numygrid-1,&
             1:numzgrid)*factor3d(0:numxgrid-1,0:numygrid-1,1:numzgrid)/tot_mu(ks,kp),&
               (/ 1,1,1,tpointer,kp,nage /), (/ numxgrid,numygrid,numzgrid,1,1,1 /) ))
 
        endif !  concentration output

        ! Mixing ratio output
        !********************

        if ((iout.eq.2).or.(iout.eq.3)) then      ! mixing ratio

          ! Wet deposition
          if ((ldirect.eq.1).and.(WETDEP)) then
            call nf90_err(nf90_put_var(ncid,wdspecID(ks),1.e12*&
                 wetgrid(0:numxgrid-1,0:numygrid-1)/area(0:numxgrid-1,0:numygrid-1),&
                 (/ 1,1,tpointer,kp,nage /), (/ numxgrid,numygrid,1,1,1 /)))

          endif

          ! Dry deposition
          if ((ldirect.eq.1).and.(DRYDEP)) then
            call nf90_err(nf90_put_var(ncid,ddspecID(ks),1.e12*&
                 drygrid(0:numxgrid-1,0:numygrid-1)/area(0:numxgrid-1,0:numygrid-1),&
                 (/ 1,1,tpointer,kp,nage /), (/ numxgrid,numygrid,1,1,1 /)))
          endif

          ! Mixing ratios
          call nf90_err(nf90_put_var(ncid,specIDppt(ks),weightair/weightmolar(ks)*&
               grid(0:numxgrid-1,0:numygrid-1,1:numzgrid)*&
               factor3d(0:numxgrid-1,0:numygrid-1,1:numzgrid)/&
               densityoutgrid(0:numxgrid-1,0:numygrid-1,1:numzgrid),&
               (/ 1,1,1,tpointer,kp,nage /), (/ numxgrid,numygrid,numzgrid,1,1,1 /)))

        endif ! output for ppt

      end do
    end do

  end do

1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135

    if (write_p0t0) then
       ! Loop over all output grid cells
       !********************************

       do jjy=0,numygrid-1
          do iix=0,numxgrid-1
             p0h=0.
             t0h=0.

             ! Take 100 samples of the topography in every grid cell
             !******************************************************

             do j1=1,10
                ylat=outlat0+(real(jjy)+real(j1)/10.-0.05)*dyout
                yl=(ylat-ylat0)/dy
                do i1=1,10
                   xlon=outlon0+(real(iix)+real(i1)/10.-0.05)*dxout
                   xl=(xlon-xlon0)/dx

                   ! Determine the nest we are in
                   !*****************************

                   ngrid=0
                   do j=numbnests,1,-1
                      if ((xl.gt.xln(j)+eps).and.(xl.lt.xrn(j)-eps).and. &
                           (yl.gt.yln(j)+eps).and.(yl.lt.yrn(j)-eps)) then
                         ngrid=j
                         goto 43
                      endif
                   end do
43                 continue

                   ! Determine (nested) grid coordinates and auxiliary parameters used for interpolation
                   !*****************************************************************************

                   if (ngrid.gt.0) then
                      xtn=(xl-xln(ngrid))*xresoln(ngrid)
                      ytn=(yl-yln(ngrid))*yresoln(ngrid)
                      ix=int(xtn)
                      jy=int(ytn)
                      ddy=ytn-real(jy)
                      ddx=xtn-real(ix)
                   else
                      ix=int(xl)
                      jy=int(yl)
                      ddy=yl-real(jy)
                      ddx=xl-real(ix)
                   endif
                   ixp=ix+1
                   jyp=jy+1
                   rddx=1.-ddx
                   rddy=1.-ddy
                   p1=rddx*rddy
                   p2=ddx*rddy
                   p3=rddx*ddy
                   p4=ddx*ddy

                   p0h=p0h+p1*ps(ix ,jy,1,memind(1)) &
                        + p2*ps(ixp,jy,1,memind(1)) &
                        + p3*ps(ix ,jyp,1,memind(1)) &
                        + p4*ps(ixp,jyp,1,memind(1))
                   t0h=t0h+p1*tt2(ix ,jy,1,memind(1)) &
                        + p2*tt2(ixp,jy,1,memind(1)) &
                        + p3*tt2(ix ,jyp,1,memind(1)) &
                        + p4*tt2(ixp,jyp,1,memind(1))
                end do
             end do

             ! Divide by the number of samples taken
             !**************************************
             p0out(iix,jjy)=p0h/100.
             t0out(iix,jjy)=t0h/100.
          end do
       end do

       call nf90_err(nf90_put_var(ncid, psID, p0out, (/ 1,1,tpointer /), (/ numxgrid,numygrid,1 /)))
       call nf90_err(nf90_put_var(ncid, tt2ID, t0out,(/ 1,1,tpointer /), (/ numxgrid,numygrid,1 /)))
    end if


1136
1137
1138
1139
1140
1141
1142
1143
  ! Close netCDF file
  !**************************
  call nf90_err(nf90_close(ncid))


  if (gridtotal.gt.0.) gridtotalunc=gridsigmatotal/gridtotal
  if (wetgridtotal.gt.0.) wetgridtotalunc=wetgridsigmatotal/ &
       wetgridtotal
1144
1145
  if (drygridtotal.gt.0.) drygridtotalunc=real(drygridsigmatotal/ &
       drygridtotal, kind=dep_prec)
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183

  ! Dump of receptor concentrations

  if (numreceptor.gt.0 .and. (iout.eq.2 .or. iout.eq.3)  ) then
    write(unitoutreceptppt) itime
    do ks=1,nspec
      write(unitoutreceptppt) (1.e12*creceptor(i,ks)/outnum* &
           weightair/weightmolar(ks)/densityoutrecept(i),i=1,numreceptor)
    end do
  endif

  ! Dump of receptor concentrations

  if (numreceptor.gt.0) then
    write(unitoutrecept) itime
    do ks=1,nspec
      write(unitoutrecept) (1.e12*creceptor(i,ks)/outnum,i=1,numreceptor)
    end do
  endif


  ! Reinitialization of grid
  !*************************

  creceptor(1:numreceptor,1:nspec) = 0.
  gridunc(:,:,:,1:nspec,:,:,1:nageclass) = 0.  


end subroutine concoutput_netcdf

subroutine concoutput_surf_netcdf(itime,outnum,gridtotalunc,wetgridtotalunc,drygridtotalunc)

  use unc_mod, only: gridunc,drygridunc,wetgridunc,drygridunc0,wetgridunc0

  implicit none

  integer, intent(in) :: itime
  real, intent(in)    :: outnum
1184
1185
  real(sp), intent(out)   :: gridtotalunc
  real(dep_prec), intent(out)   :: wetgridtotalunc,drygridtotalunc
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240

  print*,'Netcdf output for surface only not yet implemented'

end subroutine concoutput_surf_netcdf

subroutine concoutput_nest_netcdf(itime,outnum)
  !                               i     i 
  !*****************************************************************************
  !                                                                            *
  !     Output of the concentration grid and the receptor concentrations.      *
  !                                                                            *
  !     Author: A. Stohl                                                       *
  !                                                                            *
  !     24 May 1995                                                            *
  !                                                                            *
  !     13 April 1999, Major update: if output size is smaller, dump output in *
  !                    sparse matrix format; additional output of uncertainty  *
  !                                                                            *
  !     05 April 2000, Major update: output of age classes; output for backward*
  !                    runs is time spent in grid cell times total mass of     *
  !                    species.                                                *
  !                                                                            *
  !     17 February 2002, Appropriate dimensions for backward and forward runs *
  !                    are now specified in module par_mod                     *
  !                                                                            *
  !     June 2006, write grid in sparse matrix with a single write command     *
  !                    in order to save disk space                             *
  !                                                                            *
  !     2008 new sparse matrix format                                          *
  !                                                                            *
  !     19 February 2010, Dominik Brunner, Empa: Adapted for COSMO             *
  !                                                                            *
  !     April 2013, Dominik Brunner, Empa                                      *
  !                    Adapted for netcdf output                               *
  !                                                                            *
  !*****************************************************************************
  !                                                                            *
  ! Variables:                                                                 *
  ! itime           current simulation time                                    *
  ! outnum          number of samples                                          *
  !                                                                            *
  !*****************************************************************************

  use unc_mod, only: griduncn,drygriduncn,wetgriduncn,drygriduncn0,wetgriduncn0
 
  implicit none

  integer, intent(in) :: itime
  real, intent(in)    :: outnum
  real                :: densityoutrecept(maxreceptor)
  integer             :: ncid,kp,ks,kz,ix,jy,iix,jjy,kzz,kzzm1,ngrid
  integer             :: nage,i,l, jj
  real                :: tot_mu(maxspec,maxpointspec_act)
  real                :: halfheight,dz,dz1,dz2
  real                :: xl,yl,xlrot,ylrot,zagnd,zagndprev
1241
1242
  real(dep_prec)      :: auxgrid(nclassunc)
  real                :: gridtotal
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
  real, parameter     :: weightair=28.97

  ! open output file
  call nf90_err(nf90_open(trim(ncfnamen), nf90_write, ncid))

  ! write time (do not increase time counter here, done in main output domain)
  call nf90_err(nf90_put_var( ncid, timeID, itime, (/ tpointer /)))
  
  ! For forward simulations, output fields have dimension MAXSPEC,
  ! for backward simulations, output fields have dimension MAXPOINT.
  ! Thus, make loops either about nspec, or about numpoint
  !*****************************************************************

  if (ldirect.eq.1) then
    do ks=1,nspec
      do kp=1,maxpointspec_act
        tot_mu(ks,kp)=1.0
      end do
    end do
  else
    do ks=1,nspec
      do kp=1,maxpointspec_act
        tot_mu(ks,kp)=xmass(kp,ks)
      end do
    end do
  endif


  !*******************************************************************
  ! Compute air density:
  ! brd134: we now take into account whether we are in the mother or in
  !    a nested domain (before only from mother domain)
  ! Determine center altitude of output layer, and interpolate density
  ! data to that altitude
  !*******************************************************************

  do kz=1,numzgrid
    if (kz.eq.1) then
      halfheight=outheight(1)/2.
    else
      halfheight=(outheight(kz)+outheight(kz-1))/2.
    endif
    do kzz=2,nz
      if ((height(kzz-1).lt.halfheight).and. &
           (height(kzz).gt.halfheight)) exit
    end do
    kzz=max(min(kzz,nz),2)
    dz1=halfheight-height(kzz-1)
    dz2=height(kzz)-halfheight
    dz=dz1+dz2

    do jy=0,numygridn-1
      do ix=0,numxgridn-1
        xl=outlon0n+real(ix)*dxoutn
        yl=outlat0n+real(jy)*dyoutn
        xl=(xl-xlon0)/dx
        yl=(yl-ylat0)/dy

        ngrid=0
        do jj=numbnests,1,-1
          if ( xl.gt.xln(jj)+eps .and. xl.lt.xrn(jj)-eps .and. &
                 yl.gt.yln(jj)+eps .and. yl.lt.yrn(jj)-eps ) then
            ngrid=jj
            exit 
          end if
        end do

        if (ngrid.eq.0) then
          iix=max(min(nint(xl),nxmin1),0)
          jjy=max(min(nint(yl),nymin1),0)

          densityoutgrid(ix,jy,kz)=(rho(iix,jjy,kzz,memind(2))*dz1+ &
             rho(iix,jjy,kzz-1,memind(2))*dz2)/dz
        else
          xl=(xl-xln(ngrid))*xresoln(ngrid)
          yl=(yl-yln(ngrid))*yresoln(ngrid)
          iix=max(min(nint(xl),nxn(ngrid)-1),0)
          jjy=max(min(nint(yl),nyn(ngrid)-1),0)
          densityoutgrid(ix,jy,kz)=(rhon(iix,jjy,kzz,memind(2), ngrid)*dz1+ &
             rhon(iix,jjy,kzz-1,memind(2), ngrid)*dz2)/dz
        endif

      end do
    end do
  end do

  do i=1,numreceptor
    xl=xreceptor(i)
    yl=yreceptor(i)
    iix=max(min(nint(xl),nxmin1),0)
    jjy=max(min(nint(yl),nymin1),0)
    densityoutrecept(i)=rho(iix,jjy,1,memind(2))
  end do

  ! Output is different for forward and backward simulations
  if (ldirect.eq.1) then
     do kz=1,numzgrid
        do jy=0,numygridn-1
           do ix=0,numxgridn-1
              factor3d(ix,jy,kz)=1.e12/volumen(ix,jy,kz)/outnum
           end do
        end do
     end do
  else
     do kz=1,numzgrid
        do jy=0,numygridn-1
           do ix=0,numxgridn-1
              factor3d(ix,jy,kz)=real(abs(loutaver))/outnum
           end do
        end do
     end do
  endif

  !*********************************************************************
  ! Determine the standard deviation of the mean concentration or mixing
  ! ratio (uncertainty of the output) and the dry and wet deposition
  !*********************************************************************

  gridtotal=0.

  do ks=1,nspec

    do kp=1,maxpointspec_act
      do nage=1,nageclass

        do jy=0,numygridn-1
          do ix=0,numxgridn-1
            ! WET DEPOSITION
            if ((WETDEP).and.(ldirect.gt.0)) then
              if (mpi_mode.gt.0) then
                do l=1,nclassunc
                  auxgrid(l)=wetgriduncn0(ix,jy,ks,kp,l,nage)
                end do
              else
                do l=1,nclassunc
                  auxgrid(l)=wetgriduncn(ix,jy,ks,kp,l,nage)
                end do
              end if
              call mean(auxgrid,wetgrid(ix,jy), &
                   wetgridsigma(ix,jy),nclassunc)
              ! Multiply by number of classes to get total concentration
              wetgrid(ix,jy)=wetgrid(ix,jy)*real(nclassunc)
              ! Calculate standard deviation of the mean
              wetgridsigma(ix,jy)= &
                   wetgridsigma(ix,jy)* &
1388
                   sqrt(real(nclassunc,kind=dep_prec))
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
            endif

            ! DRY DEPOSITION
            if ((DRYDEP).and.(ldirect.gt.0)) then
              if (mpi_mode.gt.0) then
                do l=1,nclassunc
                  auxgrid(l)=drygriduncn0(ix,jy,ks,kp,l,nage)
                end do
              else
                do l=1,nclassunc
                  auxgrid(l)=drygriduncn(ix,jy,ks,kp,l,nage)
                end do
              end if
              call mean(auxgrid,drygrid(ix,jy), &
                   drygridsigma(ix,jy),nclassunc)
              ! Multiply by number of classes to get total concentration
              drygrid(ix,jy)=drygrid(ix,jy)*real(nclassunc)
              ! Calculate standard deviation of the mean
              drygridsigma(ix,jy)= &
                   drygridsigma(ix,jy)* &
1409
                   sqrt(real(nclassunc,kind=dep_prec))
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
            endif

            ! CONCENTRATION OR MIXING RATIO
            do kz=1,numzgrid
              do l=1,nclassunc
                auxgrid(l)=griduncn(ix,jy,kz,ks,kp,l,nage)
              end do
              call mean(auxgrid,grid(ix,jy,kz), &
                   gridsigma(ix,jy,kz),nclassunc)
              ! Multiply by number of classes to get total concentration
              grid(ix,jy,kz)= &
                   grid(ix,jy,kz)*real(nclassunc)
              gridtotal=gridtotal+grid(ix,jy,kz)
              ! Calculate standard deviation of the mean
              gridsigma(ix,jy,kz)= &
                   gridsigma(ix,jy,kz)* &
                   sqrt(real(nclassunc))
            end do
          end do
        end do

!       print*,gridtotal,maxpointspec_act

        !*******************************************************************
        ! Generate output: may be in concentration (ng/m3) or in mixing
        ! ratio (ppt) or both
        ! Output the position and the values alternated multiplied by
        ! 1 or -1, first line is number of values, number of positions
        ! For backward simulations, the unit is seconds, stored in grid_time
        !*******************************************************************

        ! Concentration output
        !*********************
        if ((iout.eq.1).or.(iout.eq.3).or.(iout.eq.5)) then

          ! Wet deposition
          if ((ldirect.eq.1).and.(WETDEP)) then
             call nf90_err(nf90_put_var(ncid,wdspecIDn(ks),1.e12*&
                  wetgrid(0:numxgridn-1,0:numygridn-1)/arean(0:numxgridn-1,0:numygridn-1),&
                  (/ 1,1,tpointer,kp,nage /), (/ numxgridn,numygridn,1,1,1 /)))
          endif

          ! Dry deposition
          if ((ldirect.eq.1).and.(DRYDEP)) then
             call nf90_err(nf90_put_var(ncid,ddspecIDn(ks),1.e12*&
                  drygrid(0:numxgridn-1,0:numygridn-1)/arean(0:numxgridn-1,0:numygridn-1),&
                  (/ 1,1,tpointer,kp,nage /), (/ numxgridn,numygridn,1,1,1 /)))
          endif

          ! Concentrations
          call nf90_err(nf90_put_var(ncid,specIDn(ks),grid(0:numxgridn-1,0:numygridn-1,&
             1:numzgrid)*factor3d(0:numxgridn-1,0:numygridn-1,1:numzgrid)/tot_mu(ks,kp),&
               (/ 1,1,1,tpointer,kp,nage /), (/ numxgridn,numygridn,numzgrid,1,1,1 /)))
 
        endif !  concentration output

        ! Mixing ratio output
        !********************

        if ((iout.eq.2).or.(iout.eq.3)) then      ! mixing ratio

          ! Wet deposition
          if ((ldirect.eq.1).and.(WETDEP)) then
             call nf90_err(nf90_put_var(ncid,wdspecIDn(ks),1.e12*&
                  wetgrid(0:numxgridn-1,0:numygridn-1)/arean(0:numxgridn-1,0:numygridn-1),&
                  (/ 1,1,tpointer,kp,nage /), (/ numxgridn,numygridn,1,1,1 /)))
          endif

          ! Dry deposition
          if ((ldirect.eq.1).and.(DRYDEP)) then
             call nf90_err(nf90_put_var(ncid,ddspecIDn(ks),1.e12*&
                  drygrid(0:numxgridn-1,0:numygridn-1)/arean(0:numxgridn-1,0:numygridn-1),&
                  (/ 1,1,tpointer,kp,nage /), (/ numxgridn,numygridn,1,1,1 /)))
          endif

          ! Mixing ratios
          call nf90_err(nf90_put_var(ncid,specIDnppt(ks),weightair/weightmolar(ks)*&
               grid(0:numxgridn-1,0:numygridn-1,1:numzgrid)*&
               factor3d(0:numxgridn-1,0:numygridn-1,1:numzgrid)/&
               densityoutgrid(0:numxgridn-1,0:numygridn-1,1:numzgrid),&
               (/ 1,1,1,tpointer,kp,nage /), (/ numxgridn,numygridn,numzgrid,1,1,1 /)))

        endif ! output for ppt

      end do
    end do

  end do

  ! Close netCDF file
  !**************************
  call nf90_err(nf90_close(ncid))

  ! Reinitialization of grid
  !*************************

  creceptor(1:numreceptor,1:nspec) = 0.
  griduncn(:,:,:,1:nspec,:,:,1:nageclass) = 0.  

end subroutine concoutput_nest_netcdf

subroutine concoutput_surf_nest_netcdf(itime,outnum)

  implicit none

  integer, intent(in) :: itime
  real, intent(in)    :: outnum

  print*,'Netcdf output for surface only not yet implemented'

end subroutine concoutput_surf_nest_netcdf

1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
subroutine fluxoutput_netcdf(itime)
     
  !                            i
  !*****************************************************************************
  !                                                                            *
  !     Output of the gridded fluxes.                                          *
  !     Eastward, westward, northward, southward, upward and downward gross    *
  !     fluxes are written to output file in either sparse matrix or grid dump *
  !     format, whichever is more efficient.                                   *
  !                                                                            *
  !     Author: A. Stohl                                                       *
  !                                                                            *
  !     04 April 2000                                                          *
  !     netcdfoutput S. Eckhardt, 2020                                         *
  !                                                                            *
  !*****************************************************************************

   use flux_mod

  implicit none

  real(kind=dp) :: jul
  integer :: itime,ix,jy,kz,ks,nage,jjjjmmdd,ihmmss,kp,i
  
  character(len=255) :: ncfname
  character :: adate*8,atime*6,timeunit*32,anspec*3

  integer :: ncid 
  integer :: timeDimID, latDimID, lonDimID, levDimID
  integer :: nspecDimID, npointDimID, nageclassDimID, ncharDimID, pointspecDimID
  integer :: tID, lonID, latID, levID, lageID, fluxID
  integer, dimension(6)       :: dIDs
  integer :: cache_size
  real, allocatable, dimension(:) :: coord


  ! Determine current calendar date, needed for the file name
  !**********************************************************

  jul=bdate+real(itime,kind=dp)/86400._dp
  call caldate(jul,jjjjmmdd,ihmmss)
  write(adate,'(i8.8)') jjjjmmdd
  write(atime,'(i6.6)') ihmmss

  ncfname=path(2)(1:length(2))//'grid_flux_'//adate// &
       atime//'.nc'

  ! setting cache size in bytes. It is set to 4 times the largest data block that is written
  !   size_type x nx x ny x nz
  ! create file

  cache_size = 16 * numxgrid * numygrid * numzgrid
  call nf90_err(nf90_create(trim(ncfname), cmode = nf90_hdf5, ncid = ncid, &
    cache_size = cache_size))  

  ! create dimensions:
  !*************************
  ! time
  call nf90_err(nf90_def_dim(ncid, 'time', nf90_unlimited, timeDimID))
  timeunit = 'seconds since '//adate(1:4)//'-'//adate(5:6)// &
     '-'//adate(7:8)//' '//atime(1:2)//':'//atime(3:4)

  call nf90_err(nf90_def_dim(ncid, 'longitude', numxgrid, lonDimID))
  call nf90_err(nf90_def_dim(ncid, 'latitude', numygrid, latDimID))
  call nf90_err(nf90_def_dim(ncid, 'height', numzgrid, levDimID))
  call nf90_err(nf90_def_dim(ncid, 'numspec', nspec, nspecDimID))
  call nf90_err(nf90_def_dim(ncid, 'pointspec', maxpointspec_act, pointspecDimID))
  call nf90_err(nf90_def_dim(ncid, 'nageclass', nageclass, nageclassDimID))
  call nf90_err(nf90_def_dim(ncid, 'nchar', 45, ncharDimID))
  call nf90_err(nf90_def_dim(ncid, 'numpoint', numpoint, npointDimID))


  ! create variables
  !*************************

  ! time
  call nf90_err(nf90_def_var(ncid, 'time', nf90_int, (/ timeDimID /), tID))
  call nf90_err(nf90_put_att(ncid, tID, 'units', timeunit))
  call nf90_err(nf90_put_att(ncid, tID, 'calendar', 'proleptic_gregorian'))
  timeID = tID

  ! lon
  call nf90_err(nf90_def_var(ncid, 'longitude', nf90_float, (/ lonDimID /), lonID))
  call nf90_err(nf90_put_att(ncid, lonID, 'long_name', 'longitude in degree east'))
  call nf90_err(nf90_put_att(ncid, lonID, 'axis', 'Lon'))
  call nf90_err(nf90_put_att(ncid, lonID, 'units', 'degrees_east'))
  call nf90_err(nf90_put_att(ncid, lonID, 'standard_name', 'grid_longitude'))
  call nf90_err(nf90_put_att(ncid, lonID, 'description', 'grid cell centers'))

  ! lat
  call nf90_err(nf90_def_var(ncid, 'latitude', nf90_float, (/ latDimID /), latID))
  call nf90_err(nf90_put_att(ncid, latID, 'long_name', 'latitude in degree north'))
  call nf90_err(nf90_put_att(ncid, latID, 'axis', 'Lat'))
  call nf90_err(nf90_put_att(ncid, latID, 'units', 'degrees_north'))
  call nf90_err(nf90_put_att(ncid, latID, 'standard_name', 'grid_latitude'))
  call nf90_err(nf90_put_att(ncid, latID, 'description', 'grid cell centers'))

  ! height
  call nf90_err(nf90_def_var(ncid, 'height', nf90_float, (/ levDimID /), levID))
  call nf90_err(nf90_put_att(ncid, levID, 'units', 'meters'))
  call nf90_err(nf90_put_att(ncid, levID, 'positive', 'up'))
  call nf90_err(nf90_put_att(ncid, levID, 'standard_name', 'height'))

  if (.not.allocated(coord)) allocate(coord(numxgrid)) 
  do i = 1,numxgrid
     coord(i) = outlon0 + (i-0.5)*dxout
  enddo
  call nf90_err(nf90_put_var(ncid, lonID, coord(1:numxgrid)))
  deallocate(coord)
  if (.not.allocated(coord)) allocate(coord(numygrid))
  do i = 1,numygrid
     coord(i) = outlat0 + (i-0.5)*dyout
  enddo
  call nf90_err(nf90_put_var(ncid, latID, coord(1:numygrid)))
  deallocate(coord)
  call nf90_err(nf90_put_var(ncid, levID, outheight(1:numzgrid)))

  ! write time, one field per time - different to the others!
  call nf90_err(nf90_put_var( ncid, timeID, itime, (/ 1 /)))
  
  dIDs = (/ londimid, latdimid, levdimid, timedimid, pointspecdimid, nageclassdimid /)

  do ks=1,nspec
    do kp=1,maxpointspec_act
      do nage=1,nageclass
 
         write(anspec,'(i3.3)') ks

 ! East Flux
        call nf90_err(nf90_def_var(ncid,'flux_east_'//anspec, nf90_float, dIDs, &
             fluxID))

        do jy=0,numygrid-1
          do ix=0,numxgrid-1
            do kz=1, numzgrid
               grid(ix,jy,kz)=flux(1,ix,jy,kz,ks,kp,nage) 
            end do
          end do
        end do

        call nf90_err(nf90_put_var(ncid,fluxid,1.e12*grid(0:numxgrid-1,0:numygrid-1,1:numzgrid)&
            /areaeast(0:numxgrid-1,0:numygrid-1,1:numzgrid)/loutstep,&
Sabine's avatar
Sabine committed
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
           (/ 1,1,1,1,kp,nage /), (/ numxgrid,numygrid,numzgrid,1,1,1 /) ))

 ! West Flux
        call nf90_err(nf90_def_var(ncid,'flux_west_'//anspec, nf90_float, dIDs, &
             fluxID))

        do jy=0,numygrid-1
          do ix=0,numxgrid-1
            do kz=1, numzgrid
               grid(ix,jy,kz)=flux(2,ix,jy,kz,ks,kp,nage) 
            end do
          end do
        end do

        call nf90_err(nf90_put_var(ncid,fluxid,1.e12*grid(0:numxgrid-1,0:numygrid-1,1:numzgrid)&
            /areaeast(0:numxgrid-1,0:numygrid-1,1:numzgrid)/loutstep,&
           (/ 1,1,1,1,kp,nage /), (/ numxgrid,numygrid,numzgrid,1,1,1 /) ))

 ! North Flux
        call nf90_err(nf90_def_var(ncid,'flux_north_'//anspec, nf90_float, dIDs, &
             fluxID))

        do jy=0,numygrid-1
          do ix=0,numxgrid-1
            do kz=1, numzgrid
               grid(ix,jy,kz)=flux(4,ix,jy,kz,ks,kp,nage) 
            end do
          end do
        end do

        call nf90_err(nf90_put_var(ncid,fluxid,1.e12*grid(0:numxgrid-1,0:numygrid-1,1:numzgrid)&
            /areanorth(0:numxgrid-1,0:numygrid-1,1:numzgrid)/loutstep,&
           (/ 1,1,1,1,kp,nage /), (/ numxgrid,numygrid,numzgrid,1,1,1 /) ))

 ! South Flux
        call nf90_err(nf90_def_var(ncid,'flux_south_'//anspec, nf90_float, dIDs, &
             fluxID))

        do jy=0,numygrid-1
          do ix=0,numxgrid-1
            do kz=1, numzgrid
               grid(ix,jy,kz)=flux(3,ix,jy,kz,ks,kp,nage) 
            end do
          end do
        end do

        call nf90_err(nf90_put_var(ncid,fluxid,1.e12*grid(0:numxgrid-1,0:numygrid-1,1:numzgrid)&
            /areanorth(0:numxgrid-1,0:numygrid-1,1:numzgrid)/loutstep,&
           (/ 1,1,1,1,kp,nage /), (/ numxgrid,numygrid,numzgrid,1,1,1 /) ))

 ! Up Flux
        call nf90_err(nf90_def_var(ncid,'flux_up_'//anspec, nf90_float, dIDs, &
             fluxID))

        do jy=0,numygrid-1
          do ix=0,numxgrid-1
            do kz=1, numzgrid
               grid(ix,jy,kz)=flux(5,ix,jy,kz,ks,kp,nage)/area(ix,jy)
            end do
          end do
        end do

        call nf90_err(nf90_put_var(ncid,fluxid,1.e12*grid(0:numxgrid-1,0:numygrid-1,1:numzgrid)&
            /loutstep,&
           (/ 1,1,1,1,kp,nage /), (/ numxgrid,numygrid,numzgrid,1,1,1 /) ))

 ! Down Flux
        call nf90_err(nf90_def_var(ncid,'flux_down_'//anspec, nf90_float, dIDs, &
             fluxID))

        do jy=0,numygrid-1
          do ix=0,numxgrid-1
            do kz=1, numzgrid
               grid(ix,jy,kz)=flux(6,ix,jy,kz,ks,kp,nage)/area(ix,jy)
            end do
          end do
        end do

        call nf90_err(nf90_put_var(ncid,fluxid,1.e12*grid(0:numxgrid-1,0:numygrid-1,1:numzgrid)&
            /loutstep,&
           (/ 1,1,1,1,kp,nage /), (/ numxgrid,numygrid,numzgrid,1,1,1 /) ))
1745
1746
1747
1748
1749
1750
1751
1752

      end do
    end do
  end do

  ! Close netCDF file
  call nf90_err(nf90_close(ncid))

1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
  ! Reinitialization of grid
  !*************************

  do ks=1,nspec
    do kp=1,maxpointspec_act
      do jy=0,numygrid-1
        do ix=0,numxgrid-1
          do kz=1,numzgrid
            do nage=1,nageclass
              do i=1,6
                flux(i,ix,jy,kz,ks,kp,nage)=0.
              end do
            end do
          end do
        end do
      end do
    end do
  end do