#!/usr/bin/env python

# script to sequentially run adcpsect, refabs and smoothr for a
# set of reference layers, then run adcpsect to generate a mask file
# for switching between two of the layers, then run the matlab
# script "blend_sm" to blend the two layers, then run putnav to
# apply the result to the database.
#
# EF 2000/09/27 written
# JH 2001/06/15 added blend_sm plotting

import sys, os, os.path, string


yearbase = 2001
dbname = '../adcpdb/a0101'
fixfile_suffix = 'ags'

# plot which reference layer was used: (goes to screen and disk ("blendsm.ps"))
# turn off by setting plotit = 0
plotit = 1


# Base directory for our matlab files; location of efpath.m, codas3, misc, etc.

matpath = '/home/noio/programs/matlab'


# Layer list that is commented out may be useful for checking
# the depth-dependence of the calibration scale factor.

#layers = ((3, 6), (20, 40), (5, 10), (10, 20), (20, 30), (30, 40), (40, 50), (50, 60),
#          (20, 40))

# Otherwise, only two layers are needed.

layers = ((5, 10),  (20, 40))

# Regardless of how many layers are calculated, the first two will
# be used to make the final position/velocity estimate file, blend.sm.

# Require a high percent good near the bottom of the deep reference
# layer for that layer to be used; otherwise switch to the shallower
# layer.  The pg threshold for switching is the following:

navmaskpg = 80


#===============================================================

shallowreffile = '%02d_%02d.sm' % layers[0]
deepreffile = '%02d_%02d.sm' % layers[1]
navmaskbins = (layers[1][1] - 5, layers[1][1])  # last 6 bins
navmaskbase = '%02d_%02d_%02d' % (navmaskbins[0], navmaskbins[1], navmaskpg)

print (shallowreffile, deepreffile, navmaskbase)

as_cnt = '''
  dbname:             %(dbname)s
  output:             %(fileroot)s
  step_size:          1        /* must be 1 for navigation */
  ndepth:             60
  time_ranges:        separate
  year_base=          %(yearbase)d

  option_list:
    pg_min=           30
    navigation:
      reference_bins  %(bin0)d  to %(bin1)d
      end
    flag_mask:        ALL_BITS
      end
    end

   all
'''

dbbase = os.path.split(dbname)[-1]
refabs_cnt = '''
  fix_file_type:    simple
  reference_file:   %(fileroot)s.nav
  fix_file:         %(dbbase)s.%(fixfile_suffix)s
  output:           %(fileroot)s.ref
  year_base=        %(yearbase)d

  ensemble_length=  300
  gap_tolerance=    10
'''


smoothr_cnt = '''
  reference_file:       %(fileroot)s.nav
  refabs_output:        %(fileroot)s.ref
  output:               %(fileroot)s.sm
  filter_hwidth=        0.0208333     /* half an hour */
  min_filter_fraction=  0.5
  max_gap_ratio=        0.05
  max_gap_distance=     50            /* meters */
  max_gap_time=         30            /* seconds */
  ensemble_time=        300           /* 5-minute ensemble */
  max_speed=            5.0
  min_speed=            1.0
  iterations=           5
  fix_to_dr_limit=      0.00050
'''

for layer in layers:

   (bin0, bin1) = layer
   fileroot = '%(bin0)02d_%(bin1)02d' % vars()

   as = open('as.cnt', 'w')
   as.write(as_cnt % vars())
   as.close()


   ref = open('ref.cnt', 'w')
   ref.write(refabs_cnt % vars())
   ref.close()

   sm = open('sm.cnt', 'w')
   sm.write(smoothr_cnt % vars())
   sm.close()

   os.system('adcpsect as.cnt')
   os.system('refabs ref.cnt')
   os.system('smoothr sm.cnt')

# Now make the mask .nav file for the deeper layer

(bin0, bin1) = navmaskbins
as_cnt = '''
  dbname:             %(dbname)s
  output:             %(navmaskbase)s
  step_size:          1        /* must be 1 for navigation */
  ndepth:             %(bin1)d
  time_ranges:        separate
  year_base=          %(yearbase)d

  option_list:
    pg_min=           %(navmaskpg)d
    navigation:
      reference_bins  %(bin0)d  to %(bin1)d
      end
    flag_mask:        ALL_BITS
      end
    end

   all
'''

as = open('as.cnt', 'w')
as.write(as_cnt % vars())
as.close()
os.system('adcpsect as.cnt')


# Blend the layers:
matpath_misc = os.path.join(matpath, 'misc')
matpath_codas3 = os.path.join(matpath, 'codas3')
matpath_utils = os.path.join(matpath, 'utils')

startup = '''
   addpath %(matpath_misc)s
   addpath %(matpath_codas3)s
   addpath %(matpath_utils)s
   plotit = %(plotit)d;
   data = blend_sm('%(navmaskbase)s.nav', '%(deepreffile)s', ...
             '%(shallowreffile)s', 'blend.sm');
   if (plotit== 1)
       figure
       plot_blendsm(data);
   end
   quit
'''

mat = open('startup.m', 'w')
mat.write(startup % vars())
mat.close()
os.system('matlab')
os.remove('startup.m')   # It would be dangerous to leave this lying around!


# Apply to the database:
putn_cnt = '''
   dbname:         %(dbname)s
   position_file:  blend.sm
   year_base=      %(yearbase)d
   tolerance=      5
   navigation_sources:
     gps
     end
'''

print "running putnav..."
putn = open('putn.cnt', 'w')
putn.write(putn_cnt % vars())
putn.close()

os.system('putnav putn.cnt')


print "NOW, make reference layer plots from the shallowest reference layer\n";




