-
Notifications
You must be signed in to change notification settings - Fork 145
/
model_mod.f90
2875 lines (2144 loc) · 98.8 KB
/
model_mod.f90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
184
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
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
543
544
545
546
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
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
! DART software - Copyright UCAR. This open source software is provided
! by UCAR, "as is", without charge, subject to all terms of use at
! http://www.image.ucar.edu/DAReS/DART/DART_download
!
! $Id$
module model_mod
! This is the interface between the POP ocean model and DART.
! Modules that are absolutely required for use are listed
use types_mod, only : r4, r8, i4, i8, SECPERDAY, MISSING_R8, rad2deg, PI, &
vtablenamelength
use time_manager_mod, only : time_type, set_time, set_date, get_date, get_time,&
print_time, print_date, &
operator(*), operator(+), operator(-), &
operator(>), operator(<), operator(/), &
operator(/=), operator(<=)
use location_mod, only : location_type, get_dist, set_location, get_location, &
VERTISHEIGHT, is_vertical, get_close_obs, &
loc_get_close_state => get_close_state, get_close_type, &
convert_vertical_obs, convert_vertical_state
use utilities_mod, only : register_module, error_handler, get_unit, &
E_ERR, E_WARN, E_MSG, logfileunit, nmlfileunit, &
do_output, to_upper, do_nml_file, do_nml_term, &
find_namelist_in_file, check_namelist_read, &
file_exist, find_textfile_dims, file_to_text
use netcdf_utilities_mod, only : nc_add_global_attribute, nc_get_global_attribute, &
nc_synchronize_file, nc_add_global_creation_time, &
nc_begin_define_mode, nc_end_define_mode, &
nc_add_attribute_to_variable, nc_define_dimension, &
nc_define_real_variable, nc_define_integer_variable, &
nc_put_variable, nc_open_file_readonly, &
nc_create_file, nc_close_file
use obs_kind_mod, only : QTY_TEMPERATURE, QTY_SALINITY, QTY_DRY_LAND, &
QTY_U_CURRENT_COMPONENT,QTY_V_CURRENT_COMPONENT, &
QTY_SEA_SURFACE_HEIGHT, QTY_SEA_SURFACE_PRESSURE, &
QTY_POTENTIAL_TEMPERATURE, QTY_SEA_SURFACE_ANOMALY, &
get_index_for_quantity, get_name_for_quantity
use mpi_utilities_mod, only: my_task_id, task_count
use random_seq_mod, only: random_seq_type, init_random_seq, random_gaussian
use dart_pop_mod, only: set_model_time_step, &
get_horiz_grid_dims, get_vert_grid_dim, &
read_horiz_grid, read_topography, read_vert_grid, &
get_pop_restart_filename, set_binary_file_conversion, &
read_mean_dynamic_topography
use ensemble_manager_mod, only : ensemble_type
use distributed_state_mod, only : get_state
use state_structure_mod, only : add_domain, get_model_variable_indices, &
get_num_variables, get_index_start, &
get_num_dims, get_domain_size, &
get_dart_vector_index
use default_model_mod, only : adv_1step, init_time, init_conditions, nc_write_model_vars
use typesizes
use netcdf
implicit none
private
! these routines must be public and you cannot change
! the arguments - they will be called *from* the DART code.
!> required routines with code in this module
public :: get_model_size, &
get_state_meta_data, &
model_interpolate, &
shortest_time_between_assimilations, &
static_init_model, &
end_model, &
pert_model_copies, &
get_close_state, &
nc_write_model_atts, &
read_model_time, &
write_model_time
!> required routines where code is in other modules
public :: adv_1step, &
init_time, &
init_conditions, &
get_close_obs, &
nc_write_model_vars, &
convert_vertical_obs, &
convert_vertical_state
! generally useful routines for various support purposes.
! the interfaces here can be changed as appropriate.
public :: get_gridsize, &
get_pop_restart_filename, &
test_interpolation
! version controlled file description for error handling, do not edit
character(len=256), parameter :: source = &
"$URL$"
character(len=32 ), parameter :: revision = "$Revision$"
character(len=128), parameter :: revdate = "$Date$"
! message strings
character(len=512) :: string1
character(len=512) :: string2
character(len=512) :: string3
logical, save :: module_initialized = .false.
! Storage for a random sequence for perturbing a single initial state
type(random_seq_type) :: random_seq
! DART state vector contents are specified in the input.nml:&model_nml namelist.
integer, parameter :: max_state_variables = 10
integer, parameter :: num_state_table_columns = 3
character(len=vtablenamelength) :: variable_table( max_state_variables, num_state_table_columns )
integer :: state_kinds_list( max_state_variables )
logical :: update_var_list( max_state_variables )
! identifiers for variable_table
integer, parameter :: VAR_NAME_INDEX = 1
integer, parameter :: VAR_QTY_INDEX = 2
integer, parameter :: VAR_UPDATE_INDEX = 3
! things which can/should be in the model_nml
integer :: assimilation_period_days = -1
integer :: assimilation_period_seconds = -1
real(r8) :: model_perturbation_amplitude = 0.2
logical :: update_dry_cell_walls = .false.
character(len=vtablenamelength) :: model_state_variables(max_state_variables * num_state_table_columns ) = ' '
integer :: debug = 0 ! turn up for more and more debug messages
! only valid values: native, big_endian, little_endian
character(len=32) :: binary_grid_file_format = 'big_endian'
character(len=256) :: mdt_reference_file_name = 'none'
! FIXME: currently the update_dry_cell_walls namelist value DOES
! NOTHING. it needs additional code to detect the cells which are
! wet, but within 1 cell of the bottom/sides/etc.
namelist /model_nml/ &
assimilation_period_days, & ! for now, this is the timestep
assimilation_period_seconds, &
model_perturbation_amplitude,&
update_dry_cell_walls, &
model_state_variables, &
binary_grid_file_format, &
mdt_reference_file_name, &
debug
!------------------------------------------------------------------
!
! The default DART state vector (control vector) will consist of: S, T, U, V, PSURF
! (Salinity, Temperature, U velocity, V velocity, Sea Surface Height).
! S, T are 3D arrays, located at cell centers. U,V are at grid cell corners.
! PSURF is a 2D field (X,Y only). The Z direction is downward.
!
! Additional variables can be read into the state vector using the
! model_state_variables namelist by specifying the netcdf variable name
! dart kind string and an update string. Currently the update string
! is not being used.
!------------------------------------------------------------------
! Number of fields in the state vector
integer :: nfields
! Grid parameters - the values will be read from a
! standard POP namelist and filled in here.
! nx, ny and nz are the size of the dipole (or irregular) grids.
integer :: Nx=-1, Ny=-1, Nz=-1 ! grid counts for each field
! locations of cell centers (C) and edges (G) for each axis.
real(r8), allocatable :: ZC(:), ZG(:)
! These arrays store the longitude and latitude of the lower left corner of
! each of the dipole u quadrilaterals and t quadrilaterals.
real(r8), allocatable :: ULAT(:,:), ULON(:,:), TLAT(:,:), TLON(:,:)
! integer, lowest valid cell number in the vertical
integer, allocatable :: KMT(:, :), KMU(:, :)
! real 'mean' dynamic sea surface topography
!>@todo only allocate if we need it ...
real(r8), allocatable :: MDT(:,:)
! compute pressure based on depth - can do once upfront.
real(r8), allocatable :: pressure(:)
real(r8) :: endTime
real(r8) :: ocean_dynamics_timestep = 900.0_r4
integer :: timestepcount = 0
type(time_type) :: model_time, model_timestep
integer(i8) :: model_size ! the state vector length
!------------------------------------------------
! NOTE (dipole/tripole grids): since both of the dipole and tripole
! grids are logically rectangular we can use the same interpolation
! scheme originally implemented for the dipole grid. Here we can
! interchange dipole and tripole when reading the code.
! The regular grid used for dipole interpolation divides the sphere into
! a set of regularly spaced lon-lat boxes. The number of boxes in
! longitude and latitude are set by num_reg_x and num_reg_y. Making the
! number of regular boxes smaller decreases the computation required for
! doing each interpolation but increases the static storage requirements
! and the initialization computation (which seems to be pretty small).
! FIX ME: to account for various grid sizes we should dynamically
! allocate these numbers. To keep max_reg_list_num < 100 we can use:
! tx0.1v2 num_reg_x = num_reg_y = 900
! tx0.5v1 num_reg_x = num_reg_y = 180
! gx1v6 num_reg_x = num_reg_y = 90
! Larger num_reg_(x,y) values require more temporary storage in
! ureg_list_lon, ureg_list_lat, treg_list_lon, treg_list_lat. For now
! we can use num_reg_(x,y) = 180 and max_reg_list_num = 800 to account
! for all of the currently implemented grid types.
integer, parameter :: num_reg_x = 180, num_reg_y = 180
! The max_reg_list_num controls the size of temporary storage used for
! initializing the regular grid. Four arrays
! of size num_reg_x*num_reg_y*max_reg_list_num are needed. The initialization
! fails and returns an error if max_reg_list_num is too small. With 180 regular
! lat lon boxes a value of 30 is sufficient for the gx3 POP grid, 80 for the
! gx1 grid, 180 for the tx0.5 grid and 800 for the tx0.1 grid.
! FIX ME: we should declare this at runtime depending on the grid size.
integer, parameter :: max_reg_list_num = 800
! The dipole interpolation keeps a list of how many and which dipole quads
! overlap each regular lon-lat box. The number for the u and t grids are
! stored in u_dipole_num and t_dipole_num. The allocatable arrays
! u_dipole_lon(lat)_list and t_dipole_lon(lat)_list list the longitude
! and latitude indices for the overlapping dipole quads. The entry in
! u_dipole_start and t_dipole_start for a given regular lon-lat box indicates
! where the list of dipole quads begins in the u_dipole_lon(lat)_list and
! t_dipole_lon(lat)_list arrays.
integer :: u_dipole_start(num_reg_x, num_reg_y)
integer :: u_dipole_num (num_reg_x, num_reg_y) = 0
integer :: t_dipole_start(num_reg_x, num_reg_y)
integer :: t_dipole_num (num_reg_x, num_reg_y) = 0
integer, allocatable :: u_dipole_lon_list(:), t_dipole_lon_list(:)
integer, allocatable :: u_dipole_lat_list(:), t_dipole_lat_list(:)
! Need to check for pole quads: for now we are not interpolating in them
integer :: pole_x, t_pole_y, u_pole_y
! Have a global variable saying whether this is dipole or regular lon-lat grid
! This should be initialized static_init_model. Code to do this is below.
logical :: dipole_grid
! global domain id to be used by routines in state_structure_mod
integer :: domain_id
contains
!------------------------------------------------------------------
!------------------------------------------------------------------
subroutine static_init_model()
! Called to do one time initialization of the model. In this case,
! it reads in the grid information.
integer :: iunit, io
integer :: ss, dd
! The Plan:
!
! read in the grid sizes from the horiz grid file and the vert grid file
! horiz is netcdf, vert is ascii
!
! allocate space, and read in actual grid values
!
! figure out model timestep. FIXME: from where?
!
! Compute the model size.
!
! set the index numbers where the field types change
!
if ( module_initialized ) return ! only need to do this once.
! Print module information to log file and stdout.
call register_module(source, revision, revdate)
! Since this routine calls other routines that could call this routine
! we'll say we've been initialized pretty dang early.
module_initialized = .true.
! Read the DART namelist for this model
call find_namelist_in_file('input.nml', 'model_nml', iunit)
read(iunit, nml = model_nml, iostat = io)
call check_namelist_read(iunit, io, 'model_nml')
! Record the namelist values used for the run
call error_handler(E_MSG,'static_init_model','model_nml values are',' ',' ',' ')
if (do_nml_file()) write(nmlfileunit, nml=model_nml)
if (do_nml_term()) write( * , nml=model_nml)
! Set the time step ... causes POP namelists to be read.
! Ensures model_timestep is multiple of 'ocean_dynamics_timestep'
model_timestep = set_model_time_step(assimilation_period_seconds, assimilation_period_days)
call get_time(model_timestep,ss,dd) ! set_time() assures the seconds [0,86400)
write(string1,*)'assimilation period is ',dd,' days ',ss,' seconds'
call error_handler(E_MSG,'static_init_model',string1,source,revision,revdate)
! BEFORE calling grid routines, set the endian-ness of the binary files if needed.
call set_binary_file_conversion(binary_grid_file_format)
! get data dimensions, then allocate space, then open the files
! and actually fill in the arrays.
call get_horiz_grid_dims(Nx, Ny)
call get_vert_grid_dim(Nz)
! Allocate space for grid variables.
allocate(ULAT(Nx,Ny), ULON(Nx,Ny), TLAT(Nx,Ny), TLON(Nx,Ny))
allocate( KMT(Nx,Ny), KMU(Nx,Ny))
allocate( ZC(Nz), ZG(Nz))
! Fill them in.
! horiz grid initializes ULAT/LON, TLAT/LON as well.
call read_horiz_grid(Nx, Ny, ULAT, ULON, TLAT, TLON)
call read_topography(Nx, Ny, KMT, KMU)
call read_vert_grid( Nz, ZC, ZG)
if (mdt_reference_file_name /= 'none') then
allocate( MDT(Nx,Ny))
call read_mean_dynamic_topography(mdt_reference_file_name, MDT)
endif
if (debug > 2) call write_grid_netcdf() ! DEBUG only
if (debug > 2) call write_grid_interptest() ! DEBUG only
! verify that the model_state_variables namelist was filled in correctly.
! returns variable_table which has variable names, kinds and update strings.
call verify_state_variables(model_state_variables, nfields, variable_table, state_kinds_list, update_var_list)
! in spite of the staggering, all grids are the same size
! and offset by half a grid cell. 4 are 3D and 1 is 2D.
! e.g. S,T,U,V = 256 x 225 x 70
! e.g. PSURF = 256 x 225
if (do_output()) write(logfileunit, *) 'Using grid : Nx, Ny, Nz = ', &
Nx, Ny, Nz
if (do_output()) write( * , *) 'Using grid : Nx, Ny, Nz = ', &
Nx, Ny, Nz
! initialize the pressure array - pressure in bars
allocate(pressure(Nz))
call dpth2pres(Nz, ZC, pressure)
! Initialize the interpolation routines
call init_interp()
!> @todo 'pop.r.nc' is hardcoded in dart_pop_mod.f90
domain_id = add_domain('pop.r.nc', nfields, &
var_names = variable_table(1:nfields, VAR_NAME_INDEX), &
update_list = update_var_list(1:nfields))
model_size = get_domain_size(domain_id)
if (do_output()) write(*,*) 'model_size = ', model_size
end subroutine static_init_model
!------------------------------------------------------------
!> Initializes data structures needed for POP interpolation for
!> either dipole or irregular grid.
!> This should be called at static_init_model time to avoid
!> having all this temporary storage in the middle of a run.
subroutine init_interp()
integer :: i
! Determine whether this is a irregular lon-lat grid or a dipole.
! Do this by seeing if the lons have the same values at both
! the first and last latitude row; this is not the case for dipole.
dipole_grid = .false.
do i = 1, nx
if(ulon(i, 1) /= ulon(i, ny)) then
dipole_grid = .true.
call init_dipole_interp()
return
endif
enddo
end subroutine init_interp
!------------------------------------------------------------
!> Build the data structure for interpolation for a dipole grid.
subroutine init_dipole_interp()
! Need a temporary data structure to build this.
! These arrays keep a list of the x and y indices of dipole quads
! that potentially overlap the regular boxes. Need one for the u
! and one for the t grid.
integer, allocatable :: ureg_list_lon(:,:,:)
integer, allocatable :: ureg_list_lat(:,:,:)
integer, allocatable :: treg_list_lon(:,:,:)
integer, allocatable :: treg_list_lat(:,:,:)
real(r8) :: u_c_lons(4), u_c_lats(4), t_c_lons(4), t_c_lats(4), pole_row_lon
integer :: i, j, k, pindex
integer :: reg_lon_ind(2), reg_lat_ind(2), u_total, t_total, u_index, t_index
logical :: is_pole
integer :: surf_index
allocate(ureg_list_lon(num_reg_x, num_reg_y, max_reg_list_num))
allocate(ureg_list_lat(num_reg_x, num_reg_y, max_reg_list_num))
allocate(treg_list_lon(num_reg_x, num_reg_y, max_reg_list_num))
allocate(treg_list_lat(num_reg_x, num_reg_y, max_reg_list_num))
! this is the level threshold for deciding whether we are over land
! or water. to be valid all 4 corners of the quad must have a level
! number greater than this index. (so 0 excludes all land points.)
! if you wanted to assimilate only in regions where the water depth is
! deeper than some threshold, set this index to N and only quads where
! all the level numbers are N+1 or deeper will be used.
surf_index = 1
! Begin by finding the quad that contains the pole for the dipole t_grid.
! To do this locate the u quad with the pole on its right boundary. This is on
! the row that is opposite the shifted pole and exactly follows a lon circle.
pole_x = nx / 2;
! Search for the row at which the longitude flips over the pole
pole_row_lon = ulon(pole_x, 1);
do i = 1, ny
pindex = i
if(ulon(pole_x, i) /= pole_row_lon) exit
enddo
! Pole boxes for u have indices pole_x or pole_x-1 and index - 1;
! (it's right before the flip).
u_pole_y = pindex - 1;
! Locate the T dipole quad that contains the pole.
! We know it is in either the same lat quad as the u pole edge or one higher.
! Figure out if the pole is more or less than halfway along
! the u quad edge to find the right one.
if(ulat(pole_x, u_pole_y) > ulat(pole_x, u_pole_y + 1)) then
t_pole_y = u_pole_y;
else
t_pole_y = u_pole_y + 1;
endif
! Loop through each of the dipole grid quads
do i = 1, nx
! There's no wraparound in y, one box less than grid boundaries
do j = 1, ny - 1
! Only update regular boxes that contain all wet corners
if( all_corners_wet(QTY_U_CURRENT_COMPONENT,i,j,surf_index) ) then
! Set up array of lons and lats for the corners of these u quads
call get_quad_corners(ulon, i, j, u_c_lons)
call get_quad_corners(ulat, i, j, u_c_lats)
! Get list of regular boxes that cover this u dipole quad
! false indicates that for the u grid there's nothing special about pole
call reg_box_overlap(u_c_lons, u_c_lats, .false., reg_lon_ind, reg_lat_ind)
! Update the temporary data structures for the u quad
call update_reg_list(u_dipole_num, ureg_list_lon, &
ureg_list_lat, reg_lon_ind, reg_lat_ind, i, j)
endif
! Repeat for t dipole quads.
! Only update regular boxes that contain all wet corners
if( all_corners_wet(QTY_TEMPERATURE,i,j,surf_index) ) then
! Set up array of lons and lats for the corners of these t quads
call get_quad_corners(tlon, i, j, t_c_lons)
call get_quad_corners(tlat, i, j, t_c_lats)
! Is this the pole quad for the T grid?
is_pole = (i == pole_x .and. j == t_pole_y)
call reg_box_overlap(t_c_lons, t_c_lats, is_pole, reg_lon_ind, reg_lat_ind)
call update_reg_list(t_dipole_num, treg_list_lon, &
treg_list_lat, reg_lon_ind, reg_lat_ind, i, j)
endif
enddo
enddo
if (do_output()) write(*,*)'to determine (minimum) max_reg_list_num values for new grids ...'
if (do_output()) write(*,*)'u_dipole_num is ',maxval(u_dipole_num)
if (do_output()) write(*,*)'t_dipole_num is ',maxval(t_dipole_num)
! Invert the temporary data structure. The total number of entries will be
! the sum of the number of dipole cells for each regular cell.
u_total = sum(u_dipole_num)
t_total = sum(t_dipole_num)
! Allocate storage for the final structures in module storage
allocate(u_dipole_lon_list(u_total), u_dipole_lat_list(u_total))
allocate(t_dipole_lon_list(t_total), t_dipole_lat_list(t_total))
! Fill up the long list by traversing the temporary structure. Need indices
! to keep track of where to put the next entry.
u_index = 1
t_index = 1
! Loop through each regular grid box
do i = 1, num_reg_x
do j = 1, num_reg_y
! The list for this regular box starts at the current indices.
u_dipole_start(i, j) = u_index
t_dipole_start(i, j) = t_index
! Copy all the close dipole quads for regular u box(i, j)
do k = 1, u_dipole_num(i, j)
u_dipole_lon_list(u_index) = ureg_list_lon(i, j, k)
u_dipole_lat_list(u_index) = ureg_list_lat(i, j, k)
u_index = u_index + 1
enddo
! Copy all the close dipoles for regular t box (i, j)
do k = 1, t_dipole_num(i, j)
t_dipole_lon_list(t_index) = treg_list_lon(i, j, k)
t_dipole_lat_list(t_index) = treg_list_lat(i, j, k)
t_index = t_index + 1
enddo
enddo
enddo
! Confirm that the indices come out okay as debug
if(u_index /= u_total + 1) then
string1 = 'Storage indices did not balance for U grid: : contact DART developers'
call error_handler(E_ERR, 'init_dipole_interp', string1, source, revision, revdate)
endif
if(t_index /= t_total + 1) then
string1 = 'Storage indices did not balance for T grid: : contact DART developers'
call error_handler(E_ERR, 'init_dipole_interp', string1, source, revision, revdate)
endif
end subroutine init_dipole_interp
!------------------------------------------------------------
!> Given a longitude and latitude in degrees returns the index of the regular
!> lon-lat box that contains the point.
subroutine get_reg_box_indices(lon, lat, x_ind, y_ind)
real(r8), intent(in) :: lon, lat
integer, intent(out) :: x_ind, y_ind
call get_reg_lon_box(lon, x_ind)
call get_reg_lat_box(lat, y_ind)
end subroutine get_reg_box_indices
!------------------------------------------------------------
!> Determine which regular longitude box a longitude is in.
subroutine get_reg_lon_box(lon, x_ind)
real(r8), intent(in) :: lon
integer, intent(out) :: x_ind
x_ind = int(num_reg_x * lon / 360.0_r8) + 1
! Watch out for exactly at top; assume all lats and lons in legal range
if(lon == 360.0_r8) x_ind = num_reg_x
end subroutine get_reg_lon_box
!------------------------------------------------------------
!> Determine which regular latitude box a latitude is in.
subroutine get_reg_lat_box(lat, y_ind)
real(r8), intent(in) :: lat
integer, intent(out) :: y_ind
y_ind = int(num_reg_y * (lat + 90.0_r8) / 180.0_r8) + 1
! Watch out for exactly at top; assume all lats and lons in legal range
if(lat == 90.0_r8) y_ind = num_reg_y
end subroutine get_reg_lat_box
!------------------------------------------------------------
!> Find a set of regular lat lon boxes that covers all of the area covered by
!> a dipole grid qaud whose corners are given by the dimension four x_corners
!> and y_corners arrays.
subroutine reg_box_overlap(x_corners, y_corners, is_pole, reg_lon_ind, reg_lat_ind)
real(r8), intent(in) :: x_corners(4), y_corners(4)
logical, intent(in) :: is_pole
integer, intent(out) :: reg_lon_ind(2), reg_lat_ind(2)
! The two dimensional arrays reg_lon_ind and reg_lat_ind
! return the first and last indices of the regular boxes in latitude and
! longitude respectively. These indices may wraparound for reg_lon_ind.
! A special computation is needed for a dipole quad that has the true north
! pole in its interior. The logical is_pole is set to true if this is the case.
! This can only happen for the t grid. If the longitude boxes overlap 0
! degrees, the indices returned are adjusted by adding the total number of
! boxes to the second index (e.g. the indices might be 88 and 93 for a case
! with 90 longitude boxes).
real(r8) :: lat_min, lat_max, lon_min, lon_max
integer :: i
! A quad containing the pole is fundamentally different
if(is_pole) then
! Need all longitude boxes
reg_lon_ind(1) = 1
reg_lon_ind(2) = num_reg_x
! Need to cover from lowest latitude to top box
lat_min = minval(y_corners)
reg_lat_ind(1) = int(num_reg_y * (lat_min + 90.0_r8) / 180.0_r8) + 1
call get_reg_lat_box(lat_min, reg_lat_ind(1))
reg_lat_ind(2) = num_reg_y
else
! All other quads do not contain pole (pole could be on edge but no problem)
! This is specific to the dipole POP grids that do not go to the south pole
! Finding the range of latitudes is cake
lat_min = minval(y_corners)
lat_max = maxval(y_corners)
! Figure out the indices of the regular boxes for min and max lats
call get_reg_lat_box(lat_min, reg_lat_ind(1))
call get_reg_lat_box(lat_max, reg_lat_ind(2))
! Lons are much trickier. Need to make sure to wraparound the
! right way. There is no guarantee on direction of lons in the
! high latitude dipole rows.
! All longitudes for non-pole rows have to be within 180 degrees
! of one another.
lon_min = minval(x_corners)
lon_max = maxval(x_corners)
if((lon_max - lon_min) > 180.0_r8) then
! If the max longitude value is more than 180
! degrees larger than the min, then there must be wraparound.
! Then, find the smallest value > 180 and the largest < 180 to get range.
lon_min = 360.0_r8
lon_max = 0.0_r8
do i=1, 4
if(x_corners(i) > 180.0_r8 .and. x_corners(i) < lon_min) lon_min = x_corners(i)
if(x_corners(i) < 180.0_r8 .and. x_corners(i) > lon_max) lon_max = x_corners(i)
enddo
endif
! Get the indices for the extreme longitudes
call get_reg_lon_box(lon_min, reg_lon_ind(1))
call get_reg_lon_box(lon_max, reg_lon_ind(2))
! Watch for wraparound again; make sure that second index is greater than first
if(reg_lon_ind(2) < reg_lon_ind(1)) reg_lon_ind(2) = reg_lon_ind(2) + num_reg_x
endif
end subroutine reg_box_overlap
!------------------------------------------------------------
!> Grabs the corners for a given quadrilateral from the global array of lower
!> right corners. Note that corners go counterclockwise around the quad.
subroutine get_quad_corners(x, i, j, corners)
real(r8), intent(in) :: x(:, :)
integer, intent(in) :: i, j
real(r8), intent(out) :: corners(4)
integer :: ip1
! Have to worry about wrapping in longitude but not in latitude
ip1 = i + 1
if(ip1 > nx) ip1 = 1
corners(1) = x(i, j )
corners(2) = x(ip1, j )
corners(3) = x(ip1, j+1)
corners(4) = x(i, j+1)
end subroutine get_quad_corners
!------------------------------------------------------------
!> Updates the data structure listing dipole quads that are in a given regular box
subroutine update_reg_list(reg_list_num, reg_list_lon, reg_list_lat, &
reg_lon_ind, reg_lat_ind, dipole_lon_index, dipole_lat_index)
integer, intent(inout) :: reg_list_num(:, :), reg_list_lon(:, :, :), reg_list_lat(:, :, :)
integer, intent(inout) :: reg_lon_ind(2), reg_lat_ind(2)
integer, intent(in) :: dipole_lon_index, dipole_lat_index
integer :: ind_x, index_x, ind_y
! Loop through indices for each possible regular cell
! Have to watch for wraparound in longitude
if(reg_lon_ind(2) < reg_lon_ind(1)) reg_lon_ind(2) = reg_lon_ind(2) + num_reg_x
do ind_x = reg_lon_ind(1), reg_lon_ind(2)
! Inside loop, need to go back to wraparound indices to find right box
index_x = ind_x
if(index_x > num_reg_x) index_x = index_x - num_reg_x
do ind_y = reg_lat_ind(1), reg_lat_ind(2)
! Make sure the list storage isn't full
if(reg_list_num(index_x, ind_y) >= max_reg_list_num) then
write(string1,*) 'max_reg_list_num (',max_reg_list_num,') is too small ... increase'
string2 = "increase model_mod:max_reg_list_num and recompile."
call error_handler(E_ERR, 'update_reg_list', string1, source, revision, revdate, &
text2=string2)
endif
! Increment the count
reg_list_num(index_x, ind_y) = reg_list_num(index_x, ind_y) + 1
! Store this quad in the list for this regular box
reg_list_lon(index_x, ind_y, reg_list_num(index_x, ind_y)) = dipole_lon_index
reg_list_lat(index_x, ind_y, reg_list_num(index_x, ind_y)) = dipole_lat_index
enddo
enddo
end subroutine update_reg_list
!------------------------------------------------------------------
!> Returns the size of the model as an integer.
!> Required for all applications.
function get_model_size()
integer(i8) :: get_model_size
if ( .not. module_initialized ) call static_init_model
get_model_size = model_size
end function get_model_size
!------------------------------------------------------------------
!> Model interpolate will interpolate any state variable (i.e. S, T, U, V, PSURF) to
!> the given location given a state vector. The type of the variable being
!> interpolated is obs_type since normally this is used to find the expected
!> value of an observation at some location. The interpolated value is
!> returned in interp_val and istatus is 0 for success.
subroutine model_interpolate(state_handle, ens_size, location, obs_type, expected_obs, istatus)
type(ensemble_type), intent(in) :: state_handle
integer, intent(in) :: ens_size
type(location_type), intent(in) :: location
integer, intent(in) :: obs_type
integer, intent(out) :: istatus(ens_size)
real(r8), intent(out) :: expected_obs(ens_size) !< array of interpolated values
! Local storage
real(r8) :: loc_array(3), llon, llat, lheight
integer(i8) :: base_offset
integer :: ind
integer :: hgt_bot, hgt_top
real(r8) :: hgt_fract
integer :: hstatus
logical :: convert_to_ssh
integer :: e
real(r8) :: expected_mdt
if ( .not. module_initialized ) call static_init_model
! Let's assume failure. Set return val to missing, then the code can
! just set istatus to something indicating why it failed, and return.
! If the interpolation is good, the interp_val will be set to the
! good value, and the last line here sets istatus to 0.
! make any error codes set here be in the 10s
expected_obs(:) = MISSING_R8 ! the DART bad value flag
istatus(:) = 99 ! unknown error
! Get the individual locations values
loc_array = get_location(location)
llon = loc_array(1)
llat = loc_array(2)
lheight = loc_array(3)
if (debug > 1) print *, 'requesting interpolation of ', obs_type, ' at ', llon, llat, lheight
if (is_vertical(location, "LEVEL")) then
! convert the level index to an actual depth
ind = nint(loc_array(3))
if ( (ind < 1) .or. (ind > size(zc)) ) then
istatus = 11
return
else
lheight = zc(ind)
endif
elseif (is_vertical(location, "HEIGHT") .or. is_vertical(location, "SURFACE")) then
! Nothing to do and it's ok
else
! a vertical coordinate of pressure or undefined isn't supported
istatus = 17
return
endif
! kind (in-situ) temperature is a combination of potential temp,
! salinity, and pressure based on depth. call a routine that
! interpolates all three, does the conversion, and returns the
! sensible/in-situ temperature.
if(obs_type == QTY_TEMPERATURE) then
! we know how to interpolate this from potential temp,
! salinity, and pressure based on depth.
call compute_temperature(state_handle, ens_size, llon, llat, lheight, expected_obs, istatus)
if (debug > 1) print *, 'interp val, istatus = ', expected_obs, istatus
return
endif
!>@todo put all these into the CASE statement ...
! POP's sea surface height and the mean dynamic topography for this location
! are needed to calculate the SSA. The mean dynamic topography can be
! extracted by providing the optional argument to lon_lat_interpolate()
! The POP SSH can be derived by converting the SEA SURFACE PRESSURE
! The POP state is CGS, the observations (and mdt) are SI.
if(obs_type == QTY_SEA_SURFACE_ANOMALY) then
if (mdt_reference_file_name == 'none') then
string1 = 'Mean Dynamic Topography unavailable.'
string2 = 'Forward Operator for QTY_SEA_SURFACE_ANOMALY observations unavailable.'
string3 = 'This filename is specified by input.nml:model_nml:mdt_reference_file_name'
call error_handler(E_ERR,'model_interpolate', string1, &
source, revision, revdate, text2=string2, text3=string3)
endif
base_offset = get_index_start(domain_id, get_varid_from_kind(QTY_SEA_SURFACE_PRESSURE))
call lon_lat_interpolate(state_handle, ens_size, base_offset, llon, llat, &
QTY_SEA_SURFACE_HEIGHT, 1, expected_obs, istatus, expected_mdt)
where(istatus == 0) expected_obs = expected_obs/98060.0_r8 - expected_mdt ! use meters
return
endif
! The following kinds are either in the state vector (so you
! can simply interpolate to find the value) or they are a simple
! transformation of something in the state vector.
convert_to_ssh = .FALSE.
SELECT CASE (obs_type)
CASE (QTY_SALINITY, &
QTY_POTENTIAL_TEMPERATURE, &
QTY_U_CURRENT_COMPONENT, &
QTY_V_CURRENT_COMPONENT, &
QTY_SEA_SURFACE_PRESSURE)
base_offset = get_index_start(domain_id, get_varid_from_kind(obs_type))
CASE (QTY_SEA_SURFACE_HEIGHT)
base_offset = get_index_start(domain_id, get_varid_from_kind(QTY_SEA_SURFACE_PRESSURE))
convert_to_ssh = .TRUE. ! simple linear transform of PSURF
CASE DEFAULT
! Not a legal type for interpolation, return istatus error
istatus = 15
return
END SELECT
! For Sea Surface Height or Pressure don't need the vertical coordinate
! SSP needs to be converted to a SSH if height is required.
if( is_vertical(location, "SURFACE") ) then
!>@todo HK CHECK surface observations
call lon_lat_interpolate(state_handle, ens_size, base_offset, llon, llat, obs_type, 1, expected_obs, istatus)
if (convert_to_ssh) where(istatus == 0) expected_obs = expected_obs/980.6_r8 ! POP uses CGS units
return
endif
! Get the bounding vertical levels and the fraction between bottom and top
call height_bounds(lheight, Nz, ZC, hgt_bot, hgt_top, hgt_fract, hstatus)
if(hstatus /= 0) then
istatus = 12
return
endif
! do a 2d interpolation for the value at the bottom level, then again for
! the top level, then do a linear interpolation in the vertical to get the
! final value. this sets both interp_val and istatus.
call do_interp(state_handle, ens_size, base_offset, hgt_bot, hgt_top, hgt_fract, &
llon, llat, obs_type, expected_obs, istatus)
if (debug > 1) print *, 'interp val, istatus = ', expected_obs, istatus
end subroutine model_interpolate
!------------------------------------------------------------------
!> Three different types of grids are used here. The POP dipole
!> grid is referred to as a dipole grid and each region is
!> referred to as a quad, short for quadrilateral.
!> The longitude latitude rectangular grid with possibly irregular
!> spacing in latitude used for some POP applications and testing
!> is referred to as the irregular grid and each region is
!> called a box.
!> Finally, a regularly spaced longitude latitude grid is used
!> as a computational tool for interpolating from the dipole
!> grid. This is referred to as the regular grid and each region
!> is called a box.
!> All grids are referenced by the index of the lower left corner
!> of the quad or box.
!>
!> The dipole grid is assumed to be global for all applications.
!> The irregular grid is also assumed to be global east
!> west for all applications.
subroutine lon_lat_interpolate(state_handle, ens_size, offset, lon, lat, var_type, &
height, expected_obs, istatus, expected_mdt)
type(ensemble_type), intent(in) :: state_handle
integer, intent(in) :: ens_size
integer(i8), intent(in) :: offset ! Not sure if this is the best way to do this
real(r8), intent(in) :: lon, lat
integer, intent(in) :: var_type, height
real(r8), intent(out) :: expected_obs(ens_size)
integer, intent(out) :: istatus(ens_size)
real(r8), optional, intent(out) :: expected_mdt ! Mean Dynamic Topography
! Is height ens_size? Should quad status be ens_size?
! Subroutine to interpolate to a lon lat location given the state vector
! for that level, x. This works just on one horizontal slice.
! NOTE: Using array sections to pass in the x array may be inefficient on some
! compiler/platform setups. Might want to pass in the entire array with a base
! offset value instead of the section if this is an issue.
! This routine works for either the dipole or a regular lat-lon grid.
! Successful interpolation returns istatus=0.
! Local storage
integer :: lat_bot, lat_top, lon_bot, lon_top, num_inds, start_ind
integer :: x_ind, y_ind
real(r8) :: x_corners(4), y_corners(4)
real(r8) :: p(4,ens_size), xbot(ens_size), xtop(ens_size)
real(r8) :: mdtbot, mdttop
real(r8) :: lon_fract, lat_fract
logical :: masked
integer :: quad_status
integer :: e
real(r8) :: pmdt(4)
if ( .not. module_initialized ) call static_init_model
! Succesful return has istatus of 0
istatus = 0
! Get the lower left corner for either grid type
if(dipole_grid) then
! Figure out which of the regular grid boxes this is in
call get_reg_box_indices(lon, lat, x_ind, y_ind)
! Is this on the U or T grid?
if(is_on_ugrid(var_type)) then
! On U grid
num_inds = u_dipole_num (x_ind, y_ind)
start_ind = u_dipole_start(x_ind, y_ind)
! If there are no quads overlapping, can't do interpolation
if(num_inds == 0) then
istatus = 1
return
endif
! Search the list of quads to see if (lon, lat) is in one
call get_dipole_quad(lon, lat, ulon, ulat, num_inds, start_ind, &
u_dipole_lon_list, u_dipole_lat_list, lon_bot, lat_bot, quad_status)
! Fail on bad istatus return
if(quad_status /= 0) then
istatus = quad_status
return
endif
! Getting corners for accurate interpolation
call get_quad_corners(ulon, lon_bot, lat_bot, x_corners)
call get_quad_corners(ulat, lon_bot, lat_bot, y_corners)
! Fail if point is in one of the U boxes that go through the
! pole (this could be fixed up if necessary)
if(lat_bot == u_pole_y .and. (lon_bot == pole_x -1 .or. &
lon_bot == pole_x)) then
istatus = 4
return