major refactoring

--HG--
rename : lib/baker/__init__.py => interp/baker/__init__.py
rename : lib/grid/DD.py => interp/grid/DD.py
rename : lib/grid/DDD.py => interp/grid/DDD.py
rename : lib/grid/__init__.py => interp/grid/__init__.py
rename : lib/grid/qhull.py => interp/grid/qhull.py
rename : lib/grid/simplex.py => interp/grid/simplex.py
rename : lib/grid/smcqdelaunay.py => interp/grid/smcqdelaunay.py
rename : lib/baker/tools.py => interp/tools.py
This commit is contained in:
sm
2010-10-22 16:10:58 -06:00
parent 98d7247497
commit 2db4169bfa
14 changed files with 56 additions and 565 deletions
+382
View File
@@ -0,0 +1,382 @@
from baker import *
from baker.tools import smblog
import numpy as np
import sys
import itertools
from tools import smberror
def get_phis(X, R):
"""
The get_phis function is used to get barycentric coordonites for a point on a triangle.
X -- the destination point (2D)
X = [0,0]
r -- the three points that make up the containing triangular simplex (2D)
r = [[-1, -1], [0, 2], [1, -1]]
this will return [0.333, 0.333, 0.333]
"""
# baker: eq 7
A = np.array([
[ 1, 1, 1],
[R[0][0], R[1][0], R[2][0]],
[R[0][1], R[1][1], R[2][1]],
])
b = np.array([ 1,
X[0],
X[1]
])
try:
phi = np.linalg.solve(A,b)
except np.linalg.LinAlgError as e:
msg = "calculation of phis yielded a linearly dependant system (%s)" % e
smblog.error(msg)
raise smberror(msg)
phi = np.dot(np.linalg.pinv(A), b)
return phi
def get_phis_3D(X, R):
"""
The get_phis function is used to get barycentric coordonites for a point on a tetrahedron.
X -- the destination point (3D)
X = [0,0,0]
R -- the four points that make up the containing simplex, tetrahedron (3D)
R = [
[0.0, 0.0, 1.0],
[0.94280904333606508, 0.0, -0.3333333283722672],
[-0.47140452166803232, 0.81649658244673617, -0.3333333283722672],
[-0.47140452166803298, -0.81649658244673584, -0.3333333283722672],
]
this (should) will return [0.25, 0.25, 0.25, 0.25]
"""
# baker: eq 7
A = np.array([
[ 1, 1, 1, 1 ],
[R[0][0], R[1][0], R[2][0], R[3][0]],
[R[0][1], R[1][1], R[2][1], R[3][1]],
[R[0][2], R[1][2], R[2][2], R[3][2]],
])
b = np.array([ 1,
X[0],
X[1],
X[2]
])
try:
phi = np.linalg.solve(A,b)
except np.linalg.LinAlgError as e:
smblog.error("calculation of phis yielded a linearly dependant system: %s" % e)
phi = np.dot(np.linalg.pinv(A), b)
return phi
def qlinear(X, R):
"""
this calculates the linear portion of q from X to R
also, this is baker eq 3
X = destination point
R = simplex points
q = CFD quantities of interest at the simplex points
"""
phis = get_phis(X, R.points)
qlin = np.sum([q_i * phi_i for q_i, phi_i in zip(R.q, phis)])
return phis, qlin
def qlinear_3D(X, R):
"""
this calculates the linear portion of q from X to R
X = destination point
R = simplex points
q = CFD quantities of interest at the simplex points(R)
"""
phis = get_phis_3D(X, R.points)
qlin = sum([q_i * phi_i for q_i, phi_i in zip(R.q, phis)])
return phis, qlin
def get_error_quadratic(phi, R, S):
B = [] # baker eq 9
w = [] # baker eq 11
for (s, q) in zip(S.points, S.q):
cur_phi, cur_qlin = qlinear(s, R)
(phi1, phi2, phi3) = cur_phi
B.append(
[
phi1 * phi2,
phi2 * phi3,
phi3 * phi1,
]
)
w.append(q - cur_qlin)
B = np.array(B)
w = np.array(w)
A = np.dot(B.T, B)
b = np.dot(B.T, w)
# baker solve eq 10
try:
(a, b, c) = np.linalg.solve(A,b)
except np.linalg.LinAlgError as e:
smblog.error("linear calculation went bad, resorting to np.linalg.pinv: %s" % e)
(a, b, c) = np.dot(np.linalg.pinv(A), b)
error_term = a * phi[0] * phi[1]\
+ b * phi[1] * phi[2]\
+ c * phi[2] * phi[0]
return error_term
def get_error_cubic(phi, R, S):
B = [] # baker eq 9
w = [] # baker eq 11
for (s, q) in zip(S.points, S.q):
cur_phi, cur_qlin = qlinear(s, R)
(phi1, phi2, phi3) = cur_phi
# basing this on eq 17
B.append(
[
phi1 * phi2 * phi2, # a
phi1 * phi3 * phi3, # b
phi2 * phi1 * phi1, # c
phi2 * phi3 * phi3, # d
phi3 * phi1 * phi1, # e
phi3 * phi2 * phi2, # f
phi1 * phi2 * phi3, # g
]
)
w.append(q - cur_qlin)
B = np.array(B)
w = np.array(w)
A = np.dot(B.T, B)
b = np.dot(B.T, w)
# baker solve eq 10
try:
(a, b, c, d, e, f, g) = np.linalg.solve(A,b)
except np.linalg.LinAlgError as e:
smblog.error("linear calculation went bad, resorting to np.linalg.pinv: %s" % e)
(a, b, c, d, e, f, g) = np.dot(np.linalg.pinv(A), b)
error_term = a * phi[0] * phi[1] * phi[1]\
+ b * phi[0] * phi[2] * phi[2]\
+ c * phi[1] * phi[0] * phi[0]\
+ d * phi[1] * phi[2] * phi[2]\
+ e * phi[2] * phi[0] * phi[0]\
+ f * phi[2] * phi[1] * phi[1]\
+ g * phi[0] * phi[1] * phi[2]\
return error_term
def get_error_sauron(phi, R, S, order = 2):
smblog.debug("len(phi): %d"% len(phi))
B = [] # baker eq 9
w = [] # baker eq 11
p = pattern(order, len(phi), offset = -1)
smblog.debug("pattern: %s" % p)
for (s,q) in zip(S.points, S.q):
cur_phi, cur_qlin = qlinear(s, R)
l = []
for i in p:
cur_sum = cur_phi[i[0]]
for j in i[1:]:
cur_sum *= cur_phi[j]
l.append(cur_sum)
B.append(l)
w.append(q - cur_qlin)
smblog.debug("B: %s" % B)
smblog.debug("w: %s" % w)
B = np.array(B)
w = np.array(w)
A = np.dot(B.T, B)
b = np.dot(B.T, w)
# baker solve eq 10
try:
abc = np.linalg.solve(A,b)
except np.linalg.LinAlgError as e:
smblog.error("linear calculation went bad, resorting to np.linalg.pinv: %s" % e)
abc = np.dot(np.linalg.pinv(A), b)
smblog.debug(len(abc) == len(p))
error_term = 0.0
for (a, i) in zip(abc, p):
cur_sum = a
for j in i:
cur_sum *= phi[j]
error_term += cur_sum
smblog.debug("error_term smb: %s" % error_term)
return error_term, abc
def run_baker(X, R, S, order=2):
"""
This is the main function to call to get an interpolation to X from the input meshes
X -- the destination point (2D)
X = [0,0]
R = Simplex
S = extra points
"""
smblog.debug("order = %d" % order)
answer = {
'qlin': None,
'error': None,
'final': None,
}
# calculate values only for the simplex triangle
phi, qlin = qlinear(X, R)
if order == 1:
answer['qlin'] = qlin
return answer
elif order in (2,3):
error_term, abc = get_error_sauron(phi, R, S, order)
else:
raise smberror('unsupported order for baker method')
q_final = qlin + error_term
answer['qlin' ] = qlin
answer['error'] = error_term
answer['final'] = q_final
return answer
def run_baker_3D(X, R, S):
"""
This is the main function to call to get an interpolation to X from the input meshes
X -- the destination point (3D)
X = [0,0,0]
R = Simplex (4 points, contains X)
S = extra points (surrounding, in some manner, R and X, but not in R)
"""
# calculate values only for the triangle
phi, qlin = qlinear_3D(X, R)
if len(S.points) == 0:
answer = {
'a': None,
'b': None,
'c': None,
'd': None,
'e': None,
'f': None,
'qlin': qlin,
'error': None,
'final': None,
}
return answer
B = [] # baker eq 9
w = [] # baker eq 11
for (s, q) in zip(S.points, S.q):
cur_phi, cur_qlin = qlinear_3D(s, R)
(phi1, phi2, phi3, phi4) = cur_phi
B.append(
[
phi1 * phi2,
phi1 * phi3,
phi1 * phi4,
phi2 * phi3,
phi2 * phi4,
phi3 * phi4,
]
)
w.append(q - cur_qlin)
B = np.array(B)
w = np.array(w)
A = np.dot(B.T, B)
b = np.dot(B.T, w)
# baker solve eq 10
try:
(a, b, c, d, e, f) = np.linalg.solve(A,b)
except np.linalg.LinAlgError as e:
smblog.error("linear calculation went bad, resorting to np.linalg.pinv: %s", e)
(a, b, c, d, e, f) = np.dot(np.linalg.pinv(A), b)
error_term = a * phi[0] * phi[1]\
+ b * phi[0] * phi[2]\
+ c * phi[0] * phi[3]\
+ d * phi[1] * phi[2]\
+ e * phi[1] * phi[3]\
+ f * phi[2] * phi[3]
q_final = qlin + error_term
answer = {
'a': a,
'b': b,
'c': c,
'd': d,
'e': e,
'f': f,
'qlin': qlin,
'error': error_term,
'final': q_final,
}
return answer
def _boxings(n, k):
"""\
source for this function:
http://old.nabble.com/Simple-combinatorics-with-Numpy-td20086915.html
http://old.nabble.com/Re:-Simple-combinatorics-with-Numpy-p20099736.html
"""
seq, i = [n] * k + [0], k
while i:
yield tuple(seq[i] - seq[i+1] for i in xrange(k))
i = seq.index(0) - 1
seq[i:k] = [seq[i] - 1] * (k-i)
def _samples_ur(items, k, offset = 0):
"""Returns k unordered samples (with replacement) from items."""
n = len(items)
for sample in _boxings(k, n):
selections = [[items[i]]*count for i,count in enumerate(sample)]
yield tuple([x + offset for sel in selections for x in sel])
def pattern(power, phicount, offset = 0):
smblog.debug("(power = %s, phicount = %s)" % (power, phicount))
r = []
for i in _samples_ur(range(1, phicount + 1), power, offset):
if not len(set(i)) == 1:
r.append(i)
return r
+92
View File
@@ -0,0 +1,92 @@
from grid import grid as basegrid
from baker.tools import exact_func, smblog
import numpy as np
class grid(basegrid):
def __init__(self, points, q):
basegrid.__init__(self, points, q)
def for_qhull_generator(self):
"""
this returns a generator that should be fed into qdelaunay
"""
yield '2';
yield '%d' % len(self.points)
for p in self.points:
yield "%f %f" % (p[0], p[1])
def for_qhull(self):
"""
this returns a single string that should be fed into qdelaunay
"""
r = '2\n'
r += '%d\n' % len(self.points)
for p in self.points:
r += "%f %f\n" % (p[0], p[1])
return r
class rect_grid(grid):
def __init__(self, xres = 5, yres = 5):
xmin = -1.0
xmax = 1.0
xspan = xmax - xmin
xdel = xspan / float(xres - 1)
ymin = -1.0
ymay = 1.0
yspan = ymay - ymin
ydel = yspan / float(yres - 1)
points = []
q = []
for x in xrange(xres):
cur_x = xmin + (x * xdel)
for y in xrange(yres):
cur_y = ymin + (y * ydel)
points.append([cur_x, cur_y])
q.append(exact_func((cur_x, cur_y)))
grid.__init__(self, points, q)
self.construct_connectivity()
class random_grid(rect_grid):
def __init__(self, num_points = 10):
smblog.debug("number of points: %d" % num_points)
points = []
q = []
r = np.random
appx_side_res = int(np.sqrt(num_points))
smblog.debug("appx_side_res: %d" % appx_side_res)
delta = 1.0 / float(appx_side_res)
for x in xrange(appx_side_res + 1):
cur_x = x * delta
for cur_y in (0, 1):
new_point = [cur_x, cur_y]
points.append(new_point)
q.append(exact_func(new_point))
for y in xrange(appx_side_res + 1):
cur_y = y * delta
for cur_x in (0, 1):
new_point = [cur_x, cur_y]
points.append(new_point)
q.append(exact_func(new_point))
for i in xrange(num_points):
cur_x = r.rand()
cur_y = r.rand()
points.append([cur_x, cur_y])
q.append( exact_func( (cur_x, cur_y) ) )
grid.__init__(self, points, q)
self.points = np.array(self.points)
self.q = np.array(self.q)
+108
View File
@@ -0,0 +1,108 @@
from grid import grid as basegrid
from baker.tools import exact_func_3D, smblog
import numpy as np
class grid(basegrid):
def __init__(self, points, q):
basegrid.__init__(self, points, q)
def for_qhull_generator(self):
"""
this returns a generator that should be fed into qdelaunay
"""
yield '3';
yield '%d' % len(self.points)
for p in self.points:
yield "%f %f %f" % tuple(p)
def for_qhull(self):
"""
this returns a single string that should be fed into qdelaunay
"""
r = '3\n'
r += '%d\n' % len(self.points)
for p in self.points:
r += "%f %f %f\n" % tuple(p)
return r
class rect_grid(grid):
def __init__(self, xres = 5, yres = 5, zres = 5):
xmin = -1.0
xmax = 1.0
xspan = xmax - xmin
xdel = xspan / float(xres - 1)
ymin = -1.0
ymay = 1.0
yspan = ymay - ymin
ydel = yspan / float(yres - 1)
zmin = -1.0
zmaz = 1.0
zspan = zmaz - zmin
zdel = zspan / float(zres - 1)
points = []
q = []
for x in xrange(xres):
cur_x = xmin + (x * xdel)
for y in xrange(yres):
cur_y = ymin + (y * ydel)
for z in xrange(zres):
cur_z = zmin + (z * zdel)
points.append([cur_x, cur_y, cur_z])
q.append(exact_func_3D((cur_x, cur_y, cur_z)))
grid.__init__(self, points, q)
# self.construct_connectivity()
def for_qhull_generator(self):
"""
this returns a generator that should be fed into qdelaunay
"""
yield '3';
yield '%d' % len(self.points)
for p in self.points:
yield "%f %f %f" % tuple(p)
def for_qhull(self):
"""
this returns a single string that should be fed into qdelaunay
"""
r = '3\n'
r += '%d\n' % len(self.points)
for p in self.points:
r += "%f %f %f\n" % tuple(p)
return r
class random_grid(rect_grid):
def __init__(self, num_points = 10):
points = []
q = []
r = np.random
appx_side_res = int(np.power(num_points, 1/3.0))
smblog.debug("appx_side_res: %d" % appx_side_res)
delta = 1.0 / float(appx_side_res)
for x in xrange(appx_side_res + 1):
pass
for i in xrange(num_points):
cur_x = r.rand()
cur_y = r.rand()
cur_z = r.rand()
points.append([cur_x, cur_y, cur_z])
q.append(exact_func_3D((cur_x, cur_y, cur_z)))
grid.__init__(self, points, q)
self.points = np.array(self.points)
self.q = np.array(self.q)
+244
View File
@@ -0,0 +1,244 @@
import sys
import re
from collections import defaultdict
import inspect
import numpy as np
import scipy.spatial
from baker import run_baker
from baker.tools import exact_func, smberror, smblog
from simplex import face, contains
from smcqdelaunay import *
class grid(object):
def __init__(self, points, q):
"""
this thing eats two pre-constructed arrays of floats:
points = array of arrays (i will convert to numpy.array)
[[x0,y0], [x1,y1], ...]
q = array (1D) of important values
"""
self.points = np.array(points)
self.q = np.array(q)
self.tree = scipy.spatial.KDTree(self.points)
self.faces = {}
self.faces_for_vert = defaultdict(list)
class delaunay_grid(grid):
facet_re = re.compile(r'''
-\s+(?P<facet>f\d+).*?
vertices:\s(?P<verts>.*?)\n.*?
neighboring\s facets:\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, points, q):
grid.__init__(self, points,q)
def create_mesh(self, indicies):
"""
this function takes a list of indicies, and then creates
and returns a grid object (collection of points and q).
note: the input is indicies, the grid contains points
"""
p = [self.points[i] for i in indicies]
q = [self.q[i] for i in indicies]
return grid(p, 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]
smblog.debug('X: %s' % X)
smblog.debug('point index: %d' % closest_point)
smblog.debug('actual point %s' % self.points[closest_point])
smblog.debug('distance = %0.4f' % dist[0])
simplex = None
checked_facets = []
facets_to_check = self.faces_for_vert[closest_point]
attempts = 0
while not simplex and facets_to_check:
attempts += 1
# if attempts > 20:
# raise smberror("probably recursing to many times")
cur_facet = facets_to_check.pop(0)
checked_facets.append(cur_facet)
if cur_facet.contains(X, self):
simplex = cur_facet
continue
new_facest = []
for neighbor in cur_facet.neighbors:
if (neighbor not in checked_facets) and (neighbor not in facets_to_check):
facets_to_check.append(neighbor)
if not simplex:
raise AssertionError('no containing simplex found')
R = self.create_mesh(simplex.verts)
smblog.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 points from all point that are not the simplex
"""
smblog.debug(inspect.stack()[1][3])
smblog.debug("extra points: %d" % extra_points)
smblog.debug("simplex size: %d" % simplex_size)
r_mesh = self.get_containing_simplex(X)
# smblog.debug("R:\n%s" % r_mesh)
# and some UNIQUE extra points
(dist, indicies) = self.tree.query(X, simplex_size + extra_points)
unique_indicies = []
for index in indicies:
if self.points[index] not in r_mesh.points:
unique_indicies.append(index)
smblog.debug("indicies: %s" % ",".join([str(i) for i in indicies]))
smblog.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.points:
if point in r_mesh.points:
smblog.error("ERROR")
smblog.error("\n%s\nin\n%s" % (point, r_mesh))
raise smberror("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 points based on
connectivity information, not just nearest-neighbor.
in theory, this will work much better for situations like
points near a short edge in a boundary layer cell where the
nearest points 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 points
"""
if not self.faces:
self.construct_connectivity()
# get closest point
(dist, indicies) = self.tree.query(X, 2)
simplex = None
for facet in self.faces_for_vert[indicies[0]]:
if facet.contains(X, self):
simplex = facet
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.points):
raise smberror("run_baker with get_simplex_and_nearest_points returned non-containing simplex")
answer = run_baker(X, R, S, order)
except smberror, e:
smblog.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
"""
smblog.debug('start')
qdelaunay_string = get_qdelaunay_dump_str(self)
facet_to_facets = []
for matcher in grid.facet_re.finditer(qdelaunay_string):
d = matcher.groupdict()
facet_name = d['facet']
verticies = d['verts']
neighboring_facets = d['neigh']
cur_face = face(facet_name)
self.faces[facet_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 = [(facet_name, i) for i in neighboring_facets.split()]
facet_to_facets.extend(nghbrs)
for rel in facet_to_facets:
if rel[1] in self.faces:
self.faces[rel[0]].add_neighbor(self.faces[rel[1]])
smblog.debug('end')
def __str__(self):
r = ''
assert( len(self.points) == len(self.q) )
for c, i in enumerate(zip(self.points, self.q)):
r += "%d %r: %0.4f" % (c,i[0], i[1])
facet_str = ", ".join([f.name for f in self.faces_for_vert[c]])
r += " faces: [%s]" % facet_str
r += "\n"
if self.faces:
for v in self.faces.itervalues():
r += "%s\n" % v
return r
+15
View File
@@ -0,0 +1,15 @@
def parse_qhull_file(filename, verbose=False):
f = open(filename, 'r')
if verbose:
print 'filename: ', filename
degree = int(f.readline().strip())
print "degree:", degree
print "number of points", f.readline().strip()
verts = []
for p in f:
v = [float(i) for i in p.strip().split()]
verts.append(v)
return verts
+64
View File
@@ -0,0 +1,64 @@
from baker import get_phis, get_phis_3D
from baker.tools import smblog
TOL = 1e-8
def contains(X, R):
"""
tests if X (point) is in R (a simplex,
represented by a list of n-degree coordinates)
it now correctly checks for 2/3-D points
"""
if len(X) == 2:
phis = get_phis(X, R)
elif len(X) == 3:
phis = get_phis_3D(X, R)
r = True
if [i for i in phis if i < 0.0 - TOL]:
r = False
return r
class face(object):
def __init__(self, name):
self.name = name
self.verts = []
self.neighbors = []
def add_vert(self, v):
"""
v should be an index into grid.points
"""
self.verts.append(v)
def add_neighbor(self, n):
"""
reference to another face object
"""
self.neighbors.append(n)
def contains(self, X, G):
"""
X = point of interest
G = corrensponding grid object (G.points)
because of the way i'm storing things,
a face simply stores indicies, and so one
must pass in a reference to the grid object
containing real points.
this simply calls grid.simplex.contains
"""
return contains(X, [G.points[i] for i in self.verts])
def __str__(self):
neighbors = [str(i.name) for i in self.neighbors]
return '<face %s: verts: %s neighbors: [%s]>' %\
(
self.name,
self.verts,
", ".join(neighbors)
)
__repr__ = __str__
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/python
from subprocess import Popen, PIPE
def get_qdelaunay_dump(g):
cmd = 'qdelaunay Qt f'
p = Popen(cmd.split(), bufsize=1, stdin=PIPE, stdout=PIPE)
so, se = p.communicate(g.for_qhull())
for i in so.splitlines():
yield i
def get_qdelaunay_dump_str(g):
return "\n".join(get_qdelaunay_dump(g))
def get_index_only(g):
cmd = 'qdelaunay Qt i'
p = Popen(cmd.split(), bufsize=1, stdin=PIPE, stdout=PIPE)
so, se = p.communicate(g.for_qhull())
for i in so.splitlines():
yield i
def get_index_only_str(g):
return "\n".join(get_index_only(g))
+84
View File
@@ -0,0 +1,84 @@
import os
import logging
import inspect
import numpy as np
class smbLog(object):
interpolator = "%s ==> %s"
def __init__(self, level = logging.DEBUG):
logging.basicConfig(
level = level,
format = '%(asctime)s %(levelname)s %(message)s',
filename = os.path.join(os.sep, 'tmp', 'baker.lol'),
)
self.log = logging.getLogger()
def debug(self, message = None):
msg = smbLog.interpolator % (inspect.stack()[1][3], message)
self.log.debug(msg)
def info(self, message = None):
msg = smbLog.interpolator % (inspect.stack()[1][3], message)
self.log.info(msg)
def warn(self, message = None):
msg = smbLog.interpolator % (inspect.stack()[1][3], message)
self.log.warn(msg)
def error(self, message = None):
msg = smbLog.interpolator % (inspect.stack()[1][3], message)
self.log.error(msg)
smblog = smbLog(logging.DEBUG)
class smberror(Exception):
"""
this is a silly little exception subclass
"""
def __init__(self, val):
self.value = val
def __str__(self):
return repr(self.value)
def rms(errors):
"""
root mean square calculation
"""
r = 0.0
for i in errors:
r += np.power(i, 2)
r = np.sqrt(r / len(errors))
return r
def exact_func(X):
"""
the exact function used from baker's article (for testing)
"""
x = X[0]
y = X[0]
return np.power((np.sin(x * np.pi) * np.cos(y * np.pi)), 2)
def exact_func_3D(X):
"""
the exact function (3D) used from baker's article (for testing)
"""
x = X[0]
y = X[1]
z = X[2]
return np.power((np.sin(x * np.pi / 2.0) * np.sin(y * np.pi / 2.0) * np.sin(z * np.pi / 2.0)), 2)
def improved_answer(answer, exact, verbose=False):
if not answer['error']:
return True
smblog.debug('error: %s' % answer['error'])
smblog.debug('qlin: %s' % answer['qlin'])
smblog.debug('final: %s' % answer['final'])
smblog.debug('exact: %s' % exact)
if np.abs(answer['final'] - exact) <= np.abs(answer['qlin'] - exact):
smblog.debug(":) improved result")
return True
else:
smblog.debug(":( damaged result")
return False