#!/usr/bin/env python

import sys
import pickle
import pdb

from interp.grid.DD import rect_grid, random_grid
from interp.baker   import run_baker
from interp.tools   import baker_exact_2D as exact_func

qfile = '/tmp/grid_regular.txt'

if __name__ == '__main__':
  try:
    rx = int(sys.argv[1])
    ry = int(sys.argv[2])
  except (IndexError, ValueError) as e:
    print "problem with argv: %s" % e
    rx = 4
    ry = 4 * rx

  source_mesh = rect_grid(rx, ry)

  # print source_mesh

  X = [0.5, 0.5]

  try:
    print "trying to get simplex and nearest points using nearest points (kdtree)"
    (R, S) = source_mesh.get_simplex_and_nearest_points(X, extra_points=4)
    print "R for nearest-neighbor:\n", R
    print "S for nearest-neighbor:\n", S
    print "trying to run baker"
    print run_baker(X, R, S)
  except Exception as e:
    print "caught error: %s" % e

    print "trying to get simplex and nearest points using connectivity scheme"
    (R, S) =  source_mesh.get_points_conn(X)
    print "R for connectivity:\n", R
    print "S for connectivity:\n", S
    print run_baker(X, R, S)


  print "repeating the above just using the grid object:"
  r = source_mesh.run_baker(X)
  exact = exact_func(X)
  print r
  print 'exact', exact
  print 'qlin' , r['qlin']
  print 'error', r['error']
  print 'final', r['final']

  if abs(r['final'] - exact) <= abs(r['qlin'] - exact):
    print "win"
  else:
    print "failure"
  open(qfile, 'w').write(source_mesh.for_qhull())
