Futurize 1, futurize 2, pasteurize.

This commit is contained in:
Brendan Smithyman
2016-07-16 14:17:02 -05:00
parent 362975d2bd
commit ca8d8f8c2d
197 changed files with 2618 additions and 1235 deletions
+11 -4
View File
@@ -1,3 +1,10 @@
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import object
import types
import time
import numpy as np
@@ -66,14 +73,14 @@ class Counter(object):
"""
Provides a text summary of the current counters and timers.
"""
print 'Counters:'
print('Counters:')
for prop in sorted(self._countList):
print " {0:<40}: {1:8d}".format(prop,self._countList[prop])
print '\nTimes:'+' '*40+'mean sum'
print(" {0:<40}: {1:8d}".format(prop,self._countList[prop]))
print('\nTimes:'+' '*40+'mean sum')
for prop in sorted(self._timeList):
l = len(self._timeList[prop])
a = np.array(self._timeList[prop])
print " {0:<40}: {1:4.2e}, {2:4.2e}, {3:4d}x".format(prop,a.mean(),a.sum(),l)
print(" {0:<40}: {1:4.2e}, {2:4.2e}, {3:4d}x".format(prop,a.mean(),a.sum(),l))
def count(f):
@wraps(f)
+20 -12
View File
@@ -1,7 +1,15 @@
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import range
from past.utils import old_div
import numpy as np
import scipy.ndimage as ndi
import scipy.sparse as sp
from matutils import mkvc
from .matutils import mkvc
def addBlock(gridCC, modelCC, p0, p1, blockProp):
"""
@@ -122,7 +130,7 @@ def defineElipse(ccMesh, center=None, anisotropy=None, slope=10., theta=0.):
G[:, i] = G[:,i]/anisotropy[i]*2.
D = np.sqrt(np.sum(G**2,axis=1))
return -np.arctan((D-1)*slope)*(2./np.pi)/2.+0.5
return -np.arctan((D-1)*slope)*(old_div(2.,np.pi))/2.+0.5
def getIndicesSphere(center,radius,ccMesh):
"""
@@ -289,9 +297,9 @@ def randomModel(shape, seed=None, anisotropy=None, its=100, bounds=None):
if seed is None:
seed = np.random.randint(1e3)
print 'Using a seed of: ', seed
print('Using a seed of: ', seed)
if type(shape) in [int, long, float]:
if type(shape) in [int, int, float]:
shape = (shape,) # make it a tuple for consistency
np.random.seed(seed)
@@ -308,13 +316,13 @@ def randomModel(shape, seed=None, anisotropy=None, its=100, bounds=None):
assert len(anisotropy.shape) is len(shape), 'Anisotropy must be the same shape.'
smth = np.array(anisotropy,dtype=float)
smth = smth/smth.sum() # normalize
smth = old_div(smth,smth.sum()) # normalize
mi = mr
for i in range(its):
mi = ndi.convolve(mi, smth)
# scale the model to live between the bounds.
mi = (mi - mi.min())/(mi.max()-mi.min()) # scaled between 0 and 1
mi = old_div((mi - mi.min()),(mi.max()-mi.min())) # scaled between 0 and 1
mi = mi*(bounds[1]-bounds[0])+bounds[0]
@@ -360,9 +368,9 @@ if __name__ == '__main__':
sigma = defineBlockConductivity(ccMesh,p0,p1,vals)
# Plot sigma model
print sigma.shape
print(sigma.shape)
M.plotImage(sigma)
print 'Done with block! :)'
print('Done with block! :)')
plt.show()
# -----------------------------------------
@@ -373,8 +381,8 @@ if __name__ == '__main__':
sigma = defineTwoLayeredConductivity(ccMesh,depth,vals)
M.plotImage(sigma)
print sigma
print 'layer model!'
print(sigma)
print('layer model!')
plt.show()
# -----------------------------------------
@@ -391,8 +399,8 @@ if __name__ == '__main__':
# Plot sigma model
M.plotImage(sigma)
print sigma
print 'Scalar conductivity defined!'
print(sigma)
print('Scalar conductivity defined!')
plt.show()
# -----------------------------------------
+17 -8
View File
@@ -1,5 +1,14 @@
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import object
from past.utils import old_div
import numpy as np, scipy.sparse as sp
from matutils import mkvc
from .matutils import mkvc
import warnings
def _checkAccuracy(A, b, X, accuracyTol):
@@ -9,7 +18,7 @@ def _checkAccuracy(A, b, X, accuracyTol):
nrm /= nrm_b
if nrm > accuracyTol:
msg = '### SolverWarning ###: Accuracy on solve is above tolerance: %e > %e' % (nrm, accuracyTol)
print msg
print(msg)
warnings.warn(msg, RuntimeWarning)
@@ -28,9 +37,9 @@ def SolverWrapD(fun, factorize=True, checkAccuracy=True, accuracyTol=1e-6, name=
self.A = A.tocsc()
self.checkAccuracy = kwargs.get("checkAccuracy", checkAccuracy)
if kwargs.has_key("checkAccuracy"): del kwargs["checkAccuracy"]
if "checkAccuracy" in kwargs: del kwargs["checkAccuracy"]
self.accuracyTol = kwargs.get("accuracyTol", accuracyTol)
if kwargs.has_key("accuracyTol"): del kwargs["accuracyTol"]
if "accuracyTol" in kwargs: del kwargs["accuracyTol"]
self.kwargs = kwargs
@@ -90,9 +99,9 @@ def SolverWrapI(fun, checkAccuracy=True, accuracyTol=1e-5, name=None):
self.A = A
self.checkAccuracy = kwargs.get("checkAccuracy", checkAccuracy)
if kwargs.has_key("checkAccuracy"): del kwargs["checkAccuracy"]
if "checkAccuracy" in kwargs: del kwargs["checkAccuracy"]
self.accuracyTol = kwargs.get("accuracyTol", accuracyTol)
if kwargs.has_key("accuracyTol"): del kwargs["accuracyTol"]
if "accuracyTol" in kwargs: del kwargs["accuracyTol"]
self.kwargs = kwargs
@@ -159,12 +168,12 @@ class SolverDiag(object):
return x.reshape((n,nrhs), order='F')
def _solve1(self, rhs):
return rhs.flatten()/self._diagonal
return old_div(rhs.flatten(),self._diagonal)
def _solveM(self, rhs):
n = self.A.shape[0]
nrhs = rhs.size // n
return rhs/self._diagonal.repeat(nrhs).reshape((n,nrhs))
return old_div(rhs,self._diagonal.repeat(nrhs).reshape((n,nrhs)))
def clean(self):
pass
+16 -10
View File
@@ -1,10 +1,16 @@
from matutils import *
from codeutils import *
from meshutils import *
from curvutils import volTetra, faceInfo, indexCube
from interputils import interpmat
from CounterUtils import *
import ModelBuilder
import SolverUtils
from coordutils import *
from modelutils import *
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from .matutils import *
from .codeutils import *
from .meshutils import *
from .curvutils import volTetra, faceInfo, indexCube
from .interputils import interpmat
from .CounterUtils import *
from . import ModelBuilder
from . import SolverUtils
from .coordutils import *
from .modelutils import *
+20 -13
View File
@@ -1,3 +1,10 @@
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from past.utils import old_div
import types
import time
import numpy as np
@@ -32,7 +39,7 @@ def memProfileWrapper(towrap, *funNames):
if hasattr(towrap,f):
attrs[f] = profile(getattr(towrap,f))
else:
print '%s not found in %s Class' % (f, towrap.__name__)
print('%s not found in %s Class' % (f, towrap.__name__))
return type(towrap.__name__ + 'MemProfileWrap', (towrap,), attrs)
@@ -50,9 +57,9 @@ def hook(obj, method, name=None, overwrite=False, silent=False):
if not hasattr(obj,name) or overwrite:
setattr(obj, name, types.MethodType( method, obj ))
if getattr(obj,'debug',False):
print 'Method '+name+' was added to class.'
print('Method '+name+' was added to class.')
elif not silent or getattr(obj,'debug',False):
print 'Method '+name+' was not overwritten.'
print('Method '+name+' was not overwritten.')
def setKwargs(obj, ignore=None, **kwargs):
@@ -76,15 +83,15 @@ def printTitles(obj, printers, name='Print Titles', pad=''):
for printer in printers:
titles += ('{:^%i}'%printer['width']).format(printer['title']) + ''
widths += printer['width']
print pad + "{0} {1} {0}".format('='*((widths-1-len(name))/2), name)
print pad + titles
print pad + "%s" % '-'*widths
print(pad + "{0} {1} {0}".format('='*(old_div((widths-1-len(name)),2)), name))
print(pad + titles)
print(pad + "%s" % '-'*widths)
def printLine(obj, printers, pad=''):
values = ''
for printer in printers:
values += ('{:^%i}'%printer['width']).format(printer['format'] % printer['value'](obj))
print pad + values
print(pad + values)
def checkStoppers(obj, stoppers):
# check stopping rules
@@ -98,18 +105,18 @@ def checkStoppers(obj, stoppers):
if stopper['stopType'] == 'critical':
critical.append(l <= r)
if obj.debug: print 'checkStoppers.optimal: ', optimal
if obj.debug: print 'checkStoppers.critical: ', critical
if obj.debug: print('checkStoppers.optimal: ', optimal)
if obj.debug: print('checkStoppers.critical: ', critical)
return (len(optimal)>0 and all(optimal)) | (len(critical)>0 and any(critical))
def printStoppers(obj, stoppers, pad='', stop='STOP!', done='DONE!'):
print pad + "%s%s%s" % ('-'*25,stop,'-'*25)
print(pad + "%s%s%s" % ('-'*25,stop,'-'*25))
for stopper in stoppers:
l = stopper['left'](obj)
r = stopper['right'](obj)
print pad + stopper['str'] % (l<=r,l,r)
print pad + "%s%s%s" % ('-'*25,done,'-'*25)
print(pad + stopper['str'] % (l<=r,l,r))
print(pad + "%s%s%s" % ('-'*25,done,'-'*25))
def callHooks(match, mainFirst=False):
"""
@@ -169,7 +176,7 @@ def dependentProperty(name, value, children, doc):
return property(fget=fget, fset=fset, doc=doc)
def isScalar(f):
scalarTypes = [float, int, long, np.float_, np.int_]
scalarTypes = [float, int, int, np.float_, np.int_]
if type(f) in scalarTypes:
return True
elif isinstance(f, np.ndarray) and f.size == 1 and type(f[0]) in scalarTypes:
+9 -2
View File
@@ -1,3 +1,10 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from past.utils import old_div
import numpy as np
from SimPEG.Utils import mkvc
@@ -31,9 +38,9 @@ def rotationMatrixFromNormals(v0,v1,tol=1e-20):
if np.linalg.norm(rotAx) < tol:
return np.eye(3,dtype=float)
rotAx *= 1./np.linalg.norm(rotAx)
rotAx *= old_div(1.,np.linalg.norm(rotAx))
cosT = n0dotn1/(np.linalg.norm(n0)*np.linalg.norm(n1))
cosT = old_div(n0dotn1,(np.linalg.norm(n0)*np.linalg.norm(n1)))
sinT = np.sqrt(1.-n0dotn1**2)
ux = np.array([[0., -rotAx[2], rotAx[1]], [rotAx[2], 0., -rotAx[0]], [-rotAx[1], rotAx[0], 0.]],dtype=float)
+12 -5
View File
@@ -1,6 +1,13 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from past.utils import old_div
import numpy as np
from scipy import sparse as sp
from matutils import mkvc, ndgrid, sub2ind, sdiag
from .matutils import mkvc, ndgrid, sub2ind, sdiag
def volTetra(xyz, A, B, C, D):
@@ -27,7 +34,7 @@ def volTetra(xyz, A, B, C, D):
CD = xyz[C, :] - xyz[D, :]
V = (BD[:, 0]*CD[:, 1] - BD[:, 1]*CD[:, 0])*AD[:, 2] - (BD[:, 0]*CD[:, 2] - BD[:, 2]*CD[:, 0])*AD[:, 1] + (BD[:, 1]*CD[:, 2] - BD[:, 2]*CD[:, 1])*AD[:, 0]
return V/6
return old_div(V,6)
def indexCube(nodes, gridSize, n=None):
@@ -163,10 +170,10 @@ def faceInfo(xyz, A, B, C, D, average=True, normalizeNormals=True):
nD = cross(DA, CD)
length = lambda x: np.sqrt(x[:, 0]**2 + x[:, 1]**2 + x[:, 2]**2)
normalize = lambda x: x/np.kron(np.ones((1, x.shape[1])), mkvc(length(x), 2))
normalize = lambda x: old_div(x,np.kron(np.ones((1, x.shape[1])), mkvc(length(x), 2)))
if average:
# average the normals at each vertex.
N = (nA + nB + nC + nD)/4 # this is intrinsically weighted by area
N = old_div((nA + nB + nC + nD),4) # this is intrinsically weighted by area
# normalize
N = normalize(N)
else:
@@ -183,7 +190,7 @@ def faceInfo(xyz, A, B, C, D, average=True, normalizeNormals=True):
# So also could be viewed as the average parallelogram.
#
# TODO: This does not compute correctly for concave quadrilaterals
area = (length(nA)+length(nB)+length(nC)+length(nD))/4
area = old_div((length(nA)+length(nB)+length(nC)+length(nD)),4)
return N, area
+16 -8
View File
@@ -1,19 +1,27 @@
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import range
from past.utils import old_div
import numpy as np
import scipy.sparse as sp
from matutils import mkvc, sub2ind, spzeros
from .matutils import mkvc, sub2ind, spzeros
try:
import interputils_cython as pyx
from . import interputils_cython as pyx
_interp_point_1D = pyx._interp_point_1D
_interpmat1D = pyx._interpmat1D
_interpmat2D = pyx._interpmat2D
_interpmat3D = pyx._interpmat3D
_interpCython = True
except ImportError, e:
print """Efficiency Warning: Interpolation will be slow, use setup.py!
except ImportError as e:
print("""Efficiency Warning: Interpolation will be slow, use setup.py!
python setup.py build_ext --inplace
"""
""")
_interpCython = False
@@ -62,7 +70,7 @@ def interpmat(locs, x, y=None, z=None):
shape = [x.size, y.size, z.size]
inds, vals = _interpmat3D(locs, x, y, z)
I = np.repeat(range(npts),2**len(shape))
I = np.repeat(list(range(npts)),2**len(shape))
J = sub2ind(shape,inds)
Q = sp.csr_matrix((vals,(I, J)),
shape=(npts, np.prod(shape)))
@@ -92,8 +100,8 @@ if not _interpCython:
return ind_x1, ind_x1, 0.5, 0.5
hx = x[ind_x2] - x[ind_x1]
wx1 = 1 - (xr_i - x[ind_x1])/hx
wx2 = 1 - (x[ind_x2] - xr_i)/hx
wx1 = 1 - old_div((xr_i - x[ind_x1]),hx)
wx2 = 1 - old_div((x[ind_x2] - xr_i),hx)
return ind_x1, ind_x2, wx1, wx2
+8 -1
View File
@@ -1,3 +1,10 @@
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import open
from future import standard_library
standard_library.install_aliases()
from SimPEG import np, Mesh
import time as tm
import vtk, vtk.util.numpy_support as npsup
@@ -124,7 +131,7 @@ def surface2inds(vrtx, trgl, mesh, boundaries=True, internal=True):
else:
extractImpDistRectGridFilt.ExtractInsideOff()
print "Extracting indices from grid..."
print("Extracting indices from grid...")
# Executing the pipe
extractImpDistRectGridFilt.Update()
+27 -18
View File
@@ -1,6 +1,15 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import object
from past.utils import old_div
import numpy as np
import scipy.sparse as sp
from codeutils import isScalar
from .codeutils import isScalar
def mkvc(x, numDims=1):
"""Creates a vector with the number of dimension specified
@@ -46,7 +55,7 @@ def sdiag(h):
def sdInv(M):
"Inverse of a sparse diagonal matrix"
return sdiag(1/M.diagonal())
return sdiag(old_div(1,M.diagonal()))
def speye(n):
"""Sparse identity"""
@@ -202,17 +211,17 @@ def inv3X3BlockDiagonal(a11, a12, a13, a21, a22, a23, a31, a32, a33, returnMatri
detA = a31*a12*a23 - a31*a13*a22 - a21*a12*a33 + a21*a13*a32 + a11*a22*a33 - a11*a23*a32
b11 = +(a22*a33 - a23*a32)/detA
b12 = -(a12*a33 - a13*a32)/detA
b13 = +(a12*a23 - a13*a22)/detA
b11 = old_div(+(a22*a33 - a23*a32),detA)
b12 = old_div(-(a12*a33 - a13*a32),detA)
b13 = old_div(+(a12*a23 - a13*a22),detA)
b21 = +(a31*a23 - a21*a33)/detA
b22 = -(a31*a13 - a11*a33)/detA
b23 = +(a21*a13 - a11*a23)/detA
b21 = old_div(+(a31*a23 - a21*a33),detA)
b22 = old_div(-(a31*a13 - a11*a33),detA)
b23 = old_div(+(a21*a13 - a11*a23),detA)
b31 = -(a31*a22 - a21*a32)/detA
b32 = +(a31*a12 - a11*a32)/detA
b33 = -(a21*a12 - a11*a22)/detA
b31 = old_div(-(a31*a22 - a21*a32),detA)
b32 = old_div(+(a31*a12 - a11*a32),detA)
b33 = old_div(-(a21*a12 - a11*a22),detA)
if not returnMatrix:
return b11, b12, b13, b21, b22, b23, b31, b32, b33
@@ -243,7 +252,7 @@ def inv2X2BlockDiagonal(a11, a12, a21, a22, returnMatrix=True):
a22 = mkvc(a22)
# compute inverse of the determinant.
detAinv = 1./(a11*a22 - a21*a12)
detAinv = old_div(1.,(a11*a22 - a21*a12))
b11 = +detAinv*a22
b12 = -detAinv*a12
@@ -319,9 +328,9 @@ def invPropertyTensor(M, tensor, returnMatrix=False):
propType = TensorType(M, tensor)
if isScalar(tensor):
T = 1./tensor
T = old_div(1.,tensor)
elif propType < 3: # Isotropic or Diagonal
T = 1./mkvc(tensor) # ensure it is a vector.
T = old_div(1.,mkvc(tensor)) # ensure it is a vector.
elif M.dim == 2 and tensor.size == M.nC*3: # Fully anisotropic, 2D
tensor = tensor.reshape((M.nC,3), order='F')
B = inv2X2BlockDiagonal(tensor[:,0], tensor[:,2],
@@ -370,7 +379,7 @@ def diagEst(matFun, n, k=None, approach='Probing'):
matFun = lambda v: A.dot(v)
if k is None:
k = np.floor(n/10.)
k = np.floor(old_div(n,10.))
if approach =='Ones':
def getv(n,i=None):
@@ -397,7 +406,7 @@ def diagEst(matFun, n, k=None, approach='Probing'):
Mv += matFun(vk)*vk
vv += vk*vk
d = Mv/vv
d = old_div(Mv,vv)
return d
@@ -451,10 +460,10 @@ class Identity(object):
def __div__(self, v):
if sp.issparse(v): raise NotImplementedError('Sparse arrays not divisibile.')
return 1/v if self._positive else -1/v
return old_div(1,v) if self._positive else old_div(-1,v)
def __truediv__(self, v):
if sp.issparse(v): raise NotImplementedError('Sparse arrays not divisibile.')
return 1.0/v if self._positive else -1.0/v
return old_div(1.0,v) if self._positive else old_div(-1.0,v)
def __rdiv__(self, v):
return v if self._positive else -v
+15 -7
View File
@@ -1,8 +1,16 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from builtins import int
from future import standard_library
standard_library.install_aliases()
from past.utils import old_div
import numpy as np
from scipy import sparse as sp
from matutils import mkvc, ndgrid, sub2ind, sdiag
from codeutils import asArray_N_x_Dim
from codeutils import isScalar
from .matutils import mkvc, ndgrid, sub2ind, sdiag
from .codeutils import asArray_N_x_Dim
from .codeutils import isScalar
import os
def exampleLrmGrid(nC, exType):
@@ -14,15 +22,15 @@ def exampleLrmGrid(nC, exType):
assert exType in possibleTypes, "Not a possible example type."
if exType == 'rect':
return list(ndgrid([np.cumsum(np.r_[0, np.ones(nx)/nx]) for nx in nC], vector=False))
return list(ndgrid([np.cumsum(np.r_[0, old_div(np.ones(nx),nx)]) for nx in nC], vector=False))
elif exType == 'rotate':
if len(nC) == 2:
X, Y = ndgrid([np.cumsum(np.r_[0, np.ones(nx)/nx]) for nx in nC], vector=False)
X, Y = ndgrid([np.cumsum(np.r_[0, old_div(np.ones(nx),nx)]) for nx in nC], vector=False)
amt = 0.5-np.sqrt((X - 0.5)**2 + (Y - 0.5)**2)
amt[amt < 0] = 0
return [X + (-(Y - 0.5))*amt, Y + (+(X - 0.5))*amt]
elif len(nC) == 3:
X, Y, Z = ndgrid([np.cumsum(np.r_[0, np.ones(nx)/nx]) for nx in nC], vector=False)
X, Y, Z = ndgrid([np.cumsum(np.r_[0, old_div(np.ones(nx),nx)]) for nx in nC], vector=False)
amt = 0.5-np.sqrt((X - 0.5)**2 + (Y - 0.5)**2 + (Z - 0.5)**2)
amt[amt < 0] = 0
return [X + (-(Y - 0.5))*amt, Y + (-(Z - 0.5))*amt, Z + (-(X - 0.5))*amt]
@@ -179,7 +187,7 @@ def ExtractCoreMesh(xyzlim, mesh, meshType='tensor'):
& (mesh.gridCC[:,2]>zmin) & (mesh.gridCC[:,2]<zmax)
else:
raise(Exception("Not implemented!"))
raise Exception
return actind, meshCore
+8 -1
View File
@@ -1,4 +1,11 @@
from matutils import mkvc, ndgrid
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import range
from .matutils import mkvc, ndgrid
import numpy as np
def surface2ind_topo(mesh, topo, gridLoc='CC'):