smbinterp/interp/grid/__init__.py

340 lines
9.9 KiB
Python
Raw Normal View History

import sys
import re
from collections import defaultdict
import inspect
import numpy as np
import scipy.spatial
2010-10-23 12:49:15 -07:00
from interp.baker import run_baker
from interp.tools import log
from simplex import face, contains
from smcqdelaunay import *
class grid(object):
def __init__(self, verts = None, q = None):
"""
this thing eats two pre-constructed arrays of floats:
verts = array of arrays (if passed in, will convert to numpy.array)
[
[x0,y0],
[x1,y1], ...
]
q = array (1D) of physical values
"""
if verts:
self.verts = np.array(verts)
self.tree = scipy.spatial.KDTree(self.verts)
if q:
self.q = np.array(q)
self.faces = {}
self.faces_for_vert = defaultdict(list)
def get_containing_simplex(self, X):
if not self.faces:
raise Exception("face connectivity is not set up")
# get closest point
(dist, indicies) = self.tree.query(X, 2)
closest_point = indicies[0]
log.debug('X: %s' % X)
log.debug('point index: %d' % closest_point)
log.debug('actual point %s' % self.verts[closest_point])
log.debug('distance = %0.4f' % dist[0])
simplex = None
checked_faces = []
faces_to_check = self.faces_for_vert[closest_point]
attempts = 0
while not simplex and faces_to_check:
attempts += 1
# if attempts > 20:
# raise Exception("probably recursing to many times")
cur_face = faces_to_check.pop(0)
checked_faces.append(cur_face)
if cur_face.contains(X, self):
simplex = cur_face
continue
new_facest = []
for neighbor in cur_face.neighbors:
if (neighbor not in checked_faces) and (neighbor not in faces_to_check):
faces_to_check.append(neighbor)
if not simplex:
raise AssertionError('no containing simplex found')
R = self.create_mesh(simplex.verts)
log.debug('total attempts before finding simplex: %d' % attempts)
return R
def create_mesh(self, indicies):
"""
this function takes a list of indicies, and then creates
and returns a grid object (collection of verts and q).
note: the input is indicies, the grid contains verts
"""
p = [self.verts[i] for i in indicies]
q = [self.q[i] for i in indicies]
return grid(p, q)
def get_simplex_and_nearest_points(self, X, extra_points = 3, simplex_size = 3):
"""
this returns two grid objects: R and S.
R is a grid object that is supposedly a containing simplex
around point X (TODO: it tends not to be)
S is S_j from baker's paper : some verts from all point that are not the simplex
"""
log.debug("extra verts: %d" % extra_points)
log.debug("simplex size: %d" % simplex_size)
r_mesh = self.get_containing_simplex(X)
# and some UNIQUE extra verts
(dist, indicies) = self.tree.query(X, simplex_size + extra_points)
log.info("extra indicies: %s" % indicies)
unique_indicies = []
for index in indicies:
close_point_in_R = False
for rvert in r_mesh.verts:
if all(rvert == self.verts[index]):
close_point_in_R = True
break
if not close_point_in_R:
unique_indicies.append(index)
else:
log.debug('throwing out %s: %s' % (index, self.verts[index]))
log.debug("indicies: %s" % indicies)
log.debug("unique indicies: %s" % unique_indicies)
s_mesh = self.create_mesh(unique_indicies)
return (r_mesh, s_mesh)
def run_baker(self, X, extra_points = 3, order = 2):
(R, S) = self.get_simplex_and_nearest_points(X, extra_points)
answer = run_baker(X, R, S, order)
return answer
def __str__(self):
r = ''
assert( len(self.verts) == len(self.q) )
for c, i in enumerate(zip(self.verts, self.q)):
r += "%d vert(%s): q(%0.4f)" % (c,i[0], i[1])
face_str = ", ".join([str(f.name) for f in self.faces_for_vert[c]])
r += " faces: [%s]" % face_str
r += "\n"
if self.faces:
for v in self.faces.itervalues():
r += "%s\n" % v
return r
class delaunay_grid(grid):
face_re = re.compile(r'''
-\s+(?P<face>f\d+).*?
vertices:\s(?P<verts>.*?)\n.*?
neighboring\s faces:\s+(?P<neigh>[\sf\d]*)
''', re.S|re.X)
point_re = re.compile(r'''
-\s+(?P<point>p\d+).*?
neighbors:\s+(?P<neigh>[\sf\d]*)
''', re.S|re.X)
vert_re = re.compile(r'''
(p\d+)
''', re.S|re.X)
def __init__(self, verts, q):
grid.__init__(self, verts,q)
def get_containing_simplex(self, X):
if not self.faces:
self.construct_connectivity()
# get closest point
(dist, indicies) = self.tree.query(X, 2)
closest_point = indicies[0]
log.debug('X: %s' % X)
log.debug('point index: %d' % closest_point)
log.debug('actual point %s' % self.verts[closest_point])
log.debug('distance = %0.4f' % dist[0])
simplex = None
checked_faces = []
faces_to_check = self.faces_for_vert[closest_point]
attempts = 0
while not simplex and faces_to_check:
attempts += 1
# if attempts > 20:
# raise Exception("probably recursing to many times")
cur_face = faces_to_check.pop(0)
checked_faces.append(cur_face)
if cur_face.contains(X, self):
simplex = cur_face
continue
new_facest = []
for neighbor in cur_face.neighbors:
if (neighbor not in checked_faces) and (neighbor not in faces_to_check):
faces_to_check.append(neighbor)
if not simplex:
raise AssertionError('no containing simplex found')
R = self.create_mesh(simplex.verts)
log.debug('total attempts before finding simplex: %d' % attempts)
return R
def get_simplex_and_nearest_points(self, X, extra_points = 3, simplex_size = 3):
"""
this returns two grid objects: R and S.
R is a grid object that is supposedly a containing simplex
around point X (it tends not to be)
S is S_j from baker's paper : some verts from all point that are not the simplex
"""
log.debug(inspect.stack()[1][3])
log.debug("extra verts: %d" % extra_points)
log.debug("simplex size: %d" % simplex_size)
r_mesh = self.get_containing_simplex(X)
# log.debug("R:\n%s" % r_mesh)
# and some UNIQUE extra verts
(dist, indicies) = self.tree.query(X, simplex_size + extra_points)
unique_indicies = []
for index in indicies:
if self.verts[index] not in r_mesh.verts:
unique_indicies.append(index)
log.debug("indicies: %s" % ",".join([str(i) for i in indicies]))
log.debug("indicies: %s" % ",".join([str(i) for i in unique_indicies]))
s_mesh = self.create_mesh(unique_indicies)# indicies[simplex_size:])
# TODO: eventually remove this test:
for point in s_mesh.verts:
if point in r_mesh.verts:
log.error("ERROR")
log.error("\n%s\nin\n%s" % (point, r_mesh))
raise Exception("repeating point S and R")
return (r_mesh, s_mesh)
def get_points_conn(self, X):
"""
this returns two grid objects: R and S.
this function differes from the get_simplex_and_nearest_points
function in that it builds up the extra verts based on
connectivity information, not just nearest-neighbor.
in theory, this will work much better for situations like
verts near a short edge in a boundary layer cell where the
nearest verts would all be colinear
also, it guarantees that we find a containing simplex
R is a grid object that is the (a) containing simplex around point X
S is a connectivity-based nearest-neighbor lookup, limited to 3 extra verts
"""
if not self.faces:
self.construct_connectivity()
# get closest point
(dist, indicies) = self.tree.query(X, 2)
simplex = None
for face in self.faces_for_vert[indicies[0]]:
if face.contains(X, self):
simplex = face
break
if not simplex:
raise AssertionError('no containing simplex found')
# self.create_mesh(simplex.verts)
R = self.get_containing_simplex(X)
s = []
for c,i in enumerate(simplex.neighbors):
s.extend([guy for guy in i.verts if not guy in simplex.verts])
S = self.create_mesh(s)
return R, S
def run_baker(self, X, extra_points = 3, order = 2):
answer = None
try:
(R, S) = self.get_simplex_and_nearest_points(X)
if not contains(X, R.verts):
raise Exception("run_baker with get_simplex_and_nearest_points returned non-containing simplex")
answer = run_baker(X, R, S, order)
except Exception, e:
log.error("caught error: %s, trying with connectivity-based mesh" % e)
(R, S) = self.get_points_conn(X)
answer = run_baker(X, R, S, order)
return answer
def construct_connectivity(self):
"""
a call to this method prepares the internal connectivity structure.
this is part of the __init__ for a rect_grid, but can be called from any grid object
"""
log.debug('start')
qdelaunay_string = get_qdelaunay_dump_str(self)
face_to_faces = []
for matcher in grid.face_re.finditer(qdelaunay_string):
d = matcher.groupdict()
face_name = d['face']
verticies = d['verts']
neighboring_faces = d['neigh']
cur_face = face(face_name)
self.faces[face_name] = cur_face
for v in grid.vert_re.findall(verticies):
vertex_index = int(v[1:])
cur_face.add_vert(vertex_index)
self.faces_for_vert[vertex_index].append(cur_face)
nghbrs = [(face_name, i) for i in neighboring_faces.split()]
face_to_faces.extend(nghbrs)
for rel in face_to_faces:
if rel[1] in self.faces:
self.faces[rel[0]].add_neighbor(self.faces[rel[1]])
log.debug('end')