Major: made scripts pass pep8 and pyflakes

This commit is contained in:
Stephen M. McQuay
2011-09-17 15:38:49 -06:00
parent 1bc797a14d
commit 837a72b246
17 changed files with 835 additions and 866 deletions
-39
View File
@@ -1,40 +1 @@
import os
import logging
import logging.handlers
import json
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
default_config = {
'filename': '/tmp/interp.log',
'level': 'debug',
'size' : 102400,
'logbackup': 10,
'pypath': None,
}
try:
with open(os.path.expanduser('~/.config/interp.json')) as config_file:
d = json.load(config_file)
except IOError as e:
d = {}
config = dict(default_config.items() + d.items())
logger = logging.getLogger('interp')
logger.setLevel(LEVELS[config['level']])
my_format = logging.Formatter('%(asctime)s %(levelname)s (%(process)d) %(filename)s %(funcName)s:%(lineno)d %(message)s')
handler = logging.handlers.RotatingFileHandler(
config['filename'], maxBytes = config['size'] * 1024, backupCount = config['logbackup'])
handler.setFormatter(my_format)
logger.addHandler(handler)
__version__ = '0.2'
+167 -183
View File
@@ -1,220 +1,204 @@
import sys
import numpy as np
from functools import wraps
import itertools
import interp
import logging
log = logging.getLogger('interp')
AGGRESSIVE_ERROR_SOLVE = True
RAISE_PATHOLOGICAL_EXCEPTION = False
__version__ = interp.__version__
def get_phis(X, R):
"""
The get_phis function is used to get barycentric coordonites for a
point on a triangle or tetrahedron. This is equation (*\ref{eq:qlinarea}*)
"""
The get_phis function is used to get barycentric coordonites for a
point on a triangle or tetrahedron (Equation (*\ref{eq:qlinarea}*))
in 2D:
in 2D:
X - the destination point (2D)
X = [0,0]
R - the three points that make up the 2-D triangular simplex
R = [[-1, -1], [0, 2], [1, -1]]
X - the destination point (2D)
X = [0,0]
R - the three points that make up the 2-D triangular simplex
R = [[-1, -1], [0, 2], [1, -1]]
this will return [0.333, 0.333, 0.333]
this will return [0.333, 0.333, 0.333]
in 3D:
in 3D:
X - the destination point (3D)
X = [0,0,0]
R - the four points that make up the 3-D simplex (tetrahedron)
R = [
[ 0.0000, 0.0000, 1.0000],
[ 0.9428, 0.0000, -0.3333],
[-0.4714, 0.8165, -0.3333],
[-0.4714, -0.8165, -0.3333],
]
X - the destination point (3D)
X = [0,0,0]
R - the four points that make up the 3-D simplex (tetrahedron)
R = [
[ 0.0000, 0.0000, 1.0000],
[ 0.9428, 0.0000, -0.3333],
[-0.4714, 0.8165, -0.3333],
[-0.4714, -0.8165, -0.3333],
]
this will return [0.25, 0.25, 0.25, 0.25]
"""
this will return [0.25, 0.25, 0.25, 0.25]
"""
# equations (*\ref{eq:lin3d}*) and (*\ref{eq:lin2d}*)
if len(X) == 2:
log.debug("running 2D")
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]
])
elif len(X) == 3:
log.debug("running 3D")
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]
])
else:
raise Exception("inapropriate demension on X")
try:
phi = np.linalg.solve(A,b)
except np.linalg.LinAlgError as e:
msg = "calculation of phis yielded a linearly dependant system (%s)" % e
log.error(msg)
# raise Exception(msg)
phi = np.dot(np.linalg.pinv(A), b)
log.debug("phi: %s", phi)
return phi
def qlinear(X, R):
"""
this calculates the linear portion of q from R to X
This is equation (*\ref{eq:qlinbasis}*)
X = destination point
R = a inter.grid object; must have R.points and R.q
"""
phis = get_phis(X, R.verts)
qlin = np.sum([q_i * phi_i for q_i, phi_i in zip(R.q, phis)])
log.debug("phis: %s", phis)
log.debug("qlin: %s", qlin)
return phis, qlin
def get_error(phi, R, S, order = 2):
"""
Calculate the error approximation terms, returning the unknowns
a,b, and c in equation (*\ref{eq:quadratic2d}*).
"""
B = [] # equation ((*\ref{eq:B2d}*)
w = [] # equation ((*\ref{eq:w}*)
cur_pattern = pattern(len(phi), order)
log.info("pattern: %s" % cur_pattern)
for (s,q) in zip(S.verts, S.q):
cur_phi, cur_qlin = qlinear(s, R)
l = []
for i in cur_pattern:
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)
log.info("B: %s" % B)
log.info("w: %s" % w)
# equations (*\ref{eq:lin3d}*) and (*\ref{eq:lin2d}*)
if len(X) == 2:
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]])
elif len(X) == 3:
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]])
else:
raise Exception("inapropriate demension on X")
phi = np.linalg.solve(A, b)
return phi
B = np.array(B)
w = np.array(w)
def qlinear(X, R, q):
"""
this calculates the linear portion of q from R to X
A = np.dot(B.T, B)
b = np.dot(B.T, w)
This is equation (*\ref{eq:qlinbasis}*)
try:
abc = np.linalg.solve(A,b)
except np.linalg.LinAlgError as e:
log.error("linear calculation went bad, resorting to np.linalg.pinv: %s" % e)
abc = np.dot(np.linalg.pinv(A), b)
X = destination point
R = a inter.grid object; must have R.points and R.q
"""
error_term = 0.0
for (a, i) in zip(abc, cur_pattern):
cur_sum = a
for j in i:
cur_sum *= phi[j]
error_term += cur_sum
phis = get_phis(X, R)
qlin = np.sum([q_i * phi_i for q_i, phi_i in zip(q, phis)])
log.debug("error_term: %s" % error_term)
return error_term, abc
return phis, qlin
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
def get_error(phi, R, R_q, S, S_q, order=2):
"""
Calculate the error approximation terms, returning the unknowns
a,b, and c in equation (*\ref{eq:quadratic2d}*).
"""
B = [] # equation ((*\ref{eq:B2d}*)
w = [] # equation ((*\ref{eq:w}*)
R = Simplex
S = extra points
"""
log.debug("order = %d" % order)
log.debug("extra points = %d" % len(S.verts))
cur_pattern = pattern(len(phi), order)
answer = {
'qlin': None,
'error': None,
'final': None,
}
# calculate values only for the simplex triangle
phi, qlin = qlinear(X, R)
for (s, cur_q) in zip(S, S_q):
cur_phi, cur_qlin = qlinear(s, R, R_q)
l = []
for i in cur_pattern:
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(cur_q - cur_qlin)
B = np.array(B)
w = np.array(w)
A = np.dot(B.T, B)
b = np.dot(B.T, w)
try:
abc = np.linalg.solve(A, b)
except np.linalg.LinAlgError:
if not AGGRESSIVE_ERROR_SOLVE:
return None, None
abc = np.dot(np.linalg.pinv(A), b)
error_term = 0.0
for (a, i) in zip(abc, cur_pattern):
cur_sum = a
for j in i:
cur_sum *= phi[j]
error_term += cur_sum
return error_term, abc
def run_baker(X, R, R_q, S, S_q, order=2):
"""
This is the main function to call to get an interpolation to X from the
input meshes
X -- the destination point
R = Simplex
S = extra points
"""
answer = {
'qlin': None,
'error': None,
'final': None,
}
# calculate values only for the simplex triangle
phi, qlin = qlinear(X, R, R_q)
if order == 1:
answer['qlin'] = qlin
answer['final'] = qlin
return answer
elif order in xrange(2, 11):
error_term, abc = get_error(phi, R, R_q, S, S_q, order)
# if a pathological vertex configuration was encountered and
# AGGRESSIVE_ERROR_SOLVE is False, get_error will return (None, None)
# indicating that only linear interpolation should be performed
if (error_term is None) and (abc is None):
if RAISE_PATHOLOGICAL_EXCEPTION:
raise np.linalg.LinAlgError("Pathological Vertex Config")
answer['qlin'] = qlin
answer['final'] = qlin
return answer
else:
raise Exception('unsupported order "%d" for baker method' % order)
q_final = qlin + error_term
if order == 1:
answer['qlin'] = qlin
answer['final'] = qlin
answer['error'] = error_term
answer['final'] = q_final
answer['abc'] = abc
return answer
elif order in xrange(2,11):
error_term, abc = get_error(phi, R, S, order)
else:
raise Exception('unsupported order "%d" for baker method' % order)
q_final = qlin + error_term
answer['qlin' ] = qlin
answer['error'] = error_term
answer['final'] = q_final
answer['abc' ] = abc
log.debug(answer)
return answer
def memoize(f):
"""
for more information on what I'm doing here, please read:
http://en.wikipedia.org/wiki/Memoize
"""
cache = {}
@wraps(f)
def memf(simplex_size, nu):
x = (simplex_size, nu)
if x not in cache:
log.debug("adding to cache: %s", x)
cache[x] = f(simplex_size, nu)
return cache[x]
return memf
"""
for more information on what I'm doing here, please read:
http://en.wikipedia.org/wiki/Memoize
"""
cache = {}
@wraps(f)
def memf(simplex_size, nu):
x = (simplex_size, nu)
if x not in cache:
cache[x] = f(simplex_size, nu)
return cache[x]
return memf
@memoize
def pattern(simplex_size, nu):
"""
This function returns the pattern requisite to compose the error
approximation function, and the matrix B.
"""
log.debug("pattern: simplex: %d, order: %d" % (simplex_size, nu))
"""
This function returns the pattern requisite to compose the error
approximation function, and the matrix B.
"""
r = []
for i in itertools.product(xrange(simplex_size), repeat = nu):
if len(set(i)) !=1:
r.append(tuple(sorted(i)))
unique_r = list(set(r))
return unique_r
r = []
for i in itertools.product(xrange(simplex_size), repeat=nu):
if len(set(i)) != 1:
r.append(tuple(sorted(i)))
unique_r = list(set(r))
return unique_r
+4 -3
View File
@@ -5,12 +5,13 @@ import rlcompleter
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
+20 -18
View File
@@ -1,28 +1,30 @@
from multiprocessing.managers import BaseManager
import Queue
tasks_q = Queue.Queue()
tasks_q = Queue.Queue()
results_q = Queue.Queue()
minions_q = Queue.Queue()
master_q = Queue.Queue()
master_q = Queue.Queue()
class QueueManager(BaseManager):
"""
One QueueManager to rule all network Queues
"""
pass
"""
One QueueManager to rule all network Queues
"""
pass
QueueManager.register('get_tasks_q', callable=lambda: tasks_q)
QueueManager.register('get_results_q', callable=lambda: results_q)
QueueManager.register('get_minions_q', callable=lambda: minions_q)
QueueManager.register('get_master_q', callable=lambda: master_q)
QueueManager.register('get_tasks_q' , callable=lambda:tasks_q )
QueueManager.register('get_results_q', callable=lambda:results_q )
QueueManager.register('get_minions_q', callable=lambda:minions_q )
QueueManager.register('get_master_q' , callable=lambda:master_q )
def get_qs(qm):
"""
pass in a QueueManager, and this function returns all relevant
queues attached to that QueueManager.
"""
return (qm.get_tasks_q(),
qm.get_results_q(),
qm.get_master_q(),
qm.get_minions_q())
"""
pass in a QueueManager, and this function returns all relevant
queues attached to that QueueManager.
"""
return (qm.get_tasks_q(),
qm.get_results_q(),
qm.get_master_q(),
qm.get_minions_q())
+19
View File
@@ -0,0 +1,19 @@
import os
import json
default_config = {
'filename': '/tmp/interp.log',
'level': 'debug',
'size': 102400,
'logbackup': 10,
'pypath': None,
}
try:
with open(os.path.expanduser('~/.config/interp.json')) as config_file:
d = json.load(config_file)
except IOError as e:
d = {}
config = dict(default_config.items() + d.items())
+2 -3
View File
@@ -1,10 +1,9 @@
from interp.grid.delaunay import dgrid as basegrid
from interp.tools import baker_exact_2D as exact_func
from itertools import product
import numpy as np
from interp.grid.delaunay import dgrid as basegrid
class rect_grid(basegrid):
def __init__(self, xres = 5, yres = 5):
xmin = 0.0
+2 -6
View File
@@ -1,10 +1,9 @@
from interp.grid.delaunay import dgrid as basegrid
from interp.tools import baker_exact_3D, log
from itertools import product
import numpy as np
from interp.grid.delaunay import dgrid as basegrid
class rect_grid(basegrid):
def __init__(self, xres = 5, yres = 5, zres = 5):
xmin = 0.0
@@ -22,7 +21,6 @@ class rect_grid(basegrid):
zspan = zmaz - zmin
zdel = zspan / float(zres - 1)
verts = []
q = np.zeros(xres * yres * zres)
for x in xrange(xres):
@@ -41,8 +39,6 @@ class random_grid(rect_grid):
def __init__(self, num_verts = 100):
verts = []
r = np.random
appx_side_res = int(np.power(num_verts, 1/3.0))
delta = 1.0 / float(appx_side_res)
+199 -191
View File
@@ -1,5 +1,4 @@
import sys
from collections import defaultdict
from collections import defaultdict
import pickle
from xml.dom.minidom import Document
@@ -9,256 +8,265 @@ from scipy.spatial import KDTree
from interp.baker import run_baker
from interp.baker import get_phis
import interp
import logging
log = logging.getLogger("interp")
MAX_SEARCH_COUNT = 256
TOL = 1e-8
__version__ = interp.__version__
class grid(object):
def __init__(self, verts = None, q = None):
"""
verts = array of arrays (if passed in, will convert to numpy.array)
[
[x0,y0 <, z0>],
[x1,y1 <, z1>],
...
]
def __init__(self, verts=None, q=None):
"""
verts = array of arrays (if passed in, will convert to numpy.array)
[
[x0,y0 <, z0>],
[x1,y1 <, z1>],
...
]
q = array (1D) of physical values
"""
q = array (1D) of physical values
"""
if verts != None:
self.verts = np.array(verts)
self.tree = KDTree(self.verts)
if verts != None:
self.verts = np.array(verts)
self.tree = KDTree(self.verts)
if q != None:
self.q = np.array(q)
if q != None:
self.q = np.array(q)
self.cells = {}
self.cells_for_vert = defaultdict(list)
self.cells = {}
self.cells_for_vert = defaultdict(list)
def get_containing_simplex(self, X):
if not self.cells:
raise Exception("cell connectivity is not set up")
def get_containing_simplex(self, X):
if not self.cells:
raise Exception("cell connectivity is not set up")
# get closest point
(dist, indicies) = self.tree.query(X, 2)
closest_point = indicies[0]
# 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])
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_cells = []
cells_to_check = list(self.cells_for_vert[closest_point])
simplex = None
checked_cells = []
cells_to_check = list(self.cells_for_vert[closest_point])
attempts = 0
while not simplex and cells_to_check:
attempts += 1
attempts = 0
while not simplex and cells_to_check:
attempts += 1
if attempts > MAX_SEARCH_COUNT:
raise Exception("Is the search becoming exhaustive? (%d attempts)" % attempts)
if attempts > MAX_SEARCH_COUNT:
raise Exception("Is the search becoming exhaustive?'\
'(%d attempts)" % attempts)
cur_cell = cells_to_check.pop(0)
checked_cells.append(cur_cell)
cur_cell = cells_to_check.pop(0)
checked_cells.append(cur_cell)
if cur_cell.contains(X, self):
simplex = cur_cell
continue
if cur_cell.contains(X, self):
simplex = cur_cell
continue
for neighbor in cur_cell.neighbors:
if (neighbor not in checked_cells) and (neighbor not in cells_to_check):
cells_to_check.append(neighbor)
for neighbor in cur_cell.neighbors:
if (neighbor not in checked_cells) \
and (neighbor not in cells_to_check):
cells_to_check.append(neighbor)
if not simplex:
raise Exception('no containing simplex found')
if not simplex:
raise Exception('no containing simplex found')
log.debug("simplex vert indicies: %s" % simplex.verts)
R = self.create_mesh(simplex.verts)
log.debug("R:\n%s", R)
log.debug("simplex vert indicies: %s" % simplex.verts)
R = self.create_mesh(simplex.verts)
log.debug("R:\n%s", R)
log.debug('total attempts before finding simplex: %d' % attempts)
return R
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).
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
"""
note: the input is indicies, the grid contains verts
"""
return grid(self.verts[indicies], self.q[indicies])
return grid(self.verts[indicies], self.q[indicies])
def get_simplex_and_nearest_points(self, X, extra_points = 3):
"""
this returns two grid objects: R and S.
def get_simplex_and_nearest_points(self, X, extra_points=3):
"""
this returns two grid objects: R and S.
R is a grid object that is a containing simplex around point X
R is a grid object that is a containing simplex around point X
S : some verts from all points that are not the simplex
"""
simplex_size = self.dim + 1
log.debug("extra verts: %d" % extra_points)
log.debug("simplex size: %d" % simplex_size)
S : some verts from all points that are not the simplex
"""
simplex_size = self.dim + 1
log.debug("extra verts: %d" % extra_points)
log.debug("simplex size: %d" % simplex_size)
r_mesh = self.get_containing_simplex(X)
r_mesh = self.get_containing_simplex(X)
# and some UNIQUE extra verts
(dist, indicies) = self.tree.query(X, simplex_size + extra_points)
log.debug("extra indicies: %s" % indicies)
# and some UNIQUE extra verts
(dist, indicies) = self.tree.query(X, simplex_size + extra_points)
log.debug("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
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]))
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)
log.debug("indicies: %s" % indicies)
log.debug("unique indicies: %s" % unique_indicies)
s_mesh = self.create_mesh(unique_indicies)
return (r_mesh, s_mesh)
return (r_mesh, s_mesh)
def run_baker(self, X, order = 2, extra_points = 3):
(R, S) = self.get_simplex_and_nearest_points(X, extra_points)
answer = run_baker(X, R, S, order)
return answer
def run_baker(self, X, order=2, extra_points=3):
(R, S) = self.get_simplex_and_nearest_points(X, extra_points)
answer = run_baker(X, R, S, order)
return answer
def for_qhull_generator(self):
"""
this returns a generator that should be fed into qdelaunay
"""
def for_qhull_generator(self):
"""
this returns a generator that should be fed into qdelaunay
"""
yield str(len(self.verts[0]));
yield '%d' % len(self.verts)
yield str(len(self.verts[0]))
yield '%d' % len(self.verts)
for p in self.verts:
yield "%f %f %f" % tuple(p)
for p in self.verts:
yield "%f %f %f" % tuple(p)
def for_qhull(self):
"""
this returns a single string that should be fed into qdelaunay
"""
r = '%d\n' % len(self.verts[0])
r += '%d\n' % len(self.verts)
for p in self.verts:
# r += "%f %f %f\n" % tuple(p)
r += "%s\n" % " ".join("%f" % i for i in p)
return r
def for_qhull(self):
"""
this returns a single string that should be fed into qdelaunay
"""
r = '%d\n' % len(self.verts[0])
r += '%d\n' % len(self.verts)
for p in self.verts:
# r += "%f %f %f\n" % tuple(p)
r += "%s\n" % " ".join("%f" % i for i in p)
return r
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])
cell_str = ", ".join([str(f.name) for f in self.cells_for_vert[c]])
r += " cells: [%s]" % cell_str
r += "\n"
if self.cells:
for v in self.cells.itervalues():
r += "%s\n" % v
return r
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])
cell_str = ", ".join([str(f.name) for f in self.cells_for_vert[c]])
r += " cells: [%s]" % cell_str
r += "\n"
if self.cells:
for v in self.cells.itervalues():
r += "%s\n" % v
return r
def normalize_q(self, new_max = 0.1):
largest_number = np.max(np.abs(self.q))
self.q *= new_max/largest_number
def normalize_q(self, new_max=0.1):
largest_number = np.max(np.abs(self.q))
self.q *= new_max / largest_number
def dump_to_blender_files(self,
pfile='/tmp/points.p', cfile='/tmp/cells.p'):
if len(self.verts[0]) == 2:
pickle.dump([(p[0], p[1], 0.0) for p in self.verts],
open(pfile, 'w'))
else:
pickle.dump([(p[0], p[1], p[2]) for p in self.verts],
open(pfile, 'w'))
def dump_to_blender_files(self, pfile = '/tmp/points.p', cfile = '/tmp/cells.p'):
if len(self.verts[0]) == 2:
pickle.dump([(p[0], p[1], 0.0) for p in self.verts], open(pfile, 'w'))
else:
pickle.dump([(p[0], p[1], p[2]) for p in self.verts], open(pfile, 'w'))
pickle.dump([f.verts for f in self.cells.itervalues()],
open(cfile, 'w'))
pickle.dump([f.verts for f in self.cells.itervalues()], open(cfile, 'w'))
def get_xml(self):
doc = Document()
ps = doc.createElement("points")
doc.appendChild(ps)
for i in zip(self.verts, self.q):
p = doc.createElement("point")
def get_xml(self):
doc = Document()
ps = doc.createElement("points")
doc.appendChild(ps)
for i in zip(self.verts, self.q):
p = doc.createElement("point")
p.setAttribute("x", str(i[0][0]))
p.setAttribute('y', str(i[0][1]))
p.setAttribute('z', str(i[0][2]))
p.setAttribute('q', str(i[1]))
ps.appendChild(p)
p.setAttribute("x", str(i[0][0]))
p.setAttribute('y', str(i[0][1]))
p.setAttribute('z', str(i[0][2]))
p.setAttribute('q', str(i[1] ))
ps.appendChild(p)
return doc
return doc
def toxml(self):
return self.get_xml().toxml()
def toxml(self):
return self.get_xml().toxml()
def toprettyxml(self):
return self.get_xml().toprettyxml()
def toprettyxml(self):
return self.get_xml().toprettyxml()
class cell(object):
def __init__(self, name):
self.name = name
self.verts = []
self.neighbors = []
def __init__(self, name):
self.name = name
self.verts = []
self.neighbors = []
def add_vert(self, v):
"""
v should be an index into grid.verts
"""
self.verts.append(v)
def add_vert(self, v):
"""
v should be an index into grid.verts
"""
self.verts.append(v)
def add_neighbor(self, n):
"""
reference to another cell object
"""
self.neighbors.append(n)
def add_neighbor(self, n):
"""
reference to another cell object
"""
self.neighbors.append(n)
def contains(self, X, G):
"""
X = point of interest
G = corrensponding grid object (G.verts)
def contains(self, X, G):
"""
X = point of interest
G = corrensponding grid object (G.verts)
because of the way i'm storing things, a cell simply stores indicies,
and so one must pass in a reference to the grid object containing real
verts.
because of the way i'm storing things, a cell simply stores
indicies, and so one must pass in a reference to the grid object
containing real verts.
this simply calls grid.simplex.contains
"""
return contains(X, [G.verts[i] for i in self.verts])
this simply calls grid.simplex.contains
"""
return contains(X, [G.verts[i] for i in self.verts])
def __str__(self):
# neighbors = [str(i.name) for i in self.neighbors]
return '<cell %s: verts: %s neighbor count: %s>' %\
(
self.name,
self.verts,
len(self.neighbors),
# ", ".join(neighbors)
)
def __str__(self):
# neighbors = [str(i.name) for i in self.neighbors]
return '<cell %s: verts: %s neighbor count: %s>' %\
(
self.name,
self.verts,
len(self.neighbors),
# ", ".join(neighbors)
)
__repr__ = __str__
__repr__ = __str__
TOL = 1e-8
def contains(X, R):
"""
tests if X (point) is in R
"""
tests if X (point) is in R
R is a simplex, represented by a list of n-degree coordinates
"""
phis = get_phis(X, R)
R is a simplex, represented by a list of n-degree coordinates
"""
phis = get_phis(X, R)
r = True
if [i for i in phis if i < 0.0 - TOL]:
r = False
return r
r = True
if [i for i in phis if i < 0.0 - TOL]:
r = False
return r
+1 -4
View File
@@ -1,7 +1,4 @@
import pickle
from itertools import combinations
from collections import defaultdict
import numpy as np
from scipy.spatial import KDTree
@@ -36,7 +33,7 @@ class ggrid(grid):
gmsh_file.readline() # $MeshFormat
fmat = gmsh_file.readline()
gmsh_file.readline()
gmsh_file.readline() # $EndMeshFormat
gmsh_file.readline() # $Nodes
+52 -59
View File
@@ -1,82 +1,75 @@
import os
import numpy as np
import logging
log = logging.getLogger("interp")
def rms(errors):
"""
root mean square calculation
"""
"""
root mean square calculation
"""
# slow pure python way for reference:
# r = 0.0
# for i in errors:
# r += np.power(i, 2)
# r = np.sqrt(r / len(errors))
# return r
# slow pure python way for reference:
# r = 0.0
# for i in errors:
# r += np.power(i, 2)
# r = np.sqrt(r / len(errors))
# return r
return np.sqrt((errors ** 2).mean())
return np.sqrt((errors**2).mean())
def baker_exact_2D(X):
"""
the exact function (2D) used from baker's article (for testing, slightly
modified)
"""
x ,y = X
"""
the exact function (2D) used from baker's article (for testing,
slightly modified)
"""
x, y = X
answer = np.power((np.sin(x * np.pi) * np.cos(y * np.pi)), 2)
return answer
answer = np.power((np.sin(x * np.pi) * np.cos(y * np.pi)), 2)
log.debug(answer)
return answer
def friendly_exact_2D(X):
"""
A friendlier 2D func
"""
x ,y = X
answer = 1.0 + x*x + y*y
log.debug(answer)
return answer
"""
A friendlier 2D func
"""
x, y = X
answer = 1.0 + x * x + y * y
return answer
def baker_exact_3D(X):
"""
the exact function (3D) used from baker's article (for testing)
"""
x = X[0]
y = X[1]
z = X[2]
answer = np.power((np.sin(x * np.pi / 2.0) * np.sin(y * np.pi / 2.0) * np.sin(z * np.pi / 2.0)), 2)
log.debug(answer)
return answer
"""
the exact function (3D) used from baker's article (for testing)
"""
x, y, z = X
answer = np.power((np.sin(x * np.pi / 2.0) * np.sin(y * np.pi / 2.0) *
np.sin(z * np.pi / 2.0)), 2)
return answer
def friendly_exact_3D(X):
x,y,z = X
return 1 + x*x + y*y + z*z
x, y, z = X
return 1 + x * x + y * y + z * z
def scipy_exact_2D(X):
x,y = X
return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2
x, y = X
return x * (1 - x) * np.cos(4 * np.pi * x) *\
np.sin(4 * np.pi * y ** 2) ** 2
def improved_answer(answer, exact):
if not answer['error']:
# was probably just a linear interpolation
return False
if not answer['error']:
# was probably just a linear interpolation
return False
log.debug('qlin: %s' % answer['qlin'])
log.debug('error: %s' % answer['error'])
log.debug('final: %s' % answer['final'])
log.debug('exact: %s' % exact)
if np.abs(answer['final'] - exact) <= np.abs(answer['qlin'] - exact):
return True
else:
return False
if np.abs(answer['final'] - exact) <= np.abs(answer['qlin'] - exact):
log.debug(":) improved result")
return True
else:
log.debug(":( damaged result")
return False
def improved(qlin, err, final, exact):
if np.abs(final - exact) <= np.abs(qlin - exact):
return True
else:
return False
if np.abs(final - exact) <= np.abs(qlin - exact):
return True
else:
return False